text
stringlengths 7
3.69M
|
|---|
module.exports = {
future: {
// removeDeprecatedGapUtilities: true,
// purgeLayersByDefault: true,
},
purge: [
'src/**/*.js',
'src/**/*.jsx',
'src/**/*.ts',
'src/**/*.tsx',
'public/**/*.html'
],
theme: {
fontSize: {
base: '1.4rem',
h1: '6.8rem',
h2: '4.5rem',
h3: '4.1rem',
h4: '3rem',
h5: '2.7rem',
h6: '2rem',
'paragraph-1': '2rem',
'paragraph-2': '1.8rem',
body: '1.6rem',
'small-text': '1.4rem',
captions: '1.2rem'
},
fontFamily: {
poppins: ['Nunito', 'sans-serif']
},
extend: {
borderRadius: {
primary: '14px',
16: '16px'
},
boxShadow: {
card: '0px 24px 64px rgba(0, 0, 0, 0.15)'
},
colors: {
primary: '#E9CB99',
secondary: '#243B7F',
'theme-dark-gray': '#263238',
'theme-green': '#0ACF83',
'theme-red': ' #FF0000',
'theme-yellow': '#FFCB4C'
}
}
},
variants: {},
plugins: []
}
|
function Blackberry() {
return "This is the blackberry page";
}
export default Blackberry;
|
var express = require("express");
var router = express.Router();
var axios = require("axios");
var fxml_url = "http://flightxml.flightaware.com/json/FlightXML3/";
var username = "YOURUSERNAME";
var apiKey = "YOURAPI";
var restclient = require("restler");
/* GET weaTHERR. */
router.get("/weather", function(req, res, next) {
restclient
.get(fxml_url + "WeatherConditions", {
username: username,
password: apiKey,
query: { airport_code: "KAUS", howMany: 1 }
})
.on("success", function(result, response) {
// util.puts(util.inspect(result, true, null));
var entry = result.WeatherConditionsResult.conditions[0];
res.send(
"The temperature at " +
entry.airport_code +
" is " +
entry.temp_air +
"C"
);
})
.on("error", function(error) {
res.send(error);
})
.on("fail", function(error) {
res.send(error);
});
});
router.get("/flight", function(req, res, next) {
restclient
.get(fxml_url + "FindFlight", {
username: username,
password: apiKey,
query: { origin: "KAUS", destination: "KSFO" }
})
.on("success", function(result, response) {
// util.puts(util.inspect(result, true, null));
res.send(result);
})
.on("error", function(error) {
res.send(error);
})
.on("fail", function(error) {
res.send(error);
});
});
module.exports = router;
|
var skills = ["HTML", "CSS", "JAVASCRIPT", "MONGODB", "MONGOOSE", "JQUERY", "RUBY", "RAILS"];
window.onload = function(skills ) {
for(var i = skills.length; i < skills.length; i++) {
document.getElementById("little").style.write(i);
}
};
|
export default class EventEmitter{
constructor(){
this.__events = {}
}
on( eventName , eventListener ){
if( this.__events[eventName] ){
this.__events[eventName].push( eventListener )
return
}
this.__events[eventName] = [ eventListener ]
}
off( eventName , eventListener ){
eventListener = eventListener || null
if( typeof this.__events[eventName] === 'undefined' ){
throw new Error(UnknownEventError(eventName))
}
if( eventListener === null ){
this.__events[eventName] = []
}else{
this.__events[eventName] = this.__events[eventName].filter(listener => listener !== eventListener)
}
if( this.__events[eventName].length <= 0 ){
delete this.__events[eventName]
}
}
emit( eventName , eventParameter ){
if( typeof this.__events[eventName] === 'undefined' || this.__events[eventName] === null ){
throw new Error(UnknownEventError(eventName))
}
this.__events[eventName].forEach(listener => listener(eventParameter))
}
}
function UnknownEventError( eventName ){
return `Unknown event (${eventName})`
}
|
import { combineReducers } from 'redux';
import loading from './LoadingReducer';
import error from './ErrorReducer';
import user from './UserReducer';
const rootReducer = combineReducers({
loading,
error,
user,
});
export default rootReducer;
|
/**
* Clear all the entries
* Create a new-entry event
* Make date dynamic
*
*
* ERRORS:
* Make Date static (to stay after having recorded the new entry of the day) : HOPEFULLY FIXED (have to fix LS first)
* HOw to read entries: you have to create a data structure. Every entry will have its title, entry and date. : FIXED
* Prevent empty entries : FIXED
* You need a separate update-btn (because it automaticcaly creates a new entry each time you click) : FIXED
* If i try to remove one element, all are removed : FIXED
* Everytime I reload, I have to save new data to the local Storage. Maybe I'll replace the old data-structure array with the new storage-array that's connected to the LS. FIXED
*LS Problem: When updating an item in the middle, all the items get updated (problem with id/index)
START UP PROBLEM: I can't start it from my file system, because the storage is initially reset as 'null' (as a result of the localStorage being. I can only use it from my live server. SOLVED
*
* Problems related to running it from the file system:
* New problem: when I create an entry, it gets saved to my LS but not to my storage-var. FIXED
* - I can't read the entries, as it says 'can't read title of undefined' FIXED
*
* TODOS:
* Make data persistent: 1. Add the items to LS. DONE 2. Make UI connected to LS-data. DONE 3. Update LS when changed.DONE 4. Delete from LS. DONE
* Add delete btn (deleting entries) : DONE
* Updating entry-function. You will need to return an id from the readEntry function, and use that id in the updatefunction. : FIXED
* Add messages 'Entry created!' 'Entry saved, updated, deleted etc' : FIXED
*
*
* UPDATES:
* - It seems like the app is functioning. :)
*
* NEW ERRORS:
* - The read-entry is not working. - FIXED
* - When removing or updating an entry, they all get removed/updated :/
*
* SUGGESTIONS:
* - Add a clear all entries-btn
*
*
* FIXINGS:
* TO-FIXES:
* - Change the date when reading an entry (to reflect the date of writing)
*
*/
const DOMstrings = {
entries: document.querySelector('.dashboard__entries'),
entryItems: document.querySelector('.dashboard__entries-item'),
currentDate: document.querySelector('.entryarea__box-date--currentdate'),
entryTitle: document.querySelector('.entryarea__box-title'),
entryField: document.querySelector('.entryarea__box-entryfield'),
saveBtn: document.querySelector('.entryarea__box-savebtn'),
updateBtn: document.querySelector('.entryarea__box-updatebtn'),
displayBox: document.querySelector('.display-message')
}
const data = [];
let storage = JSON.parse(localStorage.getItem('entries'));
if (storage) {
storage = JSON.parse(localStorage.getItem('entries'));
} else {
storage = [];
}
// Making Date Dynamic
const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const currentDay = days[new Date().getDay()];
const currentYear = new Date().getFullYear();
const currentDate = new Date().getDate();
const currentMonth = new Date().getMonth();
// Clearing Entries
document.addEventListener('DOMContentLoaded', loadPage);
DOMstrings.saveBtn.addEventListener('click', createEntry);
//Make the read entry a dbl-click event
DOMstrings.entries.addEventListener('click', readEntry);
//console.log(`This is the saved event ID: ${eventID}`);
//DOMstrings.updateBtn.addEventListener('click', updateEntry);
function loadPage() {
localStorage.setItem('entries', JSON.stringify(storage));
console.log(`Initial storage: ${storage}`);
DOMstrings.updateBtn.style.display = 'none';
// Clear entries
// while (DOMstrings.entries.firstChild) {
// DOMstrings.entries.firstChild.remove();
// }
if (storage) {
storage.forEach((element, index) => {
const markup = `
<li class="dashboard__entries-item" id="${storage[index].id}"><p class="dashboard__entries-item--title">${storage[index].title}</p>
<div class="date">
<img src="img/calendar-solid.svg" alt="Calendar Icon" class="icon-calendar"> <p class="dashboard__entries-item--date">${storage[index].entryDate}</p>
</div>
</li>
`;
DOMstrings.entries.insertAdjacentHTML('afterbegin', markup);
});
}
// Setting current date
// Sun. 8/5/2018
DOMstrings.currentDate.textContent = `${currentDay}. ${currentDate}/${currentMonth + 1}/${currentYear}`;
DOMstrings.displayBox.style.visibility = 'hidden';
}
// Creating New Entry
function createEntry() {
if (DOMstrings.entryTitle.value !== '' && DOMstrings.entryField.value !== '') {
let storage = JSON.parse(localStorage.getItem('entries'));
const title = DOMstrings.entryTitle.value;
const entryText = DOMstrings.entryField.value;
const entryDate = `${currentDay}. ${currentDate}/${currentMonth + 1}/${currentYear}`;
// id: storage.length === null ? 0 : storage.length
const entryObj = {
title,
entryText,
entryDate,
id: storage.length
};
//entryObj.id = storage.length === null ? 0 : storage.length;
storage.push(entryObj);
// Add to LS
localStorage.setItem('entries', JSON.stringify(storage));
// Display from LS
//const storage = JSON.parse(localStorage.getItem('entries'));
console.log(`Local Storage retrieved: ${storage}`);
// const storageIndex = storage.findIndex(e => e == entryObj);
// console.log(`storageIndex: ${storageIndex}`);
const objIndex = entryObj.id;
const markup = `
<li class="dashboard__entries-item" id="${storage[objIndex].id}"><p class="dashboard__entries-item--title">${storage[objIndex].title}</p>
<div class="date">
<img src="img/calendar-solid.svg" alt="Calendar Icon" class="icon-calendar"> <p class="dashboard__entries-item--date">${storage[objIndex].entryDate}</p>
</div>
</li>
`;
DOMstrings.entries.insertAdjacentHTML('afterbegin', markup);
console.log(storage);
DOMstrings.entryTitle.value = '';
DOMstrings.entryField.value = '';
DOMstrings.displayBox.style.visibility = 'visible';
DOMstrings.displayBox.firstElementChild.textContent = 'Entry Created!';
setTimeout(function(){
DOMstrings.displayBox.style.visibility = 'hidden';
}, 1500);
}
document.querySelector('.dashboard__entrymenu-item').addEventListener('click', function(e) {
console.log('You pressed the new entry-btn');
DOMstrings.entryTitle.value = '';
DOMstrings.entryField.value = '';
DOMstrings.saveBtn.style.display = 'inline-block';
DOMstrings.saveBtn.textContent = 'Save Now';
DOMstrings.updateBtn.style.display = 'none';
});
}
// Reading New Entry
function readEntry (e) {
DOMstrings.saveBtn.style.display = 'none';
DOMstrings.updateBtn.style.display = 'inline-block';
const targeted = e.target.closest('.dashboard__entries-item');
let retrievedStorage = JSON.parse(localStorage.getItem('entries'));
console.log(`This is the retrieved Storage: ${retrievedStorage}`);
const targetIndex = retrievedStorage.findIndex(e => e.id == targeted.id); // note: targetIndex is a number
console.log(targetIndex);
/* You have to find the index of the item. YOu can't read it from the targetIndex. Because, in our case:,
the id is 2, whereas the index inside of the retrievedStorage-array is 0. So, you have to find the index:
*/
DOMstrings.entryTitle.value = retrievedStorage[targetIndex].title;
DOMstrings.entryField.value = retrievedStorage[targetIndex].entryText;
DOMstrings.currentDate.textContent = retrievedStorage[targetIndex].entryDate;
DOMstrings.saveBtn.textContent = 'Update Now';
// Updating Entry
DOMstrings.updateBtn.addEventListener('click', function(e) {
console.log(`This is the saved event ID: ${targetIndex}`);
console.log(`This is the targeted id: ${targeted.id}. Its type is: ${typeof targeted.id}`);
// Update in the data
storage[targetIndex].title = DOMstrings.entryTitle.value;
storage[targetIndex].entryText = DOMstrings.entryField.value;
// Update in the LS
localStorage.setItem('entries', JSON.stringify(storage));
document.getElementById(targeted.id).firstElementChild.textContent = DOMstrings.entryTitle.value;
DOMstrings.displayBox.style.visibility = 'visible';
DOMstrings.displayBox.firstElementChild.textContent = 'Entry Updated!';
setTimeout(function(){
DOMstrings.displayBox.style.visibility = 'hidden';
}, 1500);
});
// Deleting Entry
document.querySelector('.delete-btn').addEventListener('click', function(e) {
// Handle case of empty entries
if (DOMstrings.entryTitle.value === '' || DOMstrings.entryTitle.value === '') {
// Display Box:
DOMstrings.displayBox.style.visibility = 'visible';
DOMstrings.displayBox.firstElementChild.textContent = 'Empty Inputs!';
DOMstrings.displayBox.firstElementChild.style.color = '#F04126';
setTimeout(function(){
DOMstrings.displayBox.style.visibility = 'hidden';
}, 1500);
} else {
//Delete from storage variable
let retrievedStorage = JSON.parse(localStorage.getItem('entries'));
// You have to hunt that ID, your starting point (Target) is the remove-btn...
let entryListArr = Array.from(e.target.parentElement.parentElement.parentElement.parentElement.parentElement.firstElementChild.firstElementChild.nextElementSibling.nextElementSibling.nextElementSibling.children);
let entryID;
// Loop through the children of the list and then check it with targeted.id with element.children
entryListArr.forEach((entry, index) => {
console.log(entry.id);
// Check if IDs are matching (inside of loop)
if (entry.id === targeted.id) {
// Save ID
entryID = entry.id;
console.log(entryID + 'this is the entryID');
// You can maybe remove the UI here
entry.remove();
}
});
retrievedStorage.forEach((obj, index) => {
if (obj.id == targeted.id) {
retrievedStorage.splice(index, 1);
}
});
localStorage.setItem('entries', JSON.stringify(retrievedStorage));
DOMstrings.entryTitle.value = '';
DOMstrings.entryField.value = '';
// Display Box:
DOMstrings.displayBox.style.visibility = 'visible';
DOMstrings.displayBox.firstElementChild.textContent = 'Entry Deleted!';
DOMstrings.displayBox.firstElementChild.style.color = '#F04126';
setTimeout(function(){
DOMstrings.displayBox.style.visibility = 'hidden';
}, 1500);
}
});
document.querySelector('.dashboard__entrymenu-item').addEventListener('click', function(e) {
console.log('You pressed the new entry-btn');
DOMstrings.entryTitle.value = '';
DOMstrings.entryField.value = '';
DOMstrings.saveBtn.style.display = 'inline-block';
DOMstrings.saveBtn.textContent = 'Save Now';
DOMstrings.updateBtn.style.display = 'none';
});
}
|
//document.getElementById('date').innerHTML = new Date().toDateString();
$(document).ready(function(){
$("#hide").click(function(){
$("#image3").hide();
});
$("#show").click(function(){
$(".image").show();
});
});
$(document).keydown(function(e) {
switch (e.which) {
case 37:
$("#image3").animate({
left: '-=50px'
});
break;
case 38:
$("#image3").animate({
top: '-=50px'
});
break;
case 39:
$("#image3").animate({
left: '+=50px'
});
break;
case 40:
$("#image3").animate({
top: '+=50px'
});
break;
}
})
var image1 = document.getElementById('image1');
var image2 = document.getElementById('image2');
var image3 = document.getElementById('image3');
//image1.style.visibility = 'hidden';
function showHide(h) {
if(getComputedStyle(h).visibility == 'visible') {
h.style.visibility = 'hidden';
} else if(getComputedStyle(h).visibility == 'hidden') {
h.style.visibility = 'visible';
}
}
//Hide images after so many milliseconds
//setTimeout(function(){ $("#image1").hide(); }, 3000);
//setTimeout(function(){ $("#image2").hide(); }, 4000);
//setTimeout(function(){ $("#image3").hide(); }, 5000);
//Event Listeners that show/hide images based on click event
//image1.addEventListener('click', function() {showHide(image1);});
//image2.addEventListener('click', function() {showHide(image2);});
//image3.addEventListener('click', function() {showHide(image3);});
//Using jQuery trigger() function to simulate click event.
//setInterval(function(){$('#image1').trigger('click');}, 3000);
//setInterval(function(){$('#image2').trigger('click');}, 4000);
//setInterval(function(){$('#image3').trigger('click');}, 5000);
//Create new Event
var newEvent = new Event('myEvent');
//Event Listeners that show/hide images based a newly created event
image1.addEventListener('myEvent', function() {showHide(image1);});
image2.addEventListener('myEvent', function() {showHide(image2);});
image3.addEventListener('myEvent', function() {showHide(image3);});
//Uses dispatchEvent function to send newly created event to given element
setInterval(function(){image1.dispatchEvent(newEvent);}, 3000);
setInterval(function(){image2.dispatchEvent(newEvent);}, 4000);
setInterval(function(){image3.dispatchEvent(newEvent);}, 5000);
|
import React ,{Component} from 'react';
import './style.css';
class FinishedItem extends Component{
render(){
let toDoFinished = this.props.toDo;
return(
<div className="FinishedItem">
<div className="itemFinished" >
<span>{toDoFinished.index}.</span>
<span>{toDoFinished.item}</span>
</div>
</div>
);
}
}
export default FinishedItem;
|
import { compose, withApollo } from 'react-apollo'
import Component from './MediaManager.component'
import query from '../../../apollo/queries/medias'
import OrgQuery from '../../../apollo/queries/organization'
import { withRouter } from 'next/router'
let ExportComponent = Component
ExportComponent = compose(query, OrgQuery)(ExportComponent)
ExportComponent = withRouter(ExportComponent)
export default ExportComponent
|
function millisecondsFrom({ minutes, seconds, milliseconds }) {
let time = minutes;
time *= 60;
time += seconds;
time *= 1000;
time += milliseconds;
return time;
}
export function after({ minutes = 0, seconds = 0, milliseconds = 0 }) {
return new Promise((resolve) => {
window.setTimeout(
resolve,
millisecondsFrom({ minutes, seconds, milliseconds })
);
});
}
export function debouncer({ minutes = 0, seconds = 0, milliseconds = 0 }, cb) {
let time = millisecondsFrom({ minutes, seconds, milliseconds });
let timeoutID = null;
return (...args) => {
window.clearTimeout(timeoutID);
timeoutID = window.setTimeout(() => cb(...args), time);
};
}
|
import React, { useState, useEffect, Fragment, useRef } from "react";
import queryString from "query-string";
import { Redirect } from "react-router-dom";
import {
validateEmail,
validateUsername,
validateFirstName,
validateLastName,
validatePassword,
validatePicture
} from "../../validation/validation";
import useAsyncState from "../../utils/useAsyncState";
import { auth } from "../../utils/auth";
function EmailVerified(props) {
return (
<div className="popup-notif">
{props.emailError ? (
<p>Something went wrong, please retry</p>
) : (
<p>Your email has been verified, you can now log in</p>
)}
</div>
);
}
function EmailToVerify() {
return (
<div className="popup-notif">
<p>You must verifiy your email address to validate your account</p>
</div>
);
}
function PasswordReset() {
return (
<div className="popup-notif">
<p>Your password has been successfully changed</p>
</div>
);
}
const HomePage = props => {
let isMounted = useRef(false);
const [username, setUsername] = useState("");
const [lastName, setLastName] = useState("");
const [firstName, setFirstName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [signInUsername, setSignInUsername] = useState("");
const [signInPassword, setSignInPassword] = useState("");
const [forgotEmail, setForgotEmail] = useState("");
const [forgotPassword, setForgotPassword] = useState("");
const [forgotToken, setForgotToken] = useState("");
const [passwordForgotten, setpasswordForgotten] = useState(0);
const [emailVerified, setEmailVerified] = useState(false);
const [emailToVerify, setEmailToVerify] = useState(false);
const [passwordReset, setPasswordReset] = useState(false);
const [msg, setMsg] = useState("");
const [emailError, setEmailError] = useState("");
const [errors, setErrors] = useAsyncState({});
const [isLoading, setIsLoading] = useState(0);
const [controllerSignal, setControllerSignal] = useState(new AbortController());
const renderRedirect = () => {
if (props.location.pathname.length > 1) {
return <Redirect to="/" />;
}
};
const handleChange = e => {
let reader = new FileReader();
if (e.target.files[0]) {
reader.readAsDataURL(e.target.files[0]);
reader.addEventListener(
"load",
e => {
document.querySelector("#profile-picture").src =
reader.result;
},
false
);
} else {
document.querySelector("#profile-picture").src =
"https://bikeandbrain.files.wordpress.com/2015/05/face.jpg";
}
};
const handleSignUp = async e => {
e.preventDefault();
const data = new FormData(e.target);
let invalid = {};
await setErrors({});
setEmailToVerify(false);
if (!validateUsername(data.get("username"))) invalid.username = true;
if (!validateEmail(data.get("email"))) invalid.email = true;
if (!validateFirstName(data.get("firstName"))) invalid.firstName = true;
if (!validateLastName(data.get("lastName"))) invalid.lastName = true;
if (!validatePassword(data.get("password"))) invalid.password = true;
if (!validatePicture(data.get("userPicture"))) invalid.picture = true;
try {
if (Object.keys(invalid).length === 0) {
setIsLoading(1);
let res = await fetch("http://localhost:8145/auth/signup", {
method: "POST",
body: data,
signal: controllerSignal.signal
});
if (isMounted.current){
res = await res.json();
if (!res.success) {
setErrors({ ...res.errors });
} else {
setEmailToVerify(true);
setFirstName("");
setLastName("");
setUsername("");
setEmail("");
setPassword("");
}
setIsLoading(0);
}
controllerSignal.abort();
setControllerSignal(new AbortController());
} else {
if (isMounted.current){
setErrors({ ...invalid });
}
}
} catch (err) {}
};
useEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false
controllerSignal && controllerSignal.abort();
}
}, [])
const handleSignIn = async e => {
e.preventDefault();
const data = new FormData(e.target);
await setErrors({});
setMsg("");
try {
let res = await fetch("http://localhost:8145/auth/signin", {
method: "POST",
body: data
});
if (isMounted.current){
res = await res.json();
controllerSignal.abort();
setControllerSignal(new AbortController());
if (!res.success) {
setErrors({ login: true });
setMsg(res.msg);
} else {
localStorage.setItem("jwt", res.token);
await auth.authenticate();
props.setRerender(!props.rerender);
}
}
} catch (err) {}
};
// Email Redirection
useEffect(() => {
const controller = new AbortController();
const signal = controller.signal;
(async () => {
const parsed = queryString.parse(props.location.search);
if (
parsed.action &&
parsed.action === "verifyemail" &&
parsed.email &&
parsed.token
) {
try {
let res = await fetch(
"http://localhost:8145/email/emailcheckverification",
{
headers: {
"Content-Type": "application/json"
},
method: "POST",
body: JSON.stringify({
email: parsed.email,
token: parsed.token
}),
signal: signal
}
);
if (isMounted.current){
res = await res.json();
setEmailVerified(true);
setEmailError(res.error);
}
} catch (err) {}
}
})();
return () => {
controller.abort();
};
}, []);
// Sign with Google or 42
useEffect(() => {
(async () => {
const parsed = queryString.parse(props.location.search);
if (parsed.token) {
localStorage.setItem("jwt", parsed.token);
await auth.authenticate();
props.setRerender(!props.rerender);
}
})();
}, []);
const handlePasswordForgotten = e => {
if (e) e.preventDefault();
let button = document.querySelector("#passforgot");
if (passwordForgotten === 1) {
setpasswordForgotten(0);
button.innerHTML = "Password Forgotten";
} else {
setpasswordForgotten(1);
button.innerHTML = "Go back";
}
};
const handlePasswordForgottenMail = async e => {
e.preventDefault();
setErrors({});
setMsg("");
setIsLoading(2);
let res = await fetch("http://localhost:8145/email/passwordforgotten", {
headers: {
"Content-Type": "application/json"
},
method: "POST",
body: JSON.stringify({
email: forgotEmail
})
});
if (isMounted.current){
res = await res.json();
if (!res.error) {
setpasswordForgotten(2);
} else {
setErrors({ ...errors, login: true });
setMsg(res.msg);
}
setIsLoading(0);
}
};
const handlePasswordForgottenVerify = async e => {
e.preventDefault();
setErrors({});
setMsg("");
let res = await fetch("http://localhost:8145/email/setnewpassword", {
headers: {
"Content-Type": "application/json"
},
method: "POST",
body: JSON.stringify({
email: forgotEmail,
password: forgotPassword,
token: forgotToken
})
});
if (isMounted.current){
res = await res.json();
if (!res.error) {
setpasswordForgotten(0);
setPasswordReset(true);
let button = document.querySelector("#passforgot");
button.innerHTML = "Password Forgotten";
} else {
setErrors({ ...errors, login: true });
setMsg(res.msg);
}
}
};
return (
<main className="homepage">
{renderRedirect()}
{emailVerified ? <EmailVerified emailError={emailError} /> : null}
{emailToVerify ? <EmailToVerify /> : null}
{passwordReset ? <PasswordReset /> : null}
<div className="homepage__description">
<ul className="homepage__description--list">
<li>
<i className="fas fa-film" />
<span>Popular movies totally free with no adds !</span>
</li>
<li>
<i className="fas fa-user-secret" />
<span>Torrent based, please use a VPN</span>
</li>
<li>
<i className="fas fa-globe-europe" />
<span>Best quality with subtitles</span>
</li>
</ul>
</div>
<div className="login-wrapper">
<div>
<form
className="homepage__sign-in__form"
id="signinform"
onSubmit={
passwordForgotten === 0
? handleSignIn
: passwordForgotten === 1
? handlePasswordForgottenMail
: handlePasswordForgottenVerify
}
>
<div className="homepage__sign-in__form-content">
{passwordForgotten === 0 ? (
<Fragment>
<div className="input-container">
<input
type="text"
className="input-container__input input-type-1"
placeholder="Username"
id="signin-username"
value={signInUsername}
name="username"
onChange={e =>
setSignInUsername(
e.target.value
)
}
/>
</div>
<div className="input-container">
<input
type="password"
className="input-container__input input-type-1"
placeholder="Password"
id="signin-password"
value={signInPassword}
name="password"
onChange={e =>
setSignInPassword(
e.target.value
)
}
/>
</div>
<input
className="btn btn--primary"
type="submit"
value="Sign In !"
/>
</Fragment>
) : passwordForgotten === 1 ? (
<Fragment>
{isLoading === 2 ? (
<div className="cs-loader">
<div className="cs-loader-inner">
<label>●</label>
<label>●</label>
<label>●</label>
<label>●</label>
<label>●</label>
<label>●</label>
</div>
</div>
) : (
<Fragment>
<div className="input-container">
<input
type="text"
className="input-container__input input-type-1"
placeholder="Email"
id="forgot-email"
value={forgotEmail}
name="email"
onChange={e =>
setForgotEmail(
e.target.value
)
}
/>
</div>
<input
className="btn btn--primary"
type="submit"
value="Send Mail !"
/>
</Fragment>
)}
</Fragment>
) : (
<Fragment>
<div className="input-container">
<input
type="text"
className="input-container__input input-type-1"
placeholder="Token"
id="forgot-token"
value={forgotToken}
name="token"
onChange={e =>
setForgotToken(e.target.value)
}
/>
</div>
<div className="input-container">
<input
type="password"
className="input-container__input input-type-1"
placeholder="Password"
id="forgot-password"
value={forgotPassword}
name="password"
onChange={e =>
setForgotPassword(
e.target.value
)
}
/>
</div>
<input
className="btn btn--primary"
type="submit"
value="Sign In !"
/>
</Fragment>
)}
</div>
{errors.login ? (
<div className="input-container__display-error">
{msg}
</div>
) : null}
<div className="input-container__passforgot">
<button
className="btn btn--secondary"
id="passforgot"
onClick={handlePasswordForgotten}
>
Password forgotten
</button>
</div>
</form>
</div>
<div>
{isLoading === 1 ? (
<div className="cs-loader">
<div className="cs-loader-inner">
<label>●</label>
<label>●</label>
<label>●</label>
<label>●</label>
<label>●</label>
<label>●</label>
</div>
</div>
) : (
<form
className="homepage__sign-up__form"
id="signupform"
onSubmit={handleSignUp}
>
<div className="img-upload">
<label
htmlFor="file-input"
className="img-label"
>
<img
id="profile-picture"
alt="profile"
src="https://bikeandbrain.files.wordpress.com/2015/05/face.jpg"
/>
</label>
<input
accept="image/*"
id="file-input"
type="file"
onChange={handleChange}
name="userPicture"
/>
</div>
{errors.picture ? (
<div className="input-container__display-error">
You must pick a profile picture
</div>
) : null}
<div className="input-container">
<i className="fas fa-id-card input-container__icon" />
<input
type="text"
className="input-container__input input-type-1"
placeholder="First Name"
value={firstName}
name="firstName"
onChange={e => setFirstName(e.target.value)}
/>
</div>
{errors.firstName ? (
<div className="input-container__display-error">
Wrong first name
</div>
) : null}
<div className="input-container">
<i className="far fa-id-card input-container__icon" />
<input
type="text"
className="input-container__input input-type-1"
placeholder="Last Name"
value={lastName}
name="lastName"
onChange={e => setLastName(e.target.value)}
/>
</div>
{errors.lastName ? (
<div className="input-container__display-error">
Wrong last name
</div>
) : null}
<div className="input-container">
<i className="fas fa-at input-container__icon" />
<input
type="text"
className="input-container__input input-type-1"
placeholder="Email"
value={email}
name="email"
onChange={e => setEmail(e.target.value)}
/>
</div>
{errors.email ? (
<div className="input-container__display-error">
Wrong email
</div>
) : null}
{errors.duplicateEmail ? (
<div className="input-container__display-error">
Email is already used
</div>
) : null}
<div className="input-container">
<i className="fas fa-user input-container__icon" />
<input
type="text"
className="input-container__input input-type-1"
placeholder="Username"
id="signup-username"
value={username}
name="username"
onChange={e => setUsername(e.target.value)}
/>
</div>
{errors.username ? (
<div className="input-container__display-error">
Wrong username
</div>
) : null}
{errors.duplicateUsername ? (
<div className="input-container__display-error">
Username is already used
</div>
) : null}
<div className="input-container">
<i className="fas fa-unlock input-container__icon" />
<input
type="password"
className="input-container__input input-type-1"
placeholder="Password"
id="signup-password"
value={password}
name="password"
onChange={e => setPassword(e.target.value)}
/>
</div>
{errors.password ? (
<div className="input-container__display-error">
Wrong password
</div>
) : null}
<input
className="btn btn--primary"
type="submit"
value="Sign Up !"
/>
</form>
)}
<div className="signup-OAuth">
<a
className="google btn btn--primary"
href="http://localhost:8145/auth/google"
>
{" "}
</a>
<a
className="logo42 btn btn--primary"
href="http://localhost:8145/auth/the42"
>
{" "}
</a>
<a
className="github btn btn--primary"
href="http://localhost:8145/auth/github"
>
{" "}
</a>
<a
className="facebook btn btn--primary"
href="http://localhost:8145/auth/facebook"
>
{" "}
</a>
</div>
</div>
</div>
</main>
);
};
export default HomePage;
|
function nodeReducer(state = [], action) {
switch (action.type) {
case 'ADD_NODE':
let name = action.node.name,
node = state.find(node => node.name === name);
if (typeof node !== 'undefined')
throw `Node with given name '${name}' already exists`;
return [...state, action.node];
case 'REMOVE_NODE':
return state.filter(node => node.name !== action.name);
case 'ACTIVATE_NODE':
case 'DEACTIVATE_NODE':
let nodes = [...state];
for (let i=0, len=nodes.length; i<len; i++) {
if (nodes[i].name === action.name) {
nodes[i] = Object.assign({}, nodes[i], {
active: action.type === 'ACTIVATE_NODE'
});
return nodes;
}
}
return state;
default:
return state;
}
return state;
}
export default nodeReducer;
|
import React from "react";
import _ from "lodash";
import { TwitterTweetEmbed } from "react-twitter-embed";
import tweets from "../utils/pokemon/tweets.js";
import tweetId from "../utils/pokemon/tweetId.js";
export function Card(props) {
const card = {
maxWidth: "500px",
minWidth: "220px",
borderRadius: "5px",
font: '1em/1.4 Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif',
backgroundColor: "#fff",
margin: "2% auto",
boxShadow:
"0 2px 2px 0 rgba(0,0,0,.14), 0 3px 1px -2px rgba(0, 0, 0, .2), 0 1px 5px 0 rgba(0,0,0,.12)"
};
const cardHeader = {
backgroundColor: "rgb(41,73,130)",
borderRadius: "5px 5px 0px 0px",
padding: "5px",
color: "#fff",
fontSize: "1.4rem",
textAlign: "center",
verticalAlign: "middle"
};
const cardBody = {
padding: "10px",
fontSize: ".9rem",
color: "#757575",
textAlign: "left"
};
const pokemonName = _.lowerCase(props.speciesName);
const tweetContent = tweets[props.tweetNum];
const spriteName = _.kebabCase(
_.replace(_.replace(pokemonName, "♀", "-f"), "♂", "-m"),
"mr mime"
);
const tweetEmbed = _.isUndefined(tweetContent) ? null : (
<TwitterTweetEmbed tweetId={tweetId[props.tweetNum]} />
);
return (
<div style={card}>
<div style={cardHeader}>
<strong>{"#" + props.speciesNum}</strong> {props.speciesName}
<img
alt={props.speciesName}
src={`https://img.pokemondb.net/sprites/sun-moon/icon/${spriteName}.png`}
/>
</div>
<div style={cardBody}>{tweetContent}</div>
{tweetEmbed}
</div>
);
}
|
;(function ($) {
$(function () {
});
$('a').click(function(){
$('html, body').animate({
scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
}, 1000);
return false;
});
$('.parallax-window').parallax({imageSrc: 'images/kyiv.jpg'});
$('.parallax-window-second').parallax({imageSrc: 'images/odessa.jpg'});
})(jQuery);
|
/*
* @Author: AlexiXiang
* @Date: 2018-12-04 10:21:22
* @LastEditors: AlexiXiang
* @LastEditTime: 2018-12-04 10:23:19
* @Description: 云函数调用的封装
*/
const app = getApp()
function cloudApi(fnName, data = {}, config = {}) {
return wx.cloud.callFunction({
name: fnName,
data: {
env: app.globalData.env,
...data
},
config: config
})
}
export { cloudApi }
|
console.log('main');
const divValores = document.querySelector('div.valores');
const divMedia = document.querySelector('div.media');
const divMenor = document.querySelector('div.menor');
const divMaior = document.querySelector('div.maior');
const divAmplitude = document.querySelector('div.amplitude');
const divMediana = document.querySelector('div.mediana');
const divBarras = document.querySelector('div.barras');
const divQuartio1 = document.querySelector('div.quartio1');
const divQuartio3 = document.querySelector('div.quartio3');
const divLabels = document.querySelector('div.labels');
const divDesvio = document.querySelector('div.desvio');
const divMaximo = document.querySelector('div.maximo');
const divMinimo = document.querySelector('div.minimo');
const divIntervaloCima = document.querySelector('div.intervalocima');
const divIntervaloBaixo = document.querySelector('div.intervalobaixo');
const divBoxCima = document.querySelector('div.boxcima');
const divBoxBaixo = document.querySelector('div.boxbaixo');
const Valores = {
valores: [],
classes: [],
get mediana() {
return mediana(this.valores);
},
get primeiroQuartio() {
return quartio(1, this.valores);
},
get terceiroQuartio() {
return quartio(3, this.valores);
},
get amplitude() {
return this.maior - this.menor;
},
get maior() {
return this.valores[this.valores.length - 1];
},
get menor() {
return min(this.valores);
},
get desvioPadrao() {
let somatorio = 0;
for (nota of this.valores) {
somatorio += Math.pow((nota - this.media), 2);
}
return Math.sqrt(somatorio/this.valores.length);
},
get media() {
let soma = 0;
for (let nota of this.valores) soma += nota;
return soma / this.valores.length;
},
atualizaView: function () {
remover(divValores.querySelectorAll('p'));
for (let nota of this.valores) {
let p = document.createElement('p');
p.innerText = nota;
divValores.appendChild(p);
}
let labels = divLabels.querySelectorAll('label');
divLabels.style.width = divBarras.style.width;
let width = (100/this.classes.length) - 10 + '%';
for (label of labels){
label.style.width = width;
}
for (classe of this.classes) {
classe.div.style.width = width;
}
divMedia.textContent = this.media;
divMenor.textContent = this.menor;
divMaior.textContent = this.maior;
divAmplitude.textContent = this.amplitude;
divMediana.textContent = this.mediana;
divQuartio1.textContent = this.primeiroQuartio;
divQuartio3.textContent = this.terceiroQuartio;
divDesvio.textContent = this.desvioPadrao;
let escala = 0;
for (let c of this.classes) {
c.zerar();
for (let n of this.valores) c.conta(n);
if (c.contagem > escala) escala = c.contagem;
}
for (let c of this.classes) c.desenha(escala);
divMinimo.style.height = ((this.menor / this.maior) * 100) + '%';
divIntervaloBaixo.style.height = (((this.primeiroQuartio - this.menor) / this.maior) * 100) + '%';
divBoxBaixo.style.height = (((this.mediana - this.primeiroQuartio) / this.maior) * 100) + '%';
divBoxCima.style.height = (((this.terceiroQuartio - this.mediana) / this.maior) * 100) + '%';
divIntervaloCima.style.height = (((this.maior - this.terceiroQuartio) / this.maior) * 100) + '%';
document.querySelector('#maximo').innerText = this.maior;
document.querySelector('#minimo').innerText = this.menor;
document.querySelector('#mediana').innerText = this.mediana;
document.querySelector('#quartil1').innerText = this.primeiroQuartio;
document.querySelector('#quartil3').innerText = this.terceiroQuartio;
},
adiciona: function (nota) {
let n = parseFloat(nota);
if (!isNaN(n)) {
this.valores.push(n);
this.valores.sort(function (a, b) {
return a - b
});
this.atualizaView();
}
},
adicionaClasse: function (nome, de, ate) {
ate = parseFloat(ate);
deFloat = parseFloat(de);
if (isNaN(deFloat)) {
de = encontraClasse(de);
}
let classe = new Classe(nome, de, ate);
this.classes.push(classe);
}
};
const formValores = document.querySelector('form.formvalores');
const formClasses = document.querySelector('form.formclasses');
formValores.addEventListener('submit', function (evento) {
Valores.adiciona(this.valor.value);
this.valor.value = '';
evento.preventDefault();
});
formClasses.addEventListener('submit', function (evento) {
let de = this.de.value;
let ate = this.ate.value;
let nome = this.nome.value;
if(nome && ate) {
Valores.adicionaClasse(nome, de, ate);
}
Valores.atualizaView();
this.de.value = '';
this.ate.value = '';
this.nome.value = '';
evento.preventDefault();
});
function encontraClasse(nome) {
for (classe of Valores.classes) {
if (classe.nome = nome) return classe;
}
return 0;
}
function min(vetor) {
var m = vetor[0];
for (let i = 1; i < vetor.length; i++) {
if (vetor[i] < m) m = vetor[i];
}
return m;
}
function quartio(j, dados) {
if (!dados) return undefined;
if (dados.length < 4) return undefined;
if (!j in [1, 2, 3]) return undefined;
let n = dados.length;
let k = parseInt(j*(n + 1)/4);
return dados[k - 1] + (((j*(n + 1)/4) - k)*(dados[k] - dados[k - 1]));
}
function mediana(vetor) {
if (vetor.length === 1) return vetor[0];
if (vetor.length === 3) return vetor[2];
if (vetor.length === 2) return (vetor[0] + vetor[1]) / 2;
return quartio(2, vetor);
}
function Classe(nome, de, ate) {
this.nome = nome;
this.de = de;
this.ate = ate;
this.contagem = 0;
var label = document.createElement('label');
this.label = label;
label.textContent = this.nome;
divLabels.appendChild(label);
this.div = document.createElement('div');
this.div.classList.add('barra');
this.div.textContent = '0';
divBarras.appendChild(this.div);
this.desenha = function (escala) {
let tamanho = this.contagem / escala * 100;
this.div.style.height = tamanho + '%';
this.div.textContent = this.contagem;
}
this.zerar = function () {
this.contagem = 0;
}
this.conta = function(n) {
if (this.verifica(n)) this.contagem++;
}
this.verifica = function(n) {
if (this.de instanceof Classe) {
return n > this.de.ate && n <= this.ate;
}
return n >= this.de && n <= this.ate;
}
}
function remover (elementos){
if (!elementos) return undefined;
for (let i = 0; i < elementos.length; i++) {
let elemento = elementos[i];
elementos[i] = -1;
elemento.remove();
}
}
|
import CONFIG from "web.config";
import MasterPage from "components/website/master/MasterPage";
import { useRouter } from "next/router";
import Header from "components/website/elements/Header";
import { BS } from "components/diginext/elements/Splitters";
import BannerAboutUs from "components/website/pages/about-us/section-banner/Banner";
import SeriseInJapan from "components/website/pages/about-us/section-serise-in-japan/SeriseInJapan";
import SectionCareer from "components/website/pages/about-us/section-career/Career";
import Footer from "components/website/elements/Footer";
import asset from "plugins/assets/asset";
import { useEffect, useRef, useState, useContext } from "react";
import useWindowSize from "components/website/hooks/useWindowsSize";
export async function getServerSideProps(context) {
// const params = context.params;
// const query = context.query;
// context.req.session ,
// context.res
// console.log(context.query);
console.log("SERVER CODE");
// var json = { data: [1, 2, 3, 4, 5] };
return {
props: {
// params
},
};
}
export default function AboutUs(props) {
const router = useRouter();
if (typeof window == "undefined") {
console.log("This code is on server-side");
}
const bgSectionInJapan = {
desktop: asset("/images/bg-none-890.jpg"),
mobile: asset("/images/bg-none-about-us-m2.jpg"),
}
// detect screen size
const windowSize = useWindowSize();
const [responsiveMaxScreen, setResponsiveMaxScreen] = useState(false);
const [responsiveMobile, setResponsiveMobile] = useState(false);
const [responsiveTablet, setResponsiveTablet] = useState(false);
//check responsive
useEffect(() => {
if (windowSize.width <= 1024) {
setResponsiveTablet(true);
if (windowSize.width <= 520) {
setResponsiveTablet(false);
setResponsiveMobile(true);
}
} else {
setResponsiveTablet(false);
setResponsiveMobile(false);
}
}, [windowSize]);
return (
<MasterPage pageName={"About us"}>
<Header hideButtons></Header>
<main id="aboutUsPage" style={{' background': '#F3F3F3'}}>
{
responsiveMobile === true
? (<>
<BannerAboutUs></BannerAboutUs>
<SeriseInJapan urlBackground={bgSectionInJapan.mobile}></SeriseInJapan>
<SectionCareer></SectionCareer>
</>)
:(<>
<BannerAboutUs></BannerAboutUs>
<SeriseInJapan urlBackground={bgSectionInJapan.desktop}></SeriseInJapan>
<SectionCareer></SectionCareer>
</>)
}
</main>
<Footer></Footer>
</MasterPage>
);
}
|
app.factory('JobService',function($http){
var jobService={}
jobService.createJob=function(job)
{
console.log("job service")
return $http.post("http://localhost:8010/Project2Backend/savejob",job)
}
jobService.getAllJobs=function(){
return $http.get("http://localhost:8010/Project2Backend/getalljobs")
}
jobService.getJobById=function(id){
console.log(id)
return $http.get("http://localhost:8010/Project2Backend/getjobbyid/"+id)
}
return jobService;
})
|
import CharactersService from "../services/characters.service";
import router from "../router";
const state = {
characters: {},
};
const getters = {
fetchCharacters: (state) => {
return state.characters
},
};
const actions = {
async fetchCharacters( {commit} ) {
try {
const characters = await CharactersService.fetchCharacters()
commit('fetchCharactersSuccess', characters)
} catch (e) {
commit('fetchCharactersFailure', {error: e})
return false
}
},
async createCharacter({commit}, {noFilm, noAct, nomPers}) {
try {
await CharactersService.createCharacter(noFilm, noAct, nomPers)
commit('createCharacterSuccess')
return await router.go(0)
} catch (e) {
commit('createCharacterFailure', {error: e})
return false
}
},
async getMovieCharacters( {commit}, noFilm) {
try {
const character = await CharactersService.getMovieCharacters(noFilm)
commit('getMovieCharactersSuccess', character.data)
} catch (e) {
commit('getMovieCharactersFailure', {error: e})
return false
}
},
async getActorCharacters( {commit}, noAct) {
try {
const character = await CharactersService.getActorCharacters(noAct)
commit('getActorCharactersSuccess', character)
} catch (e) {
commit('getActorCharactersFailure', {error: e})
return false
}
},
async getACharacter({commit}, {noFilm, noAct}) {
try {
const character = await CharactersService.getACharacter(noFilm, noAct)
commit('getACharacterSuccess', character)
} catch(e) {
commit('getACharacterFailure', {error: e})
return false
}
},
async editCharacter({commit}, {character, noFilm, noAct, nomPers}) {
try {
await CharactersService.editCharacter(noFilm, noAct, nomPers)
commit('editCharacterSuccess', character)
return await router.go(0)
} catch(e) {
commit('editCharacterFailure', {error: e})
return false
}
},
async deleteCharacter({commit}, {noFilm, noAct}) {
try {
await CharactersService.deleteCharacter(noFilm, noAct)
commit('deleteCharacterSuccess', noFilm, noAct)
return await router.go(0)
} catch (e) {
if (e.message === 'Request failed with status code 500') {
commit('deleteCharacterFailure', {error: "Vous ne pouvez pas supprimer ce personnage car il fait partie d'au moins un film"})
return false
} else {
commit('deleteCharacterFailure', {error: e.message})
return false
}
}
},
};
const mutations = {
fetchCharactersSuccess(state, characters) {
state.characters = { items: characters };
},
fetchCharactersFailure(state, error) {
state.characters = error
},
getMovieCharactersSuccess(state, character) {
state.characters.charactersSelected = {character}
},
getMovieCharactersFailure(state, error) {
state.characters.charactersSelected = error
},
getActorCharactersSuccess(state, character) {
state.characters.charactersSelected = {character}
},
getActorCharactersFailure(state, error) {
state.characters.charactersSelected = error
},
createCharacterSuccess(state) {
state.characters = {items: characters}
},
createCharacterFailure(state, error) {
state.characters = error
},
getACharacterSuccess(state, character) {
state.characters.charactersSelected = {character}
},
getACharacterFailure(state, error) {
state.characters.charactersSelected = error
},
editCharacterSuccess(state, character) {
Object.keys(state.characters.items).forEach(c => {
if(c.noFilm === character.noFilm && c.noAct === character.noAct) {
c = character
}
});
},
editCharacterFailure(state, error) {
state.characters = error
},
deleteCharacterSuccess(state, noFilm, noAct) {
state.characters.items = Object.keys(state.characters.items).filter(character => character.noFilm !== noFilm && character.noAct !== noAct)
},
deleteCharacterFailure(state, error) {
state.characters = error
},
};
export const characters = {
namespaced: true,
state,
getters,
actions,
mutations,
}
|
/**
* @module :: Routes
* @description :: Maps routes and actions
*/
var User = require('../models/user.js');
var Comment = require('../models/comment.js');
var Track = require('../models/track.js');
var Rating = require('../models/rating.js');
var Mix = require('../models/mix.js');
module.exports = function(app) {
/****************************************************************************************************************************/
/*********************************************** HANDLE USERS ********************************************************/
/****************************************************************************************************************************/
/**
* Find and retrieves all Users
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
findAllUsers = function(req, res) {
console.log("GET - /users");
return User.find(function(err, users) {
if(!err) {
return res.json(users);
} else {
res.statusCode = 500;
console.log('Internal error(%d): %s',res.statusCode,err.message);
return res.send({ error: 'Server error' });
}
});
};
/**
* Find and retrieves a single user by its ID
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
findById = function(req, res) {
console.log("GET - /users/:id");
return User.findById(req.params.id, function(err, user) {
if(!user) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
if(!err) {
return res.send({ status: 'OK', user:user });
} else {
res.statusCode = 500;
console.log('Internal error(%d): %s', res.statusCode, err.message);
return res.send({ error: 'Server error' });
}
});
};
/**
* Find and retrieves a single user by its username and password
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
findByUsernameAndPassword = function(req, res) {
console.log("GET - /users/:username/:passwd");
return User.find({username: req.params.username,passwd: req.params.passwd}, function(err, user) {
if(err) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
if(!err) {
return res.send({ status: 'OK', user:user });
} else {
res.statusCode = 500;
console.log('Internal error(%d): %s', res.statusCode, err.message);
return res.send({ error: 'Server error' });
}
});
};
/**
* Creates a new user from the data request
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
addUser = function(req, res) {
console.log('POST - /users');
var user = new User({
username: req.body.username,
fullname: req.body.fullname,
mail: req.body.mail,
passwd: req.body.passwd,
role: req.body.role
});
user.save(function(err) {
if(err) {
console.log('Error while saving User: ' + err);
res.send({ error:err });
return;
} else {
console.log("User created");
return res.send({ status: 'OK', user:user });
}
});
};
/**
* Update a user by its ID
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
updateUser = function(req, res) {
console.log("PUT - /users/:id");
return User.findById(req.params.id, function(err, user) {
if(!user) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
if (req.body.username != null) user.username= req.body.username;
if (req.body.fullname!= null) user.fullname= req.body.fullname;
if (req.body.mail!= null) user.mail = req.body.mail;
if (req.body.passwd != null) user.passwd = req.body.passwd;
if (req.body.role != null) user.passwd = req.body.role;
return user.save(function(err) {
if(!err) {
console.log('Updated');
return res.send({ status: 'OK', user:user });
} else {
if(err.name == 'ValidationError') {
res.statusCode = 400;
res.send({ error: 'Validation error' });
} else {
res.statusCode = 500;
res.send({ error: 'Server error' });
}
console.log('Internal error(%d): %s',res.statusCode,err.message);
}
res.send(user);
});
});
};
/**
* Delete a user by its ID
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
deleteUser = function(req, res) {
console.log("DELETE - /users/:id");
return User.findById(req.params.id, function(err, user) {
if(!user) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
return user.remove(function(err) {
if(!err) {
console.log('Removed user');
return res.send({ status: 'OK' });
} else {
res.statusCode = 500;
console.log('Internal error(%d): %s',res.statusCode,err.message);
return res.send({ error: 'Server error' });
}
})
});
}
/****************************************************************************************************************************/
/*********************************************** HANDLE COMMENTS *****************************************************/
/****************************************************************************************************************************/
/**
* Find and retrieves all Comments
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
findAllComments = function(req, res) {
console.log("GET - /comments");
return Comment.find(function(err, comments) {
if(!err) {
return res.send(comments);
} else {
res.statusCode = 500;
console.log('Internal error(%d): %s',res.statusCode,err.message);
return res.send({ error: 'Server error' });
}
});
};
/**
* Find and retrieves a single comment by its ID
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
findCommentById = function(req, res) {
console.log("GET - /comments/:id");
return Comment.findById(req.params.id, function(err, comment) {
if(!comment) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
if(!err) {
return res.send({ status: 'OK', comment:comment });
} else {
res.statusCode = 500;
console.log('Internal error(%d): %s', res.statusCode, err.message);
return res.send({ error: 'Server error' });
}
});
};
/**
* Creates a new comment from the data request
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
addComment = function(req, res) {
console.log('POST - /comments');
var comment = new Comment({
username: req.body.username,
trackName: req.body.trackName,
content: req.body.content,
mixName: req.body.mixName
});
comment.save(function(err) {
if(err) {
console.log('Error while saving Comment: ' + err);
res.send({ error:err });
return;
} else {
console.log("Comment created");
return res.send({ status: 'OK', comment:comment });
}
});
};
/**
* Update a comment by its ID
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
updateComment = function(req, res) {
console.log("PUT - /comments/:id");
return Comment.findById(req.params.id, function(err, comment) {
if(!comment) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
if (req.body.username != null) user.username= req.body.username;
if (req.body.trackName!= null) user.trackName= req.body.trackName;
if (req.body.comment!= null) user.comment= req.body.comment;
if (req.body.mixName!= null) user.mixName= req.body.mixName;
return comment.save(function(err) {
if(!err) {
console.log('Updated');
return res.send({ status: 'OK', comment:comment });
} else {
if(err.name == 'ValidationError') {
res.statusCode = 400;
res.send({ error: 'Validation error' });
} else {
res.statusCode = 500;
res.send({ error: 'Server error' });
}
console.log('Internal error(%d): %s',res.statusCode,err.message);
}
res.send(comment);
});
});
};
/**
* Delete a comment by its ID
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
deleteComment = function(req, res) {
console.log("DELETE - /comments/:id");
return Comment.findById(req.params.id, function(err, comment) {
if(!comment) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
return comment.remove(function(err) {
if(!err) {
console.log('Removed comment');
return res.send({ status: 'OK' });
} else {
res.statusCode = 500;
console.log('Internal error(%d): %s',res.statusCode,err.message);
return res.send({ error: 'Server error' });
}
})
});
}
/****************************************************************************************************************************/
/*********************************************** HANDLE RATINGS ********************************************************/
/****************************************************************************************************************************/
/**
* Find and retrieves all ratings
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
findAllRatings = function(req, res) {
console.log("GET - /ratings");
return Rating.find(function(err, ratings) {
if(!err) {
return res.send(ratings);
} else {
res.statusCode = 500;
console.log('Internal error(%d): %s',res.statusCode,err.message);
return res.send({ error: 'Server error' });
}
});
};
/**
* Creates a new rating from the data request
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
addRating = function(req, res) {
console.log('POST - /ratings');
var rating = new Rating({
username: req.body.username,
mixName: req.body.mixName,
trackName: req.body.trackName,
mark: req.body.mark
});
rating.save(function(err) {
if(err) {
console.log('Error while saving Rating: ' + err);
res.send({ error:err });
return;
} else {
console.log("Rating created");
return res.send({ status: 'OK', rating:rating });
}
});
};
/**
* Find and retrieves a single rating by its ID
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
findRatingById = function(req, res) {
console.log("GET - /ratings/:id");
return Rating.findById(req.params.id, function(err, rating) {
if(!rating) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
if(!err) {
return res.send({ status: 'OK', rating:rating });
} else {
res.statusCode = 500;
console.log('Internal error(%d): %s', res.statusCode, err.message);
return res.send({ error: 'Server error' });
}
});
};
/**
* Update a rating by its ID
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
updateRating = function(req, res) {
console.log("PUT - /ratings/:id");
return Rating.findById(req.params.id, function(err, rating) {
if(!rating) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
if (req.body.username != null) user.username= req.body.username;
if (req.body.mixName != null) user.mixName= req.body.mixName;
if (req.body.trackName != null) user.trackName= req.body.trackName;
if (req.body.mark != null) user.mark=rq.body.mark;
return rating.save(function(err) {
if(!err) {
console.log('Updated');
return res.send({ status: 'OK', rating:rating });
} else {
if(err.name == 'ValidationError') {
res.statusCode = 400;
res.send({ error: 'Validation error' });
} else {
res.statusCode = 500;
res.send({ error: 'Server error' });
}
console.log('Internal error(%d): %s',res.statusCode,err.message);
}
res.send(rating);
});
});
};
/**
* Delete a rating by its ID
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
deleteRating = function(req, res) {
console.log("DELETE - /ratings/:id");
return Rating.findById(req.params.id, function(err, rating) {
if(!rating) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
return rating.remove(function(err) {
if(!err) {
console.log('Removed rating');
return res.send({ status: 'OK' });
} else {
res.statusCode = 500;
console.log('Internal error(%d): %s',res.statusCode,err.message);
return res.send({ error: 'Server error' });
}
})
});
}
/****************************************************************************************************************************/
/*********************************************** HANDLE TRACKS **********************************************************/
/****************************************************************************************************************************/
/**
* Find and retrieves all Tracks
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
findAllTracks = function(req, res) {
console.log("GET - /tracks");
return Track.find(function(err, tracks) {
if(!err) {
return res.send(tracks);
} else {
res.statusCode = 500;
console.log('Internal error(%d): %s',res.statusCode,err.message);
return res.send({ error: 'Server error' });
}
});
};
/**
* Find and retrieves a single track by its ID
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
findTrackById = function(req, res) {
console.log("GET - /tracks/:id");
return Track.findById(req.params.id, function(err, track) {
if(!track) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
if(!err) {
return res.send({ status: 'OK', track:track});
} else {
res.statusCode = 500;
console.log('Internal error(%d): %s', res.statusCode, err.message);
return res.send({ error: 'Server error' });
}
});
};
/**
* Creates a new track from the data request
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
addTrack = function(req, res) {
console.log('POST - /tracks');
var track = new Track({
trackName: req.body.trackName,
piste: req.body.piste,
singer: req.body.singer,
album: req.body.album,
type: req.body.type,
description: req.body.description,
dateOfTrack: req.body.dateOfTrack
});
track.save(function(err) {
if(err) {
console.log('Error while saving Track: ' + err);
res.send({ error:err });
return;
} else {
console.log("Track created");
return res.send({ status: 'OK', track:track });
}
});
};
/**
* Update a track by its ID
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
updateTrack = function(req, res) {
console.log("PUT - /tracks/:id");
return Track.findById(req.params.id, function(err, track) {
if(!track) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
if (req.body.trackName != null) track.trackName= req.body.trackName;
if (req.body.piste != null) track.pisteGuitar= req.body.piste;
if (req.body.singer != null) track.singer = req.body.singer;
if (req.body.album != null) track.album = req.body.album;
if (req.body.type != null) track.type= req.body.type;
if (req.body.description != null) track.description = req.body.description;
if (req.body.dateOfTrack != null) track.dateOfTrack = req.body.dateOfTrack;
return track.save(function(err) {
if(!err) {
console.log('Updated');
return res.send({ status: 'OK', track:track });
} else {
if(err.name == 'ValidationError') {
res.statusCode = 400;
res.send({ error: 'Validation error' });
} else {
res.statusCode = 500;
res.send({ error: 'Server error' });
}
console.log('Internal error(%d): %s',res.statusCode,err.message);
}
res.send(track);
});
});
};
/**
* Delete a track by its ID
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
deleteTrack = function(req, res) {
console.log("DELETE - /tracks/:id");
return Track.findById(req.params.id, function(err, track) {
if(!track) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
return track.remove(function(err) {
if(!err) {
console.log('Removed track');
return res.send({ status: 'OK' });
} else {
res.statusCode = 500;
console.log('Internal error(%d): %s',res.statusCode,err.message);
return res.send({ error: 'Server error' });
}
})
});
}
/**************************************************************************************************************************/
/*********************************************** HANDLE MIX ********************************************************/
/**************************************************************************************************************************/
/**
* Find and retrieves all mixs
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
findAllMixs = function(req, res) {
console.log("GET - /mixs");
return Mix.find(function(err, mixs) {
if(!err) {
return res.send(mixs);
} else {
res.statusCode = 500;
console.log('Internal error(%d): %s',res.statusCode,err.message);
return res.send({ error: 'Server error' });
}
});
};
/**
* Find and retrieves a single mix by its ID
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
findMixById = function(req, res) {
console.log("GET - /mixs/:id");
return Mix.findById(req.params.id, function(err, mix) {
if(!mix) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
if(!err) {
return res.send({ status: 'OK', mix:mix });
} else {
res.statusCode = 500;
console.log('Internal error(%d): %s', res.statusCode, err.message);
return res.send({ error: 'Server error' });
}
});
};
/**
* Creates a new mix from the data request
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
addMix = function(req, res) {
console.log('POST - /mixs');
var mix = new Mix({
username: req.body.username,
mixName: req.body.mixName,
trackName: req.body.trackName,
description: req.body.description,
frequencies: req.body.frequencies,
gain: req.body.gain,
balance: req.body.balance,
compressor: req.body.compressor,
impulses: req.body.impulses
});
mix.save(function(err) {
if(err) {
console.log('Error while saving mix: ' + err);
res.send({ error:err });
return;
} else {
console.log("Mix created");
return res.send({ status: 'OK', mix:mix });
}
});
};
/**
* Update a mix by its ID
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
updateMix = function(req, res) {
console.log("PUT - /mixs/:id");
return Mix.findById(req.params.id, function(err, mix) {
if(!mix) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
if (req.body.username != null) mix.username= req.body.username;
if (req.body.mixName!= null) mix.mixName= req.body.mixName;
if (req.body.trackName!= null) mix.mixName= req.body.trackName;
if (req.body.description!= null) mix.description= req.body.description;
if (req.body.frequencies!= null) mix.frequencies = req.body.frequencies;
if (req.body.gain!= null) mix.gain= req.body.gain;
if (req.body.balance!= null) mix.balance= req.body.balance;
if (req.body.compressor!= null) mix.compressor= req.body.compressor;
if (req.body.impulses!= null) mix.impulses= req.body.impulses;
return mix.save(function(err) {
if(!err) {
console.log('Updated');
return res.send({ status: 'OK', mix:mix });
} else {
if(err.name == 'ValidationError') {
res.statusCode = 400;
res.send({ error: 'Validation error' });
} else {
res.statusCode = 500;
res.send({ error: 'Server error' });
}
console.log('Internal error(%d): %s',res.statusCode,err.message);
}
res.send(mix);
});
});
};
/**
* Delete a mix by its ID
* @param {Object} req HTTP request object.
* @param {Object} res HTTP response object.
*/
deleteMix = function(req, res) {
console.log("DELETE - /mixs/:id");
return Mix.findById(req.params.id, function(err, mix) {
if(!mix) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
return mix.remove(function(err) {
if(!err) {
console.log('Removed mix');
return res.send({ status: 'OK' });
} else {
res.statusCode = 500;
console.log('Internal error(%d): %s',res.statusCode,err.message);
return res.send({ error: 'Server error' });
}
})
});
}
/****************************************************************************************************************************/
/****************************************************************************************************************************/
/****************************************************************************************************************************/
/*********************************************** LINK ROUTES AND ACTIONS **********************************************/
/****************************************************************************************************************************/
/****************************************************************************************************************************/
/****************************************************************************************************************************/
app.get('/users', findAllUsers);
app.get('/users/:id', findById);
app.get('/users/:username/:passwd', findByUsernameAndPassword);
app.post('/users', addUser);//{ "username" : "mongoUser", "fullname" : "UserFullName", "mail" : "mg@gmail.com", "passwd" : "1234", "role":"admin"}
app.put('/users/:id', updateUser);
app.delete('/users/:id', deleteUser);
app.get('/comments', findAllComments);
app.get('/comments/:id', findCommentById);
app.post('/comments', addComment);//{ "username" : "mongoUser", "trackName" : "Michael jackson - Beat It","content" : "That's a good mix !" ,"mixName" : "michael jackson beat it mix 1"}
app.put('/comments/:id', updateComment);
app.delete('/comments/:id', deleteComment);
app.get('/ratings', findAllRatings);
app.get('/ratings/:id', findRatingById);
app.post('/ratings', addRating);//{ "username" : "mongoUser", "mixName" : "michael jackson beat it mix 1","trackName":"Michael jackson - Beat It", "mark" : "3.5" }
app.put('/ratings/:id', updateRating);
app.delete('/ratings/:id', deleteRating);
app.get('/tracks', findAllTracks);
app.get('/tracks/:id', findTrackById);
app.post('/tracks', addTrack);//{"trackName":"Michael jackson - Beat It","piste":[{"pisteMp3":"basse.mp3"},{"pisteMp3":"batterie.mp3"},{"pisteMp3":"guitare.mp3"},{"pisteMp3":"synthes.mp3"},{"pisteMp3":"voix.mp3"}],"singer":"Micheal Jackson","album":"Beat It","type":"Pop","description":"Song of Micheal Jackson","dateOfTrack":"1992-10-21T13:28:06.419Z"}
app.put('/tracks/:id', updateTrack);
app.delete('/tracks/:id', deleteTrack);
app.get('/mixs', findAllMixs);
app.get('/mixs/:id', findMixById);
app.post('/mixs', addMix);//{"username": "John", "mixName": "MixPop1", "trackName": "MixPop1", "description": "Mix Pop number 1", "frequencies":[{"frequence":"[10,15,12,10,15]"},{"frequence":"[105,152,122,10,15]"}],"gain":[{"gain":"150"},{"gain":"175"},{"gain":"102"}],"balance":[{"balance":"150"},{"balance":"175"},{"balance":"102"}],"compressor":"150","impulses":[{"impulse":"150"},{"impulse":"175"},{"impulse":"102"}]}
app.put('/mixs/:id', updateMix);
app.delete('/mixs/:id', deleteMix);
}
|
//check if the dom content already loaded or not
document.addEventListener('DOMContentLoaded', () => {
const cardArray = [
{
id: 1,
name: 'css',
img: 'src/img/css.png'
},
{
id: 2,
name: 'graphql',
img: 'src/img/graphql.png'
},
{
id: 3,
name: 'html',
img: 'src/img/html.png'
},
{
id: 4,
name: 'java',
img: 'src/img/java.png'
},
{
id: 5,
name: 'reactjs',
img: 'src/img/reactjs.png'
},
{
id: 6,
name: 'sql',
img: 'src/img/sql.png'
},
{
id: 7,
name: 'css',
img: 'src/img/css.png'
},
{
id: 8,
name: 'graphql',
img: 'src/img/graphql.png'
},
{
id: 9,
name: 'html',
img: 'src/img/html.png'
},
{
id: 10,
name: 'java',
img: 'src/img/java.png'
},
{
id: 11,
name: 'reactjs',
img: 'src/img/reactjs.png'
},
{
id: 12,
name: 'sql',
img: 'src/img/sql.png'
},
];
//declare some array for control dataflow
//mychoice is going to store name of each card
let myChoice = [];
//tempid is going store temp id for change attribute after click a card
let tempId = [];
//total flip get count of our all flip card sothat we can know when I flip the card
let totalFlip = [];
//winScore store winscore
let winScore = [];
//lostScore store winscore
let lostScore = [];
//Check if I already clicked or not so We can remove the duplicate click
const checkEvent = (i, imdCard, randomCard) => {
totalFlip.includes(randomCard[i].id) ? alert('already used') : flipcard(i, imdCard, randomCard);
}
const flipcard = (i, imdCard, randomCard) => {
totalFlip.push(randomCard[i].id);
imdCard.setAttribute('src', `${randomCard[i].img}`);
const card = document.querySelectorAll('img');
myChoice.push(randomCard[i].name);
tempId.push(`${i}`);
if (myChoice.length > 1) {
if (myChoice[0] == myChoice[1]) {
setTimeout(() => {
winScore.push(i);
document.getElementById('win').innerHTML = winScore.length;
card[tempId[0]].setAttribute('src', 'src/img/right.png');
card[tempId[1]].setAttribute('src', 'src/img/right.png');
myChoice = [];
tempId = [];
}, 100);
}
else if (myChoice.length > 0 && myChoice[0] != myChoice[1]) {
lostScore.push(i);
document.getElementById('loss').innerHTML = lostScore.length;
card[tempId[0]].setAttribute('src', 'src/img/wrong.png');
card[tempId[1]].setAttribute('src', 'src/img/wrong.png');
myChoice = [];
tempId = [];
}
}
if (totalFlip.length == 12) {
if (winScore.length / lostScore.length > 1) {
setTimeout(() => {
document.getElementById('cardContainerId').innerHTML = '';
document.getElementById('win').innerHTML = '0';
document.getElementById('loss').innerHTML = '0';
tempId = [];
myChoice = [];
totalFlip = [];
winScore = [];
lostScore = [];
alert('You Win');
gamereload();
}, 200)
}
else if (winScore.length / lostScore.length < 1) {
setTimeout(() => {
document.getElementById('win').innerHTML = '0';
document.getElementById('loss').innerHTML = '0';
document.getElementById('cardContainerId').innerHTML = '';
tempId = [];
myChoice = [];
totalFlip = [];
winScore = [];
lostScore = [];
alert('You Lose');
gamereload();
}, 200)
}
else if (winScore.length / lostScore.length == 1) {
setTimeout(() => {
document.getElementById('win').innerHTML = '0';
document.getElementById('loss').innerHTML = '0';
document.getElementById('cardContainerId').innerHTML = '';
tempId = [];
myChoice = [];
totalFlip = [];
winScore = [];
lostScore = [];
alert('Drawn');
gamereload();
}, 200)
}
}
}
function gamereload() {
let randomCard = cardArray.sort((a, b) => 0.5 - Math.random());
const cardContainer = document.querySelector('.index__cardContainer');
for (let i = 0; i < randomCard.length; i++) {
const imdCard = document.createElement('img');
imdCard.setAttribute('class', 'cardIcon disabled');
imdCard.setAttribute('src', `${randomCard[i].img}`);
imdCard.setAttribute('id', i);
let timeleft = 9;
const closetimeout = setInterval(() => {
if (timeleft <= 0) {
clearInterval(closetimeout)
}
document.getElementById('timerguess').innerHTML = `0${timeleft}`;
timeleft -= 1;
}, 1000);
setTimeout(() => {
imdCard.setAttribute('src', 'src/img/eye.png');
imdCard.setAttribute('data-id', i);
imdCard.classList.remove('disabled');
imdCard.addEventListener('click', () => checkEvent(i, imdCard, randomCard))
}
, 10000);
cardContainer.appendChild(imdCard);
};
}
gamereload();
})
|
const mongoose = require("mongoose")
const {ObjectId}=mongoose.Schema.Types
// we are creating a relation between user and the post so getting the objecId
const postSchema = new mongoose.Schema({
title:{
type:String,
required:true
},
body:{
type:String,
required:true
},
photo:{
type:String,
required:true
},
postedBy:{
// creating a relation between user and their Post
type:ObjectId,
// here we are refering to the UserSchema
ref:"User"
}
})
mongoose.model("Post" , postSchema)
|
/*global define*/
define([
'underscore',
'backbone',
'models/publication'
], function (_, Backbone, PublicationModel) {
'use strict';
var PublicationCollection = Backbone.Collection.extend({
url: function () {
var url = App.BaseUrl + '?json=get_posts&post_type=publication';
if ( this.author ) {
url = App.BaseUrl + ('?json=get_author_posts&post_type=publication&slug=' + this.author.slug);
}
// commented because sticky request is not working
if ( this.isHome ) {
return url + '&post__in=sticky_posts';
}
return url + (this.count ? '&count=' + this.count : '') + (this.page ? '&page=' + this.page : '');
//return url + (this.count ? '&count=' + this.count : '') + (this.page ? '&page=' + this.page : '');
},
model: PublicationModel,
initialize: function () {
this.page = 1;
},
parse: function (res) {
this.totalPosts = res.count_total;
return res.posts;
}
});
return PublicationCollection;
});
|
const quizCard = document.querySelector('#quizCard')
const resultCard = document.querySelector('#resultCard')
const titleCard = document.querySelector('#titleCard')
const startBtn = document.querySelector('#startBtn')
const quizImgs = document.querySelectorAll('#quizForm img');
const quizForm = document.querySelector('#quizForm');
const quizQuestion = document.querySelector('#questionDisplay');
const quizProgress = document.querySelector('.progress')
const counterHeader = document.querySelector('#counterHeader');
const quizContent = [
{
q: 'Choose something to have for breakfast...',
answers: [
{
id: 'acaibowl',
img: 'images/questions/q1_1.jpeg'
},
{
id: 'bagel',
img: 'images/questions/q1_2.jpeg'
},
{
id: 'pancakes',
img: 'images/questions/q1_3.jpeg'
},
{
id: 'avocadotoast',
img: 'images/questions/q1_4.jpeg'
}
],
category: 'breakfast'
},
{
q: 'Choose a beverage to go with your breakfast...',
answers: [
{
id: 'coffee',
img: 'images/questions/q2_1.jpeg'
},
{
id: 'tea',
img: 'images/questions/q2_2.jpeg'
},
{
id: 'juice',
img: 'images/questions/q2_3.jpeg'
},
{
id: 'hotchocolate',
img: 'images/questions/q2_4.jpeg'
}
],
category: 'breakfastbev'
},
{
q: 'Choose something to have for lunch...',
answers: [
{
id: 'salad',
img: 'images/questions/q3_1.jpeg'
},
{
id: 'sandwich',
img: 'images/questions/q3_2.jpeg'
},
{
id: 'pasta',
img: 'images/questions/q3_3.jpeg'
},
{
id: 'soup',
img: 'images/questions/q3_4.jpeg'
}
],
category: 'lunch'
},
{
q: 'Choose a midday snack...',
answers: [
{
id: 'popcorn',
img: 'images/questions/q4_1.jpeg'
},
{
id: 'chocolate',
img: 'images/questions/q4_2.jpeg'
},
{
id: 'nuts',
img: 'images/questions/q4_3.jpeg'
},
{
id: 'fruit',
img: 'images/questions/q4_4.jpeg'
}
],
category: 'snack'
},
{
q: 'Choose something to have for dinner...',
answers: [
{
id: 'sushi',
img: 'images/questions/q5_1.jpeg'
},
{
id: 'burger',
img: 'images/questions/q5_2.jpeg'
},
{
id: 'steak',
img: 'images/questions/q5_3.jpeg'
},
{
id: 'tacos',
img: 'images/questions/q5_4.jpeg'
}
],
category: 'dinner'
},
{
q: 'Choose a beverage to have with your dinner...',
answers: [
{
id: 'coke',
img: 'images/questions/q6_1.jpeg'
},
{
id: 'wine',
img: 'images/questions/q6_2.jpeg'
},
{
id: 'juice',
img: 'images/questions/q6_3.jpeg'
},
{
id: 'water',
img: 'images/questions/q6_4.jpeg'
}
],
category: 'dinnerbev'
},
{
q: 'Choose a dessert to top off your day...',
answers: [
{
id: 'icecream',
img: 'images/questions/q7_1.jpeg'
},
{
id: 'cookies',
img: 'images/questions/q7_2.jpeg'
},
{
id: 'cupcakes',
img: 'images/questions/q7_3.jpeg'
},
{
id: 'donuts',
img: 'images/questions/q7_4.jpeg'
}
],
category: 'dessert'
}
]
const quizResult = (score) => {
if (score <= 11) {
return {
img: 'images/results/japan.jpeg',
name: 'Japan',
description: 'You should visit Japan! Taste authentic sushi, go shopping in Shibuya, visit some of the many temples, take a ride on the bullet train (try to catch a glimpse of Mt. Fuji!), and have a special, cuddly encounter at an animal cafe. *Don\'t forget to sample treats in the unique vending machines!'
}
}
else if (11 < score && score <= 16) {
return {
img: 'images/results/france.jpeg',
name: 'France',
description: 'You should visit France! Explore the many museums, spend a night in a french chateau, enjoy macarons in a Paris cafe, and take in the sights of the Eiffel Tower. *Buy a beret for the perfect souvenir of your French holiday!'
}
}
else if (16 < score && score <= 21) {
return {
img: 'images/results/hawaii.jpeg',
name: 'Hawaii',
description: 'You should visit Hawaii! Soak up the sun in the many, beautiful beaches, encounter manta rays while scuba diving along the island, hike up a volcano, and snorkel with sea turtles. *Take a tour of the Dole Plantation and taste their delicious Dole Whip!'
}
}
else if (score > 21) {
return {
img: 'images/results/disneyworld.jpeg',
name: 'Walt Disney World',
description: 'You should visit Disneyworld! Experience feeling like a kid again in the happiest place on Earth! Get your thrill on while riding your favorite rides including Space Mountain, Expedition Everest, and Rock \'n\' Rollercoaster. Sample your way through unique treats from around the world in Disney\'s Epcot World Pavilion. *Buy a pair of Mickey ears to match all of your outfit!'
}
}
}
const renderQuestion = (index => {
const content = quizContent[index];
quizQuestion.innerHTML = content.q;
for (i = 0; i < 4; i++){
quizImgs[i].src = content.answers[i].img;
// render images
quizForm[i].labels[0].htmlFor = content.answers[i].id;
quizForm[i].id = content.answers[i].id;
quizForm[i].name = content.category;
// update form information
};
})
const displayResult = (result) => {
const resultImg = document.querySelector('#resultImg');
const resultName = document.querySelector('#resultName');
const resultDescription = document.querySelector('#resultDescription');
resultImg.src = result.img;
resultName.innerHTML = result.name;
resultDescription.innerHTML = result.description;
}
const quizStart = (() => {
let questionCounter = 0;
let scoreCounter = 0;
const quizLength = quizContent.length;
const progressIncrement = 100/quizLength;
// calculate how much progress bar should increase based on quiz length
renderQuestion(0);
counterHeader.innerHTML = `Question 1 of ${quizLength}`;
for (input of quizForm) {
input.addEventListener('input', (e) => {
const answer = document.querySelector('input:checked');
const selectedImg = document.querySelector('input:checked + label img');
selectedImg.classList.toggle('selected');
questionCounter += 1;
//track question #
scoreCounter += parseInt(answer.value);
// add to score total
for (input of quizForm) {
input.setAttribute('disabled','');
}
// disable the rest of inputs to prevent multiple clicks
setTimeout(function() {
if (questionCounter < quizLength) {
renderQuestion(questionCounter);
// render next question
counterHeader.innerHTML = `Question ${questionCounter + 1} of ${quizLength}`;
quizProgress.value += progressIncrement;
// update quiz progress on bar and header
answer.checked = false;
// uncheck input
selectedImg.classList.toggle('selected');
// remove selected img
for (input of quizForm) {
input.removeAttribute('disabled');
}
// remove disabled attribute from inputs
} else {
const result = quizResult(scoreCounter);
displayResult(result);
quizCard.classList.toggle('is-hidden');
resultCard.classList.toggle('is-hidden');
}
}, 700)
});
}
})
startBtn.addEventListener('click', (e) => {
titleCard.classList.toggle('is-hidden')
quizStart();
quizCard.classList.toggle('is-hidden')
})
|
// pages/post/posts/posts.js
const { $Message } = require('../../../dist/base/index');
var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var user = require('../../../utils/user.js');
var app = getApp();
Page({
/**
* 页面的初始数据
*/
data: {
showRigh2: false,
visible5: false,
cate_id: 0,
confirm:'',
title: '',
menu_id:'',
hiddenAlertPu: true,
posts:[],
updateTime: '',
createTime: '',
failMes:'',
actions5: [
{
name: '取消'
},
{
name: '删除',
color: '#ed3f14',
loading: false
}
]
},
toggleRight2() {
this.setData({
showRight2: !this.data.showRight2
});
},
handleOpen5() {
this.setData({
visible5: true
});
},
handleClick5({ detail }) {
if (detail.index === 0) {
this.setData({
visible5: false
});
} else {
const action = [...this.data.actions5];
action[1].loading = true;
this.setData({
actions5: action
});
if (this.data.confirm != this.data.title) {
this.setData({
visible5: false,
});
$Message({
content: '目录名输入错误!',
type: 'error'
});
} else {
setTimeout(() => {
action[1].loading = false;
this.setData({
visible5: false,
actions5: action
});
var cateId = this.data.cate_id;
var menu_id = this.data.menu_id;
this.delCategory(cateId, menu_id);
}, 1000);
}
}
},
delCategory: function (cateId, menu_id) {
let that = this;
util.request(api.DelCategory, {
cateId: cateId,
menu_id: menu_id,
}, 'DELETE').then(function (res) {
if (res.errno === 0) {
$Message({
content: '删除成功!',
type: 'success'
});
wx.navigateBack({
delta: 1
})
} else {
$Message({
content: res.errmsg,
type: 'error'
});
}
});
},
goPostDetail(e) {
var id = e.currentTarget.dataset.id
wx.navigateTo({
url: "/pages/post/posts/posts?post_id=" + id + "&cate_id=" + this.data.cate_id
})
},
goEditCate() {
wx.navigateTo({
url: "/pages/content/editcategory/editcategory?cate_id="+this.data.cate_id
})
},
goCreatePost() {
wx.navigateTo({
url: "/pages/content/createpost/createpost?cate_id=" + this.data.cate_id
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.setData({
createTime: options.creTime,
updateTime: options.upTime,
cate_id: options.id,
title: options.title,
menu_id: options.menu_id
});
wx.setNavigationBarTitle({
title: options.title
})
this.getPostsAll();
},
getPostsAll: function () {
let that = this;
util.request(api.GetPostsAll + this.data.cate_id).then(function (res) {
if (res.errno === 0) {
that.setData({
posts: res.data.posts,
});
} else if (res.errno === 801) {
that.setData({
failMes: res.errmsg,
hiddenAlertPu: !that.data.hiddenAlertPu
})
}
});
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
wx.showNavigationBarLoading() //在标题栏中显示加载
this.getPostsAll()
wx.hideNavigationBarLoading() //完成停止加载
wx.stopPullDownRefresh() //停止下拉刷新
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
confirmDel: function (e) {
this.setData({
confirm: e.detail.detail.value
})
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})
|
const fs = require('fs')
const googleStorage = require('@google-cloud/storage')
// const gcsHelpers = require('../helpers/google-cloud-storage')
const GOOGLE_CLOUD_PROJECT_ID = process.env.PROJECT_ID
const GOOGLE_CLOUD_KEYFILE = process.env.CLOUD_KEYFILE
const storage = new googleStorage.Storage({
projectId: GOOGLE_CLOUD_PROJECT_ID,
keyFilename: GOOGLE_CLOUD_KEYFILE
})
getPublicUrl = (bucketName, fileName) => `https://storage.googleapis.com/${bucketName}/${fileName}`;
const DEFAULT_BUCKET_NAME = 'mini-wp-qfs'; // Replace with the name of your bucket
module.exports = function (req, res, cb) {
let img = req.body.img
let extension = req.body.extension
let base64Data = img.replace(/^data:image\/png;base64,|^data:image\/jpeg;base64,/, "");
let newFileName = Date.now() + '.' + extension
let newFile = '../../uploads/' + newFileName
fs.writeFile(newFile, base64Data, 'base64', (err) => {
if (err) {
console.log(err);
res.status(500).json({
msg: err,
});
} else {
console.log(extension)
req.file = {}
req.file.buffer = fs.readFileSync(newFile)
req.file.originalName = Date.now() + newFileName
if (extension === 'png') {
req.file.mimetype = 'image/png'
} else if (extension === 'jpeg' || extension === 'jpg') {
req.file.mimetype = 'image/jpg'
}
sendUploadToGCS(req, res, cb)
}
});
}
sendUploadToGCS = (req, res, cb) => {
if (!req.file) {
console.log('aaa')
console.log('there is nothing to upload!');
cb(title, content, createdAt, newFile, id)
}
const bucketName = req.body.bucketName || DEFAULT_BUCKET_NAME;
const bucket = storage.bucket(bucketName);
const gcsFileName = `${Date.now()}-${req.file.originalName}`;
const file = bucket.file(gcsFileName);
const stream = file.createWriteStream({
metadata: {
contentType: req.file.mimetype,
},
});
stream.on('error', (err) => {
console.log('bbb')
console.log(err)
req.file.cloudStorageError = err;
res.status(500).json(err.message);
});
stream.on('finish', () => {
console.log('ccc')
req.file.cloudStorageObject = gcsFileName;
return file.makePublic()
.then(() => {
console.log('ddd')
req.file.gcsUrl = getPublicUrl(bucketName, gcsFileName);
console.log('Your file has been uploaded successfully!', req.file)
let id = req.body.id
let title = req.body.title
let content = req.body.content
let createdAt = req.body.createdAt
let field = req.body.field
let value = req.body.value
let author = req.body.author
let user = req.headers.idAuthenticated
cb(title, content, createdAt, req.file.gcsUrl, author, user, id, field, value)
});
});
stream.end(req.file.buffer);
};
|
import React, { Component } from "react";
import Router from "next/router";
import moment from "moment";
import _ from "lodash";
import withAuth from "../libs/withAuth";
import CordaService from "../services/CordaService";
import StandardService from "~/services/StandardService";
import Layout from "../components/Layout";
import BlockUi from "react-block-ui";
import TextAreaField from "../components/Fields/TextAreaField";
import SectionInfo from "../components/SectionInfo";
import SectionTwoHeaderInfo from "../components/SectionTwoHeaderInfo";
import SectionCancelAndNext from "../components/SectionCancelAndNext";
import DocumentItemTableEdit from "../components/document-item-edit/DocumentItemTableEdit";
import {
REQUEST_HEADER_INFO,
REQUEST_ITEM_INFO
} from "../components/request/models/request-info-edit";
import { REQUEST_ROUTES } from "../configs/routes.config";
import {
toBigNumber,
getKeyElementField,
setValueDefault,
isValueEmpty
} from "~/helpers/app";
import {
SYSTEM_FAILED,
EDIT_FAILED,
CONFIG_NOT_FOUND
} from "../configs/errorMessage.config";
import ModalMessage from "~/components/common/SweetAlert";
import { REQUEST_ATTACHMENT_TYPE } from "../configs/attachmentType.config";
import { REFERENCE_TYPE } from "../components/request/config";
import statusColor from "../configs/color.rq.json";
import { withTranslation } from "~/i18n";
import GA from "~/libs/ga";
const amountField = ["subTotal", "vatTotal", "total", "withholdingTaxAmount"];
const filesField = ["requestAttachment", "documentAttachment"];
const lang = "request-edit";
class RequestEdit extends Component {
constructor(props) {
super(props);
this.state = {
blocking: false,
header: "",
linearId: null,
request: {},
requestItems: [],
headerInfoModel: REQUEST_HEADER_INFO,
requestItemModel: REQUEST_ITEM_INFO,
editedHeaderSubTotal: false,
isDataValid: false,
isDocumentNumberValid: false,
itemAmountValid: false
};
}
cordaService = new CordaService();
standardService = new StandardService();
layout = React.createRef();
componentDidMount() {
this.handleToggleBlocking();
this.setState({
linearId: this.props.url.query.linearId
});
this.getRequestDetails(this.props.url.query.linearId);
}
handleToggleBlocking = () => {
this.setState({ blocking: !this.state.blocking });
};
//----- GET CONFIGURATIONS -------------------------------------------------
getEditMode(lifecycle) {
let header;
switch (lifecycle) {
case "PENDING_SELLER":
header = "Response to Request";
break;
case "PENDING_BUYER":
header = "Edit Mode";
break;
case "ISSUED":
header = "Edit Mode";
break;
default:
header = "";
}
this.setState({ header });
}
async getConfigurations(requestModel) {
const { user } = this.props;
this.getEditMode(requestModel.lifecycle);
let attachmentConfig = await this.getRequestAttachmentConfigurations(
requestModel
);
let options = await this.getRequestConfigurationFromSubtype(requestModel);
let action = requestModel.lifecycle;
if (requestModel.lifecycle === "PENDING_BUYER")
action += requestModel.agreementFlag ? "_ACCEPT" : "_DECLINE";
else if (requestModel.lifecycle === "PENDING_SELLER")
action += requestModel.agreementFlag ? "_ACCEPT" : "_DECLINE";
let permission = await this.getRequestPermissionFromSubtype(
requestModel,
action
);
let taxList =
user.organisationUnit === "BUYER"
? await this.getTaxCodeConfiguration(requestModel)
: [];
if (!attachmentConfig || !options || !permission || !taxList) return;
this.prepareRequestItems(
requestModel.requestItems,
taxList,
permission.filter(p => p.level === "ITEM")
);
const resultRequest = this.setEditableField(permission);
return { attachmentConfig, options, resultRequest };
}
setDisplayField = (field, permissions) => {
const keyElement = getKeyElementField(field);
const permission = _.find(permissions, {
field: keyElement
});
if (permission) {
const { displayName } = permission;
field.placeholder = displayName;
field.title = displayName;
field.header = displayName;
field.name = displayName;
}
};
prepareRequestItems(requestItems, taxList, permission) {
let { requestItemModel } = this.state;
let requestItemEditable = permission.some(p => p.editable);
if (
!requestItemEditable &&
requestItemModel &&
requestItemModel.length > 0 &&
requestItemModel[requestItemModel.length - 1]["selector"] === "delete"
) {
requestItemModel.splice(-1, 1);
}
requestItemModel.forEach(field => {
this.setDisplayField(field, permission);
});
requestItems.forEach((r, index) => {
r = setValueDefault(r, permission);
let quantityInitial =
r.quantity && r.quantity.initial ? r.quantity.initial : 0.0;
let quantityUnit = r.quantity && r.quantity.unit ? r.quantity.unit : "";
if (
r.quantityInitial !== undefined &&
r.quantityInitial !== null &&
r.quantityInitial !== ""
) {
quantityInitial = r.quantityInitial;
}
if (
r.quantityUnit !== undefined &&
r.quantityUnit !== null &&
r.quantityUnit !== ""
) {
quantityUnit = r.quantityUnit;
}
permission.forEach(p => {
r[`${p.field}Editable`] = p.editable;
r[`${p.field}Required`] = p.required;
r[`${requestItemEditable}`] = requestItemEditable;
});
if (_.isEmpty(taxList)) {
r.vatCodeEditable = false;
}
r.vatCodeOptions = taxList;
r.vatCodeDisplay = this.setVatCodeDisplay(taxList, r);
r.quantityUnit = quantityUnit;
r.quantityInitial = quantityInitial;
r.onChange = event => this.updateItems(index, event);
r.onBlur = event => this.updateItems(index, event);
r.onClick = event => this.deleteItems(index, event);
});
this.setState(
{
requestItems: _.orderBy(requestItems),
requestItemEditable,
requestItemModel,
blocking: false,
permission
},
() => {
this.recalculateHeaderSubtotal();
this.validateFields();
}
);
}
async getTaxCodeConfiguration(requestModel) {
let taxList = [];
const { status, message, data } = await this.standardService.callApi({
group: "Tax",
action: "list",
requestParams: {
companyTaxId: requestModel.companyTaxNumber,
taxType: "VAT"
}
});
if (!status) {
const errorMessagePattern = CONFIG_NOT_FOUND.replace("%m", "Vat code");
ModalMessage({
title: "Error",
message: `${errorMessagePattern} ${message}`,
buttons: [
{
label: "OK",
attribute: {
onClick: e => this.routeCancel(e)
}
}
]
});
return null;
}
if (_.has(data, "rows") && !_.isEmpty(data.rows)) {
taxList = _.orderBy(
data.rows.map(Item => {
return {
value: Item.pk.taxCode,
percentage:
Item.taxRate !== undefined &&
Item.taxRate !== null &&
Item.taxRate !== ""
? parseInt(Item.taxRate)
: "",
display: `${Item.pk.taxCode} ${
Item.taxRate !== undefined &&
Item.taxRate !== null &&
Item.taxRate !== ""
? `(${parseInt(Item.taxRate)}%)`
: ""
}`
};
}),
"percentage",
"asc"
);
}
this.setState({ taxList });
return taxList;
}
async getRequestAttachmentConfigurations(requestModel) {
const requestParams = {
legalName: requestModel.buyer.legalName,
companyTaxId: requestModel.companyTaxNumber,
counterPartyTaxId: requestModel.vendorTaxNumber
};
const { status, message, data } = await this.cordaService.callApi({
group: "offledgers",
action: "getConfigurationForRequest",
requestParams: requestParams
});
if (!status) {
const errorMessagePattern = CONFIG_NOT_FOUND.replace("%m", "Attachment");
ModalMessage({
title: "Error",
message: `${errorMessagePattern} ${message}`,
buttons: [
{
label: "OK",
attribute: {
onClick: e => this.routeCancel(e)
}
}
]
});
return null;
}
this.setState({ attachmentConfigurations: data });
return data;
}
async getRequestConfigurationFromSubtype(requestModel) {
const requestParams = {
party: requestModel.buyer.legalName,
companyTaxId: requestModel.companyTaxNumber,
type: requestModel.type,
subtype: requestModel.subType
};
const { status, message, data } = await this.cordaService.callApi({
group: "offledgers",
action: "getRequestConfigurationBySubtype",
requestParams: requestParams
});
if (!status) {
const errorMessagePattern = CONFIG_NOT_FOUND.replace(
"%m",
"Document type"
);
ModalMessage({
title: "Error",
message: `${errorMessagePattern} ${message}`,
buttons: [
{
label: "OK",
attribute: {
onClick: e => this.routeCancel(e)
}
}
]
});
return null;
}
let options = [];
data.documentType.forEach(dt => {
options.push({ ...dt, value: dt.documentType, display: dt.documentType });
});
this.setState({
documentTypeConfigurations: data
});
return options;
}
async getRequestPermissionFromSubtype(requestModel, action) {
const requestParams = {
party: requestModel.buyer.legalName,
companyTaxId: requestModel.companyTaxNumber,
type: requestModel.type,
subtype: requestModel.subType,
action: action
};
const { status, message, data } = await this.cordaService.callApi({
group: "offledgers",
action: "getRequestPermission",
requestParams: requestParams
});
if (!status) {
const errorMessagePattern = CONFIG_NOT_FOUND.replace("%m", "Permission");
ModalMessage({
title: "Error",
message: `${errorMessagePattern} ${message}`,
buttons: [
{
label: "OK",
attribute: {
onClick: e => this.routeCancel(e)
}
}
]
});
return null;
}
this.setState({ permissionConfigurations: data });
//this.setEditableField(data);
return data;
}
setEditableField(fieldConfigs) {
let { headerInfoModel, request } = this.state;
for (var key in headerInfoModel) {
headerInfoModel[key].fields.forEach(field => {
let config = fieldConfigs.find(
c => c.level === "HEADER" && c.field === field.key
);
if (config) {
if (
config.defaultValue &&
config.editable &&
(request[field.key] == undefined || request[field.key] == "")
) {
request[field.key] = config.defaultValue;
}
field.disabled =
amountField.includes(field.key) &&
this.state.requestItems.length <= 0;
field.title = config.displayName;
field.required = config.required;
field.canEdit = config.editable;
field.onChange =
config.editable && !amountField.includes(field.key)
? this.handleInputChange
: null;
field.onBlur =
config.editable && amountField.includes(field.key)
? this.handleInputChange
: null;
}
if (filesField.includes(field.key)) {
field.onRemove = this.onFilesRemoved;
field.onFileAdded = this.onFileAdded;
}
});
}
this.setState({ headerInfoModel });
return request;
}
//----- GET REQUEST DETAILS -------------------------------------------------
getRequestDetails = async linearId => {
const pathParams = { linearId: linearId };
const { status, message, data } = await this.cordaService.callApi({
group: "request",
action: "getRequestDetail",
pathParams: pathParams
});
if (status) {
if (data.rows.length == 0) {
ModalMessage({
title: "Error",
message: "Request Not Found.",
buttons: [
{
label: "OK",
attribute: {
onClick: e => this.routeCancel(e)
}
}
]
});
return;
}
const requestConfigByTaxId = await this.getRequestConfigurationByTaxId(
data.rows[0].companyTaxNumber,
data.rows[0].buyer.legalName
);
const { type, subType, referenceType } = data.rows[0];
const typeSelected = requestConfigByTaxId.find(
config => config.type === type
);
const { purchaseOrder, invoice, others } = REFERENCE_TYPE;
const referenceTypeSelected =
referenceType === purchaseOrder.value
? purchaseOrder
: referenceType === invoice.value
? invoice
: others;
let subTypeSelected = [];
if (typeSelected !== undefined && typeSelected !== null) {
subTypeSelected = typeSelected.subType.find(
item => item.value === subType
);
}
let request = {
...data.rows[0],
vendorBranchCodeDisplay: `${data.rows[0].vendorBranchCode} ${
data.rows[0].vendorBranchName
? `(${data.rows[0].vendorBranchName})`
: ""
}`,
companyBranchCodeDisplay: `${data.rows[0].companyBranchCode} ${
data.rows[0].companyBranchName
? `(${data.rows[0].companyBranchName})`
: ""
}`,
typeDisplay:
typeSelected && typeSelected.typeDisplayName
? typeSelected.typeDisplayName
: type,
subTypeDisplay:
subTypeSelected && subTypeSelected.subtypeDisplayName
? subTypeSelected.subtypeDisplayName
: subType,
referenceTypeDisplay: referenceTypeSelected.display,
documentDate: data.rows[0].documentDate
? moment(data.rows[0].documentDate).format("DD/MM/YYYY")
: data.rows[0].documentDate,
paymentDueDate: data.rows[0].paymentDueDate
? moment(data.rows[0].paymentDueDate).format("DD/MM/YYYY")
: data.rows[0].paymentDueDate,
agreementFlag:
data.rows[0].lifecycle === "PENDING_SELLER"
? data.rows[0].agreementFlag || data.rows[0].agreementFlag === false
? data.rows[0].agreementFlag
: true
: data.rows[0].agreementFlag
};
const configs = await this.getConfigurations(request);
if (!configs) return;
request = { ...request, ...configs.resultRequest };
this.setState(
{
request: { ...request, configs, documentTypeOptions: configs.options }
},
() => {
this.validateFields();
this.setConfigAttachmentField();
}
);
} else {
const errorMessagePattern = SYSTEM_FAILED.replace("%m", "find request");
ModalMessage({
title: "Error",
message: `${errorMessagePattern} ${message}`,
buttons: [
{
label: "OK",
attribute: {
onClick: e => this.routeCancel(e)
}
}
]
});
}
};
setVatCodeDisplay = (taxList, item) => {
const vatSelect = taxList.find(tax => tax.value === item.vatCode);
return vatSelect !== undefined
? vatSelect.display
: item.vatCode !== undefined &&
item.vatCode !== null &&
item.vatCode !== ""
? `${item.vatCode} ${
item.vatRate !== undefined &&
item.vatRate !== null &&
item.vatRate !== ""
? `(${parseInt(item.vatRate)}%)`
: ""
}`
: "-";
};
getRequestConfigurationByTaxId = async (companyTaxNumber, party) => {
const requestParams = {
companyTaxId: companyTaxNumber,
party: party
};
const { status, message, data } = await this.cordaService.callApi({
group: "offledgers",
action: "getRequestConfigurationByTaxId",
requestParams: requestParams
});
if (!status) {
const errorMessagePattern = SYSTEM_FAILED.replace(
"%m",
"get request configuration by tax id"
);
ModalMessage({
title: "Error",
message: `${errorMessagePattern} ${message}`,
buttons: [
{
label: "OK",
attribute: {
onClick: () => {}
}
}
]
});
return [];
}
return data;
};
setConfigAttachmentField = () => {
const { request } = this.state;
const { attachmentConfig } = request.configs;
const attachmentConfiguration = attachmentConfig.attachmentConfiguration[0];
filesField.forEach(field => {
request[`${field}Format`] = attachmentConfiguration.fileType;
request[`${field}RequiredTooltip`] =
attachmentConfiguration.minimumNumberOfFiles ===
attachmentConfiguration.maximumNumberOfFiles
? attachmentConfiguration.minimumNumberOfFiles
: `${attachmentConfiguration.minimumNumberOfFiles} - ${attachmentConfiguration.maximumNumberOfFiles}`;
this.setState({
request
});
});
};
//----- SAVE AND SUBMIT ---------------------------------------------------
prepareDataToSubmit = async () => {
const { request, requestItems, overrideDocumentType } = this.state;
let result = request;
if (overrideDocumentType) {
result.documentType = request.documentTypeOverride;
}
const allRequestAttachment = request.requestAttachment;
const allDocumentAttachment = request.documentAttachment;
const requestAttachmentNoHash = allRequestAttachment.filter(
a => !a.attachmentHash
);
const requestAttachmentWithHash = allRequestAttachment.filter(
a => a.attachmentHash
);
let uploadedRequestAttachment = await this.uploadAttachment(
requestAttachmentNoHash
);
const documentAttachmentNoHash = allDocumentAttachment.filter(
a => !a.attachmentHash
);
const documentAttachmentWithHash = allDocumentAttachment.filter(
a => a.attachmentHash
);
let uploadedDocumentAttachment = await this.uploadAttachment(
documentAttachmentNoHash
);
const requestAttachment = [
...requestAttachmentWithHash,
...uploadedRequestAttachment
];
const documentAttachment = [
...documentAttachmentWithHash,
...uploadedDocumentAttachment
];
requestItems.forEach(i => {
i.quantity = {
initial: toBigNumber(i.quantityInitial).toNumber(),
consumed: 0,
unit: i.quantityUnit,
remaining: toBigNumber(i.quantityInitial).toNumber()
};
i.unitDescription = i.quantityUnit;
});
result.requestAttachment = requestAttachment;
result.documentAttachment = documentAttachment;
result.requestItems = requestItems;
return result;
};
async uploadAttachment(attachments) {
let result = [];
for (let i = 0; i < attachments.length; i++) {
const { status, message, data } = await this.cordaService.callApi({
group: "file",
action: "handleMultipleFileUpload",
body: attachments[i].data
});
if (status) {
result.push({
...data[0],
attachmentType: attachments[i].attachmentType
});
}
}
return result;
}
submit = async send => {
this.handleToggleBlocking();
const body = await this.prepareDataToSubmit();
const requestParams = { isAutoSendRequest: send };
const { status, message, data } = await this.cordaService.callApi({
group: "request",
action: "editRequests",
requestParams: requestParams,
body: body
});
this.handleToggleBlocking();
if (status) {
GA.event({
category: "Request",
action: "Edit Request (Success)",
label: `Request | ${body.externalId} | ${moment().format()}`,
value: body.subTotal
});
this.routeCancel();
} else {
const errorMessagePattern = EDIT_FAILED.replace("%m", "request");
ModalMessage({
title: "Error",
message: `${errorMessagePattern} ${message}`,
buttons: [
{
label: "OK",
attribute: {
onClick: () => {}
}
}
]
});
GA.event({
category: "Request",
action: "Edit Request (Failed)",
label: `Request | ${body.externalId} | ${moment().format()}`
});
}
};
//----- OTHER METHODS -----------------------------------------------------
async validateFields() {
const { request, requestItems, permissionConfigurations } = this.state;
let requiredFieldsValid = true;
const checkRequireDocumentNumber = this.state.permissionConfigurations.find(
p => p.field == "documentNumber"
);
let isDocumentNumberValid = true;
if (
checkRequireDocumentNumber &&
!checkRequireDocumentNumber.required &&
(!request.documentNumber || request.documentNumber.trim() == "")
) {
isDocumentNumberValid = true;
this.setState({
request: {
...this.state.request,
[`documentNumber-invalid`]: false,
[`documentNumber-message`]: "Document number already exists."
}
});
} else if (request.documentNumber && request.documentNumber.trim() != "") {
const body = {
type: request.type,
documentNumber: request.documentNumber.trim(),
vendorTaxNumber: request.vendorTaxNumber
};
const checkUniquenessRequest = await this.cordaService.callApi({
group: "request",
action: "checkUniquenessRequest",
body: body
});
isDocumentNumberValid = checkUniquenessRequest.data;
this.setState({
request: {
...this.state.request,
[`documentNumber-invalid`]: !checkUniquenessRequest.data,
[`documentNumber-message`]: "Document number already exists."
}
});
}
_.forEach(
_.filter(permissionConfigurations, {
level: "HEADER",
required: true
}),
p => {
let hasNoItem =
amountField.includes(p.field) && !this.state.requestItems.length;
requiredFieldsValid =
(requiredFieldsValid && !isValueEmpty(request[p.field], true)) ||
hasNoItem;
}
);
const requiredItemRequest = this.validateItemRequest(
permissionConfigurations,
requestItems
);
// validate seller agreed remark
if (_.has(request, "agreementFlag") && request.agreementFlag === false) {
requiredFieldsValid =
requiredFieldsValid && !isValueEmpty(request["agreedRemark"]);
}
let itemAmountValid = requestItems.some(
i => toBigNumber(i.subTotal).toNumber() > 0
);
let headerTotal = request.total;
let headerSubTotal = request.subTotal;
let headerVatTotal = request.vatTotal;
let headerTotalValid =
toBigNumber(headerTotal).toNumber() ===
toBigNumber(headerSubTotal)
.plus(toBigNumber(headerVatTotal))
.toNumber();
let isDataValid =
requiredFieldsValid &&
requiredItemRequest &&
headerTotalValid &&
isDocumentNumberValid;
this.setState({ isDataValid, itemAmountValid });
}
validateItemRequest = (permissionConfigurations, requestItems) => {
let requiredFieldsValid = true;
_.forEach(
_.filter(permissionConfigurations, {
level: "ITEM",
required: true
}),
p => {
if (!requiredFieldsValid) return;
_.forEach(requestItems, item => {
requiredFieldsValid =
requiredFieldsValid &&
this.checkValueFieldByPermission(item, p.field);
});
}
);
return requiredFieldsValid;
};
checkValueFieldByPermission = (item, permissionField) => {
if (permissionField === "quantity") {
return (
_.has(item, "quantityInitial") &&
!isValueEmpty(item.quantityInitial, true)
);
}
if (permissionField === "unit") {
return (
_.has(item, "quantityUnit") && !isValueEmpty(item.quantityUnit, true)
);
}
return (
_.has(item, permissionField) && !isValueEmpty(item[permissionField], true)
);
};
handleAgreementFlagChange = event => {
const { request } = this.state;
request.agreementFlag = event.target.value === "Y";
this.setState({ request }, () => {
this.validateFields();
});
};
handleInputChange = async event => {
let { headerInfoModel, documentTypeConfigurations } = this.state;
let name = event.target.name;
let value = event.target.value;
let fieldEdited = "field-edited";
var { overrideDocumentType } = this.state;
if (name === "documentType") {
const optionFieldName = "documentTypeOverride";
let configFound = documentTypeConfigurations.documentType.find(
t => t.documentType == value
);
if (configFound && configFound.textfield) {
overrideDocumentType = true;
let modelIndex =
headerInfoModel.MODEL_DOCUMENT_INFO_LEFT.fields.findIndex(
item => item.key === "documentType"
) + 1;
let fieldAdded = headerInfoModel.MODEL_DOCUMENT_INFO_LEFT.fields.findIndex(
item => item.key === optionFieldName
);
if (fieldAdded < 0) {
headerInfoModel.MODEL_DOCUMENT_INFO_LEFT.fields.splice(
modelIndex,
0,
{
key: optionFieldName,
type: "text",
canEdit: true,
onChange: this.handleInputChange,
classInput: "col-7",
message: "Please specify document type"
}
);
}
} else {
overrideDocumentType = false;
let fieldAdded = headerInfoModel.MODEL_DOCUMENT_INFO_LEFT.fields.findIndex(
item => item.key === optionFieldName
);
if (fieldAdded >= 0)
headerInfoModel.MODEL_DOCUMENT_INFO_LEFT.fields.splice(fieldAdded, 1);
}
}
let total = name === "total" ? value : this.state.request.total;
if (name === "subTotal" || name === "vatTotal") {
value = toBigNumber(value).toNumber();
total = this.recalculateHeaderTotal(name, value);
}
this.setState(
{
request: {
...this.state.request,
[`${name}`]: value,
[`${name}-className`]: fieldEdited,
[`${name}-edited`]: true,
total
},
overrideDocumentType,
headerInfoModel
},
() => this.validateFields()
);
};
recalculateHeaderTotal(name, value) {
const { request } = this.state;
this.setState({ editedHeaderSubTotal: true });
if (name == "subTotal")
return toBigNumber(request.vatTotal)
.plus(toBigNumber(value))
.toNumber();
else if (name == "vatTotal")
return toBigNumber(request.subTotal)
.plus(toBigNumber(value))
.toNumber();
}
addItem() {
let { requestItems } = this.state;
let data = !_.isEmpty(requestItems) ? requestItems : [];
data.push(this.getDataDefault(data));
this.prepareRequestItems(
data,
this.state.taxList,
this.state.permissionConfigurations.filter(p => p.level === "ITEM")
);
}
getDataDefault(data) {
const highestExternalId = Math.max.apply(
Math,
data.map(o => +o.externalId)
);
let externalId = !_.isEmpty(data) ? `${+highestExternalId + 1}` : "1";
let index = externalId - 1;
return {
externalId: externalId,
description: undefined,
quantityInitial: undefined,
unitDescription: undefined,
unitPrice: undefined,
vatCodeOptions: this.state.taxList,
vatCode: undefined,
subTotal: undefined,
currency: this.state.request.currency.toUpperCase(),
onBlur: event => this.updateItems(index, event),
onChange: event => this.updateItems(index, event),
onClick: event => this.deleteItems(index, event)
};
}
updateItems = (index, event) => {
const { requestItems } = this.state;
requestItems[index][event.target.name] = event.target.value;
if (event.target.name === "currency") {
requestItems[index][event.target.name] = event.target.value.toUpperCase();
}
if (
(event.target.name === "subTotal" || event.target.name === "vatCode") &&
!this.state.editedHeaderSubTotal
) {
if (event.target.name === "subTotal") {
requestItems[index].subTotal = toBigNumber(
event.target.value
).toNumber();
}
if (event.target.name === "vatCode") {
const vatCode = event.target.value;
const taxSelect = _.find(this.state.taxList, {
value: vatCode
});
const vatRate = _.has(taxSelect, "percentage")
? taxSelect.percentage
: null;
requestItems[index].vatRate = vatRate;
requestItems[index].vatCodeDisplay = _.has(taxSelect, "display")
? taxSelect.display
: null;
}
requestItems[index].vatTotal = toBigNumber(requestItems[index].subTotal)
.multipliedBy(toBigNumber(requestItems[index].vatRate).dividedBy(100))
.toNumber();
requestItems[index].total = toBigNumber(requestItems[index].subTotal)
.plus(toBigNumber(requestItems[index].vatTotal))
.toNumber();
this.recalculateHeaderSubtotal();
}
this.setState({ requestItems }, () => {
this.validateFields();
});
};
recalculateHeaderSubtotal = () => {
const { request, requestItems } = this.state;
let subTotal = requestItems.reduce((acc, curr) => {
return toBigNumber(acc)
.plus(toBigNumber(curr.subTotal))
.toNumber();
}, 0);
let vatTotal = requestItems.reduce((acc, curr) => {
return toBigNumber(acc)
.plus(
toBigNumber(curr.subTotal).multipliedBy(
toBigNumber(curr.vatRate).dividedBy(100)
)
)
.toNumber();
}, 0);
subTotal = toBigNumber(subTotal).toNumber();
vatTotal = subTotal > 0 ? toBigNumber(vatTotal).toNumber() : 0;
const total = toBigNumber(subTotal)
.plus(toBigNumber(vatTotal))
.toNumber();
let withholdingTaxAmount =
request && request.withholdingTaxAmount
? request.withholdingTaxAmount
: 0;
withholdingTaxAmount = subTotal > 0 ? withholdingTaxAmount : 0;
this.setState({
request: {
...this.state.request,
subTotal,
vatTotal,
total,
withholdingTaxAmount
}
});
};
deleteItems = async (index, externalId) => {
if (!_.isEmpty(this.state.requestItems)) {
let data = _.remove(this.state.requestItems, function(e, i) {
return e.externalId != externalId;
});
if (_.isEmpty(data)) {
data = [this.getDataDefault(data)];
}
this.prepareRequestItems(
data,
this.state.taxList,
this.state.permissionConfigurations.filter(p => p.level === "ITEM")
);
}
};
routeCancel() {
Router.push(REQUEST_ROUTES.LIST);
}
onFilesRemoved = (attactmentFieldName, index) => {
let newAttachedList = this.state.request[attactmentFieldName];
newAttachedList.splice(index, 1);
this.setState(
{
request: {
...this.state.request,
[attactmentFieldName]: newAttachedList
}
},
() => this.validateFields()
);
};
onFileAdded = event => {
const attachmentFieldName = event.target.name;
const attachment = event.target.files[0];
this.handleUploadAttachment(attachment, attachmentFieldName);
event.target.value = null;
};
handleUploadAttachment(attachment, attachmentFieldName) {
const isValidAttachmentCondition = this.isValidAttachmentCondition(
attachment,
attachmentFieldName
);
if (isValidAttachmentCondition) {
const data = new FormData();
data.append("file", attachment);
attachment.data = data;
attachment.attachmentName = attachment.name;
attachment.attachmentType = REQUEST_ATTACHMENT_TYPE.OTHERS;
const attachments = this.state.request[attachmentFieldName];
attachments.push(attachment);
this.setState(
{
request: { ...this.state.request, [attachmentFieldName]: attachments }
},
() => this.validateFields()
);
}
}
isValidAttachmentCondition = (attachment, attachmentFieldName) => {
let valid = false;
const attachmentConfigurations = this.state.attachmentConfigurations
.attachmentConfiguration[0];
const ext = attachment.name.substring(
attachment.name.lastIndexOf(".") + 1,
attachment.name.length
);
let isAttachmentNotExceeded =
this.state.request[attachmentFieldName].length <
attachmentConfigurations.maximumNumberOfFiles;
attachmentConfigurations.minimumNumberOfFiles;
let isValidAttachmentType = attachmentConfigurations.fileType
.split(",")
.map(format => format.trim().toUpperCase())
.includes(ext.trim().toUpperCase());
let isAttachmentSizeNotExceeded = attachment.size <= 3000000;
if (!isAttachmentSizeNotExceeded) {
ModalMessage({
title: "Validation Error",
message: "File size is larger than 3 MB."
});
}
const isAttachmentValid =
isAttachmentNotExceeded &&
isValidAttachmentType &&
isAttachmentSizeNotExceeded;
this.setState({ [`${attachmentFieldName}Valid`]: isAttachmentValid });
return isAttachmentValid;
};
getSubmitTextButton = request => {
const sendText = "Send Request";
const confirmText = "Confirm Request";
let text = "";
switch (true) {
case request.lifecycle === "ISSUED":
text = sendText;
break;
case (request.lifecycle === "PENDING_BUYER" ||
request.lifecycle === "PENDING_SELLER") &&
request.agreementFlag === true:
text = confirmText;
break;
case (request.lifecycle === "PENDING_BUYER" ||
request.lifecycle === "PENDING_SELLER") &&
request.agreementFlag === false:
text = sendText;
break;
}
return text;
};
handleClickBackButton = request => {
Router.push(`${REQUEST_ROUTES.DETAIL}?linearId=${request.linearId}`);
};
//----- RENDER ------------------------------------------------------------
render() {
const { t } = this.props;
let {
blocking,
header,
headerInfoModel,
request,
requestItems,
requestItemEditable,
isDataValid,
permission
} = this.state;
return (
<div>
<Layout hideNavBar={true} ref={this.layout} {...this.props}>
<BlockUi tag="div" blocking={blocking}>
<div className="page__header col-12">
<h2 className="text-center">{t(header)}</h2>
</div>
<div id="invoice_detail_edit_page" className="row rq_edit">
<div className="form-group form-inline col-12 mb-3">
<label className="control-label h3 font-bold">
{`${t("Request No")}: ` + (request ? request.externalId : ``)}
</label>
</div>
<section className="box box--width-header col-12">
<div className="box__header">
<div className="row justify-content-between align-items-center mb-2">
<div className="col">
{t("Entry Date")} :{" "}
<strong>
{moment(request.issuedDate).format("DD/MM/YYYY")}
</strong>
</div>
<div className="col text-right">
{t("Status")} :{" "}
<strong
style={{
color: statusColor[request.status],
marginRight: "15px"
}}
>
{request.status}
</strong>
</div>
</div>
<SectionTwoHeaderInfo
id="vendor-company-info"
datas={request}
modelOne={headerInfoModel.MODEL_VENDOR_INFO}
modelTwo={headerInfoModel.MODEL_COMPANY_INFO}
/>
<SectionTwoHeaderInfo
id="request-info"
datas={request}
modelOne={headerInfoModel.MODEL_REQUEST_INFO}
modelTwo={headerInfoModel.MODEL_REFERENCE}
/>
{permission && _.get(request, "configs", false) && (
<SectionInfo
id="document-info"
datas={request}
header="Document Information"
modelOne={headerInfoModel.MODEL_DOCUMENT_INFO_LEFT}
modelTwo={headerInfoModel.MODEL_DOCUMENT_INFO_RIGHT}
/>
)}
{permission && (
<DocumentItemTableEdit
tableHeader={
<h4
style={{ margin: "10px 0 15px -9px" }}
className="gray-1"
>
{t("Request Items")}
</h4>
}
columns={this.state.requestItemModel}
data={requestItems}
footer={
requestItemEditable && (
<div className="text-center footer-create-request">
<a
href="javasctip:void(0)"
className="purple center"
onClick={e => this.addItem(e)}
>
<i className="fa fa-plus-circle" />{" "}
<span>{t("Add Item")}</span>
</a>
</div>
)
}
lang={lang}
/>
)}
{/* */}
<ResponseSection
id="SellerResponse"
header="Seller Agreement"
hidden={request.lifecycle !== "PENDING_SELLER"}
componentLeft={sellerResponse(
request,
this.handleAgreementFlagChange,
this.handleInputChange,
this.props.t
)}
t={t}
/>
<ResponseSection
id="BuyerResponse"
header="Remark"
hidden={request.lifecycle !== "PENDING_BUYER"}
componentLeft={
<TextAreaField
field={{
placeholder: "Add Remark",
key: "clarifiedRemark",
type: "textArea",
canEdit: true,
onChange: this.handleInputChange
}}
datas={request}
lang={lang}
/>
}
t={t}
/>
<SectionCancelAndNext
backButton
submitButton
submitText={this.getSubmitTextButton(request)}
handleClickSubmitButton={() => this.submit(true)}
handleClickBackButton={() =>
this.handleClickBackButton(request)
}
disabled={
isDataValid &&
this.state.itemAmountValid &&
this.state.request.subTotal > 0
}
customButtons={[
{
disabled: isDataValid,
className: "btn btn--transparent btn-wide",
text: "Save",
onClick: () => this.submit(false)
}
]}
lang={lang}
/>
</div>
</section>
</div>
<CancelWarning onConfirmed={this.routeCancel} />
</BlockUi>
</Layout>
</div>
);
}
}
export default withAuth(withTranslation(["request-edit"])(RequestEdit));
const CancelWarning = ({ onConfirmed }) => (
<div
id="cancelWarning"
className="modal hide fade"
tabIndex="-1"
role="dialog"
aria-labelledby="cancel"
aria-hidden="true"
>
<div className="modal-dialog modal-sm" role="document">
<div className="modal-content">
<div className="modal-header d-flex justify-content-center">
<h3 id="myModalLabel">Cancel</h3>
</div>
<div className="modal-body text-center">
Do you want to cancel editing this request?
</div>
<div className="modal-footer justify-content-center">
<button
type="button"
name="btnCloseModal"
id="btnCloseModal"
className="btn btn-wide"
data-dismiss="modal"
aria-hidden="true"
>
No
</button>
<button
type="button"
name="btnCloseModal"
id="btnCloseModal"
className="btn btn--transparent btn-wide"
data-dismiss="modal"
aria-hidden="true"
onClick={() => onConfirmed()}
>
Yes
</button>
</div>
</div>
</div>
</div>
);
const ResponseSection = ({
id,
classColumnWidth = "w-100",
hidden,
header,
componentLeft,
componentRight,
t
}) =>
hidden ? null : (
<div className="d-flex flex-wrap box">
<a area-controls={id} className={`d-flex ${classColumnWidth} btnToggle`}>
<div className="col-6">
<h3 className="border-bottom gray-1">{t(header)}</h3>
</div>
<div className="col-6" />
</a>
<div
id={id}
className={`collapse multi-collapse ${classColumnWidth} show`}
>
<div className="card card-body noborder">
<div className="row col-12">
<div className="col-6">{componentLeft ? componentLeft : null}</div>
<div className="col-6">
{componentRight ? componentRight : null}
</div>
</div>
</div>
</div>
</div>
);
const sellerResponse = (
request,
handleAgreementFlagChange,
handleInputChange,
t
) => [
<div
className="custom-control custom-radio"
key="seller_accept"
style={{ margin: "auto" }}
>
<input
id="seller_accept"
type="radio"
value="Y"
className="custom-control-input"
checked={request.agreementFlag}
onChange={handleAgreementFlagChange}
/>
<label className="custom-control-label" htmlFor="seller_accept">
{t("I have read all information and agree with this request")}
</label>
</div>,
<div
className="custom-control custom-radio"
key="seller_decline"
style={{ margin: "auto" }}
>
<input
id="seller_decline"
type="radio"
value="N"
className="custom-control-input"
checked={!request.agreementFlag}
onChange={handleAgreementFlagChange}
/>
<label className="custom-control-label" htmlFor="seller_decline">
{t("I disagree with this request")}
</label>
</div>,
<TextAreaField
key="agreedRemark"
field={{
placeholder: "Reason",
key: "agreedRemark",
type: "textArea",
canEdit: true,
disabled: request.agreementFlag,
onChange: handleInputChange
}}
datas={request}
/>
];
|
const Theme = {
colors: {
cinza: '#bdbdbd',
},
};
export default Theme;
|
const path = require('path');
// eslint-disable-next-line import/no-extraneous-dependencies
const tsImportPluginFactory = require('ts-import-plugin');
const CSSLoader = {
test: /\.css$/,
// exclude: /node_modules/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: { importLoaders: 1 },
},
{
loader: 'postcss-loader',
options: {
config: {
path: `${__dirname}/postcss.config.js`,
},
},
},
],
};
const FONTLoader = {
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'assets/webfonts/',
},
},
],
};
const LessLoader = {
test: /\.less$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
{
loader: 'less-loader',
options: {
paths: [path.resolve(__dirname, 'node_modules')],
javascriptEnabled: true,
},
},
],
};
const htmlLoader = {
test: /\.html$/,
use: [
{
loader: 'html-loader',
},
],
};
const JSLoader = {
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
babelrcRoots: ['.', '../'],
presets: ['@babel/preset-react', '@babel/preset-env', 'linaria/babel'],
plugins: [
'@babel/plugin-proposal-class-properties',
'@babel/plugin-proposal-export-default-from',
'syntax-dynamic-import',
['import', { libraryName: 'antd', style: true }],
],
},
},
};
const TSLoader = {
test: /\.(tsx|js|ts)$/,
exclude: /node_modules/,
use: [
{
loader: 'ts-loader',
options: {
transpileOnly: true,
getCustomTransformers: () => ({
before: [
tsImportPluginFactory({
libraryName: 'antd',
libraryDirectory: 'es',
style: true,
}),
],
}),
configFile: path.join(__dirname, '..', 'tsconfig.json'),
compilerOptions: {
module: 'es2015',
},
},
},
],
};
const SVGLoader = {
test: /\.svg/,
use: {
loader: 'svg-url-loader',
options: {},
},
};
const ESLintLoader = {
test: /\.js$/,
enforce: 'pre',
exclude: /node_modules/,
use: {
loader: 'eslint-loader',
options: {
configFile: `${__dirname}/../.eslintrc`,
},
},
};
const TSLintLoader = {
test: /\.tsx$/,
enforce: 'pre',
exclude: /node_modules/,
use: {
loader: 'tslint-loader',
options: {},
},
};
module.exports = {
JSLoader,
htmlLoader,
CSSLoader,
LessLoader,
SVGLoader,
ESLintLoader,
TSLintLoader,
FONTLoader,
TSLoader,
};
|
const { mergeSort } = require("./mergeSort");
describe("mergeSort", () => {
const unorderedNumbers = [6, 5, 3, 1, 8, 7, 2, 4];
it("should sort numbers into ascending order", () => {
expect(mergeSort(unorderedNumbers)).toEqual([1, 2, 3, 4, 5, 6, 7, 8]);
});
});
|
import React, { useContext, createContext, useState } from "react";
import { useHistory, useLocation } from "react-router-dom";
import axios from "axios";
import logo from "../../src/images/child.png";
import Cookies from 'universal-cookie';
import swal from 'sweetalert';
const authContext = createContext();
function useAuth() {
return useContext(authContext);
}
export default function LoginPage() {
let user_credentials = {
username: "",
password: ""
}
const [user, setUser] = useState({
...user_credentials
});
function handleInputChange(event) {
var node = document.getElementsByName(event.target.name)[0];
setUser({
...user,
[event.target.name]: event.target.value
});
}
let history = useHistory();
let location = useLocation();
let auth = useAuth();
let { from } = location.state || { from: { pathname: "/" } };
let login = (e) => {
e.preventDefault()
axios.post("http://localhost:3005/authenticate-user",{
username: user.username,
password: user.password
})
.then(res => {
const cookies = new Cookies();
cookies.set('current_user', res.data.data, { path: '/' });
if(res.data.data.position == 'HOSPITAL'){
window.location = "/approved-certs"
}else{
window.location = "/index"
}
})
.catch(err => {
swal({
title: "Birth Registration",
text: "Invalid login credentials",
icon: "error",
})
})
};
return (
<div>
<meta charSet="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<title>Majestic Admin</title>
<link
rel="stylesheet"
href="../../vendors/mdi/css/materialdesignicons.min.css"
/>
<link rel="stylesheet" href="../../vendors/base/vendor.bundle.base.css" />
<link rel="stylesheet" href="../../css/style.css" />
<link rel="shortcut icon" href="../../images/favicon.png" />
<div className="container-scroller">
<div className="container-fluid page-body-wrapper full-page-wrapper">
<div className="content-wrapper d-flex align-items-center auth px-0">
<div className="row w-100 mx-0">
<div className="col-lg-4 mx-auto">
<div className="auth-form-light text-left py-5 px-4 px-sm-5">
<div className="brand-logo">
<img
src={logo}
alt="Logo"
style={{ height: "40px", width: "40px" }}
/>
</div>
<h4>GHS Birth Certification</h4>
<h6 className="font-weight-light">Sign in to continue.</h6>
<form className="pt-3">
<div className="form-group">
<input
type="email"
className="form-control form-control-lg"
id="exampleInputEmail1"
placeholder="Username"
name="username" onChange={handleInputChange}
/>
</div>
<div className="form-group">
<input
type="password"
className="form-control form-control-lg"
id="exampleInputPassword1"
placeholder="Password"
name="password" onChange={handleInputChange}
/>
</div>
<div className="mt-3">
<button
onClick={login}
className="btn btn-block btn-primary btn-lg font-weight-medium auth-form-btn"
>
SIGN IN
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
|
import '../styles/index.scss';
const proxyurl = 'https://cors-anywhere.herokuapp.com/',
apiKey = '6958609d-7fcc-44ef-8996-71ea12a520e9',
start = 1,
limit = 50,
url = `https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?CMC_PRO_API_KEY=${apiKey}&start=${start}&limit=${limit}&convert=USD`;
const getData = () => {
// Fetching and outputing data
fetch(proxyurl + url)
.then(res => res.json())
.then(data => {
document.querySelector('.loader').style.display = 'none';
let output = '';
data.data.forEach(doc => {
let num =
doc.quote.USD.percent_change_24h > 0 ? 'text-success' : 'text-danger';
output += `
<tr>
<td><a class="text-primary" href="#">${doc.name}</a></td>
<td>${doc.symbol}</td>
<td>$ ${doc.quote.USD.price}</td>
<td class="crypto-value" style="display:none;">${
doc.quote.USD.price
}</td>
<td class="${num}">${doc.quote.USD.percent_change_24h} %</td>
<td>
<div class="input-group input-group-sm">
<input type="number" class="form-control mb-2" />
<button class="btn btn-success btn-block btn-sm" disabled>
Submit
</button>
</div>
</td>
<td class="myCoin"></td>
</tr>
`;
document.getElementById('table-js').innerHTML = output;
});
//Counting crypto amount you own
// Getting array of buttons
let buttons = document
.getElementById('table-js')
.getElementsByClassName('btn');
// Adding Event listeners to every button
Array.from(buttons).forEach(button => {
button.addEventListener('click', e => {
// Finding closest table row
const selectedRow = e.target.closest('tr');
let amount = selectedRow.querySelector('.myCoin');
// Parse String to number
const cryptoValue = parseFloat(
selectedRow.querySelector('.crypto-value').textContent
);
const myValue = parseFloat(selectedRow.querySelector('input').value);
amount.innerHTML = `${cryptoValue * myValue}$`;
});
});
// Enabling buttons and input values submited on ENTER
// Getting array of inputs
let inputs = document
.getElementById('table-js')
.getElementsByClassName('form-control');
// Adding Event listeners for every button
Array.from(inputs).forEach(input => {
input.addEventListener('keyup', e => {
// Finding closes input
const selectedInput = e.target.closest('input');
let buttons = document
.getElementById('table-js')
.getElementsByClassName('btn');
const selectedRow = e.target.closest('tr');
let amount = selectedRow.querySelector('.myCoin');
const button = e.target.parentElement.querySelector('button');
if (selectedInput.value) {
button.removeAttribute('disabled');
} else {
button.setAttribute('disabled', true);
// Clearing value of your coin after clearing input
amount.innerHTML = '';
}
// Button clicks when ENTER is pressed
if (e.keyCode === 13) {
button.click();
}
});
});
})
.catch(err => console.log(err));
};
getData();
// Set refresh interval
setInterval(() => {
getData();
console.log('reload!');
}, 60000);
|
module.exports.isAllow = function (req,iss,rules) {
try {
// Is are iss valid and have a rules for him. Else unauthorized.
if (req.user.iss !==iss || !rules[iss]){return false}
// If have no direct route rule then use "*" route
const route = (rules[iss].allowed[req.route.path]) ? req.route.path : "*";
// If direct route have no method then use "*" method
const method = (rules[iss].allowed[route][req.method.toLowerCase()]) ? req.method.toLowerCase() : "*";
// if have no ruole for route and method then use "*" both
const rule = (rules[iss].allowed[route][method]) ? (rules[iss].allowed[route][method]): (rules[iss].allowed["*"]["*"]);
// if have no rule for * route and * method then unauthorized
if (!rule){return false}
// Return true if in rule have one of role user
return req.user.userRole.some(role => rule.roles.includes(role));
} catch (e) {
console.log(e.message);
return false;
}
};
|
// 驳回原因
require('./PageRebutinfo.less');
import logic from './PageLogic';
import { Component, LogicRender } from 'refast';
import {
Checkbox,
InputItem,
TextareaItem,
SearchBar
} from 'antd-mobile';
import { createForm } from 'rc-form';
import mydingready from './../../dings/mydingready';
import moment from 'moment';
import {
Control,
Link
} from 'react-keeper';
import contractJson from './../../test_json/contract';
const { AUTH_URL, IMGCOMMONURI ,CONFIG_APP_URL} = require(`config/develop.json`);
class RebutInfoCom extends Component {
constructor(props) {
super(props, logic);
mydingready.ddReady({pageTitle: '驳回'});
}
/**
* 发送自定义事件(设置state)
*/
dispatchFn = (val) => {
this.dispatch('setStateData',val);
}
/**
* 搜索
*/
goSearch = (val) => {
console.log('文本框内容',val,this.state.searchVal)
this.getSearchResult({
searchWord: val
})
}
/*
* 离焦
*/
searchBlur = (e) => {
this.dispatch('setStateData',{searchVal: ''});
}
/**
* 文本输入变化
*/
searchChange = (e) => {
this.dispatch('setStateData',{searchVal: e});
}
submit = () => {
this.props.form.validateFields((error, value) => {
if (!error) {
console.log(value)
if (!value.reason) {
dd.device.notification.alert({
message: "请填写驳回原因!",
title: "警告",
buttonName: "确定"
});
return
}
function checking_type () {
let type = localStorage.getItem('checking_type');
if (type == '招投标') { return 1; }
if (type == '合同') { return 2; }
if (type == '内审审批') { return 3; }
}
let url = encodeURIComponent(`${CONFIG_APP_URL}#/detailcontract/${this.props.params.id}`),
type = checking_type(),// 1是招投标 2是合同,3是内审
userId = localStorage.getItem('userId'),
state = 'REBUT',
reason = value.reason,
params = `redirectUrl=${url}&stateEnum=${state}&type=${type}&userId=${userId}&reason=${reason}`;
fetch(`${AUTH_URL}bidding/approval/pass/${this.props.params.id}?${params}`,{
method: 'POST'
})
.then(res => res.json())
.then(data => {
/*dd.device.notification.alert({
message: "合同详情数据" + JSON.stringify(data),
title: "提示",
buttonName: "确定"
})*/
if (data.state == 'SUCCESS') {
dd.device.notification.alert({
message: "操作成功!",
title: "提示",
buttonName: "确定",
onSuccess: () => {
Control.go(-2);
localStorage.removeItem('checking_type');
}
})
return
}
dd.device.notification.alert({
message: data.info,
title: "温馨提示",
buttonName: "确定"
});
Control.go(-1);
})
}
});
}
render() {
const { getFieldProps } = this.props.form;
let { searchVal } = this.state;
return (
<div className="contractSearch">
<p className="title">驳回原因或说明(必填)</p>
<TextareaItem
className="textArea"
rows={7}
placeholder="请填写驳回原因"
{...getFieldProps('reason',{
rules:[{required: false,message:'请填写驳回原因'}]
})}
></TextareaItem>
<div className="btnRedLong" onClick={this.submit}>确定驳回</div>
</div>
);
}
}
const RebutInfo = createForm()(RebutInfoCom);
export default RebutInfo ;
|
import * as React from 'react';
import useControl, {useFinalControl} from '../src';
import {mapSetter} from '../src/transform';
function Counter({control}) {
const useState = useFinalControl(control);
const [total, setTotal] = useState('total', 0);
return (
<div>
<span> {total} </span>
<button onClick={() => setTotal((n) => n + 1)}>ADD</button>
</div>
);
}
export function DoubleCounter({control}) {
const [m] = useControl(control, {
total: mapSetter(t => t * 1)
});
return <Counter control={m} />;
}
export default {title: 'transform'};
|
import mix from "@vestergaard-company/js-mixin";
import Command from "./abstract/Command.js";
import AriaChecked from "../attributes/aria-checked.js";
/**
* A checkable input in a group of elements with the same role,
* only one of which can be checked at a time.
*
* @extends Command
* @mixes AriaChecked
* @example
* <div role="radio" aria-checked="true" tabindex="0">Apple</div>
*/
class Radio extends mix(Command).with(AriaChecked) {
/**
* @constructs Radio
*/
}
export default Radio;
|
import CharacterSkill from './CharacterSkill';
export default baseClass => {
return class SkillsMixedIn extends baseClass {
constructor(props) {
if (!props) {
props = {};
}
super(props);
this._initSkills(props.skills);
}
/* ------------------- SKILLS --------------------- */
_initSkills(skills) {
this._skills = {};
if (skills) {
for (let skill of skills) {
this.addSkill(skill);
}
}
}
get skills() {
const skills = {};
for (let p in this._skills) {
if (this._skills.hasOwnProperty(p)) {
let skill = this._skills[p];
skills[skill.name] = skill.rank;
}
}
return skills;
}
skillRank(name) {
if (!this._skills[name]) {
return 0;
}
return this._skills[name].rank;
}
addSkill(alpha, beta, gamma) {
let name;
let attr;
let level;
if (typeof alpha === 'object') {
name = alpha.name;
attr = alpha.attr;
level = alpha.level || 0;
} else {
name = alpha;
attr = beta;
level = gamma || 0;
}
this._skills[name] = new CharacterSkill(this, name, attr, level);
}
};
};
|
/**
* @author Guilherme Nogueira <guilhermenogueira90@gmail.com>
*/
import React, { Component, PropTypes } from 'react'
import { LinkContainer } from 'react-router-bootstrap'
import FontAwesome from 'react-fontawesome'
import {
Col,
Alert,
HelpBlock,
Button,
ButtonGroup,
Panel,
Form,
Checkbox,
FormGroup,
FormControl,
ControlLabel
} from 'react-bootstrap'
import AppTitle from '../../components/AppTitle'
import UserService from '../service/UserService'
class UserForm extends Component {
constructor(props) {
super(props)
this.state = {
loading: false,
loaded: false,
submited: false,
data: {
name: '',
email: '',
userType: '',
active: true
},
validation: {}
}
}
componentDidMount() {
const me = this
const userId = me.context.router.params.userId
if (userId) {
me.setState({
loading: true
})
UserService.findById(userId)
.then(payload => {
me.setState({
loading: false,
loaded: true,
data: payload.data
})
})
.catch(error => {
console.log(error)
})
}
}
handleSubmit = (e) => {
e.preventDefault()
const me = this
const userId = me.context.router.params.userId
const data = {
name: me.name.value,
email: me.email.value,
userType: me.userType.value,
password: me.password.value,
active: me.active.checked
}
me.setState({
submited: true
})
return UserService.save(data, userId)
.then(payload => {
me.context.router.push('/users')
})
.catch(error => {
me.setState({
submited: false,
validation: error.response.data
})
})
}
onChangeValue = (event) => {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
data: {
...this.state.data,
[name]: value
}
})
}
render() {
const me = this.state
const isLoaded = me.loaded
const user = me.data
const validation = me.validation
return (
<AppTitle title={isLoaded ? 'Editar Usuário' : 'Adicionar Usuário'}>
<Panel header={(<h4><FontAwesome name="plus" /> {isLoaded ? 'Editar Usuário' : 'Adicionar Usuário'}</h4>)}>
<Form horizontal>
<FormGroup validationState={validation.name && 'error'}>
<Col sm={6} md={6}>
<ControlLabel>Nome</ControlLabel>
<FormControl
type="text"
name="name"
value={user.name || ''}
onChange={this.onChangeValue}
placeholder="Informe o nome do usuário"
autoComplete="off"
inputRef={input => { this.name = input; }}
disabled={me.submited} />
<FormControl.Feedback />
{validation.name && validation.name.length && validation.name.map((message, index) => (
<HelpBlock key={index}><FontAwesome name="remove" /> {message}</HelpBlock>
))}
{validation.email && validation.email.message && (
<HelpBlock><FontAwesome name="remove" /> {validation.email.message}</HelpBlock>
)}
</Col>
</FormGroup>
<FormGroup validationState={validation.userType && 'error'}>
<Col sm={6} md={6}>
<ControlLabel>Tipo de Usuário</ControlLabel>
<FormControl
componentClass="select"
name="userType"
value={user.userType || ''}
onChange={this.onChangeValue}
inputRef={input => { this.userType = input; }}
disabled={me.submited}>
<option value=""></option>
<option value="Administrador">Administrador</option>
<option value="Administrativo">Administrativo</option>
<option value="Vendedor">Vendedor</option>
</FormControl>
<FormControl.Feedback />
{validation.userType && validation.userType.map((message, index) => (
<HelpBlock key={index}><FontAwesome name="remove" /> {message}</HelpBlock>
))}
</Col>
</FormGroup>
<FormGroup validationState={validation.email && 'error'}>
<Col sm={6} md={6}>
<ControlLabel>Email</ControlLabel>
<FormControl
type="email"
name="email"
value={user.email || ''}
onChange={this.onChangeValue}
placeholder="Informe um email válido"
autoComplete="off"
inputRef={input => { this.email = input; }}
disabled={me.submited} />
<FormControl.Feedback />
{validation.email && validation.email.length && validation.email.map((message, index) => (
<HelpBlock key={index}><FontAwesome name="remove" /> {message}</HelpBlock>
))}
{validation.email && validation.email.message && (
<HelpBlock><FontAwesome name="remove" /> {validation.email.message}</HelpBlock>
)}
</Col>
</FormGroup>
<FormGroup validationState={validation.password && 'error'}>
<Col sm={6} md={6}>
<ControlLabel>Senha</ControlLabel>
<FormControl
type="password"
name="password"
onChange={this.onChangeValue}
placeholder="Mínimo 6 caracteres"
autoComplete="off"
inputRef={input => { this.password = input; }}
disabled={me.submited} />
<FormControl.Feedback />
{validation.password && validation.password.map((message, index) => (
<HelpBlock key={index}><FontAwesome name="remove" /> {message}</HelpBlock>
))}
</Col>
</FormGroup>
<FormGroup>
<Col sm={6} md={6}>
{isLoaded && (
<Checkbox
name="active"
inputRef={input => { this.active = input; }}
onChange={this.onChangeValue}
checked={user.active}
inline>
<span>
Esse usuário está <strong className={user.active ? 'text-info' : 'text-danger'}>{user.active ? 'ATIVADO' : 'INATIVO'}</strong>
</span>
</Checkbox>
)}
{!isLoaded && (
<Checkbox
name="active"
inputRef={input => { this.active = input; }}
onChange={this.onChangeValue}
checked={user.active}
inline>
<span>Por padrão, este novo usuário será salvo como <strong className="text-info">ATIVO</strong></span>
</Checkbox>
)}
</Col>
</FormGroup>
<ButtonGroup>
<LinkContainer to="/users">
<Button bsStyle="success" disabled={me.submited}>
<FontAwesome name="reply" /> Voltar
</Button>
</LinkContainer>
<Button onClick={this.handleSubmit} bsStyle="primary" disabled={me.submited}>
<FontAwesome name="save" /> Salvar
</Button>
</ButtonGroup>
</Form>
</Panel>
</AppTitle>
);
}
}
UserForm.contextTypes = {
router: PropTypes.object.isRequired
}
export default UserForm
|
'use strict';
const Marionette = require('backbone.marionette');
module.exports = Marionette.AppRouter.extend({
appRoutes: {
'register(/:method)': 'register',
profile: 'profile',
index: 'main'
}
});
|
$(document).ready(function(){
$('#btnSubmit').on('click', function(){
var searchValue = $('#inputSeach').val();
$('#inputSeach').val('')
getCity(searchValue)
});
});
function getCity(searchValue){
$.ajax({
url: `https://developers.zomato.com/api/v2.1/locations?query=${searchValue.trim()}`,
method: "GET",
headers: {
"user-key": "1df36fe20e0293046e468f4ee5246765"
}, success: function(data){
console.log(data)
//process the JSON data etc
if(data.location_suggestions.length > 0){
getRestaurant(data.location_suggestions[0].longitude, data.location_suggestions[0].latitude)
} else{
alert('City Not Found, please try again')
$('#inputSeach').focus();
}
}
})
}
function getRestaurant(lon, lat){
$.ajax({
url: `https://developers.zomato.com/api/v2.1/search?lon=${lon}&lat=${lat}`,
method: "GET",
headers: {
"user-key": "1df36fe20e0293046e468f4ee5246765"
}, success: function(data){
console.log(data)
var defaultImg= "./images/foodoption.jpg"
$('#searchResults').empty();
//process the JSON data etc
if(data.restaurants.length > 0){
data.restaurants.forEach(res => {
var col = $('<div class="col s6 m4 l3">').css({
"min-height": "459px",
"max-height": "460px",
"overflow-y": "scroll"
});
var card = $('<div class="card blue-grey darken-1">').css({
"overflow": "hidden",
});
var content = $('<div class="card-content white-text">');
var name = $('<span class="card-title">').text(res.restaurant.name);
var img = $('<img>').attr("src", res.restaurant.featured_image || defaultImg).css({
"max-width": "270px",
"min-width": "250px",
"min-height": "199px",
"max-height": "200px"
});
var cuisinesIcon = $('<i class="material-icons right small">').text('restaurant_menu');
var cuisinesText = $('<span>').text(res.restaurant.cuisines);
var cuisines = $('<p>').append(cuisinesIcon, cuisinesText)
var action= $('<div class="card-action">');
var time = $('<p>').text("Times: " +res.restaurant.timings);
var location = $('<p>').text("Location: " +res.restaurant.location.address + ", " + res.restaurant.location.city + " " + res.restaurant.location.zipcode);
action.append(time, location);
content.append(name, img, cuisines)
card.append(content, action)
col.append(card)
$('#searchResults').append(col)
})
} else {
alert('This city has no restaurants.')
}
}
})
}
|
import React, { Component } from 'react';
import Particles from 'react-particles-js';
import './App.css';
import Header from './components/Header/Header';
import SearchBar from './components/SearchBar/SearchBar';
import Timeline from './components/Timeline/Timeline';
const particlesOptions = {
particles: {
number: {
value: 100,
density: {
enable: true,
value_area: 1000
},
size:{
value:100,
random:true
},
polygon:{
enable:true,
scale:0.5,
type:'inline',
move:{
radius:10
},
url:"./components/Header/spotify.svg",
inline:{
arrangement:"equidistant"
},
draw:{
enable:true,
stroke:{
color:"rgba(255,255,255,.2)"
}
}
}
}
}
};
class App extends Component {
constructor(){
super();
this.state = {
input:'',
route:'searchhome',
currentUser:'',
playlistData:[],
loading:false
}
}
onInputChange = (event) => {
this.setState({input: event.target.value});
}
setCurrentUser = (user) => {
this.setState({currentUser:user});
}
onSubmit = () => {
const input = this.state.input;
this.setState({loading:true});
fetch(`http://localhost:8000/user/${input}`,{
method:'get',
headers:{'Content-Type':'application/json'},
})
.then(res=>res.json())
.then(response=>{
//console.log(response);
this.setCurrentUser(input);
this.setState({playlistData:response});
this.setState({loading:false});
response.forEach(element => {
console.log(element)
// fetch(`http://localhost:3000/playlist/${element.playlist_id}`,{
// method:'get',
// headers:{'Content-Type':'application/json'}
// }).then(res2=>res2.json())
// .then(response2=>{
// console.log(response2);
// }
// );
});
})
.catch(err=>console.log(err));
}
onRouteChange = (route) => {
this.setState({route:route});
}
render() {
//console.log(this.state.route);
return (
<div>
<Particles className='particles'
params={particlesOptions}
/>
{this.state.route === 'searchhome'
? <div className="App">
<Header/>
<SearchBar
onInputChange={this.onInputChange}
onSubmit={this.onSubmit}
onRouteChange={this.onRouteChange}
setCurrentUser={this.setCurrentUser}
/>
</div>
:(
<div >
<br></br>
<div className="App">
<SearchBar
onInputChange={this.onInputChange}
onSubmit={this.onSubmit}
onRouteChange={this.onRouteChange}
setCurrentUser={this.setCurrentUser}
/>
</div>
<Timeline
playlistData={this.state.playlistData}
loading={this.state.loading}
currentUser={this.state.currentUser}
/>
</div>
)
}
</div>
);
}
}
export default App;
|
import React, { PropTypes } from 'react';
import styles from './ScheduleTable.module.scss';
import cssModules from 'react-css-modules';
import {
Table,
TableBody,
TableHeader,
TableHeaderColumn,
TableRow,
TableRowColumn
} from 'material-ui/Table';
import moment from 'moment';
const parseTime = (t) =>
moment(t, ['HH:mm']).format('h:mm A');
const ScheduleTable = ({
items,
onSelection,
selectedItemIndex
}) => (
<Table
height={200}
onRowSelection={onSelection}
selectable
>
<TableHeader>
<TableRow>
<TableHeaderColumn
tooltip="The ID"
className={styles.hideSmall}
>
ID
</TableHeaderColumn>
<TableHeaderColumn tooltip="The Departure Time">Departure Time</TableHeaderColumn>
<TableHeaderColumn tooltip="The Arrival Time">Arrival Time</TableHeaderColumn>
<TableHeaderColumn tooltip="The Duration">Duration</TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody
displayRowCheckbox
stripedRows={false}
deselectOnClickaway={false}
showRowHover
>
{items && items.map((item, index) =>
<TableRow key={index} selected={selectedItemIndex === index}>
<TableRowColumn className={styles.hideSmall}>{index}</TableRowColumn>
<TableRowColumn>{parseTime(item.departureTime)}</TableRowColumn>
<TableRowColumn>{parseTime(item.arrivalTime)}</TableRowColumn>
<TableRowColumn>{item.duration}</TableRowColumn>
</TableRow>
)}
</TableBody>
</Table>
);
ScheduleTable.propTypes = {
isOffline: PropTypes.bool.isRequired,
items: PropTypes.array.isRequired,
onSelection: PropTypes.func.isRequired,
selectedItemIndex: PropTypes.number.isRequired
};
export default cssModules(ScheduleTable, styles);
|
const Sequelize = require('sequelize')
const sequelize = require('../../database/database')
const Ponto = sequelize.define('ponto', {
matricula: {
type: Sequelize.STRING,
allowNull: false
},
tipo: {
type: Sequelize.STRING,
allowNull: false
},
data: {
type: Sequelize.DATEONLY,
allowNull: false
},
hora: {
type: Sequelize.TIME,
allowNull: false
},
observacao: {
type: Sequelize.STRING
},
})
module.exports = Ponto
|
import { useEffect, useState } from 'react'
import { Link } from "react-router-dom";
import Support from '../components/Support';
import "./Home.css";
export default function Supports() {
const date = new Date().getFullYear();
const [supports, setSupports] = useState([]);
const getSupports = async () => {
await fetch("./data/supports.json", {
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
})
.then((res) => res.json())
.then((data) => {
setSupports(data);
});
};
useEffect(() => {
getSupports();
}, []);
return (
<div className="flow-container">
<p className="my-proj">
<Link to="/" className="back-to-home">
<i className="fa fa-chevron-left" aria-hidden="true"></i>
</Link>{" "}
Become a Supporter
</p>
{supports
.slice(0)
.reverse()
.map((support, index) => (
<Support support={support} key={index} />
))}
<p className="copyr">Copyright © {date} Thirasha Praween</p>
</div>
);
}
|
// # Learning Resource
// ## index.js (Questions)
// Imports the required dependencies.
const _ = require('lodash');
const { AMQP_URL } = require('./config');
const questionRouter = require('./router');
const questionProcessor = require('./processor');
const AmqpLib = require('simple-amqplib-wrapper');
const amqp = new AmqpLib(AMQP_URL);
const questionStream = amqp.consumeStream('questions');
const questionAck = _.bind(amqp.acknowledge, amqp, _, true);
// Orchestrates the pipeline
// 1. The input `questionStream` coming from the questions
// consumer is piped to the `questionProcessor`.
// 2. `questionProcessor` processes the questions and create nodes for questions.
// 3. Then the output from the `questionProcessor` is piped to the `questionRouter`
// which routes the question to the node_factory and relation_factory.
// 4. Once the entire processing on the questions is performed an acknowledgement
// is sent to the queue using `questionAck`.
questionStream.pipe(questionProcessor).pipe(questionRouter).each(questionAck);
|
import React, {PureComponent} from 'react';
import TextField from 'material-ui/TextField';
class TodoInput extends PureComponent {
componentWillReceiveProps ({editingTodo: {name = ''}}) {
this.input.value = name;
this.input.focus();
}
render () {
console.log('render TodoInput');
const {upsertTodo, editingTodo : {id, name}} = this.props;
return (
<TextField
id="name"
label="Name"
margin="normal"
defaultValue={name}
inputRef={(input) => this.input = input}
onKeyDown={(e) => {
if (e.key === 'Enter') {
upsertTodo(id, e.target.value);
e.target.value = '';
e.preventDefault();
}
}}
/>
);
}
}
export default TodoInput;
|
import React from 'react'
import PropTypes from 'prop-types'
import styles from './ListItem.module.scss'
import ListMessage from './ListMessage'
const icon = {
droid: 'fab fa-android',
human: 'fas fa-user-circle',
}
const ListItem = (props) => {
const {
item: {
name,
height,
mass,
gender,
species,
},
} = props
const iconClassName = icon[species] || 'fas fa-question'
return (
<ListMessage
iconClassName={iconClassName}
message={name}
submessage={
<div className={styles.stats}>
<span>
height: { height }
</span>
<span>
mass: { mass }
</span>
<span>
gender: { gender }
</span>
</div>
}
/>
)
}
ListItem.propTypes = {
item: PropTypes.shape({
name: PropTypes.string.isRequired,
height: PropTypes.string.isRequired,
mass: PropTypes.string.isRequired,
gender: PropTypes.string.isRequired,
species: PropTypes.oneOf([
'droid',
'human',
]),
}).isRequired,
}
export default ListItem
|
import {Map, fromJS} from 'immutable';
export const INIT_STATE = Map({
email: null,
id: null,
pending: false,
error: false
});
export const actionType = {
FETCH_USER_PENDING : 'FETCH_USER_PENDING',
FETCH_USER_FULFILLED : 'FETCH_USER_FULFILLED',
FETCH_USER_REJECTED : 'FETCH_USER_REJECTED',
CLEAR_USER_ERROR : 'CLEAR_USER_ERROR',
CLEAR_USER : 'CLEAR_USER'
};
export default (state=INIT_STATE, action) => {
switch(action.type){
case actionType.FETCH_USER_PENDING:
return state.set('pending', true);
case actionType.FETCH_USER_FULFILLED:
return state.merge({
email: action.payload.email,
id: action.payload.id,
pending: false
});
case actionType.FETCH_USER_REJECTED:
return state.merge({
pending: false,
error: action.payload.error
});
case actionType.CLEAR_USER_ERROR:
return state.set('error', null);
case actionType.CLEAR_USER:
return INIT_STATE;
}
return state;
}
|
/*
* @class StackManagerView
* @extends Backbone.View
*/
var StackManagerView = Backbone.View.extend({
tagName: 'li',
className: 'stack-manager-list',
initialize: function(options) {
this.listenTo(this.model, 'change', this.render);
},
events: {
'click input.js-archive': 'archive',
'click input.js-unarchive': 'unarchive'
},
archive: function(event) {
event.stopPropagation();
this.model.setDeleted(true);
this.save();
},
unarchive: function(event) {
event.stopPropagation();
this.model.setDeleted(false);
this.save();
},
save: function() {
this.model.save(undefined, {
error:function(){
console.log('failed to update stack');
},
success:function(model, response, options){
console.log('successfully updated stack');
}
});
},
render: function() {
var name = this.model.getName();
var display = '';
if (this.model.getDeleted()) {
display += '<input type="button" ' +
'class="small-button js-unarchive" ' +
'value="unarchive" /> ';
} else {
display += '<input type="button" ' +
'class="small-button js-archive" ' +
'value="archive" /> ';
}
display += name;
this.$el.html(display);
return this;
}
});
|
const accounts = [
{ name: '@VersaAgency', id: 'versaagency', tweets: [], amount: 30 },
{ name: '@RainAgency', id: 'rainagency', tweets: [], amount: 30 },
{ name: '@alexadevs', id: 'alexadevs', tweets: [], amount: 30 }
];
export default accounts;
|
import React, { useRef } from "react";
import axios from "axios";
export default function Login(props) {
const username = useRef(null);
const password = useRef(null);
const login = e => {
e.preventDefault();
axios
.post("http://localhost:4500/api/login", {
username: username.current.value,
password: password.current.value
})
.then(res => {
localStorage.setItem("token", res.data.token);
props.history.push("/");
})
.catch(err => {
console.log(err);
});
};
return (
<div>
<h1>Login</h1>
<form>
<input placeholder="Username" ref={username} type="text" />
<input placeholder="Password" ref={password} type="password" />
<button onClick={login}>Login</button>
</form>
</div>
);
}
|
angular.module('starter.tiquetesFactoria', [])
.factory('tiquetesFactoria', function($http) {
// Might use a resource here that returns a JSON array
// Some fake testing data
var tiquetes;
function cargarFactoria(valor){
tiquetes = valor;
}
return {
all: function() {
return tiquetes;
},
remove: function(chat) {
chats.splice(chats.indexOf(chat), 1);
},
get: function(pIdEvento) {
for (var i = 0; i < tiquetes.length; i++) {
if (tiquetes[i].idEvento == parseInt(pIdEvento)) {
return tiquetes[i];
}
}
return null;
},
cargar: function(valor) {
cargarFactoria(valor);
return null;
}
};
});
|
import React from "react";
import PropTypes from "prop-types";
import Banner from "../Banner";
import styles from "./Banners.module.css";
const Banners = ({ banners }) => {
return (
<section className={styles.banners}>
<h2 className="visually-hidden">Promo Banners</h2>
<ul className={styles.bannersList}>
{banners.length
? banners.map((banner) => (
<li key={banner.id} className={styles.bannersItem}>
<Banner {...banner} />
</li>
))
: null}
</ul>
</section>
);
};
Banners.propTypes = {
banners: PropTypes.arrayOf(
PropTypes.shape({
url: PropTypes.string.isRequired,
src: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
isMain: PropTypes.bool,
})
),
};
export default Banners;
|
function UserParamsValidate(req, res, next) {
const { username, password, email } = req.body;
if ((username && typeof (username) === 'string' && username.length > 5)
|| (email && typeof (email) === 'string' && email.length > 8)) {
if (password && typeof (password) === 'string' && password.length > 6) {
next();
} else {
return res.status(500).json({ status: 500, message: 'password length will be more then 6count' });
}
} else {
return res.status(500).json({ status: 500, message: 'username length will be more then 5 count or email length more then 8counts' });
}
}
function userParamsTokenValidate(req, res, next) {
const { token } = req.body;
if (token && typeof (token) === 'string' && token.length > 20) {
return next();
}
return res.status(403).json({ status: 403, message: 'please check token/ Token is required' });
}
module.exports = { UserParamsValidate, userParamsTokenValidate };
|
var React = require('react');
var Router = require('react-router');
var Navigation = Router.Navigation;
var ReactBootstrap = require('react-bootstrap');
var Row = ReactBootstrap.Row;
var Col = ReactBootstrap.Col;
var Button = ReactBootstrap.Button;
var Alert = ReactBootstrap.Alert;
function getHomePage(UserStore, UserActions) {
return React.createClass({
mixins: [ Navigation ],
getInitialState() {
return UserStore.getState();
},
componentDidMount() {
UserStore.listen(this.onChange);
},
componentWillUnmount() {
UserStore.unlisten(this.onChange);
},
onChange(state) {
this.setState(state);
},
render: function () {
var homeView = '';
if (this.state.currentUser === undefined) {
homeView = 'Loading...';
} else if (this.state.currentUser === null) {
homeView = (
<div>
<p>
<Button
href="/saml/login"
bsStyle="primary"
bsSize="large">
Kirjaudu sisään Partio ID:llä
</Button>
</p>
<Alert bsSize="medium" bsStyle="info">Kirjautumalla hyväksyn henkilötietojeni luovutuksen käsiteltäväksi Euroopan Talousalueen ulkopuolelle.</Alert>
</div>
);
} else if (this.state.currentUser.hasRole('orderer')) {
this.replaceWith('my_purchase_orders');
} else {
this.replaceWith('costcenter_purchase_orders');
}
return (
<Row>
<Col>
<div className="text-center">
<h1>Tervetuloa Hankiin!</h1>
<p>...ja eikun hankkimaan!</p>
{ homeView }
</div>
</Col>
</Row>
);
},
});
}
module.exports = getHomePage;
|
const { expect } = require("chai");
const supertest = require("supertest");
const logger = require("../../src/config/logger");
let TEST_URL = "https://gorest.co.in/public-api";
const request = supertest(TEST_URL);
describe("User test suite", () => {
it("should POST /users", (done) => {
const data = {
email: `test-${Math.floor(Math.random() * 9999)}@mail.ca`,
name: "Test name",
gender: "Male",
status: "Inactive",
};
request
.post("users")
.send(data)
.end((err, res) => {
expect(res.body.data).to.deep.include(data);
done(err);
});
});
it("should GET /users", (done) => {
request.get("/users").end((err, res) => {
expect(res.body.data).to.not.be.empty;
done();
});
});
it("should GET /users/:id", (done) => {
request.get("/users/1").end((err, res) => {
expect(res.body.data.id).to.be.eq(1);
done(err);
});
});
it("should GET /users with query params", (done) => {
TEST_URL = "users&page=5&gender=Female&status=Active";
request.get(TEST_URL).end((err, res) => {
expect(res.body.data).to.not.be.empty;
res.body.data.forEach((data) => {
expect(data.gender).to.eq("Female");
expect(data.status).to.eq("Active");
});
done(err);
});
});
//updated get for TDD
it("should GET /users with query params", (done) => {
TEST_URL = "users&page=5&gender=Female&status=Active";
});
it("should GET /users with query params", (done) => {
TEST_URL = "users&page=5&gender=Female&status=Active";
request.get(TEST_URL).end((err, res) => {
expect(res.body.data).to.not.be.empty;
res.body.data.forEach((data) => {
expect(data.gender).to.eq("Female");
expect(data.status).to.eq("Active");
});
done(err);
});
});
it("should PUT /users/:id", () => {
// data to update
const data = {
status: "Active",
name: `Luffy - ${Math.floor(Math.random() * 9999)}`,
};
return request
.put("users/132")
.set("Authorization", `Bearer ${TOKEN}`)
.send(data)
.then((res) => {
expect(res.body.data).to.deep.include(data);
});
});
// code added post to update data
it("should POST/users/:id", () => {
// data to update
const data = {
status: "Active",
name: `Luffy - ${Math.floor(Math.floor() * 9999)}`,
};
return request
.put("users/132")
.set("Authorization", `Bearer ${TOKEN}`)
.send(data)
.then((res) => {
expect(res.body.data).to.deep.include(data);
});
});
// code added post to update data
it("should POST/users/:id", () => {
it("should PUT/users/:id", () => {
// data to update
const data = {
status: "Active",
name: `Luffy - ${Math.floor(Math.floor() * 9999)}`,
};
return request
.put("users/132")
.set("Authorization", `Bearer ${TOKEN}`)
.send(data)
.then((res) => {
expect(res.body.data).to.deep.include(data);
});
});
// code added post to update data
it("should PUT/users/:id", () => {
it("should POST/users/:id", () => {
// data to update
const data = {
status: "Active",
name: `Luffy - ${Math.floor(Math.floor() * 9999)}`,
};
return request
.put("users/132")
.set("Authorization", `Bearer ${TOKEN}`)
.send(data)
.then((res) => {
expect(res.body.data).to.deep.include(data);
});
});
//updated delete
it("should DELETE /users/:id", () =>
request
.delete("users/2")
.set("Authorization", `Bearer ${TOKEN}`)
.then((res) => {
expect(res.body.data).to.be.eq(null);
}));
it("should DELETE /users/:id", () =>
request
.delete("users/2")
.set("Authorization", `Bearer ${TOKEN}`)
.then((res) => {
expect(res.body.data).to.be.eq(null);
}));
});
|
/**
* IMPORTANT NOTE:
* Please do not use Logical Operators such as && and || which breaks the functionality in Windows8 Device.
*
* @author: Amit Gharat <amit.gharat@hurix.com>
* @modified: 29th July 2013
* @modified: 5th August 2013
*/
function getAbsolutePath(url) {
if ("unknown" == DetectBrowser()) {
return url;
} else {
var url = url.replace("./", "");
}
var loc = window.location;
var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
return loc.href.substring(0, loc.href.length - ((loc.pathname + loc.search + loc.hash).length - pathName.length)) + url;
}
function DetectBrowser() {
var val = navigator.userAgent.toLowerCase();
if (val.indexOf("firefox") > -1) {
return "firefox";
} else if (val.indexOf("opera") > -1) {
return "opera";
} else if (val.indexOf("msie") > -1) {
return "msie";
} else if (val.indexOf("safari") > -1) {
return "safari";
} else {
return "unknown";
}
}
function loadPopup(id, type, markupUrl) {
markupUrl = getAbsolutePath(markupUrl);
if ("audio" == type) {
audioBlob(markupUrl);
} else if ("image" == type) {
imageBlob(markupUrl);
} else if ("video" == type) {
videoBlob(markupUrl);
} else if ("audio_NOUI" == type) {
audioNOUIBlob(markupUrl);
}
}
function stopOnHide($markupBox) {
$markupBox.dialog({
close: function(event, ui) {
var $video = $(event.target).find('video');
var $audio = $(event.target).find('audio');
if ($video.length > 0) $video.each(function() {
$(this)[0].pause();
});
if ($audio.length > 0) $audio.each(function() {
$(this)[0].pause();
});
}
});
}
function getMarkupBox(iframeId) {
var $markupBox = '';
// If inside iframe and device is windows8
// IMP: Applicable only for Kitaboo ePub Reader - Windows8 Device
if ($('[ng-app]').length > 0) {
if (window.CONFIG.device === 'windows8') {
$markupBox = $('#' + iframeId).contents().find('body').find('#markupBox');
} else {
$markupBox = $('#markupBox');
}
} else {
$markupBox = $('#markupBox');
}
$markupBox.css('padding', '.5em 0.5em');
return $markupBox;
}
function getBody(iframeId) {
var $body = '';
// If inside iframe and device is windows8
// IMP: Applicable only for Kitaboo ePub Reader - Windows8 Device
if ($('[ng-app]').length > 0) {
if (window.CONFIG.device === 'windows8') {
$body = $('#' + iframeId).contents().find('body');
} else {
$body = $('body');
}
} else {
$body = $('body');
}
return $body;
}
function imageBlob(blob, iframeId) {
var $markupBox = getMarkupBox(iframeId);
var $body = getBody(iframeId);
var bodyWidth = $body.width();
var bodyHeight = $body.height();
var popupWidth = 0;
var popupHeight = 0;
var padding = 50;
var margin = 50;
$markupBox
.html("<img id='markupimage' src='" + blob + "'/>")
.find('#markupimage').load(function() {
popupWidth = $(this).width() + padding;
popupHeight = $(this).height() + padding;
// Add padding from left & right if an image is larger than viewport
if (popupWidth > bodyWidth) {
popupWidth = bodyWidth - margin
}
// Add padding from top & bottom if an image is larger than viewport
if (popupHeight > bodyHeight) {
popupHeight = bodyHeight - margin
}
$markupBox.dialog({
width: popupWidth,
height: popupHeight
});
}).end().dialog({});
// Delay is important
window.setTimeout(function() {
$markupBox.parent('.ui-dialog').css({
left: (bodyWidth - $markupBox.width() - padding/2) / 2,
top: (bodyHeight - $markupBox.height() - padding/2) / 2
}).end().show("slow");
}, 0);
}
function audioBlob(blob, iframeId) {
var $markupBox = getMarkupBox(iframeId);
var $body = getBody(iframeId);
var bodyWidth = $body.width();
var bodyHeight = $body.height();
var popupWidth = 0;
var popupHeight = 0;
var padding = 50;
var margin = 50;
if ($('[ng-app]').length > 0) {
if (window.CONFIG.device === 'windows8') {
$markupBox.html("<audio id='markupaudio' controls='controls'><source src='" + blob + "' type='audio/mp3'></source></audio>");
}
} else {
var type1 = blob.replace('.ogg', '.mp3');
var type2 = blob.replace('.mp3', '.ogg');
$markupBox.html("<audio id='markupaudio' controls='controls'><source src='" + type1 + "' type='audio/mp3'></source><source src='" + type2 + "' type='audio/ogg'></source></audio>");
}
$markupBox.dialog({height: 100, width: 340});
stopOnHide($markupBox);
// Delay is important
window.setTimeout(function() {
$markupBox.parent('.ui-dialog').css({
left: (bodyWidth - $markupBox.width() - padding/2) / 2,
top: (bodyHeight - $markupBox.height() - padding/2) / 2
}).end().show("slow");
}, 0);
}
function audioNOUIBlob(blob, iframeId) {
var $markupBox = getMarkupBox(iframeId);
var $body = getBody(iframeId);
var bodyWidth = $body.width();
var bodyHeight = $body.height();
var popupWidth = 0;
var popupHeight = 0;
var padding = 50;
var margin = 50;
if ($('[ng-app]').length > 0) {
if (window.CONFIG.device === 'windows8') {
$markupBox.html("<audio id='markupaudio' controls='controls'><source src='" + blob + "' type='audio/mp3'></source></audio>");
}
} else {
var type1 = blob.replace('.ogg', '.mp3');
var type2 = blob.replace('.mp3', '.ogg');
$markupBox.html("<audio id='markupaudio' controls='controls'><source src='" + type1 + "' type='audio/mp3'></source></audio>");
}
$markupBox.dialog({height: 100, width: 330}).parent('.ui-dialog').hide().find('#markupaudio')[0].play();
}
function videoBlob(blob, iframeId) {
var $markupBox = getMarkupBox(iframeId);
var $body = getBody(iframeId);
var bodyWidth = $body.width();
var bodyHeight = $body.height();
var popupWidth = 0;
var popupHeight = 0;
var padding = 50;
var margin = 50;
if ($('[ng-app]').length > 0) {
if (window.CONFIG.device === 'windows8') {
$markupBox.html("<video width='100%' controls='controls'><source src='" + blob + "' type='video/mp4'></source></video>");
}
} else {
var type1 = blob.replace('.flv', '.mp4');
// FLV format is not supported by VIDEO tag
// todo: Need an alternative
// var type2 = blob.replace('.mp4', '.flv');
// <source src='"+vtype1+"' type='video/flv'>
// @author: Amit Gharat dated 25th July 2013
$markupBox.html("<video width='100%' controls='controls'><source src='" + type1 + "' type='video/mp4'></source></video>");
}
// Resize popup once video is loaded to avoid the scrollbars
$markupBox.find('video').get(0).addEventListener('loadeddata', function() {
$markupBox.dialog({height: $markupBox.find('video').height() + 65/* header's height */, width: 370});
// Delay is important
window.setTimeout(function() {
$markupBox.parent('.ui-dialog').css({
left: (bodyWidth - $markupBox.width() - padding/2) / 2,
top: (bodyHeight - $markupBox.height() - padding/2) / 2
}).end().show("slow");
}, 0);
}, false);
$markupBox.dialog({height: 270, width: 370});
stopOnHide($markupBox);
// Delay is important
window.setTimeout(function() {
$markupBox.parent('.ui-dialog').css({
left: (bodyWidth - $markupBox.width() - padding/2) / 2,
top: (bodyHeight - $markupBox.height() - padding/2) / 2
}).end().show("slow");
}, 0);
}
|
OC.L10N.register(
"federatedfilesharing",
{
"Federated sharing" : "Partekatze federatua",
"Add to your ownCloud" : "Gehitu zure ownCloud-era",
"Invalid Federated Cloud ID" : "Hodei Federatu ID baliogabea",
"Sharing %s failed, because this item is already shared with %s" : "%s elkarbanatzeak huts egin du, dagoeneko %s erabiltzailearekin elkarbanatuta dagoelako",
"Not allowed to create a federated share with the same user" : "Ez da onartzen partekatze federatu bat sortzea erabiltzaile berdinarekin",
"File is already shared with %s" : "Fitxategia dagoeneko partekatua datgo %s-(r)ekin",
"Sharing %s failed, could not find %s, maybe the server is currently unreachable." : "%s partekatzeak huts egin du, ezin da %s aurkitu, agian zerbitzaria ez dago eskuragarri.",
"Federated Sharing failed: %s" : "Partekatze Federatuak huts egin du: %s",
"\"%1$s\" shared \"%3$s\" with you (on behalf of \"%2$s\")" : "\"%1$s\"-(e)k \"%3$s\" partekatu du zurekin (\"%2$s\"-(r)en izenean)",
"\"%1$s\" shared \"%3$s\" with you" : "\"%1$s\"-(e)k \"%3$s\" partekatu du zurekin",
"\"%1$s\" invited you to view \"%3$s\" (on behalf of \"%2$s\")" : "\"%1$s\"-(e)k \"%3$s\" ikustera gonbidatu zaitu (\"%2$s\"-(r)en izenean)",
"\"%1$s\" invited you to view \"%3$s\"" : "\"%1$s\"-(e)k \"%3$s\" ikustera gonbidatu zaitu",
"Accept" : "Onartu",
"Decline" : "Uko egin",
"Share with me through my #ownCloud Federated Cloud ID, see %s" : "Partekatu nirekin nire #ownCloud Hodei Federatu ID bidez, ikusi %s",
"Share with me through my #ownCloud Federated Cloud ID" : "Partekatu nirekin nire #ownCloud Hodei Federatu ID bidez",
"Federated Cloud Sharing" : "Federatutako Hodei Partekatzea",
"Open documentation" : "Ireki dokumentazioa",
"Allow users on this server to send shares to other servers" : "Baimendu zerbitzari honetako erabiltzaileak beste zerbitzariekin partekatzera",
"Allow users on this server to receive shares from other servers" : "Baimendu zerbitzari honetako erabiltzaileak beste zerbitzarietatik partekatutakoak jasotzen",
"Automatically accept remote shares from trusted servers" : "Automatikoki urrutiko partekatzeak onartu zerbitzari fidagarriengandik",
"Federated Cloud" : "Hodei Federatua",
"Your Federated Cloud ID:" : "Zure Hode Federatu IDa:",
"Share it:" : "Partekatu:",
"Add to your website" : "Gehitu zure webgunean",
"Share with me via ownCloud" : "Partekatu nirekin ownCloud bidez",
"HTML Code:" : "HTML Kodea:",
"Nothing to configure." : "Konfiguratzeko ezer"
},
"nplurals=2; plural=(n != 1);");
|
const fs = require('fs')
const argv = require('./argv')
const Configuration = require('./configuration/Configuration')
const lib = require('../lib')
function makeObtainOptions (args, config) {
const options = {
artifactName: args.artifact
}
if (!args.ignoreLocal) {
options.useLocalRepository = true
options.localRepository = {
path: args.localRepository
}
}
if (!args.onlyLocal) {
options.useRemoteRepository = true
const { repository } = lib.maven.parseArtifact(args.artifact)
options.remoteRepository = config.getRemoteRepositoryConfiguration(repository || lib.repository.defaultRemoteRepositoryUrl)
}
return options
}
function makeExecuteOptions (artifactPath, args) {
return {
jar: artifactPath,
arguments: args.arguments,
javaExecutable: args.javaExecutable
}
}
async function run (originalArgv) {
const parsedArgv = argv.parse(originalArgv)
lib.log.configure({ quiet: parsedArgv.quiet })
const config = await Configuration.read(parsedArgv.localRepository)
const obtainOptions = makeObtainOptions(parsedArgv, config)
let obtainedArtifact
try {
obtainedArtifact = await lib.maven.obtainArtifact(obtainOptions)
if (!obtainedArtifact) {
process.exit(1)
}
const executeOptions = makeExecuteOptions(obtainedArtifact.path, parsedArgv)
await lib.java.executeJar(executeOptions)
} finally {
if (obtainedArtifact && obtainedArtifact.temporary) {
await fs.promises.unlink(obtainedArtifact.path)
}
}
}
module.exports = {
run
}
|
var secret = require("../secret")
var config = require("../config")
var httpUtil = require('../interface/httpUtil')
var moment = require('moment')
var dbUtils = require('../mongoSkin/mongoUtils.js')
var userCollection= new dbUtils("user")
var async = require('async')
var MD5 = require("crypto-js/md5")
var redisClient = require('../redis/redis_client.js').redisClient()
//生成sessionKey
exports.getSessionKey = function (code, cb) {
var url = config.wxApiHost + '/sns/jscode2session'
var param = {
appid: secret.AppID,
secret: secret.AppSecret,
js_code: code,
grant_type: 'authorization_code'
}
httpUtil.getJSON(url, param, function (err, result) {
if (err) {
return cb(err)
}
if (result.errcode) {
return cb(result.errmsg)
}
cb(null, result)
})
}
//创建用户
exports.createUser = function (openid, cb) {
var time = new Date()
var data = {
_id: openid,
createTime: time.getTime(),
strTime: moment(time).format('YYYY-MM-DD HH:mm:ss')
}
async.auto({
check: function (cb) {
userCollection.findById(openid, function (err, result) {
if (err) {
return cb(err)
}
cb(null, result)
})
},
save: [ 'check', function (result, cb) {
var check = result.check
if (check) {
return cb()
}
userCollection.save(data, function (err, result) {
if (err) {
return cb(err)
}
cb(null, result)
})
}]
}, function (err, result) {
console.log('[%j] login.createUser ,data:%j, result:%j, err:%j', new Date().toLocaleString(),data, result,err)
if (err) {
return cb(err)
}
cb(null, result.save ? result.save._id : null)
})
}
//登录
exports.login = function (req, res) {
var code = req.param('code')
if (!code) {
return res.send(400,'参数错误')
}
async.auto({
getSessionKey: function (cb) {
exports.getSessionKey(code, function (err, result) {
if (err) {
return cb(err)
}
cb(null, result)
})
},
createUser: [ 'getSessionKey', function (result, cb) {
var openid = result.getSessionKey.openid
exports.createUser(openid, function (err, result) {
if (err) {
return cb(err)
}
cb(null, result)
})
}],
createSession: [ 'createUser', function (result, cb) {
var info = result.getSessionKey
exports.createSession(info.openid, info.session_key, function (err, result) {
if (err) {
return cb(err)
}
cb(null, result)
})
}]
}, function (err, result) {
console.log('[%j] login.login ,code:%j, result:%j, err:%j', new Date().toLocaleString(),code, result,err)
if (err) {
return res.send(400, err)
}
res.send(200, result.createSession)
})
}
//检查session
exports.checkSession = function (session, cb) {
redisClient.exsits(session, function (err, result) {
if (err) {
return cb(err)
}
cb(null,result)
})
}
//创建session
exports.createSession = function (openid,sessionKey,cb) {
var session = MD5(openid+sessionKey).toString()
var param = {
openid : openid,
sessionKey : sessionKey
}
redisClient.set(session, JSON.stringify(param), function (err) {
if (err) {
return cb(err)
}
redisClient.expire(session, 604800, function () {})
cb(null, session)
})
}
//获取本地查找微信sessionKey
exports.getSessionInfo = function (session, cb) {
redisClient.get(session, function (err, result) {
if (err) {
return cb(err)
}
if (!result) {
return cb('session已过期')
}
cb(null, result)
})
}
//更新用户信息
exports.updateUserInfo = function (req, res) {
var opneid = req.openid
var info = {
avatarUrl: req.param('avatarUrl'),
city: req.param('city'),
country: req.param('country'),
gender: req.param('gender'),
language: req.param('language'),
nickName: req.param('nickName')
}
userCollection.updateById(opneid, {$set:info}, function (err, result) {
if (err) {
return res.send(400,err)
}
res.send(200, result)
})
}
|
import React from 'react';
import PropTypes from 'prop-types';
import * as Highcharts from 'highcharts';
import HighchartsMore from 'highcharts/highcharts-more';
Highcharts.setOptions({
global: {
useUTC: false
},
lang: {
noData: 'No Data'
},
credits: {
enabled: false
}
});
HighchartsMore(Highcharts);
class ReactHighcharts extends React.Component {
static defaultProps = {
config: {}
}
static propTypes = {
config: PropTypes.object
}
componentDidMount() {
this.renderChart();
}
shouldComponentUpdate(nextProps) {
if (nextProps.config !== this.props.config) {
this.renderChart(nextProps.config);
}
return false;
}
componentWillUnmount() {
this.chart.destroy();
}
setChartRef = (chartRef) => {
this.chartRef = chartRef;
}
renderChart(config = this.props.config) {
if (!config) {
throw new Error('Config must be specified');
}
const chartConfig = config.chart;
if (this.chart) {
this.chart.destroy();
}
this.chart = new Highcharts.Chart({
title: { text: '' },
...config,
chart: {
...chartConfig,
renderTo: this.chartRef
}
});
}
render() {
const { config, ...domProps } = this.props;
return (
<div ref={this.setChartRef} {...domProps} />
);
}
}
export default ReactHighcharts;
|
import { makeActionCreator } from '../../../utils/helpers/redux';
const USER_FORGOT_PASSWORD_REQUEST = 'forgot-password/USER_FORGOT_PASSWORD_REQUEST';
const USER_FORGOT_PASSWORD_RESPONSE = 'forgot-password/USER_FORGOT_PASSWORD_RESPONSE';
const CLEAR_STATE = 'forgot-password/CLEAR_STATE';
export const userForgotPasswordRequest = makeActionCreator(USER_FORGOT_PASSWORD_REQUEST, 'request');
export const userForgotPasswordResponse = makeActionCreator(USER_FORGOT_PASSWORD_RESPONSE, 'response');
export const clearState = makeActionCreator(CLEAR_STATE, 'response');
export const ActionsTypes = {
USER_FORGOT_PASSWORD_REQUEST,
USER_FORGOT_PASSWORD_RESPONSE,
CLEAR_STATE
};
export const Actions = {
userForgotPasswordRequest,
userForgotPasswordResponse,
clearState
};
|
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const SALT_I = 10;
require('dotenv').config();
const adminSchema = mongoose.Schema(
{
email: {
type: String,
trim: true,
unique: 1
},
password: {
type: String,
trim: true
},
role: {
type: Number,
default: 0
}
},
{ timestamps: true }
);
adminSchema.pre('save', function(next) {
var admin = this;
if (admin.password) {
bcrypt.hash(admin.password, SALT_I, function(err, hash) {
if (err) return next(err);
admin.password = hash;
next();
});
} else {
next();
}
});
adminSchema.methods.comparePassword = function(candidatePassword, cb) {
let actualPassword = this.password;
bcrypt.compare(candidatePassword, actualPassword, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch, actualPassword);
});
};
const Admin = mongoose.model('Admin', adminSchema);
module.exports = Admin;
|
/**
* Created by a88u on 2016/12/9.
*/
// 力导向图,机构基金页面
var tree_force_option_nonode = {
title: {
show: false,
text: '',
x: 'right',
y: 'bottom'
},
tooltip: {
trigger: 'item',
formatter: function (data) {
//var result="hh:";
//for(var i in data.data){
// result=result+"<br>"+i+":"+data.data[i];
//}
var result = data.data.text;
//console.log(data.data);
return result;
}
},
toolbox: {
show: true,
feature: {
restore: {show: false},
magicType: {show: false, type: ['force', 'chord']},
saveAsImage: {show: true}
}
},
legend: {
x: 'left',
data: ['基金', '投资事件', '退出事件']
},
series: [
{
type: 'force',
name: "Force tree",
ribbonType: false,
categories: [
{
name: '基金'
},
{
name: '投资事件'
},
{
name: '退出事件'
}
],
itemStyle: {
normal: {
label: {
show: false,
//formatter: function (params, ticket, callback) {
// console.log(params.name, params.data);
// var res= params;
// setTimeout(function (){callback(ticket, res);}, 1000);
// return 'loading';
//},
//formatter:function (params,ticket,callback) {
//
// var result="hh:";
// for(var i in params){
// result=result+"\n"+i+":"+params[i];
// }
// alert(result);
// return result;
// //setTimeout(function (){callback(ticket, res);}, 1000);
// //return 'loading';
//}
//position:"left",
//formatter:"{a}:{c}:{d}:{b}"
},
nodeStyle: {
brushType: 'both',
borderColor: 'rgba(255,215,0,0.6)',
borderWidth: 1
},
linkStyle: { // 曲线
type: 'curve'
}
}
},
minRadius: 10,
maxRadius: 20,
nodes: [],
links: [],
steps: 1
}
]
};
var tree_force_option = {
title: {
show: false,
text: '',
x: 'right',
y: 'bottom'
},
tooltip: {
trigger: 'item',
formatter: function (data) {
//var result="hh:";
//for(var i in data.data){
// result=result+"<br>"+i+":"+data.data[i];
//}
var result = data.data.text;
//console.log(data.data);
return result;
}
},
toolbox: {
show: true,
feature: {
restore: {show: false},
magicType: {show: false, type: ['force', 'chord']},
saveAsImage: {show: true}
}
},
legend: {
x: 'left',
data: ['基金', '投资', '退出', '投资事件', '退出事件']
},
series: [
{
type: 'force',
name: "Force tree",
ribbonType: false,
categories: [
{
name: '基金'
},
{
name: '投资'
},
{
name: '退出'
},
{
name: '投资事件'
},
{
name: '退出事件'
}
],
itemStyle: {
normal: {
label: {
show: false,
//formatter: function (params, ticket, callback) {
// console.log(params.name, params.data);
// var res= params;
// setTimeout(function (){callback(ticket, res);}, 1000);
// return 'loading';
//},
//formatter:function (params,ticket,callback) {
//
// var result="hh:";
// for(var i in params){
// result=result+"\n"+i+":"+params[i];
// }
// alert(result);
// return result;
// //setTimeout(function (){callback(ticket, res);}, 1000);
// //return 'loading';
//}
//position:"left",
//formatter:"{a}:{c}:{d}:{b}"
},
nodeStyle: {
brushType: 'both',
borderColor: 'rgba(255,215,0,0.6)',
borderWidth: 1
},
linkStyle: { // 曲线
type: 'curve'
}
}
},
minRadius: 10,
maxRadius: 30,
coolDown: 0.995,
//steps: 1,
nodes: [],
links: [],
steps: 1
}
]
};
var invest_exit_tree_option = {
title: {
text: '投资-退出关系图谱',
show:false
},
toolbox: {
show: true,
feature: {
saveAsImage: {show: true}
}
},
series: [
{
name: '树图',
type: 'tree',
orient: 'horizontal', // vertical horizontal
rootLocation: {x: 100, y: 230}, // 根节点位置 {x: 100, y: 'center'}
nodePadding: 8,
layerPadding: 200,
hoverable: false,
roam: true,
symbolSize: 6,
itemStyle: {
normal: {
color: '#4883b4',
label: {
show: true,
position: 'right',
formatter: "{b}",
textStyle: {
color: '#000',
fontSize: 5
}
},
lineStyle: {
color: '#ccc',
type: 'curve' // 'curve'|'broken'|'solid'|'dotted'|'dashed'
}
},
emphasis: {
color: '#4883b4',
label: {
show: false
},
borderWidth: 0
}
},
data: []
}
]
};
|
import { useState, useEffect } from 'react';
import { useDispatch, useSelector } from "react-redux";
import { Form, Select, Input, Button } from 'antd'
import NumberFormat from "react-number-format";
import DetailExpense from '../../assets/icons/detail-expense.png'
import YourExpense from '../../assets/icons/your-expense.png'
import TakenFrom from '../../assets/icons/brangkas.svg'
import SelectIcon from '../../assets/icons/select.svg'
import './AddTransactionForm.scss'
import { getCategory } from '../../services';
import { addTransactionAsync, getCategoriesAsync, getSafesAsc2 } from '../../redux/actions';
import Loading from '../loading/Loading';
import { isThisMonth } from 'date-fns';
function AddTransactionForm({ handleOk }) {
const [categories, setCategories] = useState([])
// const [safes, setSafes] = useState([])
const dispatch = useDispatch()
const { isLoading } = useSelector(state => state.GetTransactionReducer)
const token = localStorage.getItem('token')
const safes = useSelector(
(state) => state.GetSafeReducer.safes.map(safe => ({ ...safe, createdAt: new Date(safe.createdAt) }))
.filter(safe => isThisMonth(safe.createdAt))
);
useEffect(() => {
getCategory()
.then((res) => {
setCategories(res?.data?.data)
})
.catch((error) => {
console.log(error)
})
}, [])
useEffect(() => {
dispatch(getSafesAsc2(token))
}, [])
useEffect(() => {
dispatch(getCategoriesAsync())
}, [])
const onFinish = (values) => {
dispatch(addTransactionAsync(values.category_id, values.detailExpense, values.expense, values.safe_id))
.then(res => handleOk())
};
const onFinishFailed = (errorInfo) => {
console.log('Failed:', errorInfo);
};
return (
<>
{isLoading ? <Loading /> : ''}
<Form
name='addTransaction'
layout='vertical'
onFinish={onFinish}
onFinishFailed={onFinishFailed}
>
<Form.Item
name='category_id'
label="Category"
className='category-wrapper'
>
<Select className='select-container' size='large' placeholder="Select" defaultValue='select'>
<Select.Option value="select" className='transaction-modal-default'>
<img src={SelectIcon} alt='Select' />
Select
</Select.Option>
{categories?.map((category) => {
return (
<Select.Option key={category.category_id} value={category.category_id} >
<div className='transaction-modal-select'>
<img src={category.Limit.image_url} alt={category.Limit.categoryName} />
<div style={{ flex: 1 }}>
<div className='transaction-category-title'>{category.Limit.categoryName}</div>
<div className='transaction-category-caption'>{category.Limit.caption}</div>
<div className='transaction-category-limit'>Limit: <NumberFormat
value={category.limit}
displayType="text"
thousandSeparator="."
decimalSeparator=","
prefix="Rp"
/>
</div>
</div>
</div>
</Select.Option>
)
})}
</Select>
</Form.Item>
<Form.Item
name='detailExpense'
label="Detail Expense"
className='detail-expense-label'>
{/* <p className='desc-label' >Explain to us in more detail, what are your expenses for?</p> */}
<div className='input-wrapper' >
<img src={DetailExpense} alt='Detail Expense' />
<Input placeholder='Detail Expense' size='large' />
</div>
</Form.Item>
<Form.Item
name='expense'
label="Your Expense"
rules={[
{
pattern: new RegExp(/^[0-9]+$/),
message: "Please input your expense!",
}
]}>
<div className='input-wrapper' >
<img src={YourExpense} alt='Your Expense' />
<Input size='large' prefix='Rp' type='number' min='0' />
</div>
</Form.Item>
<Form.Item
name='safe_id'
label="Taken From"
>
<Select className='select-container' size='large' placeholder="Select" defaultValue='select' >
<Select.Option value="select" className='transaction-modal-default'>
<img src={SelectIcon} alt='Select' />
Select
</Select.Option>
{safes?.map((safe) => {
return (
<Select.Option key={safe.id} value={safe.id} >
<div className='transaction-modal-safe'>
<img src={TakenFrom} alt={safe.safeName} />
<div className='transaction-safe-title'>{safe.safeName}</div>
</div>
</Select.Option>
)
})}
</Select>
</Form.Item>
<Form.Item >
<Button className='button-submit' htmlType="submit" block size='large' >
Create
</Button>
</Form.Item>
</Form>
</>
)
}
export default AddTransactionForm
|
import React, { Component } from 'react';
import {Link,Redirect} from 'react-router-dom';
import './Body.css';
class Body extends Component{
constructor(){
super();
this.state={
purpose:'instamo',
amount:0
}
}
// handler to check amount is more than Rs 9 or not
payHandler=()=>{
let amount = document.getElementById('amount-input').value;
let purpose = document.getElementById('purpose-input').value;
this.setState({
amount:amount,
})
if(purpose===''){
this.setState({
purpose:this.state.purpose
})
}
else{
this.setState({
purpose:purpose
})
}
if(amount<9)
{
let min = "<p id='min-amount'>Min amount should be Rs.9</p>";
document.getElementById('min-cond').innerHTML=min;
}
if(amount>=9){
document.getElementById('min-cond').style.display='none';
localStorage.setItem('amount',amount)
localStorage.setItem('purpose',purpose)
return <Link to='your-details'/>
}
}
render(){
return(
<div className='body'>
<div id='purpose'><label>purpose of payment</label></div>
<input id='purpose-input' type='text' value={this.state.purpose} onChange={(e)=>this.setState({purpose:e.target.value})}></input>
<div id='amount'><label>Amount</label></div>
<input id='amount-input' type='number'></input>
<div id='min-cond'></div>
<button onClick={this.payHandler}>pay</button>
{
this.state.amount>=9?
<Redirect to={{
pathname: '/your-details',
state:{
name:this.state.purpose,
amount:this.state.amount
}
}}/>
:null
}
</div>
);
}
}
export default Body;
|
import firebase, {db} from '../firebase'
export default function LogIn() {
return new Promise((resolve, reject) => {
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then(result => {
console.log(result.user.displayName)
resolve(result.user.displayName)
}).catch(function (error) {
// Handle Errors here.
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
db.collection("LoginErrors").doc(email).set(
{
errorMessage: errorMessage,
email: email,
credential: credential
}
)
});
});
}
|
define("gui", ["expose"], function(expose){
var _main,
_synchIcon,
_loginName;
function init(main){
_main = main;
_synchIcon = $("#synch")[0];
_loginName = $("#loginName");
$("#loginForm").on("submit", onPlayClicked);
$("a[href=#play]").on("click", onPlayClicked);
$("a[href=#login]").on("click", onLoginClicked);
$("a[href=#highscore]").on("click", onHighscoreClicked);
$("#synch").on("click", onSynchClicked);
_loginName.val(localStorage.getItem("name"));
$(window).on("load", function(){setTimeout(scrollTo, 0, 0, 1);});
$(window).on("orientationchange", function(){scrollTo(0,1);});
setTimeout(function(){
if(document.location.hash.indexOf("#play") === 0){
onPlayClicked({preventDefault:function(){}});
}
}, 100);
}
function showLogin(){
showSection($("#login"));
};
function showScore(){
showSection($("#score"));
};
function showPlay(){
showSection($("#play"));
};
function populateScores(scores){
var list = $("#score ul");
list.empty();
for(var i=0; i<scores.length; i++){
list.append("<li>"+scores[i].name+"<span>"+scores[i].score+"</span></li>");
}
};
function synchStarted(){
_synchIcon.className = "synch";
};
function synchFailed(){
_synchIcon.className = "warning";
};
function synchCompleted(){
_synchIcon.className = "ok";
};
function onLoginClicked(e){
showLogin();
e.preventDefault();
return false;
};
function onPlayClicked(e){
var form = $("#loginForm");
if(form[0].checkValidity()){
_main.startPlay(_loginName.val());
form.removeClass("invalid");
localStorage.setItem("name", _loginName.val());
setTimeout(function(){_loginName.blur()},1);
}else{
form.addClass("invalid");
}
e.preventDefault();
return false;
};
function onHighscoreClicked(e){
_main.synchScores();
showScore();
e.preventDefault();
return false;
};
function onSynchClicked(e){
_main.synchScores();
e.preventDefault();
return false;
};
function showSection(section){
$(".current").toggleClass("current");
section.toggleClass("current");
};
return expose(init,
showLogin,
showPlay,
showScore,
synchStarted,
synchFailed,
synchCompleted,
populateScores);
});
|
import staffData from '../../helpers/data/staffsData';
import staffBuilder from '../staffBuilder/staffBuilder';
const deleteStaffMember = (e) => {
const staffMemberId = e.target.id;
staffData.deleteStaffCard(staffMemberId)
.then(() => {
staffBuilder.printStaffCards();
})
.catch((error) => console.error(error));
};
export default { deleteStaffMember };
|
const fs = require('fs')
var db = require('./mongoCollections')
var Picture_DB = db.collection_picture()
function getExtensionOfFilename(filename) {
var _fileLen = filename.length;
var _lastDot = filename.lastIndexOf('.');
var _fileExt = filename.substring(_lastDot, _fileLen).toLowerCase();
return _fileExt;
}
module.exports = {
createPicture: function(req, res){
var newPicture = new Picture_DB({
path : req.file.path,
contentsType : getExtensionOfFilename(req.file.path)
})
newPicture.save(function(err, picture){
if (err) res.send(err)
res.json(picture);
})
},
updatePicture: function (req, res) {
Picture_DB.findById(req.body.picture_id, function(err, picture){
if (err) res.send(err)
pastPath = picture.path
picture.path = req.file.path
picture.contentsType = getExtensionOfFilename(req.file.path)
picture.save(function(err2, updatedPicture){
if (err2) res.send(err2)
fs.unlink(pastPath, function(err3){
if (err3) res.send(err3)
res.json(updatedPicture)
})
})
})
}
}
|
import { SET_USER } from '../actions'
const initialState = {}
export default function modal(state = initialState, action) {
switch(action.type) {
case SET_USER:
return Object.assign({}, state, action.user)
default:
return state
}
}
|
(function () {
'use strict';
var myApp = angular.module("list"); //Music corresponds to the module//
myApp.controller("dataControl", function($scope, $http,$window) { //Scope defines variables that can be accessed through HTML//
//data on songs
$http.get("getlists.php")
.then(function(response){
$scope.data = response.data.value;
});
//Acount Related Functions
//Save new account
$scope.newAccount = function(accountDetails) {
var account = angular.copy(accountDetails);
$http.post("newaccount.php", account)
.then(function (response) {
if (response.status == 200) {
if (response.data.status == 'error') {
alert ('error: ' + response.data.message);
} else {
//successful
$window.location.href ="index.html";
}
} else {
alert('unexpected error');
}
});
};
// save list
$scope.saveList = function(listDetails) {
var list = angular.copy(listDetails);
$http.post("savelist.php", list)
.then(function (response) {
if (response.status == 200) {
if (response.data.status == 'error') {
alert ('error: ' + response.data.message);
} else {
//successful
$window.location.href ="addItemName.html";
}
} else {
alert('unexpected error');
}
});
};
// add to list
$scope.addToItem = function(listDetails) {
var list = angular.copy(listDetails);
$http.post("addToItem.php", list)
.then(function (response) {
if (response.status == 200) {
if (response.data.status == 'error') {
alert ('error: ' + response.data.message);
} else {
//successful
$window.location.href ="addList2.html";
}
} else {
alert('unexpected error');
}
});
};
// add to attribute
$scope.addToAttribute = function(listDetails) {
var list = angular.copy(listDetails);
$http.post("addToAttribute.php", list)
.then(function (response) {
if (response.status == 200) {
if (response.data.status == 'error') {
alert ('error: ' + response.data.message);
} else {
//successful
$window.location.href ="addList2.html";
}
} else {
alert('unexpected error');
}
});
};
// vote up on list
$scope.voteList = function(listid) {
$http.post("vote.php", {"vote":"1", "listid":listid})
.then(function (response) {
if (response.status == 200) {
if (response.data.status == 'error') {
alert ('error: ' + response.data.message);
} else {
//successful
$window.location.href ="index.html";
}
} else {
alert('unexpected error');
}
});
};
// vote down on list
$scope.voteDownList = function(listid) {
$http.post("votedown.php", {"vote":"-1", "listid":listid})
.then(function (response) {
if (response.status == 200) {
if (response.data.status == 'error') {
alert ('error: ' + response.data.message);
} else {
//successful
$window.location.href ="index.html";
}
} else {
alert('unexpected error');
}
});
};
// logs in
$scope.login = function(credentialDetails) {
var credentials = angular.copy(credentialDetails);
$http.post("log-in.php", credentials)
.then(function (response) {
if (response.status == 200) {
if (response.data.status == 'error') {
alert ('error: ' + response.data.message);
} else {
//successful
$window.location.href ="index.html";
}
} else {
alert('unexpected error');
}
});
};
// function to delete a list
$scope.deleteList = function(listName, id){
if(confirm("Are you sure you want to delete " + listName +"?")){
$http.post("deletelist.php", {"id" : id})
.then(function(response){
if(response.status == 200){
if(response.data.status == 'error'){
alert ('error: ' + response.data.message);
} else{
//successful
$window.location.href ="index.html";
}
} else{
alert('unexpected error');
}
});
}
};
// function to delete a item
$scope.deleteItem = function(name, id){
if(confirm("Are you sure you want to delete " + name +"?")){
$http.post("deleteitem.php", {"id" : id})
.then(function(response){
if(response.status == 200){
if(response.data.status == 'error'){
alert ('error: ' + response.data.message);
} else{
//successful
$window.location.href ="index.html";
}
} else{
alert('unexpected error');
}
});
}
};
// logs out
$scope.logout = function() {
$http.post("log-out.php")
.then(function (response) {
if (response.status == 200) {
if (response.data.status == 'error') {
alert ('error: ' + response);
} else {
//successful
$window.location.href ="index.html";
}
} else {
alert('unexpected error');
}
});
};
// is logged in
$scope.isloggedin = function() {
$http.post("is-log-in.php")
.then(function (response) {
if (response.status == 200) {
if (response.data.status == 'error') {
alert ('error: ' + response.data.message);
} else {
//successful
// return whether logged in or not
$scope.isloggedin = response.data.loggedin;
}
} else {
alert('unexpected error');
}
});
};
// get session variable
$scope.getSessionVariable = function(attribute) {
$http.post("getsessionvariable.php", attribute)
.then(function (response) {
if (response.status == 200) {
if (response.data.status == 'error') {
alert ('error: ' + response.data.message);
} else {
//successful
// return value of attribute
return response.data.value;
}
} else {
alert('unexpected error');
}
});
};
// set session variable
$scope.setSessionVariable = function(attribute, value) {
$http.post("setsessionvariable.php", {"attribute": attribute, "value":value})
.then(function (response) {
if (response.status == 200) {
if (response.data.status == 'error') {
alert ('error: ' + response.data.message);
} else {
//successful
return true;
}
} else {
alert('unexpected error');
}
});
};
//Updates the list name
$scope.updateList = function(listDetails){
var list = angular.copy(listDetails);
$http.post("editlistname.php", list)
.then(function(response){
if(response.status == 200){
if(response.data.status == 'error'){
alert ('error: ' + response.data.message);
} else{
//successful
$window.location.href ="index.html";
}
} else{
alert('unexpected error');
}
});
};
//Edit item
$scope.updateItem = function(listDetails){
var list = angular.copy(listDetails);
$http.post("editItemName.php", list)
.then(function(response){
if(response.status == 200){
if(response.data.status == 'error'){
alert ('error: ' + response.data.message);
} else{
//successful
$window.location.href ="addList2.html";
}
} else{
alert('unexpected error');
}
});
};
$scope.updateAttribute = function(listDetails){
var list = angular.copy(listDetails);
$http.post("editAttribute.php", list)
.then(function(response){
if(response.status == 200){
if(response.data.status == 'error'){
alert ('error: ' + response.data.message);
} else{
//successful
$window.location.href ="index.html";
}
} else{
alert('unexpected error');
}
});
};
$scope.setEditMode= function(on,item){
if(on){
//put in edit mode
$scope.editlist= angular.copy(item);
item.editMode =true;
}else{
//no edit
item.editMode = false;
}
};
//returns editMode for the current item
$scope.getEditMode = function(item){
return item.editMode;
};
//These are variables used for the search bar//
$scope.query ={};
$scope.queryBy = "$";
//variable that tells us which menu item should be highlighted
$scope.menuHighlight = 0;
});
} )();
|
import firebase from 'firebase';
export default function FirebaseInstance() {
if (firebase.apps.length === 0) {
// Configure Firebase.
const config = {
apiKey: 'AIzaSyASs_Hf1R0pib5FErgK-4nTGYWnxvTU5JY',
authDomain: 'triberelations-94f8c.firebaseapp.com',
projectId: 'triberelations-94f8c',
storageBucket: 'triberelations-94f8c.appspot.com',
messagingSenderId: '552371995257',
appId: '1:552371995257:web:b64373a66e4064fcc5caa8',
measurementId: 'G-54KEQ9T435',
};
globalThis.firebase = firebase.initializeApp(config);
}
return globalThis.firebase;
}
|
export default {
verifiCode: null, // 验证码
shuldLoginFormShow: false,
loginFormType: 'login', // <'login'|'regist'|'authentication_student'|'authentication_teacher'|'authentication_company'>
userInfo: {}, // 用户信息
isShowSave: true,
isLogin: false, // 是否登录
mobilePhone: '', // 注册手机号码
password: '', // 注册密码
nextActiveone: false,
nextActivetwo: false,
attestationShow: true,
headIsShow: false, //控制头像是否为编辑状态
nameIsShow: false, //控制用户名是否为编辑状态
sexIsShow: false, //控制性别是否为编辑状态
accountStudent: {}, //实名认证的个人信息
schoolTakeList: '',
homeSchoolList: [],
schoolimages: {},
}
|
import React from "react";
import { AppSidebarWrapper } from "../styles/base";
import uuid from "uuid";
import ProjectTree from "./ProjectTree";
import { connect } from "react-redux";
import { importProject } from "../actions/projectActions";
class AppSidebar extends React.Component {
handleClick = e => {
e.preventDefault();
const { dialog } = window.require("electron").remote;
let path = dialog.showOpenDialog({ properties: ["openDirectory"] });
let split_path = path[0].split("/");
let project_name = split_path[split_path.length - 1];
console.log(split_path, project_name);
let project = {
id: uuid(),
name: project_name,
path: path[0],
};
this.props.importProject(project);
};
render() {
const { projects } = this.props;
console.log("got all projects", projects);
return (
<AppSidebarWrapper>
<div style={styles.container}>
<div className="projects-container">
{projects && <ProjectTree projects={projects} />}
</div>
<button
style={styles.createProject}
onClick={this.handleClick.bind(this)}
>
Add project
</button>
</div>
</AppSidebarWrapper>
);
}
}
const styles = {
container: {
padding: "15px 0",
display: "flex",
flexDirection: "column",
height: "100vh",
justifyContent: "space-between",
},
createProject: {
background: "#8BC34A",
textTransform: "uppercase",
color: "#fff",
padding: "15px 55px",
fontWeight: 500,
letterSpacing: "1px",
cursor: "pointer",
marginLeft: "auto",
marginRight: "auto",
border: "0",
borderRadius: "5px",
},
};
const mapStateToProps = state => ({
projects: state.projects.projects,
});
export default connect(
mapStateToProps,
{ importProject },
)(AppSidebar);
|
import React from 'react'
import { connect } from 'react-redux'
import { Field, reduxForm } from 'redux-form'
import { transactionRequest } from './actions.js'
import settings from './../../util/settings.js'
const submit = (data, state, props)=>{
props.transactionRequest(data)
}
const SimpleForm = (props) => {
const { handleSubmit, pristine, reset, submitting } = props
return (
<form onSubmit={handleSubmit(submit)}>
<div>
<label>Ethereum Address</label>
<div>
<Field name="ethAddress" component="textarea" value="0xbbD63Bae82A8c720583aa491ad875564Bc4B393f"
style={{
width: "260px"
}}
/>
</div>
</div>
<div>
<button type="submit" disabled={submitting}>Submit</button>
<button type="button" disabled={pristine || submitting} onClick={reset}>Clear Values</button>
</div>
</form>
)
}
const mapStateToProps = (state, props) => {
return {
initialValues: {
ethAddress: settings.ethAddressDefault
}
}
}
const mapDispatchToProps = (dispatch) => {
return {
transactionRequest: (data) => {
event.preventDefault();
dispatch(transactionRequest(data))
}
}
}
const Form = reduxForm({
form: 'simple' // a unique identifier for this form
})(SimpleForm)
export default connect(
mapStateToProps,
mapDispatchToProps
)(Form);
|
var delay;
var editor;
var codeviewReadyDelay;
var preview;
var previewFrame;
function updatePreview() {
if (document.getElementById('preview')) {
var previewFrame = document.getElementById('preview');
var preview = previewFrame.contentDocument || previewFrame.contentWindow.document;
preview.open();
preview.write(editor.getValue());
preview.close();
}
}
function initCodeview () {
console.log('initCodeview');
// Initialize CodeMirror editor with a nice html5 canvas demo.
editor = CodeMirror.fromTextArea(document.getElementById('code'), {
mode: 'text/html',
tabMode: 'indent',
theme: 'default',
lineNumbers: true,
onChange: function() {
clearTimeout(delay);
delay = setTimeout(updatePreview, 300);
}
});
setTimeout(updatePreview, 300);
jQuery(".cb-codeview").colorbox({
inline: true, width:"90%", height: "90%",
onComplete:function(){
var listingNumber = $(this).data('listing');
var codeObj = codeListings[listingNumber];
editor.setValue(codeObj.code);
jQuery('#code-view-source h1').html('Listing ' + listingNumber + ': ' + codeObj.title);
},
onClosed:function(){
editor.setValue('');
jQuery('#code-view-source h1').html('');
}
});
console.log('codeview initialized');
}
function codeviewReady() {
clearTimeout(codeviewReadyDelay);
if($('.ignore-me').length && $('a.cb-codeview').length && $('#preview').length) {
initCodeview();
} else {
codeviewReadyDelay = setTimeout(codeviewReady, 100);
}
}
var codeListings = {
'2-6': {
'title': 'Diagonal line example',
'code': '<!DOCTYPE html>\n' +
'<html>\n' +
' <title>Diagonal line example</title>\n' +
'\n' +
' <canvas id="diagonal" style="border: 1px solid;" width="200" height="200"></canvas>\n' +
' <script>\n' +
' function drawDiagonal() {\n' +
' // Get the canvas element and its drawing context\n' +
' var canvas = document.getElementById(\'diagonal\');\n' +
' var context = canvas.getContext(\'2d\');\n' +
'\n' +
' // Create a path in absolute coordinates\n' +
' context.beginPath();\n' +
' context.moveTo(70, 140);\n' +
' context.lineTo(140, 70);\n' +
'\n' +
' // Stroke the line onto the canvas\n' +
' context.stroke();\n' +
' }\n' +
'\n' +
' window.addEventListener("load", drawDiagonal, true);\n' +
' </scr' + 'ipt>\n' +
'</html>\n'
},
'2-7': {
'title': 'Translated diagonal line example',
'code': '<!DOCTYPE html>\n' +
'<html>\n' +
' <title>Translated diagonal line example</title>\n' +
'\n' +
' <canvas id="diagonal" style="border: 1px solid;" width="200" height="200"></canvas>\n' +
' <script>\n' +
' function drawDiagonal() {\n' +
' var canvas = document.getElementById(\'diagonal\');\n' +
' var context = canvas.getContext(\'2d\');\n' +
'\n' +
' // Save a copy of the current drawing state\n' +
' context.save();\n' +
'\n' +
' // Move the drawing context to the right, and down\n' +
' context.translate(70, 140);\n' +
'\n' +
' // Draw the same line as before, but using the origin as a start\n' +
' context.beginPath();\n' +
' context.moveTo(0, 0);\n' +
' context.lineTo(70, -70);\n' +
' context.stroke();\n' +
'\n' +
' // Restore the old drawing state\n' +
' context.restore();\n' +
' }\n' +
'\n' +
' window.addEventListener("load", drawDiagonal, true);\n' +
' </scr' + 'ipt>\n' +
'</html>\n'
},
'2-9': {
'title': 'Closed path example',
'code': '<!DOCTYPE html>\n' +
'<html>\n' +
' <title>Closed path example</title>\n' +
'\n' +
' <canvas id="trails" style="border: 1px solid;" width="400" height="600"> </canvas>\n' +
' <script>\n' +
' function createCanopyPath(context) {\n' +
' // Draw the tree canopy\n' +
' context.beginPath();\n' +
'\n' +
' context.moveTo(-25, -50);\n' +
' context.lineTo(-10, -80);\n' +
' context.lineTo(-20, -80);\n' +
' context.lineTo(-5, -110);\n' +
' context.lineTo(-15, -110);\n' +
'\n' +
' // Top of the tree\n' +
' context.lineTo(0, -140);\n' +
'\n' +
' context.lineTo(15, -110);\n' +
' context.lineTo(5, -110);\n' +
' context.lineTo(20, -80);\n' +
' context.lineTo(10, -80);\n' +
' context.lineTo(25, -50);\n' +
'\n' +
' // Close the path back to its start point\n' +
' context.closePath();\n' +
' }\n' +
'\n' +
' function drawTrails() {\n' +
' var canvas = document.getElementById(\'trails\');\n' +
' var context = canvas.getContext(\'2d\');\n' +
'\n' +
' context.save();\n' +
' context.translate(130, 250);\n' +
'\n' +
' // Create the shape for our canopy path\n' +
' createCanopyPath(context);\n' +
'\n' +
' // Stroke the current path\n' +
' context.stroke();\n' +
' context.restore();\n' +
' }\n' +
'\n' +
' window.addEventListener("load", drawTrails, true);\n' +
' </scr' + 'ipt>\n' +
'</html>\n'
},
'2-10': {
'title': 'Stroke style example',
'code': '<!DOCTYPE html>\n' +
'<html>\n' +
' <title>Stroke style example</title>\n' +
'\n' +
' <canvas id="trails" style="border: 1px solid;" width="400" height="600"> </canvas>\n' +
' <script>\n' +
' function createCanopyPath(context) {\n' +
' context.beginPath();\n' +
' context.moveTo(-25, -50);\n' +
' context.lineTo(-10, -80);\n' +
' context.lineTo(-20, -80);\n' +
' context.lineTo(-5, -110);\n' +
' context.lineTo(-15, -110);\n' +
'\n' +
' context.lineTo(0, -140);\n' +
'\n' +
' context.lineTo(15, -110);\n' +
' context.lineTo(5, -110);\n' +
' context.lineTo(20, -80);\n' +
' context.lineTo(10, -80);\n' +
' context.lineTo(25, -50);\n' +
' context.closePath();\n' +
' }\n' +
'\n' +
' function drawTrails() {\n' +
' var canvas = document.getElementById(\'trails\');\n' +
' var context = canvas.getContext(\'2d\');\n' +
'\n' +
' context.save();\n' +
' context.translate(130, 250);\n' +
'\n' +
' createCanopyPath(context);\n' +
'\n' +
' // Increase the line width\n' +
' context.lineWidth = 4;\n' +
'\n' +
' // Round the corners at path joints\n' +
' context.lineJoin = \'round\';\n' +
'\n' +
' // Change the color to brown\n' +
' context.strokeStyle = \'#663300\';\n' +
'\n' +
' context.stroke();\n' +
' context.restore();\n' +
' }\n' +
'\n' +
' window.addEventListener("load", drawTrails, true);\n' +
' </scr'+ 'ipt>\n' +
'</html>\n'
},
'2-11': {
'title': 'Fill style example',
'code': '<!DOCTYPE html>' +
'<html>\n' +
' <title>Fill style example</title>\n' +
'\n' +
' <canvas id="trails" style="border: 1px solid;" width="400" height="600"> </canvas>\n' +
' <script>\n' +
' function createCanopyPath(context) {\n' +
' context.beginPath();\n' +
' context.moveTo(-25, -50);\n' +
' context.lineTo(-10, -80);\n' +
' context.lineTo(-20, -80);\n' +
' context.lineTo(-5, -110);\n' +
' context.lineTo(-15, -110);\n' +
'\n' +
' context.lineTo(0, -140);\n' +
'\n' +
' context.lineTo(15, -110);\n' +
' context.lineTo(5, -110);\n' +
' context.lineTo(20, -80);\n' +
' context.lineTo(10, -80);\n' +
' context.lineTo(25, -50);\n' +
' context.closePath();\n' +
' }\n' +
'\n' +
' function drawTrails() {\n' +
' var canvas = document.getElementById(\'trails\');\n' +
' var context = canvas.getContext(\'2d\');\n' +
'\n' +
' context.save();\n' +
' context.translate(130, 250);\n' +
'\n' +
' createCanopyPath(context);\n' +
'\n' +
' context.lineWidth = 4;\n' +
' context.lineJoin = \'round\';\n' +
' context.strokeStyle = \'#663300\';\n' +
' context.stroke();\n' +
'\n' +
' // Set the fill color to green and fill the canopy\n' +
' context.fillStyle = \'#339900\';\n' +
' context.fill();\n' +
'\n' +
' context.restore();\n' +
' }\n' +
'\n' +
' window.addEventListener("load", drawTrails, true);\n' +
' </scr' + 'ipt>\n' +
'</html>\n'
},
'2-12': {
'title': 'Fill rectangle example',
'code': '<!DOCTYPE html>\n' +
'<html>\n' +
' <title>Fill rectangle example</title>\n' +
'\n' +
' <canvas id="trails" style="border: 1px solid;" width="400" height="600"> </canvas>\n' +
' <script>\n' +
' function createCanopyPath(context) {\n' +
' context.beginPath();\n' +
' context.moveTo(-25, -50);\n' +
' context.lineTo(-10, -80);\n' +
' context.lineTo(-20, -80);\n' +
' context.lineTo(-5, -110);\n' +
' context.lineTo(-15, -110);\n' +
'\n' +
' context.lineTo(0, -140);\n' +
'\n' +
' context.lineTo(15, -110);\n' +
' context.lineTo(5, -110);\n' +
' context.lineTo(20, -80);\n' +
' context.lineTo(10, -80);\n' +
' context.lineTo(25, -50);\n' +
' context.closePath();\n' +
' }\n' +
'\n' +
' function drawTrails() {\n' +
' var canvas = document.getElementById(\'trails\');\n' +
' var context = canvas.getContext(\'2d\');\n' +
'\n' +
' context.save();\n' +
' context.translate(130, 250);\n' +
'\n' +
' createCanopyPath(context);\n' +
'\n' +
' context.lineWidth = 4;\n' +
' context.lineJoin = \'round\';\n' +
' context.strokeStyle = \'#663300\';\n' +
' context.stroke();\n' +
'\n' +
' context.fillStyle = \'#339900\';\n' +
' context.fill();\n' +
'\n' +
' // Change fill color to brown\n' +
' context.fillStyle = \'#663300\';\n' +
'\n' +
' // Fill a rectangle for the tree trunk\n' +
' context.fillRect(-5, -50, 10, 50);\n' +
'\n' +
' context.restore();\n' +
' }\n' +
'\n' +
' window.addEventListener("load", drawTrails, true);\n' +
' </scr' + 'ipt>\n' +
'</html>\n'
},
'2-13': {
'title': 'Curve example',
'code': '<!DOCTYPE html>\n' +
'<html>\n' +
' <title>Curve example</title>\n' +
'\n' +
' <canvas id="trails" style="border: 1px solid;" width="400" height="600"> </canvas>\n' +
' <script>\n' +
' function createCanopyPath(context) {\n' +
' context.beginPath();\n' +
' context.moveTo(-25, -50);\n' +
' context.lineTo(-10, -80);\n' +
' context.lineTo(-20, -80);\n' +
' context.lineTo(-5, -110);\n' +
' context.lineTo(-15, -110);\n' +
'\n' +
' context.lineTo(0, -140);\n' +
'\n' +
' context.lineTo(15, -110);\n' +
' context.lineTo(5, -110);\n' +
' context.lineTo(20, -80);\n' +
' context.lineTo(10, -80);\n' +
' context.lineTo(25, -50);\n' +
' context.closePath();\n' +
' }\n' +
'\n' +
' function drawTrails() {\n' +
' var canvas = document.getElementById(\'trails\');\n' +
' var context = canvas.getContext(\'2d\');\n' +
'\n' +
' context.save();\n' +
' context.translate(130, 250);\n' +
'\n' +
' createCanopyPath(context);\n' +
'\n' +
' context.lineWidth = 4;\n' +
' context.lineJoin = \'round\';\n' +
' context.strokeStyle = \'#663300\';\n' +
' context.stroke();\n' +
'\n' +
' context.fillStyle = \'#339900\';\n' +
' context.fill();\n' +
'\n' +
' context.fillStyle = \'#663300\';\n' +
' context.fillRect(-5, -50, 10, 50);\n' +
'\n' +
' context.restore();\n' +
'\n' +
' // Save the canvas state and draw the path\n' +
' context.save();\n' +
'\n' +
' context.translate(-10, 350);\n' +
' context.beginPath();\n' +
'\n' +
' // The first curve bends up and right\n' +
' context.moveTo(0, 0);\n' +
' context.quadraticCurveTo(170, -50, 260, -190);\n' +
'\n' +
' // The second curve continues down and right\n' +
' context.quadraticCurveTo(310, -250, 410,-250);\n' +
'\n' +
' // Draw the path in a wide brown stroke\n' +
' context.strokeStyle = \'#663300\';\n' +
' context.lineWidth = 20;\n' +
' context.stroke();\n' +
'\n' +
' // Restore the previous canvas state\n' +
' context.restore();\n' +
' }\n' +
'\n' +
' window.addEventListener("load", drawTrails, true);\n' +
' </scr' + 'ipt>\n' +
'</html>\n'
},
'2-15': {
'title':'Image example',
'code': '<!DOCTYPE html>\n' +
'<html>\n' +
' <title>Image example</title>\n' +
'\n' +
' <canvas id="trails" style="border: 1px solid;" width="400" height="600"> </canvas>\n' +
' <script>\n' +
' // Load the bark image\n' +
' var bark = new Image();\n' +
' bark.src = "bark.jpg";\n' +
'\n' +
' // Once the image is loaded, draw on the canvas\n' +
' bark.onload = function () {\n' +
' drawTrails();\n' +
' }\n' +
'\n' +
' function createCanopyPath(context) {\n' +
' context.beginPath();\n' +
' context.moveTo(-25, -50);\n' +
' context.lineTo(-10, -80);\n' +
' context.lineTo(-20, -80);\n' +
' context.lineTo(-5, -110);\n' +
' context.lineTo(-15, -110);\n' +
'\n' +
' context.lineTo(0, -140);\n' +
'\n' +
' context.lineTo(15, -110);\n' +
' context.lineTo(5, -110);\n' +
' context.lineTo(20, -80);\n' +
' context.lineTo(10, -80);\n' +
' context.lineTo(25, -50);\n' +
' context.closePath();\n' +
' }\n' +
'\n' +
' function drawTrails() {\n' +
' var canvas = document.getElementById(\'trails\');\n' +
' var context = canvas.getContext(\'2d\');\n' +
'\n' +
' context.save();\n' +
' context.translate(130, 250);\n' +
'\n' +
' createCanopyPath(context);\n' +
'\n' +
' context.lineWidth = 4;\n' +
' context.lineJoin = \'round\';\n' +
' context.strokeStyle = \'#663300\';\n' +
' context.stroke();\n' +
'\n' +
' context.fillStyle = \'#339900\';\n' +
' context.fill();\n' +
'\n' +
' // Draw the bark pattern image where\n' +
' // the filled rectangle was before\n' +
' context.drawImage(bark, -5, -50, 10, 50);\n' +
'\n' +
' context.restore();\n' +
'\n' +
' context.save();\n' +
' context.translate(-10, 350);\n' +
' context.beginPath();\n' +
' context.moveTo(0, 0);\n' +
' context.quadraticCurveTo(170, -50, 260, -190);\n' +
' context.quadraticCurveTo(310, -250, 410,-250);\n' +
' context.strokeStyle = \'#663300\';\n' +
' context.lineWidth = 20;\n' +
' context.stroke();\n' +
' context.restore();\n' +
' }\n' +
'\n' +
' </scr' + 'ipt>\n' +
'</html>\n'
},
'2-16': {
'title': 'Gradient example',
'code': '<!DOCTYPE html>\n' +
'<html>\n' +
' <title>Gradient example</title>\n' +
'\n' +
' <canvas id="trails" style="border: 1px solid;" width="400" height="600"> </canvas>\n' +
' <script>\n' +
' var gravel = new Image();\n' +
' gravel.src = "gravel.jpg";\n' +
' gravel.onload = function () {\n' +
' drawTrails();\n' +
' }\n' +
'\n' +
' function createCanopyPath(context) {\n' +
' context.beginPath();\n' +
' context.moveTo(-25, -50);\n' +
' context.lineTo(-10, -80);\n' +
' context.lineTo(-20, -80);\n' +
' context.lineTo(-5, -110);\n' +
' context.lineTo(-15, -110);\n' +
'\n' +
' context.lineTo(0, -140);\n' +
'\n' +
' context.lineTo(15, -110);\n' +
' context.lineTo(5, -110);\n' +
' context.lineTo(20, -80);\n' +
' context.lineTo(10, -80);\n' +
' context.lineTo(25, -50);\n' +
' context.closePath();\n' +
' }\n' +
'\n' +
' function drawTrails() {\n' +
' var canvas = document.getElementById(\'trails\');\n' +
' var context = canvas.getContext(\'2d\');\n' +
'\n' +
' context.save();\n' +
' context.translate(130, 250);\n' +
'\n' +
' // Create a 3 stop gradient horizontally across the trunk\n' +
' var trunkGradient = context.createLinearGradient(-5, -50, 5, -50);\n' +
'\n' +
' // The beginning of the trunk is medium brown\n' +
' trunkGradient.addColorStop(0, \'#663300\');\n' +
'\n' +
' // The middle-left of the trunnk is lighter in color\n' +
' trunkGradient.addColorStop(0.4, \'#996600\');\n' +
'\n' +
' // The right edge of the trunk is darkest\n' +
' trunkGradient.addColorStop(1, \'#552200\');\n' +
'\n' +
' // Apply the gradient as the fill style, and draw the trunk\n' +
' context.fillStyle = trunkGradient;\n' +
' context.fillRect(-5, -50, 10, 50);\n' +
'\n' +
'\n' +
' // A second, vertical gradient creates a shadow from the\n' +
' // canopy on the trunk\n' +
' var canopyShadow = context.createLinearGradient(0, -50, 0, 0);\n' +
'\n' +
' // The beginning of the shadow gradient is black, but with\n' +
' // a 50% alpha value\n' +
' canopyShadow.addColorStop(0, \'rgba(0, 0, 0, 0.5)\');\n' +
'\n' +
' // Slightly further down, the gradient completely fades to\n' +
' // fully transparent. The rest of the trunk gets no shadow.\n' +
' canopyShadow.addColorStop(0.2, \'rgba(0, 0, 0, 0.0)\');\n' +
'\n' +
' // Draw the shadow gradient on top of the trunk gradient\n' +
' context.fillStyle = canopyShadow;\n' +
' context.fillRect(-5, -50, 10, 50);\n' +
'\n' +
' createCanopyPath(context);\n' +
'\n' +
' context.lineWidth = 4;\n' +
' context.lineJoin = \'round\';\n' +
' context.strokeStyle = \'#663300\';\n' +
' context.stroke();\n' +
'\n' +
' context.fillStyle = \'#339900\';\n' +
' context.fill();\n' +
'\n' +
' context.restore();\n' +
'\n' +
' context.save();\n' +
' context.translate(-10, 350);\n' +
' context.beginPath();\n' +
' context.moveTo(0, 0);\n' +
' context.quadraticCurveTo(170, -50, 260, -190);\n' +
' context.quadraticCurveTo(310, -250, 410,-250);\n' +
' context.strokeStyle = \'#663300\';\n' +
' context.lineWidth = 20;\n' +
' context.stroke();\n' +
' context.restore();\n' +
' }\n' +
'\n' +
' </scr' + 'ipt>\n' +
'</html>\n'
},
'2-18': {
'title':'Pattern example',
'code': '<!DOCTYPE html>\n' +
'<html>\n' +
' <title>Pattern example</title>\n' +
'\n' +
' <canvas id="trails" style="border: 1px solid;" width="400" height="600"> </canvas>\n' +
' <script>\n' +
' // Replace the bark image with\n' +
' // a trail gravel image\n' +
' var gravel = new Image();\n' +
' gravel.src = "gravel.jpg";\n' +
' gravel.onload = function () {\n' +
' drawTrails();\n' +
' }\n' +
'\n' +
' function createCanopyPath(context) {\n' +
' context.beginPath();\n' +
' context.moveTo(-25, -50);\n' +
' context.lineTo(-10, -80);\n' +
' context.lineTo(-20, -80);\n' +
' context.lineTo(-5, -110);\n' +
' context.lineTo(-15, -110);\n' +
'\n' +
' context.lineTo(0, -140);\n' +
'\n' +
' context.lineTo(15, -110);\n' +
' context.lineTo(5, -110);\n' +
' context.lineTo(20, -80);\n' +
' context.lineTo(10, -80);\n' +
' context.lineTo(25, -50);\n' +
' context.closePath();\n' +
' }\n' +
'\n' +
' function drawTrails() {\n' +
' var canvas = document.getElementById(\'trails\');\n' +
' var context = canvas.getContext(\'2d\');\n' +
'\n' +
' context.save();\n' +
' context.translate(130, 250);\n' +
'\n' +
' createCanopyPath(context);\n' +
'\n' +
' context.lineWidth = 4;\n' +
' context.lineJoin = \'round\';\n' +
' context.strokeStyle = \'#663300\';\n' +
' context.stroke();\n' +
'\n' +
' context.fillStyle = \'#339900\';\n' +
' context.fill();\n' +
'\n' +
' var trunkGradient = context.createLinearGradient(-5, -50, 5, -50);\n' +
' trunkGradient.addColorStop(0, \'#663300\');\n' +
' trunkGradient.addColorStop(0.4, \'#996600\');\n' +
' trunkGradient.addColorStop(1, \'#552200\');\n' +
' context.fillStyle = trunkGradient;\n' +
' context.fillRect(-5, -50, 10, 50);\n' +
'\n' +
' var canopyShadow = context.createLinearGradient(0, -50, 0, 0);\n' +
' canopyShadow.addColorStop(0, \'rgba(0, 0, 0, 0.5)\');\n' +
' canopyShadow.addColorStop(0.2, \'rgba(0, 0, 0, 0.0)\');\n' +
' context.fillStyle = canopyShadow;\n' +
' context.fillRect(-5, -50, 10, 50);\n' +
'\n' +
' context.restore();\n' +
'\n' +
' context.save();\n' +
'\n' +
' context.translate(-10, 350);\n' +
' context.beginPath();\n' +
' context.moveTo(0, 0);\n' +
' context.quadraticCurveTo(170, -50, 260, -190);\n' +
' context.quadraticCurveTo(310, -250, 410,-250);\n' +
'\n' +
' // Replace the solid stroke with a repeated\n' +
' // background pattern\n' +
' context.strokeStyle = context.createPattern(gravel, \'repeat\');\n' +
' context.lineWidth = 20;\n' +
' context.stroke();\n' +
'\n' +
' context.restore();\n' +
' }\n' +
'\n' +
' </scr' + 'ipt>\n' +
'</html>\n'
},
'2-20': {
'title':'Scaling example',
'code': '<!DOCTYPE html>\n' +
'<html>\n' +
' <title>Scaling example</title>\n' +
'\n' +
' <canvas id="trails" style="border: 1px solid;" width="400" height="600"> </canvas>\n' +
' <script>\n' +
' var gravel = new Image();\n' +
' gravel.src = "gravel.jpg";\n' +
' gravel.onload = function () {\n' +
' drawTrails();\n' +
' }\n' +
'\n' +
' function createCanopyPath(context) {\n' +
' context.beginPath();\n' +
' context.moveTo(-25, -50);\n' +
' context.lineTo(-10, -80);\n' +
' context.lineTo(-20, -80);\n' +
' context.lineTo(-5, -110);\n' +
' context.lineTo(-15, -110);\n' +
'\n' +
' context.lineTo(0, -140);\n' +
'\n' +
' context.lineTo(15, -110);\n' +
' context.lineTo(5, -110);\n' +
' context.lineTo(20, -80);\n' +
' context.lineTo(10, -80);\n' +
' context.lineTo(25, -50);\n' +
' context.closePath();\n' +
' }\n' +
'\n' +
' // Move tree drawing into its own function for reuse\n' +
' function drawTree(context) {\n' +
' var trunkGradient = context.createLinearGradient(-5, -50, 5, -50);\n' +
' trunkGradient.addColorStop(0, \'#663300\');\n' +
' trunkGradient.addColorStop(0.4, \'#996600\');\n' +
' trunkGradient.addColorStop(1, \'#552200\');\n' +
' context.fillStyle = trunkGradient;\n' +
' context.fillRect(-5, -50, 10, 50);\n' +
'\n' +
' var canopyShadow = context.createLinearGradient(0, -50, 0, 0);\n' +
' canopyShadow.addColorStop(0, \'rgba(0, 0, 0, 0.5)\');\n' +
' canopyShadow.addColorStop(0.2, \'rgba(0, 0, 0, 0.0)\');\n' +
' context.fillStyle = canopyShadow;\n' +
' context.fillRect(-5, -50, 10, 50);\n' +
'\n' +
' createCanopyPath(context);\n' +
'\n' +
' context.lineWidth = 4;\n' +
' context.lineJoin = \'round\';\n' +
' context.strokeStyle = \'#663300\';\n' +
' context.stroke();\n' +
'\n' +
' context.fillStyle = \'#339900\';\n' +
' context.fill();\n' +
' }\n' +
'\n' +
'\n' +
' function drawTrails() {\n' +
' var canvas = document.getElementById(\'trails\');\n' +
' var context = canvas.getContext(\'2d\');\n' +
'\n' +
' // Draw the first tree at X=130, Y=250\n' +
' context.save();\n' +
' context.translate(130, 250);\n' +
' drawTree(context);\n' +
' context.restore();\n' +
'\n' +
' // Draw the second tree at X=260, Y=500\n' +
' context.save();\n' +
' context.translate(260, 500);\n' +
'\n' +
' // Scale this tree twice normal in both dimensions\n' +
' context.scale(2, 2);\n' +
' drawTree(context);\n' +
' context.restore();\n' +
'\n' +
' context.save();\n' +
' context.translate(-10, 350);\n' +
' context.beginPath();\n' +
' context.moveTo(0, 0);\n' +
' context.quadraticCurveTo(170, -50, 260, -190);\n' +
' context.quadraticCurveTo(310, -250, 410,-250);\n' +
' context.strokeStyle = context.createPattern(gravel, \'repeat\');\n' +
' context.lineWidth = 20;\n' +
' context.stroke();\n' +
' context.restore();\n' +
' }\n' +
'\n' +
' </scr' + 'ipt>\n' +
'</html>\n'
},
'2-22': {
'title': 'Transform example',
'code': '<!DOCTYPE html>\n' +
'<html>\n' +
' <title>Transform example</title>\n' +
'\n' +
' <canvas id="trails" style="border: 1px solid;" width="400" height="600"> </canvas>\n' +
' <script>\n' +
' var gravel = new Image();\n' +
' gravel.src = "gravel.jpg";\n' +
' gravel.onload = function () {\n' +
' drawTrails();\n' +
' }\n' +
'\n' +
' function createCanopyPath(context) {\n' +
' context.beginPath();\n' +
' context.moveTo(-25, -50);\n' +
' context.lineTo(-10, -80);\n' +
' context.lineTo(-20, -80);\n' +
' context.lineTo(-5, -110);\n' +
' context.lineTo(-15, -110);\n' +
'\n' +
' context.lineTo(0, -140);\n' +
'\n' +
' context.lineTo(15, -110);\n' +
' context.lineTo(5, -110);\n' +
' context.lineTo(20, -80);\n' +
' context.lineTo(10, -80);\n' +
' context.lineTo(25, -50);\n' +
' context.closePath();\n' +
' }\n' +
'\n' +
' function drawTree(context) {\n' +
' // Save the current canvas state for later\n' +
' context.save();\n' +
'\n' +
' // Create a slanted tree as the shadow by applying\n' +
' // a shear transform, changing X values to increase\n' +
' // as Y values increase\n' +
' context.transform(1, 0,\n' +
' -0.5, 1,\n' +
' 0, 0);\n' +
'\n' +
' // Shrink the shadow down to 60% height in the Y dimension\n' +
' context.scale(1, 0.6);\n' +
'\n' +
' // Set the tree fill to be black, but at only 20% alpha\n' +
' context.fillStyle = \'rgba(0, 0, 0, 0.2)\';\n' +
' context.fillRect(-5, -50, 10, 50);\n' +
'\n' +
' // Redraw the tree with the shadow effects applied\n' +
' createCanopyPath(context);\n' +
' context.fill();\n' +
'\n' +
' // Restore the canvas state\n' +
' context.restore();\n' +
'\n' +
' var trunkGradient = context.createLinearGradient(-5, -50, 5, -50);\n' +
' trunkGradient.addColorStop(0, \'#663300\');\n' +
' trunkGradient.addColorStop(0.4, \'#996600\');\n' +
' trunkGradient.addColorStop(1, \'#552200\');\n' +
' context.fillStyle = trunkGradient;\n' +
' context.fillRect(-5, -50, 10, 50);\n' +
'\n' +
' var canopyShadow = context.createLinearGradient(0, -50, 0, 0);\n' +
' canopyShadow.addColorStop(0, \'rgba(0, 0, 0, 0.5)\');\n' +
' canopyShadow.addColorStop(0.2, \'rgba(0, 0, 0, 0.0)\');\n' +
' context.fillStyle = canopyShadow;\n' +
' context.fillRect(-5, -50, 10, 50);\n' +
'\n' +
' createCanopyPath(context);\n' +
'\n' +
' context.lineWidth = 4;\n' +
' context.lineJoin = \'round\';\n' +
' context.strokeStyle = \'#663300\';\n' +
' context.stroke();\n' +
'\n' +
' context.fillStyle = \'#339900\';\n' +
' context.fill();\n' +
' }\n' +
'\n' +
'\n' +
' function drawTrails() {\n' +
' var canvas = document.getElementById(\'trails\');\n' +
' var context = canvas.getContext(\'2d\');\n' +
'\n' +
' context.save();\n' +
' context.translate(130, 250);\n' +
' drawTree(context);\n' +
' context.restore();\n' +
'\n' +
' context.save();\n' +
' context.translate(260, 500);\n' +
'\n' +
' context.scale(2, 2);\n' +
' drawTree(context);\n' +
' context.restore();\n' +
'\n' +
' context.save();\n' +
' context.translate(-10, 350);\n' +
' context.beginPath();\n' +
' context.moveTo(0, 0);\n' +
' context.quadraticCurveTo(170, -50, 260, -190);\n' +
' context.quadraticCurveTo(310, -250, 410,-250);\n' +
' context.strokeStyle = context.createPattern(gravel, \'repeat\');\n' +
' context.lineWidth = 20;\n' +
' context.stroke();\n' +
' context.restore();\n' +
' }\n' +
'\n' +
' </scr' + 'ipt>\n' +
'</html>\n'
}
};
jQuery(function () {
codeviewReady();
});
|
import Vue from 'vue';
import { ApolloClient } from 'apollo-client'
import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory'
import VueApollo from 'vue-apollo';
const httpLink = new HttpLink({
// You should use an absolute URL here
uri: 'http://localhost:4000/graphql',
})
// Create the apollo client
const apolloClient = new ApolloClient({
link: httpLink,
cache: new InMemoryCache(),
connectToDevTools: true,
})
Vue.use(VueApollo)
const apolloProvider = new VueApollo({
defaultClient: apolloClient,
})
export default apolloProvider
|
module.exports = function(source) {
this.cacheable();
return source.replace(/{{(?:[\S\s])*?\n((?:[\S\s])*?\n)*?[\s\S]*?}}/mg, '');
};
|
import React from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image,
TouchableOpacity,
Button,
ImageBackground
} from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import auth from '@react-native-firebase/auth';
import { createStackNavigator } from '@react-navigation/stack';
import Home from './home.js'
import Students from './Students'
const Stack = createStackNavigator();
class Adminnav extends React.Component {
state = { }
componentDidMount=()=>{
console.log("hehehhhehehlohohlhihlojih ")
auth()
.createUserWithEmailAndPassword('nagarajuuuuuuuu1@gmail.com', 'S')
.then(() => {
console.log('User account created & signed in!');
})
.catch(error => {
alert(error.code)
// if (error.code === 'auth/email-already-in-use') {
// console.log('That email address is already in use!');
// }
// if (error.code === 'auth/invalid-email') {
// console.log('That email address is invalid!');
// }
// console.error(error);
});
}
render() {
return (
// <View>
// {/* <Text>hello</Text> */}
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={Home} options={{
headerShown: false
}}/>
<Stack.Screen name="Students" component={Students} />
{/* <Stack.Screen name="Fee" component={Fee} />
<Stack.Screen name="Attendence" component={Attendence} />
<Stack.Screen name="Posts" component={Posts} /> */}
</Stack.Navigator>
</NavigationContainer>
// </View>
);
}
}
export default Adminnav;
|
var submit = document.getElementById("submitButton");
//var assignmentGrade = 0.0;
//var groupProjectGrade = 0.0;
//var quizGrade = 0.0;
//var examGrade = 0.0;
//var intexGrade = 0.0;
//var totalGrade = 0.0;
submit.addEventListener("click", function () {
var assignmentGrade = parseInt(document.getElementById("Assignments").value) * .5;
var groupProjectGrade = parseInt(document.getElementById("GroupProject").value) * .1;
var quizGrade = parseInt(document.getElementById("Quizzes").value) * .1;
var examGrade = parseInt(document.getElementById("Exams").value) * .2;
var intexGrade = parseInt(document.getElementById("INTEX").value) * .1;
var totalGrade = assignmentGrade + groupProjectGrade + quizGrade + examGrade + intexGrade;
var letterGrade = "";
if (totalGrade >= 94) {
letterGrade = 'A';
}
else if (totalGrade < 94 && totalGrade >= 90) {
letterGrade = 'A-';
}
else if (totalGrade < 90 && totalGrade >= 87) {
letterGrade = 'B+';
}
else if (totalGrade < 87 && totalGrade >= 84) {
letterGrade = 'B';
}
else if (totalGrade < 84 && totalGrade >= 80) {
letterGrade = 'B-';
}
else if (totalGrade < 80 && totalGrade >= 77) {
letterGrade = 'C+';
}
else if (totalGrade < 77 && totalGrade >= 74) {
letterGrade = 'C';
}
else if (totalGrade < 74 && totalGrade >= 70) {
letterGrade = 'C-';
}
else if (totalGrade < 70 && totalGrade >= 67) {
letterGrade = 'D+';
}
else if (totalGrade < 67 && totalGrade >= 64) {
letterGrade = 'D';
}
else if (totalGrade < 64 && totalGrade >= 60) {
letterGrade = 'D-';
}
else if (totalGrade < 60) {
letterGrade = 'E';
}
alert("Your Final Grade: " + letterGrade + " " + totalGrade + "% ");
});
|
var authorizeButton = null;
var signoutButton = null;
var eventList = [];
function handleClientLoad() {
// Loads the client library and the auth2 library together for efficiency.
// Loading the auth2 library is optional here since `gapi.client.init` function will load
// it if not already loaded. Loading it upfront can save one network request.
gapi.load("client:auth2", initClient);
authorizeButton = document.getElementById("signin-button");
signoutButton = document.getElementById("signout-button");
}
function initClient() {
// Initialize the client with API key and People API, and initialize OAuth with an
// OAuth 2.0 client ID and scopes (space delimited string) to request access.
gapi.client
.init({
apiKey: check_key(),
discoveryDocs: [
"https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"
],
clientId:
"568249120290-13q4r09h6jldf1lj5d19jo3c3tbbsuhd.apps.googleusercontent.com",
scope: "https://www.googleapis.com/auth/calendar.readonly"
})
.then(function() {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleSignInClick;
signoutButton.onclick = handleSignOutClick;
});
}
function updateSigninStatus(isSignedIn) {
// When signin status changes, this function is called.
// If the signin status is changed to signedIn, we make an API call.
if (isSignedIn) {
authorizeButton.style.display = "none";
signoutButton.style.display = "inline-block";
$("#update_availability").css("display", "inline-block");
listUpcomingEvents();
} else {
authorizeButton.style.display = "inline-block";
signoutButton.style.display = "none";
$("#update_availability").css("display", "none");
}
}
function handleSignInClick(event) {
// Ideally the button should only show up after gapi.client.init finishes, so that this
// handler won't be called before OAuth is initialized.
gapi.auth2.getAuthInstance().signIn();
}
function handleSignOutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
function makeApiCall() {
// Make an API call to the People API, and print the user's given name.
listUpcomingEvents();
}
function listUpcomingEvents() {
var date = new Date();
date.setDate(date.getDate() + 7);
// console.log(date);
gapi.client.calendar.events
.list({
calendarId: "primary",
timeMin: new Date().toISOString(),
timeMax: date.toISOString(),
showDeleted: false,
singleEvents: true,
// 'maxResults': 10,
orderBy: "startTime"
})
.then(function(response) {
eventList = response.result.items;
// console.log(eventList);
});
}
|
/**
Core script to handle the entire layout and base functions
**/
'use strict';
var App = function () {
return {
//main function to initiate template pages
init: function () {
}
}
}();
/* initizalize common actions */
function init(entity){
$.fn.dataTable.ext.errMode = 'throw';
if(typeof loadTable==="function") loadTable();
/* Invoke eidt form modal and edit entities */
btnClickDelete(entity);
/* Invoke eidt form modal and edit entities */
// editEntity("#edit-form",entity);
/* Invoke new form modal and create new entity*/
// newEntity("#new-form",entity);
$("#btnNew").click(function () {
$("#new-entity-modal").dialog({modal:true});
});
crudEntity("#new-form",entity,'/tks/' + entity + '/create.action');
// below line to be overrwiteen in each page
btnClickEdit();
if(entity!=="release" || entity !=="task") {
crudEntity("#edit-form", entity, '/tks/' + entity + '/update.action');
crudEntity("#delete-form", entity, '/tks/' + entity + '/delete.action');
}
/* refresh data table when modal closed */
refreshTableOnCloseModal();
/* refresh datable when click refresh button */
refreshTable('#list',"#bthRefresh");
// newStatusAjaxPost("/tks/user/create.action");
/* global style change */
$("label").addClass(" text-success");
$("h4").addClass(" text-success");
$("h5").addClass(" text-success");
$("th").addClass(" text-success");
$(".text-primary").addClass("animated shake");
$(".panel-title").parent().css("background-clor","green");
$(".navbar-brand").parent().css("background-clor","green");
$('input:button').addClass("btn-success");
$('input:submit').addClass("btn-success");
/* load delete modal on page loading */
//$('.delete-modal').load("/tks/content/delete-modal.html");
}
/* Post New Entity */
function newStatusAjaxPost(url){
$("#new-form").submit(function(e)
{
// e.preventDefault();
var formInput=$(this).serializeArray();
console.log( formInput );
var str={
name: "tst",
password: "fjoe",
email: "em"
};
$.ajax({
type:"POST",
contentType:"application/json; charset=utf-8",
url: url,//"/tks/product/listAll",
dataType:"json",
data: formInput,// JSON.stringify(data),
success: function (jsonResult) {
// alert(jsonResult);
}
});
// doAjaxPost(url,data);
$('.entity-id').text(''+data.entity.id + '');
$('.result').text(''+data.message + '');
});
return false;
};
/* regresh data after modal close */
function refreshTableOnCloseModal() {
/* Close modal and refresh page or data table*/
$('body').on('hidden.bs.modal', '.modal', function () {
var table=$("#list").dataTable;
table.ajax.reload();
//document.location.reload(); // refresh page
//loadTable(); // refresh data table only
});
}
function refreshTable(tableid,clickid){
$(clickid).click(function(){
var table = $(tableid).DataTable();
table.ajax.reload();
}
)}
/* Select data rows and Edit
function btnClickEdit(a){
$('#btnEdit').click( function () {
var fields = $("#edit-form").serializeArray();
jQuery.each( fields, function(i, field){
$(":input[name='"+field.name+"']").val(a[i]);
// if(field.name=="id") $(":input[name='"+field.name+"']").setAttr("disabled","true");
});
// $(":input[name='mark']").val("edit");
$("#entity-id").prop("disabled",true);
$('#edit-entity-modal').dialog({modal:true});
});
};*/
/* Start New Entity - Ajax GET
function newEntity(clickid,entity){
$(clickid).submit(function()
{
var formInput=$(this).serialize();
console.log("---form input data--");
console.log( formInput );
$(function() {
doAjaxGet('/tks/' + entity + '/create.action', formInput);
}
);
return false;
});
};*/
/* Convert form data to JSON */
function formData2Json(clickid){
var formArray = $(clickid).serializeArray();
$('input[disabled]').each( function() {
//formInput = formInput + '&' + $(this).attr('name') + '=' + $(this).val();
formArray.push($(clickid).val());
});
var jsonObj = {};
$.each(formArray,
function(i, v) {
jsonObj[v.name] = v.value;
});
var jsonObjNew={};
jsonObjNew["entity"]=jsonObj;
console.log(jsonObjNew);
return jsonObjNew;
}
/* ajax call POST*/
function doAjaxPost(url,formdata){
$.ajax({
type:"POST",
contentType:"application/json; charset=utf-8",
url: url,
data: JSON.stringify(formdata),
dataType:"json"
/* beforeSend: function(request) {
request.setRequestHeader("Accept", "application/json");
},*/
}).done(function (data) {
// alert(JSON.stringify(data));
// alert(data.message);
if(url.indexOf("task") < 0){
$('.result').html('<label class="text-success"><i class="glyphicon glyphicon-ok">'+data.message + '</label>');
}
})
.fail(function (data) {
console.log(data);
console.log(data.message);
if(url.indexOf("task") < 0){
$('.result').html('<label class="text-danger"><i class="glyphicon glyphicon-exclamation-sign"> '+data.responseJSON.message + '</i></label>');
}
});
}
function doAjaxGet(url,formInput){
//alert(url);
return $.getJSON(url, formInput,function(data) {
console.log("....tasks list ...");
console.log(data);
}).done(function (data) {
if(!(/task/i.test(url))){
$('.result').html('<label class="text-success"><i class="glyphicon glyphicon-ok">'+data.message + '</label>');
}
})
.fail(function (data) {
console.log(data);
console.log(data.message);
if(!(/task/i.test(url))){
$('.result').html('<label class="text-danger"><i class="glyphicon glyphicon-exclamation-sign"> '+data.responseJSON.message + '</i></label>');
}
});
}
/* ajax call GET*/
function doAjaxGet(url){
return $.ajax({
type:"get",
url: url,//"/tks/product/listAll",
dataType:"json"
});
}
/* Start Edit Task */
function editEntity(clickid,entity){
/* $(clickid).submit(function()
{
console.log(formInput);
var data =formData2Json(clickid);
console.log("***********form input******");
console.log( data );
$(function(){
// doAjaxGet('/tks/'+entity+'/update.action',formInput)
doAjaxPost('/tks/' + entity + '/create.action', data);
});
return false;
});*/
$(clickid).submit(function()
{
// var formInput=$(this).serialize(); // for Get method
var data =$(function() {formData2Json(clickid)});
console.log("***********form input******");
console.log( data );
$(function() {
doAjaxPost('/tks/' + entity + '/create.action', data);
}
);
return false;
});
};
/* End Edit Task */
/* Start New Entity */
function newEntity(clickid,entity){
$(clickid).submit(function () {
var formInput = $(clickid).serialize();
console.log("****do get ****");
console.log(formInput);
doAjaxGet('/tks/'+entity+'create.action',formInput);
});
};
/* Start CRUD Entity */
function crudEntity(clickid,entity,url){
$(clickid).submit(function()
{
var jsonObjNew={};
var formArray = $(clickid).serializeArray();
alert(JSON.stringify(formArray));
// console.log(formArray);
$('input[disabled]').each( function() {
//formInput = formInput + '&' + $(this).attr('name') + '=' + $(this).val();
//alert($(this).val());
var di = {"name":"id","value":$(this).val()};
formArray.push(di);
alert(JSON.stringify(formArray));
});
// alert(JSON.stringify(formArray));
var jsonObj = {};
var listSelected=[];
$.each(formArray,
function(i, v) {
if (v.name.indexOf(".") >= 0) {
// alert(v.name);
var substr = v.name.split(".");
var tempObj = {};
tempObj[substr[1]] = v.value;
jsonObj[substr[0]]=tempObj;
}
else if(v.name==="listSelected"){
listSelected.push(v.value);
}
else if(v.name==="statusListSelected"){
jsonObjNew["statusListSelected"]=v.value;
}
else jsonObj[v.name] = v.value;
});
jsonObjNew["listSelected"]=listSelected;
jsonObjNew["entity"]=jsonObj;
console.log("***********form input******");
console.log( jsonObjNew );
// $(function() {
// jsonObjNew={"entity":{"name":"fjfefeefff grffeffesfeefefoe","description":"fjoe","product":{"name":"test"} }};
doAjaxPost(url, jsonObjNew);
// }
// );
return false;
});
};
/* End CRUD Entity */
/* Select data rows and Delete */
function btnClickDelete(entity) {
$('#confirm-delete').on('click', '.btn-ok', function (e) {
var $modalDiv = $(e.delegateTarget);
// $.ajax({url: '/api/record/' + id, type: 'DELETE'})
// $.post('/api/record/' + id).then()
$modalDiv.addClass('loading');
setTimeout(function () {
$modalDiv.modal('hide').removeClass('loading');
}, 1000);
var table = $('#list').DataTable();
var formInput="";
$.each(table.rows('.selected').data(), function () {
formInput="";
var a = [];
a.push(this["id"]);
// a.push(this["summary"]);
//a.push(this["description"]);
formInput = {"entity":{"id":a[0]}};//"id="+a[0];
console.log(JSON.stringify(formInput));
//alert(formInput);
$('#confirm-delete').on('show.bs.modal', function(e) {
var data = $(e.relatedTarget).data();
console.log("-----confirm delete---");
$('.id-to-be-deleted').text(formInput);
});
// alert ("formInput is "+formInput);
/* $.getJSON('/tks/' + entity + '/delete.action', formInput, function (data) {
//$('#result').text(''+data.message + '');
// add check if successfully removed
table.rows('.selected').remove().draw(false);
}).done(function (data) {
alert(data.message);
})
.fail(function (data) {
alert(data.responseJSON.message);
});
}
);*/
doAjaxPost("/tks/" + entity + "/delete.action",formInput);
});
});
}
/*
$('#confirmDeleteModal').find('.modal-footer #confirm-delete-ok').click(function (e) {
e.preventDefault();
var id = $('#confirmDeleteModal').data('id');
$('[data-id="' + id + '"]').closest('tr').remove();
$('#confirmDeleteModal').modal('hide');
return true;
});
/* end Delete */
function fillDataTable(clickID, url,columnArray, columnDefsArray,order){
var id;
var responsedata;
var table=$(clickID).dataTable({
"destroy":true,
"deferRender": true,
// "fnInitComplete": function (oSettings, json) {
// },
"ajax": /*ajaxCall(url) */
{
"cache":false,
"type": 'GET',
"url": url,
"dataType":"json",
"dataSrc": function (json) {
// alert(JSON.stringify(json));
// alert(json.entities);
responsedata=JSON.stringify(json.entities);
console.log("*******resp");
console.log(responsedata);
return $.parseJSON(responsedata);
},
"async": true/*,
"success": function (data) {
console.log("........");
responsedata = data;
console.log(responsedata);
console.log(url);
console.log("yes or no:" + url.indexOf("release"));
if (url.indexOf("release") >= 0)
console.log(responsedata);
callbackRelease(responsedata);
},
"error": function () {
alert("something went wrong");
}*/
} ,
"select": {
"style": 'multi'
},
"dom": 'Bfrtip',
"buttons": [
'selectAll',
'selectNone'
],
// "processData": false,
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
/* console.log(nRow);
console.log("**** aData *****");
console.log(JSON.stringify(aData));*/
$('tr:eq(0)', nRow).attr("data-id",iDisplayIndexFull);
$('td:eq(1)', nRow).attr("data-id",iDisplayIndexFull);
$('td:eq(2)', nRow).attr("data-id",iDisplayIndexFull);
$('td:eq(3)', nRow).attr("data-id","id-"+aData.id);
},
"columnDefs": columnDefsArray,
"columns": columnArray,
"order": order,
"bLengthChange":true,
"bFilter": true,
"bAutoWidth": true
});
console.log("responsedata------");
console.log(responsedata);
return responsedata;
}
/*function ajaxCall(url){
var datalist;
$.ajax({
"dataType": "json",
"contentType": "application/json; charset=utf-8",
"type": "POST",
"url": url,
"async": "false",
"dataSrc": function (json) {
console.log(json);
datalist= $.parseJSON(JSON.stringify(json));
return datalist;
},
"success": function (data) {
console.log("........");
//datalist = data;
console.log(datalist);
console.log(url);
console.log("yes or no:" + url.indexOf("release"));
if (url.indexOf("release") >= 0) {
console.log(data);
callbackRelease(data);
}
}
/*$('#employee-list').html("Please select Employee under Department: <select name = \"employee\"></select>");
$.each(list, function(index, data){
$('#employee-list select').html("<option value = "+data.empID+">"+data.givenName+"</option>");
});
,
"error": function(){
alert("something went wrong");
}
})
console.log("------datalist in ajaxCall function");
console.log(datalist);
return datalist;
}
*/
function callbackRelease(data) {
var langlist=data[1].languages;
console.log("langlist is:"+langlist);
$.each(langlist,function(index){
console.log("lang is: "+langlist[index]+",");
});
}
function refreshTableOnCloseModal(){
/* Close modal and refresh page or data table*/
$('body').on('hidden.bs.modal', '.modal', function () {
$('#list').DataTable().ajax.reload();
//document.location.reload(); // refresh page
//loadTable(); // refresh data table only
});
}
function markStatus() {
$('#status_name').each(function() {
var lastColumn = $(this).html();
var replaceValue = lastColumn.Append("Changed Content");
$(this).html(replaceContent);
});
};
/* retrieve all languages and dynamic create select options*/
//$(document).ready(
function handleLangSelectOptions(){
$.ajax({
type:"get",
url:"/tks/lang/listAll",
dataType:"json",
//success: function (data) {
}).done(function (data) {
// alert(JSON.stringify(data));
var str=$('<select id ="seleLangInForm" title="" multiple="multiple" list="languages" name="listSelected" value="listSelected" listKey="id" listValue="label" emptyOption="true">');
data=data.entities;
$.each(data,function(index){
var option=$('<option value="'+data[index].code+'" name="code">'+data[index].code+'</option>');
option.appendTo(str);
});
$("#languagesInForm").html(str );
// if(typeof setupSelect==="function") setupSelect();
}
)
}
/* retrieve all languages and dynamic create select options*/
//$(document).ready(
function handleProductSelectOptions(){
setupSelect();
$.ajax({
type:"get",
url:"/tks/product/listAll",
dataType:"json",
//success: function (data) {
}).done(function (data) {
// alert(JSON.stringify(data));
var str=$('<select id ="seleProductInForm" title="" multiple="multiple" list="product" name="listSelected" value="listSelected" listKey="id" listValue="label" emptyOption="true">');
data=data.entities;
$.each(data,function(index){
var option=$('<option value="'+data[index].name+'" name="code">'+data[index].name+'</option>');
option.appendTo(str);
});
$("#productInForm").html(str );
}
)
}
function setupSelect(clickid){
$(clickid).multiselect({
noneSelectedText: "Please select",
checkAllText: "All Selected",
uncheckAllText: 'None Selected',
// selectedList:numberOfLanguages
});
};
//)
|
"use strict";
exports.__esModule = true;
var YahooAdapter = /** @class */ (function () {
function YahooAdapter(destinatario, fecha, yahoo) {
this.yahoo = yahoo;
this.destinatario = destinatario;
this.fecha = fecha;
}
YahooAdapter.prototype.enviar = function (titulo, mensaje) {
this.yahoo.enviarCorreo(this.destinatario, titulo, mensaje, this.fecha);
};
;
return YahooAdapter;
}());
;
exports["default"] = YahooAdapter;
|
module("Movie App Unit Tests", {
setup: function () {
},
teardown: function () {
}
});
test("Verify We Have movieApp with expected members", function () {
//basic sainty assertions to know members are present
isFunction(movieapp, "movieapp object should exist");
isFunction(movieapp.fn.init, "init function should exist");
ok(movieapp.fn.version, "version should exist");
ok(movieapp.fn.mainTitle, "mainTitle should exist");
isFunction(movieapp.fn.hideBurgerMenu, "hideBurgerMenu should exist");
isObject(movieapp.fn.movieTypes, "movieTypes function should exist");
isFunction(movieapp.fn.setMainTitle, "setMainTitle function should exist");
isFunction(movieapp.fn.bindBackButton, "bindBackButton function should exist");
isObject(movieapp.fn.templates, "templates should exist");
isFunction(movieapp.fn.compileTemplates, "compileTemplates function should exist");
isFunction(movieapp.fn.showLoading, "showLoading function should exist");
isFunction(movieapp.fn.mergeData, "mergeData function should exist");
isObject(movieapp.fn.resizeEvents, "resizeEvents should exist");
equal(movieapp.fn.viewWidth, 0, "viewWidth should exist");
isFunction(movieapp.fn.setMoviePanelWidth, "setMoviePanelWidth function should exist");
isFunction(movieapp.fn.setupPanorama, "setupPanorama function should exist");
isFunction(movieapp.fn.setPanoramaWings, "setPanoramaWings function should exist");
isObject(movieapp.fn.settings, "settings function should exist");
});
test("Verify can a new movieapp instance", function () {
var m = movieApp();
equal(typeof m, "object", "movieapp object should exist");
});
test("Verify can a new movieapp with a overriding setting adds the overide value", function () {
var appTitle = "This is the test app title",
customSetting = { "appTitle": appTitle },
m = movieApp(customSetting);
equal(m.settings.appTitle, appTitle, "m.settings.appTitle should be " + appTitle);
});
test("Verify can a new movieapp with a custom setting adds the custom setting", function () {
var customSetting = {"test": "value"},
m = movieApp(customSetting);
equal(m.settings.test, "value", "m.settings.test should be 'value'");
});
|
import * as actions from './action';
import {resetForm} from "../../../functions/serialize";
const initialState = {
registered: false,
register_error: false,
register_error_cause: [],
};
export default (state = initialState, {payload, type}) => {
switch (type) {
case actions.REGISTER_FAILED:
return {
...state,
registered: false,
register_error: true,
register_error_cause: payload.violations,
};
case actions.REGISTER_REQUEST:
return {
...state,
register_error: false,
register_error_cause: [],
};
case actions.REGISTER_SUCCESS:
resetForm('escort-register');
return {
...state,
registered: true,
register_error: false,
register_error_cause: [],
};
default:
return state;
}
};
|
import React, { PureComponent } from "react";
import { Button, DialogContainer } from "react-md";
export default class SimpleModal extends PureComponent {
state = { visible: false };
show = () => {
this.setState({ visible: true });
};
hide = () => {
this.setState({ visible: false });
};
render() {
const { visible } = this.state;
const actions = [
{
onClick: this.hide,
primary: true,
children: "Volver"
}
];
return (
<div>
<Button raised secondary onClick={this.show}>
Información adicional
</Button>
<DialogContainer
id="speed-boost"
visible={visible}
onHide={this.hide}
title="Datos Adicionales"
aria-describedby="speed-boost-description"
modal
actions={actions}
>
<p id="speed-boost-description" className="md-color--secondary-text">
Según lo establecido por la constitución política de Colombia de
1991 la cual en el artículo número 15 cita, “Todas las personas
tienen derecho a su intimidad personal y familiar y a su buen
nombre, y el Estado debe respetarlos y hacerlos respetar. (…) En la
recolección, tratamiento y circulación de datos se respetarán la
libertad y demás garantías consagradas en la Constitución.” Los
datos personales deben ser respetados en todo el territorio nacional
y se debe informar al usuario que su información va a ser usada de
manera legal y estará segura siempre. Para la manipulación de la
información personal almacenada en diferentes bases de datos
digitales o físicas, es estado colombiano dispone de leyes
establecidas las cuales son claras a expresar, cuál es el manejo de
esta información y las definiciones de la misma.
</p>
<p>
Así pues, la información de todo colombiano tiene como estructura de
manipulación las siguientes partes:
</p>
<ul>
<li>
{" "}
Titular de la información: es el individuo a la que se refiere la
información, y está sujeto por consiguiente a los derechos y
deberes de toda persona natural o jurídica.
</li>
<li>
Fuente de información: es la persona, organización o entidad que
conoce los datos de los titulares de la información, y que ante
cualquier trámite legal brinda a el operador de la información los
datos necesarios en el momento que se necesiten.
</li>
<li>
{" "}
Operador de información: es la persona, entidad u organización que
recibe la fuente de datos y los pone bajo conocimiento de los
usuarios según los parámetros de la ley.
</li>
<li>
Usuario: es la persona natural o jurídica que puede acceder a la
información de uno o varios usuarios, esto, según las
circunstanciadas en donde la ley lo permita.
</li>
</ul>
</DialogContainer>
</div>
);
}
}
|
import Vue from 'vue'
import vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
Vue.use(vuex)
const state = {
songlist:[],
musiclist:[],
// 当前播放音乐的信息
plaingsong:{},
//存取排行所有信息
ranklist:[],
//存储当前播放mvli列表
mvlist:[],
userinfo:{},
userdetail:{},
//存储个人的音乐列表
personmusiclist:{}
}
const store = new vuex.Store({
state,
mutations:{
'SETPERSONMUSICLIST'(state,uploade){
state.personmusiclist = uploade
},
'SETSONGLIST'(state,uploade){
state.songlist = uploade
} ,
'SETMUSICLIST'(state,uploade){
state.musiclist = uploade
},
'SETSONG'(state,uploade){
state.plaingsong = uploade
}
,
'SETRANKLIST'(state,uploade){
state.ranklist = uploade
},
'SETMVLIST'(state,uploade){
state.mvlist = uploade
},
'SETUSERINFO'(state,uploade){
state.userinfo = uploade
},
// 存取用户详细信息
'SETUSEDETAIL'(state,uploade){
state.userdetail = uploade
}
},
plugins: [
createPersistedState({
storage: {
getItem: key => localStorage.getItem(key),
// Please see https://github.com/js-cookie/js-cookie#json, on how to handle JSON.
setItem: (key, value) =>
localStorage.setItem(key, value),
removeItem: key => localStorage.removeItem(key),
},
}),
],
})
export default store
|
export const getRedirectUri = () => {
if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
return 'http://localhost:3000/app';
} else {
return 'https://moodify.benmiz.com/app';
}
};
export const login = () => {
const CLIENT_ID = process.env.REACT_APP_CLIENT_ID;
const scope = 'user-read-recently-played,user-top-read,playlist-modify-public';
const authUri = `https://accounts.spotify.com/authorize?client_id=${CLIENT_ID}&response_type=token&redirect_uri=${getRedirectUri()}&scope=${scope}`;
window.location.replace(authUri);
};
|
function relay(){
console.log("This is relay function");
}
function shortjump(){
console.log("This is shortjump function");
}
module.exports.relay = relay
|
// eslint-disable-next-line no-restricted-imports
import ko from 'knockout';
import variableWrapper from '../../core/utils/variable_wrapper';
if (ko) {
variableWrapper.inject({
isWrapped: ko.isObservable,
isWritableWrapped: ko.isWritableObservable,
wrap: ko.observable,
unwrap: function unwrap(value) {
if (ko.isObservable(value)) {
return ko.utils.unwrapObservable(value);
}
return this.callBase(value);
},
assign: function assign(variable, value) {
if (ko.isObservable(variable)) {
variable(value);
} else {
this.callBase(variable, value);
}
}
});
}
|
window.onload = function () {
show(0);
}
let questions = [
{
id: 1,
question: "What is the capital of USA?",
answer: "Washington, D.C.",
options: [
"New York",
"Chicago",
"Washington, D.C.",
"Las Vegas"
]
},
{
id: 2,
question: "Who invented the computer?",
answer: "Charles Babbage",
options: [
"Albert Einstein",
"Charles Babbage",
"Thomas Edison",
"John Vincent"
]
},
{
id: 3,
question: "What is the abbreviation of HTML?",
answer: "Hyper Text Markup Language",
options: [
"Hyper Text Markup Language",
"Hyper Tool Markup Language",
"Hyper Tool Maker Language",
"High Tabular Markup Language"
]
},
{
id: 4,
question: "Who is called The Father of Chemistry?",
answer: "Antoine Lavoisier",
options: [
"Albert Einstein",
"Marie Curie",
"John Dalton",
"Antoine Lavoisier"
]
},
{
id: 5,
question: "Who is the first prime minister of Pakistan?",
answer: "Liaquat Ali Khan",
options: [
"Chaudhry Mohammad Ali",
"Liaquat Ali Khan",
"Mohammad Ali Jinnah",
"Imran Khan"
]
}
];
function submitForm(e) {
e.preventDefault();
var name = document.getElementById("nameStart").value;
sessionStorage.setItem("name", name);
var user$name = document.getElementById("nameStart").value;
if (user$name == "") {
alert("Enter your Name!")
location.href = "index.html"
}else{
location.href = "quiz.html";
}
// console.log(name)
}
let question_count = 0
let points = 0
function next() {
let user_ans = document.querySelector("li.option.active").innerHTML;
if (user_ans == questions[question_count].answer) {
points += 10
sessionStorage.setItem("points", points);
}
if (question_count == questions.length - 1) {
sessionStorage.setItem("time", `${mins} minutes and ${secs} seconds`);
clearInterval(mytime)
location.href = "end.html";
return;
}
question_count++
show(question_count);
}
function show(count) {
let question = document.getElementById("questions")
question.innerHTML = `<h2>${questions[count].question}</h2>
<ul class="option-group">
<li class="option">${questions[count].options[0]}</li>
<li class="option">${questions[count].options[1]}</li>
<li class="option">${questions[count].options[2]}</li>
<li class="option">${questions[count].options[3]}</li>
</ul> `
activeO();
}
function activeO() {
let option = document.querySelectorAll("li.option");
for (let i = 0; i < option.length; i++) {
option[i].onclick = function () {
for (let j = 0; j < option.length; j++) {
if (option[j].classList.contains("active")) {
option[j].classList.remove("active");
}
}
option[i].classList.add("active");
}
}
}
|
var fs = require('fs');
var data = "Some data i want to write to a file";
fs.writeFile('file.txt',data,function(err){
if(!err){
console.log('Wrote to the file');
}else{
throw err;
}
});
|
// Write a function to alphabetize words of a given string. Alphabetizing a string means rearranging the letters so they are sorted from A to Z.
// "Republic Of Serbia" -> "Rbceilpu Of Sabeir"
function alphabetizeString(string){
var result = "";
var newStr = "";
var sorted;
newStr = string.split(" ");
//console.log(newStr);
newStr.forEach(function (elem){ // elem = newStr[i]
sorted = elem.split("").sort().join("");
//console.log(sorted);
result += sorted.concat(" ");
});
return result;
}
console.log(alphabetizeString("Republic Of Serbia"));
|
import React, {Component} from "react";
export class Tabs extends Component {
constructor(props) {
super(props);
this.state={
activeIndex:props.activeIndex
}
}
TabsChange = (event,index)=>{
event.preventDefault()
this.setState({
activeIndex:index
})
this.props.onChangeTabs(index)
}
render() {
const {children} = this.props
const {activeIndex} = this.state
return (
<ul class="nav nav-tabs nav-fill my-4 ">
{
React.Children.map(children,(child,index)=>{
const activeClassName = (activeIndex === index) ? 'nav-link active' : 'nav-link';
return (
<li className="nav-item ">
<a href="#"
key={index}
onClick={(event) => {this.TabsChange(event,index)}}
className={activeClassName}
>
{child}
</a>
</li>
)
})
}
</ul>
);
}
}
export const Tab = ({children}) =>
<React.Fragment>{children}</React.Fragment>
|
var currentState,
width,
height,
frames = 0,
theBird,
theCacti,
textAndButtonContainer,
rowOneText,
rowTwoText,
theButton,
theScore = 0;
var states = {
splash: 0,
game: 1,
score: 2
};
var canvas,
renderingContext
function CactusGroup()
{
this.collection = [];
this.reset = function() {
this.collection = [];
}
this.add = function() {
this.collection.push(new Cactus());
}
this.update = function() {
if(frames % 100 === 0)
{
this.add();
}
for (var i = 0, len = this.collection.length; i < len; i++)
{
var cactus = this.collection[i];
if(i === 0)
{
cactus.detectCollision();
cactus.checkScore();
}
cactus.x -= 2;
if(cactus.x < -cactus.width)
{
this.collection.splice(i, 1);
i--;
len--;
}
}
}
this.draw = function() {
for (var i = 0, len = this.collection.length; i < len; i++)
{
var cactus = this.collection[i];
cactus.draw();
}
}
}
function Cactus()
{
this.x = width;
this.y = 0;
this.width = topMediumCactusSprite.width;
this.height = topMediumCactusSprite.height;
this.scored = false;
this.detectCollision = function() {
if (this.x <= (theBird.x + theBird.width) && this.x >= theBird.x && theBird.y <= 95)
{
currentState = states.score;
checkHighScore();
rowOneText.innerText = "Score: " + theScore + " High score: localStorage.getItem("highScore") + " ";
textAndButtonContainer.appendChild(rowTwoText);
textAndButtonContainer.appendChild(theButton);
}
if (this.x <= (theBird.x + theBird.width) && this.x >= theBird.x && theBird.y >= 185)
{
currentState = states.score;
checkHighScore();
rowOneText.innerText = "Score: " + theScore + " High score: localStorage.getItem("highScore") + " ";
textAndButtonContainer.appendChild(rowTwoText);
textAndButtonContainer.appendChild(theButton);
}
}
// var cx = Math.min(Math.max(theBird.x, this.x), this.x + this.width);
// var cy1 = Math.min(Math.max(theBird.y, this.y), this.y + this.height);
// var cy2 = Math.min(Math.max(theBird.y, this.y + this.height + 110), this.y + 2 * this.height + 80);
// // Closest difference
// var dx = theBird.x - cx;
// var dy1 = theBird.y - cy1;
// var dy2 = theBird.y - cy2;
// // Vector length
// var d1 = dx * dx + dy1 * dy1;
// var d2 = dx * dx + dy2 * dy2;
// var r = theBird.radius * theBird.radius;
// // Determine intersection
// if (r > d1 || r > d2)
// {
// currentState = states.score;
// }
this.draw = function() {
topMediumCactusSprite.draw(renderingContext, this.x, this.y);
bottomMediumCactusSprite.draw(renderingContext, this.x, height - this.height);
}
this.checkScore = function() {
if((this.x + this.width) < 150 && !this.scored) //If the bird passes the right edge of the cactus
{
theScore++;
this.scored = true;
rowOneText.innerText = "Score: " + theScore;
console.log("Score: " + theScore);
}
}
}
//
function UserGuy()
{
this.x = 0;
this.y = 130;
this.width = 45;
this.height = 55;
this.frame = 0;
this.velocity = 0;
this.animation = [0, 1, 2, 3];
this.rotation = 0;
this.radius = 12;
this.gravity = 0.35;
this._jump = 4.5;
this.flap = function() {
this.velocity = -this._jump;
}
this.update = function() {
var h = currentState === states.splash ? 15 : 10;
this.frame += frames % h === 0 ? 1 : 0
this.frame %= this.animation.length;
if(currentState === states.splash)
{
this.updateIdleBird();
}
else
{
this.updatePlayingBird();
}
};
this.updateIdleBird = function() //This function does nothing, so why does it exist?
{
// this.y = 250;
};
this.updatePlayingBird = function()
{
this.velocity += this.gravity;
this.y += this.velocity;
this.ground = 300;
//Checks if the dude hits the ground and stays there.
if(this.y >= this.ground)
{
this.y = this.ground;
this.velocity = this._jump;
currentState = states.score;
checkHighScore();
rowOneText.innerText = "Score: " + theScore + " High score: localStorage.getItem("highScore") + " ";
textAndButtonContainer.appendChild(rowTwoText);
textAndButtonContainer.appendChild(theButton);
}
};
this.draw = function(renderingContext) {
renderingContext.save();
renderingContext.translate(this.x, this.y);
renderingContext.rotate(this.rotation);
if(currentState === states.splash || currentState === states.game)
{
var h = this.animation[this.frame];
birdSprites[h].draw(renderingContext, 20, this.y);
}
else
{
birdSprites[0].draw(renderingContext, 20, theBird.y);
}
renderingContext.restore();
};
}
function onpress(evt) //This evt parameter is not used, so why does it exist?
{
switch (currentState)
{
case states.splash:
theBird.flap();
currentState = states.game;
rowOneText.innerText = "Score: ";
break;
case states.game:
theBird.flap();
break;
}
}
function executeJS()
{
setUpWindow();
setUpCanvas();
currentState = states.splash;
document.body.appendChild(canvas);
textAndButtonContainer = document.createElement("div");
textAndButtonContainer.id = "box";
document.body.appendChild(textAndButtonContainer);
rowOneText = document.createElement("span");
rowOneText.className = "text";
rowOneText.innerText = "Click to play";
textAndButtonContainer.appendChild(rowOneText);
rowTwoText = document.createElement("span");
rowTwoText.className = "text";
rowTwoText.innerText = "You died!";
//I don't append rowTwoText here.
theButton = document.createElement("input");
theButton.id = "theButton";
theButton.setAttribute("type", "button");
theButton.setAttribute("value", "Play again");
// theButton.onclick = resetGame();
theButton.onclick = buttonTest(); //If you look at the console, you'll see that the button onclick gets called every time the page refreshes, instead of whenever the button is clicked. This is obviously a problem.
//I don't append theButton here.
loadGraphics();
theBird = new UserGuy();
theCacti = new CactusGroup();
}
function buttonTest()
{
console.log("Does the button work?"); //Just tesing to see when the button onclick gets called.
}
function setUpWindow()
{
var inputEvent = "touchstart";
var windowWidth = window.innerWidth;
console.log(windowWidth);
if(windowWidth < 500)
{
width = 320;
height = 430;
}
else
{
width = 900;
height = 666;
inputEvent = "mousedown";
}
document.addEventListener("mousedown", onpress);
}
function setUpCanvas()
{
canvas = document.createElement("canvas");
canvas.style.border = "4px solid black";
canvas.id = "canvas";
canvas.width = width;
canvas.height = height;
renderingContext = canvas.getContext("2d");
}
function checkHighScore()
{
// Check browser support
if (typeof(Storage) !== "undefined" && theScore > localStorage.getItem("highScore"))
{
// Store
localStorage.setItem("highScore", theScore);
// Retrieve
console.log(localStorage.getItem("highScore"));
}
}
function resetGame()
{
currentState = states.splash;
theCacti.reset();
rowOneText.innerText = "Click to play";
textAndButtonContainer.removeChild(rowTwoText);
textAndButtonContainer.removeChild(theButton);
theBird.y = 130;
theScore = 0;
}
function loadGraphics()
{
var spriteSheet = new Image();
spriteSheet.src = "spriteSheet.png";
spriteSheet.onload = function() {
initSprites(this);
gameLoop();
};
}
function gameLoop()
{
update();
render();
window.requestAnimationFrame(gameLoop);
}
function update()
{
frames++;
theBird.update();
if(currentState === states.game)
{
theCacti.update();
}
}
function render()
{
backgroundSprite.draw(renderingContext, 0, 0);
theCacti.draw(renderingContext);
theBird.draw(renderingContext);
}
|
import React, { useState, useEffect } from "react";
import { useHistory } from "react-router-dom";
import { Col, Row, Layout } from "antd";
import ContentWrapper from "../atoms/ContentWraper";
import FooterWrapper from "../atoms/FooterWrapper";
import MenuItem from "../molecules/MenuItem";
import Logo from "../molecules/Logo";
const { Header, Footer } = Layout;
const SiteLayout = ({ children }) => {
const { push } = useHistory();
const handleGoToMainPage = () => push("/");
return (
<Layout>
<Header>
<Row justify="space-between">
<Col>
<Logo onClick={handleGoToMainPage} />
</Col>
<Col>
<MenuItem text={"Login"} onClick={handleGoToMainPage} />
<MenuItem text={"Map"} onClick={handleGoToMainPage} />
</Col>
</Row>
</Header>
<ContentWrapper>{children}</ContentWrapper>
<Footer>
<FooterWrapper>
<p>Created by Antonín Světinský</p>
</FooterWrapper>
</Footer>
</Layout>
);
};
export default SiteLayout;
|
/**
* Clients Slider
*/
import React, { Component } from "react";
import Slider from "react-slick";
// api
import api from 'Api';
export default class Clientslider extends Component {
state = {
clients: null
}
componentDidMount() {
this.getClients();
}
// get clients
getClients() {
api.get('clients.js')
.then((response) => {
this.setState({ clients: response.data });
})
.catch(error => {
// error handling
})
}
render() {
const { clients } = this.state;
const settings = {
dots: false,
infinite: true,
speed: 1000,
slidesToShow: 6,
slidesToScroll: 1,
autoplay: true,
rtl: false,
responsive: [
{
breakpoint: 1367,
settings: {
slidesToShow: 4,
slidesToScroll: 1,
infinite: true
}
},
{
breakpoint: 575,
settings: {
slidesToShow: 3,
slidesToScroll: 1
}
},
{
breakpoint: 400,
settings: {
slidesToShow: 2,
slidesToScroll: 1
}
}
]
};
return (
<div>
<Slider {...settings}>
{clients && clients.map((client, key) => (
<div key={key}>
<img src={client.photo_url} alt="client log" className="img-fluid" width="" height="" />
</div>
))}
</Slider>
</div>
);
}
}
|
import React, { Component } from 'react';
import { Text, View,StyleSheet,Image,ScrollView,TouchableOpacity,SafeAreaView,TouchableWithoutFeedback } from 'react-native';
import { time_red, check, uncheck, back_arrow,invite, location, calendar_red, time, scanner } from '../../assets/icons/index';
import { event_image, register_input_bg,register,logo } from '../../assets/images/index';
import { Button_add,Button_next } from "../button";
import FBFont from '../font';
export default class RegistrationReview extends Component {
static navigationOptions = {
};
constructor() {
super();
this.state = { isChecked01: true};
}
jumpTo(route){
this.props.navigation.navigate(route)
}
renderImage = (isChecked) => {
let imageSrc = isChecked ? uncheck : check;
return (
<Image
style={styles.checkBox}
source={imageSrc}
/>
);
}
render() {
return (
<SafeAreaView style={{ flex: 1, backgroundColor: '#FFFFFF' }}>
<ScrollView>
<View style={styles.container}>
<Text style={[FBFont.AlternateGot(23), styles.heading]}>Event Registration Review</Text>
<View style={[styles.shadow,styles.card]}>
<Text style={[styles.heading1,styles.strong]}>THE BEST HIGH SCHOOL FOOTBALL WORLDWIDE</Text>
<Text>It may be America’s sport, but competition comes from all over the world. Come see the top football players from the U.S., Mexico, Japan, Canada, Panama and more compete at the tenth annual International Bowl. It may be America’s sport, but competition comes from all over the world. </Text>
<View style={[styles.row, styles.imgText]}>
<Image source={location} style={{ width: 15.2, height: 16.5 }} resizeMode="contain" />
<Text style={[styles.wrap, styles.txt]}>High School Training Camp - CANTON</Text>
</View>
<View style={[styles.row,styles.timeDate]}>
<View style={{width:"60%"}}>
<View style={[styles.row,styles.imgText]}>
<Image source={calendar_red} style={{width:25,height:25,marginTop:3}}/>
<Text style={[styles.wrap,styles.txt,styles.txtColor,styles.strong]}>Dec 28 & 29, 2019</Text>
</View>
<View style={[styles.row,styles.imgText]}>
<Image source={time_red} style={{width:25,height:25,marginTop:3}}/>
<Text style={[styles.wrap,styles.txt,styles.txtColor,styles.strong]}>08:00 am - 02:00 pm</Text>
</View>
</View>
<View style={styles.line}></View>
<View style={{width:"35%",justifyContent:"center",alignItems:"center"}}>
<Text style={styles.attendeesText}>ATTENDEES</Text>
<Text style={[styles.strong,styles.attendeesText]}>275/300</Text>
</View>
</View>
</View>
<View style={[styles.shadow,styles.card1]}>
<Text style={[styles.strong,styles.nameText]}>Sean Wilkening</Text>
<Text style={styles.horizontalLine}></Text>
<Text style={[styles.strong,styles.nameText]}>Dennis Wilkening</Text>
<View style={[styles.row,styles.agree]}>
<TouchableWithoutFeedback
style={styles.checkBox}
onPress={() => this.setState({ isChecked01: !this.state.isChecked01 })}
>
<View style={[styles.row,{alignItems:"center"}]}>
{this.renderImage(this.state.isChecked01)}
<Text style={styles.agreeText}>I agree to waiver for all attendees</Text>
</View>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback>
<Text style={styles.link}>Link To Waiver</Text>
</TouchableWithoutFeedback>
</View>
</View>
<View style={[styles.shadow,styles.card1]}>
<View style={styles.rate}>
<Text style={styles.strong}>Sub Total</Text>
<Text style={styles.strong}>$200.00</Text>
</View>
<View style={styles.rate}>
<Text style={styles.strong}>Discount</Text>
<Text style={styles.strong}>$10.00</Text>
</View>
<View style={styles.rate}>
<Text style={styles.strong}>Tax</Text>
<Text style={styles.strong}>$3.60</Text>
</View>
<View style={styles.horizontalLine}></View>
<View style={styles.rate}>
<Text style={styles.strong}>Total</Text>
<Text style={styles.strong}>$193.60</Text>
</View>
</View>
<View style={[styles.row,styles.buttons]}>
<View style={styles.btnCancel}>
<Button_next text="Cancel" height={39} page={()=>this.jumpTo('Events')}/>
</View>
<View style={styles.btnNext}>
<Button_next text="Register" height={39} page={()=>this.jumpTo('RegistrationDone')}/>
</View>
</View>
</View>
</ScrollView>
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#FFFFFF',
paddingHorizontal: 14.5,
alignItems:"center",
justifyContent:"center",
flex:1
},
heading: {
marginTop: 31,
marginBottom: 12.5,
textAlign: "center"
},
row:{
flexDirection:"row"
},
wrap:{
flexWrap:'wrap'
},
shadow:{
shadowColor:'#000000',
shadowOffset:{width:0,height:8},
shadowOpacity:0.4,
shadowRadius:6,
elevation:6,
backgroundColor:'#FFFFFF'
},
strong:{
fontWeight:"bold",
},
card:{
marginVertical:12.5,
paddingVertical:15,
paddingHorizontal:19
},
heading1:{
fontSize:14,
color:'#8F0026',
marginBottom:3
},
imgText: {
alignItems: "center",
marginVertical: 12
},
txt: {
marginLeft: 9
},
txtColor:{
color:'#8F0026',
fontSize:16
},
timeDate:{
justifyContent:"space-between"
},
line:{
width:1,
height:"100%",
backgroundColor:"#59575D"
},
attendeesText:{
textAlign:"center",
fontSize:15,
marginTop:3
},
card1:{
marginVertical:12.5,
paddingVertical:15,
width:"100%"
},
horizontalLine:{
width:"100%",
height:1,
backgroundColor:"#59575D",
marginVertical:3
},
nameText:{
paddingVertical:5,
paddingHorizontal:19,
fontSize:16
},
agree:{
flexDirection:"row",
justifyContent:"space-between",
alignItems:"center",
paddingHorizontal:19,
paddingTop:15
},
checkBox:{
width:15,
height:15
},
link:{
color:'#8F0026',
textDecorationLine:"underline",
textDecorationColor:'#8F0026'
},
agreeText:{
marginLeft:5
},
rate:{
paddingHorizontal:19,
flexDirection:"row",
justifyContent:"space-between",
paddingVertical:3
},
buttons:{
justifyContent:"center",
marginTop:12.5,
marginBottom:25
},
btnNext:{
width:101
},
btnCancel:{
width:101,
marginRight:27
}
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.