text
stringlengths
7
3.69M
function showOverlay() { var div = document.createElement("div"); div.id = "ulitharidoverlay"; div.style.borderRadius = "3px"; div.style.overflow = "hidden !important"; div.style.boxShadow = "0px 0px 8px #389515"; div.style.zIndex = "1100"; div.style.boxSizing = "content-box"; div.style.left = "471px"; div.style.top = "354px"; div.style.visibility = "visible"; div.style.position = "absolute"; div.style.padding = "10px"; div.style.backgroundColor = "#cccccc"; div.style.textAlign = "center"; headline = document.createElement("span"); headline.innerHTML = "Ulitharid"; headline.style.color = "#CC2D4F"; close = document.createElement("span"); close.addEventListener("click", closeOverlay); close.innerHTML = "close"; div.appendChild(headline); div.appendChild(document.createElement("br")); div.appendChild(document.createElement("br")); div.appendChild(close); document.body.appendChild(div); var x = ((window.innerWidth - div.offsetWidth) / 2) + "px"; var y = ((window.innerHeight - div.offsetHeight) / 2 + window.scrollY) + "px"; div.style.left = x; div.style.top = y; } function closeOverlay() { var div = document.getElementById("ulitharidoverlay"); div.parentElement.removeChild(div); } showOverlay();
const hobbies = ['sports', 'reading']; console.log(hobbies.slice()); console.log(...hobbies); const toArray = (arg1, arg2, arg3) => { return [1, 2, 3]; } console.log(toArray(1, 2, 3)); const toArrayWithRest = (...arg) => { return arg; } console.log(toArrayWithRest(1, 2, 3));
import './style.css' import firebase from 'firebase/app'; import 'firebase/firestore'; // For Firebase JS SDK v7.20.0 and later, measurementId is optional const firebaseConfig = { apiKey: "AIzaSyBICgq7PthNQownOfWMpC8SH2Lg-6391KQ", authDomain: "vidchat-b53cc.firebaseapp.com", projectId: "vidchat-b53cc", storageBucket: "vidchat-b53cc.appspot.com", messagingSenderId: "436718064604", appId: "1:436718064604:web:36e3fa4ef319bdd0623519", measurementId: "G-T24N3WTLML" }; if (!firebase.apps.length) { firebase.initializeApp(firebaseConfig); } const firestore = firebase.firestore(); //ice candidates for connections const servers = { iceServers: [ { urls: ['stun:stun1.l.google.com:19302', 'stun:stun2.l.google.com:19302'], }, ], iceCandidatePoolSize: 10, }; //Globals to share across STUN server let pc = new RTCPeerConnection(servers); let localStream = null; let remoteStream = null; const webcamButton = document.getElementById('webcamButton'); const webcamVideo = document.getElementById('webcamVideo'); const callButton = document.getElementById('callButton'); const callInput = document.getElementById('callInput'); const answerButton = document.getElementById('answerButton'); const remoteVideo = document.getElementById('remoteVideo'); const hangupButton = document.getElementById('hangupButton'); //initialize media webcamButton.onclick = async () => { console.log(navigator.mediaDevices); //promises -> objects localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true }); remoteStream = new MediaStream(); //update page localStream.getTracks().forEach((track) => { pc.addTrack(track, localStream); }); //listen to peer connections pc.ontrack = (event) => { event.streams[0].getTracks().forEach((track) => { remoteStream.addTrack(track); }); }; webcamVideo.srcObject = localStream; remoteVideo.srcObject = remoteStream; callButton.disabled = false; answerButton.disabled = false; webcamButton.disabled = true; }; //Connect calls = offers callButton.onclick = async () => { //use firestore signalling const callDoc = firestore.collection('calls').doc(); const offerCandidates = callDoc.collection('offerCandidates'); const answerCandidates = callDoc.collection('answerCandidates'); callInput.value = callDoc.id; //generate firestore id //save candidates to database pc.onicecandidate = (event) => { event.candidate && offerCandidates.add(event.candidate.toJSON()); }; //create the offer const offerDescription = await pc.createOffer(); await pc.setLocalDescription(offerDescription); const offer = { sdp: offerDescription.sdp, type: offerDescription.type, }; //save session-description-protocol to database await callDoc.set({ offer }); //listen for changes in firestore to determine answer callDoc.onSnapshot((snapshot) => { const data = snapshot.data(); //answer candidate is not occupied if (!pc.currentRemoteDescription && data?.answer) { //when answer is heard, create SDP const answerDescription = new RTCSessionDescription(data.answer); pc.setRemoteDescription(answerDescription); } }); //add candidate to peer connections answerCandidates.onSnapshot((snapshot) => { snapshot.docChanges().forEach((change) => { if (change.type === 'added') { const candidate = new RTCIceCandidate(change.doc.data()); pc.addIceCandidate(candidate); } }); }); hangupButton.disabled = false; }; // Answering calls answerButton.onclick = async () => { //retrieve ID const callId = callInput.value; const callDoc = firestore.collection('calls').doc(callId); const answerCandidates = callDoc.collection('answerCandidates'); const offerCandidates = callDoc.collection('offerCandidates'); //save candidate to database pc.onicecandidate = (event) => { event.candidate && answerCandidates.add(event.candidate.toJSON()); }; const callData = (await callDoc.get()).data(); //create peer connection const offerDescription = callData.offer; await pc.setRemoteDescription(new RTCSessionDescription(offerDescription)); //generate description a local and set it as answer const answerDescription = await pc.createAnswer(); await pc.setLocalDescription(answerDescription); const answer = { sdp: answerDescription.sdp, type: answerDescription.type, }; //update SDP in database so streams can listen to one-another await callDoc.update({ answer }); //add candidate to peer connection offerCandidates.onSnapshot((snapshot) => { snapshot.docChanges().forEach((change) => { if (change.type === 'added') { let data = change.doc.data(); pc.addIceCandidate(new RTCIceCandidate(data)); } }); }); hangupButton.disabled = false; }; //Ending the connection hangupButton.onclick = async () => { remoteStream = null; pc.close(); };
import React, {useState} from 'react'; import { StyleSheet, Text, useColorScheme, View, TouchableOpacity, TextInput, ImageBackground, } from 'react-native'; import Content from './Content'; import SkipButton from '../buttons/SkipButton'; const page = ['MARRY', 'AGE', 'ASSET']; const Poll = ({navigation}) => { const [index, setIndex] = useState(0); const onPress = () => { if (index == page.length - 1) { navigation.navigate('Result'); } }; const onNext = () => { if (index == page.length - 1) { return; } setIndex(index + 1); }; const onPrev = () => { if (index == 0) { return; } setIndex(index - 1); }; return ( <View style={styles.container}> <ImageBackground source={require('../images/house.png')} resizeMode="cover" style={styles.image}> <View style={styles.header}> {/* <Text style={{fontWeight: 'bold', fontSize: 20, marginLeft: 20, marginTop: 20, color: 'black'}}>실거주 1주택은 진리</Text> */} </View> <View style={styles.content}> <View style={styles.contentHeader}> <Text style={styles.headerText}> 몇 가지 질문으로 적정 대출 금액을 계산해봅니다. </Text> </View> <Content div={page[index]} /> <View style={styles.contentFooter}> <SkipButton style={styles.prevButton} onPress={onPrev} text={'이전'} disabled={index == 0 ? true : false} /> <SkipButton style={styles.nextButton} onPress={onNext} text={'다음'} disabled={index == page.length - 1 ? true : false} /> </View> </View> <View style={styles.footer}> <TouchableOpacity style={index < page.length - 1 ? styles.btnDisabled : styles.btn} onPress={onPress} disabled={index < page.length - 1 ? true : false}> <Text style={styles.text}>적정 금액 확인</Text> </TouchableOpacity> </View> </ImageBackground> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, // backgroundColor: 'white', // padding: 30, }, image: { flex: 1, justifyContent: 'center', }, header: { height: '15%', }, content: { flex: 1, /* box shadow */ shadowColor: '#000', shadowOffset: { width: 0, height: 5, }, shadowOpacity: 0.34, shadowRadius: 6.27, elevation: 10, borderRadius: 10, marginHorizontal: 15, backgroundColor: 'white', }, footer: { height: '15%', justifyContent: 'center', }, btn: { height: 50, backgroundColor: '#4F4F4F', alignItems: 'center', justifyContent: 'center', }, btnDisabled: { height: 50, backgroundColor: '#A19F9F', alignItems: 'center', justifyContent: 'center', }, text: { color: 'white', fontWeight: 'bold', fontSize: 20, }, contentHeader: { height: '20%', justifyContent: 'center', }, headerText: { backgroundColor: '#8155FF', color: 'white', fontWeight: 'bold', height: 50, marginHorizontal: 15, textAlign: 'center', textAlignVertical: 'center', borderRadius: 10, shadowColor: '#000', shadowOpacity: 0.25, shadowOffset: { width: 0, height: 5, }, shadowRadius: 0, elevation: 10, }, contentFooter: { height: '15%', flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginHorizontal: 20, }, }); export default Poll;
function createContentDiv() { let rDiv = document.createElement('div'); rDiv.innerText = '我是内容'; document.getElementById('root').appendChild(rDiv); } exports.createContentDiv = createContentDiv;
import React, { Component } from 'react' import { AppRegistry } from 'react-native' import { StackNavigator } from 'react-navigation' import Main from './App/Components/MainScreen' import Home from './App/Components/HomeScreen' const nativeSocketioTessel = StackNavigator({ home: { screen: Home }, main: { screen: Main } }) AppRegistry.registerComponent('nativeSocketioTessel', () => nativeSocketioTessel)
var webqr = function () { var gCtx = null; var gCanvas = null; var c = 0; var stype = 0; var gUM = false; var webkit = false; var moz = false; var v = null; var qrCanvas=null; var qrResult=null; function dragenter(e) { e.stopPropagation(); e.preventDefault() } function dragover(e) { e.stopPropagation(); e.preventDefault() } function drop(e) { e.stopPropagation(); e.preventDefault(); var dt = e.dataTransfer; var files = dt.files; if (files.length > 0) { handleFiles(files) } else { if (dt.getData("URL")) { qrcode.decode(dt.getData("URL")) } } } /** * 解析二维码 * @param {*} f */ function handleFiles(f) { var o = []; for (var i = 0; i < f.length; i++) { var reader = new FileReader(); reader.onload = (function (theFile) { return function (e) { gCtx.clearRect(0, 0, gCanvas.width, gCanvas.height); var img = new Image(); img.onload = function () { setTimeout(function () { gCtx.drawImage(img, 0, 0, gCanvas.width, gCanvas.height) }, 0) }; img.src = e.target.result; qrcode.decode(e.target.result) } })(f[i]); reader.readAsDataURL(f[i]) } } function initCanvas(w, h) { gCanvas = document.getElementById(qrCanvas); gCanvas.style.width = w + "px"; gCanvas.style.height = h + "px"; gCanvas.width = w; gCanvas.height = h; gCtx = gCanvas.getContext("2d"); gCtx.clearRect(0, 0, w, h) } function captureToCanvas() { if (stype != 1) { return } if (gUM) { try { gCtx.drawImage(v, 0, 0); try { qrcode.decode() } catch (e) { setTimeout(captureToCanvas, 500) } } catch (e) { console.log(e); setTimeout(captureToCanvas, 500) } } } function htmlEntities(str) { return String(str).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;") } function read(a) { var html = ""; if (a.indexOf("http://") === 0 || a.indexOf("https://") === 0) { html += "<a target='_blank' href='" + a + "'>" + a + "</a><br>" } else { html += "<bdi>" + htmlEntities(a) + "</bdi>"; } document.getElementById(qrResult).innerHTML = html } function isCanvasSupported() { var elem = document.createElement("canvas"); return !!(elem.getContext && elem.getContext("2d")) } function success(stream) { if (webkit) { v.src = window.webkitURL.createObjectURL(stream) } else { if (moz) { v.mozSrcObject = stream; v.play() } else { v.src = stream } } gUM = true; setTimeout(captureToCanvas, 500) } function error(error) { gUM = false; return } /** * 初始化 * @param {String} qrfile 初始化的区域,id值, qrCanvas:canvas的Id,qrResult分析结果区块的ID * @param {*} width canvas宽度 * @param {*} heigth canvas高度 */ function load(qrfile,width, heigth) { if (isCanvasSupported() && window.File && window.FileReader) { initR(qrfile) initCanvas(width || 200, heigth || 200); qrcode.callback = read; } else { } } function initR(qr) { var qrfile = document.getElementById(qr); qrCanvas=qrfile.getAttribute('qrCanvas'); qrResult=qrfile.getAttribute('qrResult'); qrfile.addEventListener("dragenter", dragenter, false); qrfile.addEventListener("dragover", dragover, false); qrfile.addEventListener("drop", drop, false) }; return { load, handleFiles } } window.webqr = webqr()
/*global Validate, valueFromAttrName */ describe('validate', function() { describe('validator', function() { it('should validate data object attribute', function() { expect(Validate.validate( {bar: 1}, { foo: {notEmpty: {msg: 'empty'}}, baz: {same: {as: 'bar', msg: 'same'}} })) .to.eql([ {name: 'foo', message: 'empty'}, {name: ['baz', 'bar'], message: 'same'} ]); }); it('should validate multiple fields', function() { expect(Validate.validate( {bar: 1}, { 'foo baz': {notEmpty: {msg: 'empty'}} })) .to.eql([ {name: 'foo', message: 'empty'}, {name: 'baz', message: 'empty'} ]); }); it('should execute array objects multiple times', function() { expect(Validate.validate( {bar: 1}, { foo: { same: [ {as: 'bar', msg: 'same'}, {as: 'baz', msg: 'same2'} ] } })) .to.eql([ {name: ['foo', 'bar'], message: 'same'} ]); expect(Validate.validate( {baz: 1}, { foo: { same: [ {as: 'bar', msg: 'same'}, {as: 'baz', msg: 'same2'} ] } })) .to.eql([ {name: ['foo', 'baz'], message: 'same2'} ]); }); it('should execute custom validators', function() { expect(Validate.validate( {bar: 1}, { anyShitYouWant: { same: function() { return ['msg']; } } })) .to.eql(['msg']); }); it('should only display one error per field', function() { expect(Validate.validate( {bar: 1, baz: 1}, { foo: { same: [ {as: 'bar', msg: 'same'}, {as: 'baz', msg: 'same2'} ] } })) .to.eql([ {name: ['foo', 'bar'], message: 'same'} ]); }); it('should handle primitives', function() { expect(Validate.validate( {bar: 'a', baz: '{', bak: 'k', bat: 'bar'}, { foo: { notEmpty: true, }, bar: { numeric: true, }, baz: { invalidCharacters: true, }, bak: { invalidCharacters: /k/, }, bat: { pattern: /foo/ } })) .to.eql([ {name: 'foo', message: {format: '{{attribute}} cannot be blank'}}, {name: 'bar', message: {value: 'a', format: '{{attribute}} must be a number.'}}, {name: 'baz', message: {value: '{', format: '{{attribute}} cannot contain \'{{value}}\''}}, {name: 'bak', message: {value: 'k', format: '{{attribute}} cannot contain \'{{value}}\''}}, {name: 'bat', message: {value: 'bar', format: '{{attribute}} value {{value}} is invalid.'}} ]); }); }); describe('#notEmpty', function() { it('should not error with content', function() { var options = {fields: ['foo']}; expect(Validate.notEmpty({foo: 'bar'}, options)).to.eql([]); expect(Validate.notEmpty({foo: 0}, options)).to.eql([]); }); it('should error when empty', function() { var errors = [{name: 'foo', message: 'foo'}], options = {fields: ['foo'], msg: 'foo'}; expect(Validate.notEmpty({foo: ''}, options)).to.eql(errors); expect(Validate.notEmpty({foo: ' '}, options)).to.eql(errors); expect(Validate.notEmpty({foo: ' \n\t '}, options)).to.eql(errors); expect(Validate.notEmpty({}, options)).to.eql(errors); }); }); describe('#same', function() { var options = {fields: ['foo', 'bar'], msg: 'YOUR SHIT MUST MATCH!'}; it('should not error if two fields are the same', function() { expect(Validate.same({foo: 1, bar: 1}, options)).to.eql([]); expect(Validate.same({}, options)).to.eql([]); expect(Validate.same({foo: 'a', bar: 'a'}, options)).to.eql([]); expect(Validate.same( {foo: 'a', bar: 'a', baz: 'a'}, {fields: ['foo', 'bar', 'baz']})) .to.eql([]); }); it('should error if two fields do not match', function() { var errors = [{name: ['foo', 'bar'], message: 'YOUR SHIT MUST MATCH!'}]; expect(Validate.same({foo: 1}, options)).to.eql(errors); expect(Validate.same({bar: 1}, options)).to.eql(errors); expect(Validate.same({foo: 1, bar: '1'}, options)).to.eql(errors); expect(Validate.same({foo: 'asdf', bar: 'jkl;'}, options)).to.eql(errors); expect(Validate.same( {foo: 'a', bar: 'a', baz: 'b'}, {fields: ['foo', 'bar', 'baz'], msg: 'YOUR SHIT MUST MATCH!'})) .to.eql([{name: ['foo', 'bar', 'baz'], message: 'YOUR SHIT MUST MATCH!'}]); }); }); describe('#pattern', function() { it('should not error when valid', function() { var options = {fields: ['foo'], pattern: /abcd/}; expect(Validate.pattern({foo: 'abcd'}, options)).to.eql([]); options = {fields: ['foo'], pattern: /abc/}; expect(Validate.pattern({foo: 'abcd'}, options)).to.eql([]); }); it('should error when does not match', function() { var errors = [{name: 'foo', message: {value: '123', format: 'foo'}}], options = {fields: ['foo'], msg: {format: 'foo'}, pattern: /abcd/}; expect(Validate.pattern({foo: '123'}, options)).to.eql(errors); options = {fields: ['foo'], msg: {format: 'foo'}, pattern: /^12$/}; expect(Validate.pattern({foo: '123'}, options)).to.eql(errors); }); it('should match email', function() { expect(Validate.pattern( {foo: 'blaz@blaz.me'}, {fields: ['foo'], pattern: Validate.email})) .to.eql([]); }); }); describe('#invalidCharacters', function() { it('should not error when valid', function() { var options = {fields: ['foo']}; expect(Validate.invalidCharacters({foo: 'abcd'}, options)).to.eql([]); }); it('should error when matches', function() { var errors = [{name: 'foo', message: {value: '{', format: 'foo'}}], options = {fields: ['foo'], msg: {format: 'foo'}}; expect(Validate.invalidCharacters({foo: '{'}, options)).to.eql(errors); }); it('should pull pattern from options', function() { var errors = [{name: 'foo', message: 'foo'}], options = {fields: ['foo'], msg: 'foo', pattern: /a/}; expect(Validate.invalidCharacters({foo: 'a'}, options)).to.eql(errors); options = {fields: ['foo'], msg: 'foo', pattern: {foo: /a/}}; expect(Validate.invalidCharacters({foo: 'a'}, options)).to.eql(errors); options = {fields: ['foo'], msg: 'foo', pattern: {bar: /a/}}; expect(Validate.invalidCharacters({foo: 'a'}, options)).to.eql([]); options = {fields: ['foo'], msg: 'foo', pattern: /a/}; expect(Validate.invalidCharacters({foo: '{'}, options)).to.eql([]); }); }); describe('#numeric', function() { it('should cast to integers', function() { var attributes = {foo: '1'}; expect(Validate.numeric(attributes, {fields: ['foo']})).to.eql([]); expect(attributes.foo).to.equal(1); attributes = {foo: '-1'}; expect(Validate.numeric(attributes, {fields: ['foo']})).to.eql([]); expect(attributes.foo).to.equal(-1); attributes = {foo: ' 1 '}; expect(Validate.numeric(attributes, {fields: ['foo']})).to.eql([]); expect(attributes.foo).to.equal(1); attributes = {foo: '0'}; expect(Validate.numeric(attributes, {fields: ['foo']})).to.eql([]); expect(attributes.foo).to.equal(0); attributes = {foo: '0.1'}; expect(Validate.numeric(attributes, {fields: ['foo']})).to.eql([]); expect(attributes.foo).to.equal(0.1); attributes = {foo: 1}; expect(Validate.numeric(attributes, {fields: ['foo']})).to.eql([]); expect(attributes.foo).to.equal(1); }); it('should allow for custom matcher', function() { var attributes = {foo: 'a1'}; expect(Validate.numeric( attributes, {fields: ['foo'], pattern: /^a(\d+)$/})) .to.eql([]); expect(attributes.foo).to.equal(1); }); it('should error on mismatch', function() { var options = {fields: ['foo'], msg: 'FAIL'}, error = [{name: 'foo', message: 'FAIL'}]; var attributes = {foo: 'asdf'}; expect(Validate.numeric(attributes, options)).to.eql(error); expect(attributes.foo).to.equal('asdf'); attributes = {foo: '1a'}; expect(Validate.numeric(attributes, options)).to.eql(error); expect(attributes.foo).to.equal('1a'); attributes = {foo: 'a1'}; expect(Validate.numeric(attributes, options)).to.eql(error); expect(attributes.foo).to.equal('a1'); }); }); describe('#range', function() { it('should accept a valid input range', function() { expect(Validate.range({foo: 1}, {fields: ['foo']})).to.eql([]); expect(Validate.range({foo: 1}, {fields: ['foo'], lt: 1.1})).to.eql([]); expect(Validate.range({foo: 1}, {fields: ['foo'], lte: 1})).to.eql([]); expect(Validate.range({foo: 1}, {fields: ['foo'], gte: 1})).to.eql([]); expect(Validate.range({foo: 1}, {fields: ['foo'], gt: 0.9})).to.eql([]); expect(Validate.range({foo: -1}, {fields: ['foo'], lt: 0})).to.eql([]); expect(Validate.range({foo: -1}, {fields: ['foo'], lte: 0})).to.eql([]); expect(Validate.range({foo: 1}, {fields: ['foo'], gte: 0})).to.eql([]); expect(Validate.range({foo: 1}, {fields: ['foo'], gt: 0})).to.eql([]); expect(Validate.range({foo: 'bar'}, {fields: ['foo']})).to.eql([]); expect(Validate.range({foo: 'bar'}, {fields: ['foo'], lt: 'bas'})).to.eql([]); expect(Validate.range({foo: 'bar'}, {fields: ['foo'], lte: 'bar'})).to.eql([]); expect(Validate.range({foo: 'bar'}, {fields: ['foo'], gte: 'bar'})).to.eql([]); expect(Validate.range({foo: 'bar'}, {fields: ['foo'], gt: 'ba'})).to.eql([]); }); it('should error if out of range', function() { expect(Validate.range({foo: 1}, {fields: ['foo'], gt: 1.1, msg: 'it died'})) .to.eql([{name: 'foo', message: 'it died'}]); expect(Validate.range({foo: 0.9}, {fields: ['foo'], gte: 1, msg: 'it died'})) .to.eql([{name: 'foo', message: 'it died'}]); expect(Validate.range({foo: 1.1}, {fields: ['foo'], lte: 1, msg: 'it died'})) .to.eql([{name: 'foo', message: 'it died'}]); expect(Validate.range({foo: 1}, {fields: ['foo'], lt: 0.9, msg: 'it died'})) .to.eql([{name: 'foo', message: 'it died'}]); expect(Validate.range({foo: -1}, {fields: ['foo'], gt: 0, msg: 'it died'})) .to.eql([{name: 'foo', message: 'it died'}]); expect(Validate.range({foo: -1}, {fields: ['foo'], gte: 0, msg: 'it died'})) .to.eql([{name: 'foo', message: 'it died'}]); expect(Validate.range({foo: 1}, {fields: ['foo'], lte: 0, msg: 'it died'})) .to.eql([{name: 'foo', message: 'it died'}]); expect(Validate.range({foo: 1}, {fields: ['foo'], lt: 0, msg: 'it died'})) .to.eql([{name: 'foo', message: 'it died'}]); expect(Validate.range({foo: 'bar'}, {fields: ['foo'], gt: 'bas', msg: 'it died'})) .to.eql([{name: 'foo', message: 'it died'}]); expect(Validate.range({foo: 'bar'}, {fields: ['foo'], gte: 'bas', msg: 'it died'})) .to.eql([{name: 'foo', message: 'it died'}]); expect(Validate.range({foo: 'bar'}, {fields: ['foo'], lte: 'ba', msg: 'it died'})) .to.eql([{name: 'foo', message: 'it died'}]); expect(Validate.range({foo: 'bar'}, {fields: ['foo'], lt: 'ba', msg: 'it died'})) .to.eql([{name: 'foo', message: 'it died'}]); }); }); describe('#valueFromAttrName', function() { it('should lookup simple values', function() { expect(valueFromAttrName({foo: 123}, 'foo')).to.equal(123); expect(valueFromAttrName({foo: 0}, 'foo')).to.equal(0); }); it('should lookup nested values', function() { expect(valueFromAttrName({baz: {foo: 123}}, 'baz[foo]')).to.equal(123); expect(valueFromAttrName({baz: {bar: {foo: 123}}}, 'baz[bar][foo]')).to.equal(123); }); it('should handle missing fields', function() { expect(valueFromAttrName({foo: 123}, 'bar')).to.equal(''); expect(valueFromAttrName({baz: {foo: 123}}, 'bar')).to.equal(''); expect(valueFromAttrName({baz: {foo: 123}}, 'bar[baz]')).to.equal(''); expect(valueFromAttrName({baz: {foo: 123}}, 'baz[foo][bat]')).to.equal(''); }); }); });
function solve(data) { const regex = /<svg>.*<\/svg>/g; const catRGX = /(<cat>.*?<\/cat>)/g; const labelRGX = /<text>.*\[([a-zA-Z\s].*)\]<\/text>/g; const valsRGX = /<val>([1-90-9]*?)<\/val>(\d*)/g; data = regex.exec(data); if (data === null) { console.log('No survey found'); return; } let currMatch; let matches = []; let label = ''; let valuesCount = []; while (currMatch = catRGX.exec(data)) { matches.push((decodeURIComponent(currMatch[1]))); } label = labelRGX.exec(matches[0]); if(label === null) { label = labelRGX.exec(matches[0]); } else { label = labelRGX.exec(matches[0])[1]; } if (label === null) { console.log('Invalid format'); return; } while (currMatch = valsRGX.exec(matches[1])) { valuesCount.push(currMatch[1] + ' ' + currMatch[2]); } let sum = 0; let c = 0; for (let i = 0; i < valuesCount.length; i++) { let rating = Number(valuesCount[i].split(' ')[0]); let count = Number(valuesCount[i].split(' ')[1]); c += count; sum += rating * count; } console.log(`${label}: ${+(parseFloat((sum / c).toString())).toFixed(2)}`); } solve('<p>Some random text</p><svg><cat><text>How do you rate our food? [Food - General]</text></cat><cat><g><val>1</val>0</g><g><val>2</val>1</g><g><val>3</val>3</g><g><val>4</val>10</g><g><val>5</val>7</g></cat></svg><p>Some more random text</p>'); solve('<svg><cat><text>How do you rate the special menu? [Food - Special]</text></cat> <cat><g><val>1</val>5</g><g><val>5</val>13</g><g><val>10</val>22</g></cat></svg>'); solve(`<p>How do you suggest we improve our service?</p><p>More tacos.</p><p>Its great, dont mess with it!</p><p>Id like to have the option for delivery</p>`); solve(`<svg><cat><text>Which is your favourite meal from our selection?</text></cat><cat><g><val>Fish</val>15</g><g><val>Prawns</val>31</g><g><val>Crab Langoon</val>12</g><g><val>Calamari</val>17</g></cat></svg>`);
console.log("这是个在branch1的log"); console.log("这是个在branch1的log");asdasdadsdsadsaads adsasdadasd
module.exports = { mode: "jit", purge: ["./app/**/*.{ts,tsx}"], darkMode: false, // or 'media' or 'class' theme: { colors: { theme: "#3474CE", accent: "#FF6B6A", bgMain: "#FFFFFF", bgSub: "#E5EAEE", textMain: "#444444", textSub1: "#777777", textSub2: "#999999", borderMain: "#BBBBBB", borderSub: "#D8D8D8", }, }, variants: { extend: {}, }, plugins: [], }
const mongoose = require('mongoose'); var Float = require('mongoose-float').loadType(mongoose, 3); const ConfigSchema = new mongoose.Schema( { global: { inflation: Float, mapSize: Number }, attackStat: { value: { baseValue: Float, mulLevel: Float, minValue: Float, maxValue: Float, bonus: { multiplier: Float, bonusTile: String }, }, cost: { selfLevelMultiplier: Float, } }, buildDistanceStat: { value: { baseValue: Float, mulLevel: Float, minValue: Float, maxValue: Float, bonus: { multiplier: Float, bonusTile: String }, }, cost: { selfLevelMultiplier: Float, } }, claimDistanceStat: { value: { baseValue: Float, mulLevel: Float, minValue: Float, maxValue: Float, bonus: { multiplier: Float, bonusTile: String }, }, cost: { selfLevelMultiplier: Float, } }, defenceStat: { value: { baseValue: Float, mulLevel: Float, minValue: Float, maxValue: Float, bonus: { multiplier: Float, bonusTile: String }, }, cost: { selfLevelMultiplier: Float, } }, generationStat: { value: { baseValue: Float, mulLevel: Float, minValue: Float, maxValue: Float, bonus: { multiplier: Float, bonusTile: String }, }, cost: { selfLevelMultiplier: Float, } }, viewDistanceStat: { value: { baseValue: Float, mulLevel: Float, minValue: Float, maxValue: Float, bonus: { multiplier: Float, bonusTile: String }, }, cost: { selfLevelMultiplier: Float, } }, player: { attackCooldown: Float, tokenRate: Float, tokenTime: Float, inflationPerBuilding: Float, attackHeightMul: Float, capitalInflationBonus: Float, buildingInflationBonus: Float, buildingLostInflationBonus: Float }, ai: [{ lowerBoundTime: Float, upperBoundTime: Float, probabilisticAi: { upgradeProbability: Float, attackProbability: Float, sellProbability: Float, buildProbability: Float }, aiAimer: { playAStar: Float, maxAttempts: Number, tries: Number }, }, { lowerBoundTime: Float, upperBoundTime: Float, probabilisticAi: { upgradeProbability: Float, attackProbability: Float, sellProbability: Float, buildProbability: Float }, aiAimer: { playAStar: Float, maxAttempts: Number, tries: Number }, }, { lowerBoundTime: Float, upperBoundTime: Float, probabilisticAi: { upgradeProbability: Float, attackProbability: Float, sellProbability: Float, buildProbability: Float }, aiAimer: { playAStar: Float, maxAttempts: Number, tries: Number }, }, { lowerBoundTime: Float, upperBoundTime: Float, probabilisticAi: { upgradeProbability: Float, attackProbability: Float, sellProbability: Float, buildProbability: Float }, aiAimer: { playAStar: Float, maxAttempts: Number, tries: Number }, } ] }, {timestamps: false} ); module.exports = mongoose.models.Config || mongoose.model('Config', ConfigSchema);
const uuidv4 = require('uuid/v4'); const mongoose = require('mongoose'); mongoose.Promise = global.Promise; const slug = require('slugs'); const storeSchema = new mongoose.Schema({ _id: { type: String, default: uuidv4 }, created: { type: Date, default: Date.now }, description: { type: String, trim: true }, location: { address: { type: String, required: 'You must supply address.' }, coordinates: [{ type: Number, required: 'You must supply coordinates.' }], type: { type: String, default: 'Point' } }, name: { type: String, trim: true, required: 'Please enter a store name.' }, photo: String, author: { type: mongoose.Schema.ObjectId, ref: 'User', required: 'You must supply an author.' }, slug: String, tags: [String] }); // Define Indices storeSchema.index({ name: 'text', description: 'text' }); storeSchema.pre('save', async function(next) { if (!this.isModified('name')) { return next(); } this.slug = slug(`store-${uuidv4().substring(0, 8)}`); next(); }) storeSchema.statics.getTagsList = function() { return this.aggregate([ { $unwind: '$tags' }, { $group: { _id: '$tags', count: { $sum: 1 } } }, { $sort: { count: -1 } } ]); } module.exports = mongoose.model('Store', storeSchema);
/** * Created by gautam on 19/12/16. */ import React from 'react'; import {browserHistory} from 'react-router'; export default class ThankYouFooter extends React.Component { render() { return ( <footer className='a-footer col-xs-12 pad0' onClick={this.reload}> <span className='col-xs-12' style = {{color: '#fff'}}> Thank you for booking with Lookplex! </span> </footer> ) } reload = () => { browserHistory.push(''); } }
!function (t, e) { var n = function (t) { var e = {}; function n(i) { if (e[i]) return e[i].exports; var o = e[i] = {i: i, l: !1, exports: {}}; return t[i].call(o.exports, o, o.exports, n), o.l = !0, o.exports } return n.m = t, n.c = e, n.d = function (t, e, i) { n.o(t, e) || Object.defineProperty(t, e, {configurable: !1, enumerable: !0, get: i}) }, n.r = function (t) { Object.defineProperty(t, "__esModule", {value: !0}) }, n.n = function (t) { var e = t && t.__esModule ? function () { return t.default } : function () { return t }; return n.d(e, "a", e), e }, n.o = function (t, e) { return Object.prototype.hasOwnProperty.call(t, e) }, n.p = "", n(n.s = 456) }({ 456: function (t, e, n) { "use strict"; function i(t) { return Array.isArray(t) ? t : Array.from(t) } Object.defineProperty(e, "__esModule", {value: !0}); var o = ["transitionend", "webkitTransitionEnd", "oTransitionEnd"], a = ["transition", "MozTransition", "webkitTransition", "WebkitTransition", "OTransition"]; function s(t) { throw new Error("Parameter required" + (t ? ": `" + t + "`" : "")) } var r = { CONTAINER: "undefined" != typeof window ? document.documentElement : null, LAYOUT_BREAKPOINT: 992, RESIZE_DELAY: 200, _curStyle: null, _styleEl: null, _resizeTimeout: null, _resizeCallback: null, _transitionCallback: null, _transitionCallbackTimeout: null, _listeners: [], _initialized: !1, _autoUpdate: !1, _lastWindowHeight: 0, _addClass: function (t) { var e = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : this.CONTAINER; t.split(" ").forEach(function (t) { return e.classList.add(t) }) }, _removeClass: function (t) { var e = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : this.CONTAINER; t.split(" ").forEach(function (t) { return e.classList.remove(t) }) }, _hasClass: function (t) { var e = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : this.CONTAINER, n = !1; return t.split(" ").forEach(function (t) { e.classList.contains(t) && (n = !0) }), n }, _supportsTransitionEnd: function () { if (window.QUnit) return !1; var t = document.body || document.documentElement; if (!t) return !1; var e = !1; return a.forEach(function (n) { void 0 !== t.style[n] && (e = !0) }), e }, _getAnimationDuration: function (t) { var e = window.getComputedStyle(t).transitionDuration; return parseFloat(e) * (-1 !== e.indexOf("ms") ? 1 : 1e3) }, _triggerWindowEvent: function (t) { if ("undefined" != typeof window) if (document.createEvent) { var e = void 0; "function" == typeof Event ? e = new Event(t) : (e = document.createEvent("Event")).initEvent(t, !1, !0), window.dispatchEvent(e) } else window.fireEvent("on" + t, document.createEventObject()) }, _triggerEvent: function (t) { this._triggerWindowEvent("layout" + t), this._listeners.filter(function (e) { return e.event === t }).forEach(function (t) { return t.callback.call(null) }) }, _updateInlineStyle: function () { var t = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : 0; this._styleEl || (this._styleEl = document.createElement("style"), this._styleEl.type = "text/css", document.head.appendChild(this._styleEl)); var e = "\n.layout-fixed .layout-1 .layout-sidenav,\n.layout-fixed-offcanvas .layout-1 .layout-sidenav {\n top: {navbarHeight}px !important;\n}\n.layout-container {\n padding-top: {navbarHeight}px !important;\n}".replace(/\{navbarHeight\}/gi, t); this._curStyle !== e && (this._curStyle = e, this._styleEl.textContent = e) }, _removeInlineStyle: function () { this._styleEl && document.head.removeChild(this._styleEl), this._styleEl = null, this._curStyle = null }, _redrawLayoutSidenav: function () { var t = this.getLayoutSidenav(); if (t && t.querySelector(".sidenav")) { var e = t.querySelector(".sidenav-inner"), n = e.scrollTop, i = document.documentElement.scrollTop; return t.style.display = "none", t.offsetHeight, t.style.display = "", e.scrollTop = n, document.documentElement.scrollTop = i, !0 } return !1 }, _getNavbarHeight: function () { var t = this, e = this.getLayoutNavbar(); if (!e) return 0; if (!this.isSmallScreen()) return e.getBoundingClientRect().height; var n = e.cloneNode(!0); n.id = null, n.style.visibility = "hidden", n.style.position = "absolute", Array.prototype.slice.call(n.querySelectorAll(".collapse.show")).forEach(function (e) { return t._removeClass("show", e) }), e.parentNode.insertBefore(n, e); var i = n.getBoundingClientRect().height; return n.parentNode.removeChild(n), i }, _bindLayoutAnimationEndEvent: function (t, e) { var n = this, i = this.getSidenav(), a = i ? this._getAnimationDuration(i) + 50 : 0; if (!a) return t.call(this), void e.call(this); this._transitionCallback = function (t) { t.target === i && (n._unbindLayoutAnimationEndEvent(), e.call(n)) }, o.forEach(function (t) { i.addEventListener(t, n._transitionCallback, !1) }), t.call(this), this._transitionCallbackTimeout = setTimeout(function () { n._transitionCallback.call(n, {target: i}) }, a) }, _unbindLayoutAnimationEndEvent: function () { var t = this, e = this.getSidenav(); this._transitionCallbackTimeout && (clearTimeout(this._transitionCallbackTimeout), this._transitionCallbackTimeout = null), e && this._transitionCallback && o.forEach(function (n) { e.removeEventListener(n, t._transitionCallback, !1) }), this._transitionCallback && (this._transitionCallback = null) }, _bindWindowResizeEvent: function () { var t = this; this._unbindWindowResizeEvent(); var e = function () { t._resizeTimeout && (clearTimeout(t._resizeTimeout), t._resizeTimeout = null), t._triggerEvent("resize") }; this._resizeCallback = function () { t._resizeTimeout && clearTimeout(t._resizeTimeout), t._resizeTimeout = setTimeout(e, t.RESIZE_DELAY) }, window.addEventListener("resize", this._resizeCallback, !1) }, _unbindWindowResizeEvent: function () { this._resizeTimeout && (clearTimeout(this._resizeTimeout), this._resizeTimeout = null), this._resizeCallback && (window.removeEventListener("resize", this._resizeCallback, !1), this._resizeCallback = null) }, _setCollapsed: function (t) { var e = this; this.isSmallScreen() ? t ? this._removeClass("layout-expanded") : setTimeout(function () { e._addClass("layout-expanded") }, this._redrawLayoutSidenav() ? 5 : 0) : this[t ? "_addClass" : "_removeClass"]("layout-collapsed") }, getLayoutSidenav: function () { return document.querySelector(".layout-sidenav") }, getSidenav: function () { var t = this.getLayoutSidenav(); return t ? this._hasClass("sidenav", t) ? t : t.querySelector(".sidenav") : null }, getLayoutNavbar: function () { return document.querySelector(".layout-navbar") }, getLayoutContainer: function () { return document.querySelector(".layout-container") }, isMobileDevice: function () { return void 0 !== window.orientation || -1 !== navigator.userAgent.indexOf("IEMobile") }, isSmallScreen: function () { return (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) < this.LAYOUT_BREAKPOINT }, isLayout1: function () { return !!document.querySelector(".layout-wrapper.layout-1") }, isCollapsed: function () { return this.isSmallScreen() ? !this._hasClass("layout-expanded") : this._hasClass("layout-collapsed") }, isFixed: function () { return this._hasClass("layout-fixed layout-fixed-offcanvas") }, isOffcanvas: function () { return this._hasClass("layout-offcanvas layout-fixed-offcanvas") }, isNavbarFixed: function () { return this._hasClass("layout-navbar-fixed") || !this.isSmallScreen() && this.isFixed() && this.isLayout1() }, isReversed: function () { return this._hasClass("layout-reversed") }, setCollapsed: function () { var t = this, e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : s("collapsed"), n = !(arguments.length > 1 && void 0 !== arguments[1]) || arguments[1], i = this.getLayoutSidenav(); i && (this._unbindLayoutAnimationEndEvent(), n && this._supportsTransitionEnd() ? (this._addClass("layout-transitioning"), this._bindLayoutAnimationEndEvent(function () { t._setCollapsed(e) }, function () { t._removeClass("layout-transitioning"), t._triggerWindowEvent("resize"), t._triggerEvent("toggle") })) : (this._addClass("layout-no-transition"), this._setCollapsed(e), setTimeout(function () { t._removeClass("layout-no-transition"), t._triggerWindowEvent("resize"), t._triggerEvent("toggle") }, 1))) }, toggleCollapsed: function () { var t = !(arguments.length > 0 && void 0 !== arguments[0]) || arguments[0]; this.setCollapsed(!this.isCollapsed(), t) }, setPosition: function () { var t = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : s("fixed"), e = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : s("offcanvas"); this._removeClass("layout-offcanvas layout-fixed layout-fixed-offcanvas"), !t && e ? this._addClass("layout-offcanvas") : t && !e ? (this._addClass("layout-fixed"), this._redrawLayoutSidenav()) : t && e && (this._addClass("layout-fixed-offcanvas"), this._redrawLayoutSidenav()), this.update() }, setNavbarFixed: function () { var t = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : s("fixed"); this[t ? "_addClass" : "_removeClass"]("layout-navbar-fixed"), this.update() }, setReversed: function () { var t = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : s("reversed"); this[t ? "_addClass" : "_removeClass"]("layout-reversed") }, update: function () { this.getLayoutNavbar() && (!this.isSmallScreen() && this.isLayout1() && this.isFixed() || this.isNavbarFixed()) && this._updateInlineStyle(this._getNavbarHeight()) }, setAutoUpdate: function () { var t = this, e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : s("enable"); e && !this._autoUpdate ? (this.on("resize.layoutHelpers:autoUpdate", function () { return t.update() }), this._autoUpdate = !0) : !e && this._autoUpdate && (this.off("resize.layoutHelpers:autoUpdate"), this._autoUpdate = !1) }, on: function () { var t = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : s("event"), e = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : s("callback"), n = t.split("."), o = i(n), a = o[0], r = o.slice(1); r = r.join(".") || null, this._listeners.push({event: a, namespace: r, callback: e}) }, off: function () { var t = this, e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : s("event"), n = e.split("."), o = i(n), a = o[0], r = o.slice(1); r = r.join(".") || null, this._listeners.filter(function (t) { return t.event === a && t.namespace === r }).forEach(function (e) { return t._listeners.splice(t._listeners.indexOf(e), 1) }) }, init: function () { var t = this; this._initialized || (this._initialized = !0, this._updateInlineStyle(0), this._bindWindowResizeEvent(), this.off("init._layoutHelpers"), this.on("init._layoutHelpers", function () { t.off("resize._layoutHelpers:redrawSidenav"), t.on("resize._layoutHelpers:redrawSidenav", function () { t.isSmallScreen() && !t.isCollapsed() && t._redrawLayoutSidenav() }), "number" == typeof document.documentMode && document.documentMode < 11 && (t.off("resize._layoutHelpers:ie10RepaintBody"), t.on("resize._layoutHelpers:ie10RepaintBody", function () { if (!t.isFixed()) { var e = document.documentElement.scrollTop; document.body.style.display = "none", document.body.offsetHeight, document.body.style.display = "block", document.documentElement.scrollTop = e } })) }), this._triggerEvent("init")) }, destroy: function () { var t = this; this._initialized && (this._initialized = !1, this._removeClass("layout-transitioning"), this._removeInlineStyle(), this._unbindLayoutAnimationEndEvent(), this._unbindWindowResizeEvent(), this.setAutoUpdate(!1), this.off("init._layoutHelpers"), this._listeners.filter(function (t) { return "init" !== t.event }).forEach(function (e) { return t._listeners.splice(t._listeners.indexOf(e), 1) })) } }; "undefined" != typeof window && (r.init(), r.isMobileDevice() && window.chrome && document.documentElement.classList.add("layout-sidenav-100vh"), "complete" === document.readyState ? r.update() : document.addEventListener("DOMContentLoaded", function t() { r.update(), document.removeEventListener("DOMContentLoaded", t) })), e.layoutHelpers = r } }); if ("object" == typeof n) { var i = ["object" == typeof module && "object" == typeof module.exports ? module.exports : null, "undefined" != typeof window ? window : null, t && t !== window ? t : null]; for (var o in n) i[0] && (i[0][o] = n[o]), i[1] && "__esModule" !== o && (i[1][o] = n[o]), i[2] && (i[2][o] = n[o]) } }(this);
var page = (function () { return { gotoURL: function (url) { location.href = url; }, reload: function () { document.location.reload(); } }; })();
import React from "react"; import EmployeesBase from "./components/EmployeesBase"; function App() { return ( <div className="App"> <EmployeesBase /> </div> ); } export default App;
import React from 'react'; import styled, { css, keyframes } from 'styled-components'; import { device } from '../../../theme'; export default function Loader({ size, children, ...props }) { return ( <LoaderWrapper {...props}> <LoaderContainer size={size}> <LoaderInner /> </LoaderContainer> {children && <LoaderText>{children}</LoaderText>} </LoaderWrapper> ); } const loader = keyframes` 0% { transform: rotate(0deg); } 25% { transform: rotate(180deg); } 50% { transform: rotate(180deg); } 75% { transform: rotate(360deg); } 100% { transform: rotate(360deg); } `; const loaderInner = keyframes` 0% { height: 0%; } 25% { height: 0%; } 50% { height: 100%; } 75% { height: 100%; } 100% { height: 0%; } `; const size = css` width: ${(props) => props.size || '3em'}; height: ${(props) => props.size || '3rem'}; `; const LoaderWrapper = styled.div` display: inline-flex; flex-direction: column; align-items: center; `; const LoaderContainer = styled.div` ${size} position: relative; border: 4px solid var(--color-primary); top: 50%; @media ${device.noReduceMotion} { animation: ${loader} 4s infinite ease; } `; const LoaderInner = styled.div` vertical-align: top; display: inline-block; width: 100%; background-color: var(--color-primary); @media ${device.noReduceMotion} { animation: ${loaderInner} 3s infinite ease-in; } `; const LoaderText = styled.span` font-size: var(--font-size-small); margin-top: 1em; display: inline-block; `;
"use strict"; tripnoutApp.factory('Search', function($http) { // create a new object var searchFactory = {}; // get query searchFactory.query = function(query) { return $http.get('/api/search/' + query); }; // return entire userFactory object return searchFactory; });
import React from 'react' import { render } from 'react-dom' import { createStore, combineReducers, applyMiddleware } from 'redux' import { Provider } from 'react-redux' import { Router, Route, browserHistory } from 'react-router' import { syncHistoryWithStore, routerReducer, routerMiddleware } from 'react-router-redux' // views import AppView from './views/AppView' // devtools import { createDevTools } from 'redux-devtools' import LogMonitor from 'redux-devtools-log-monitor' import DockMonitor from 'redux-devtools-dock-monitor' const DevTools = createDevTools( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-q"> <LogMonitor theme="tomorrow" preserveScrollTop={false} /> </DockMonitor> ) const reducer = combineReducers({ routing: routerReducer }) const store = createStore(reducer, DevTools.instrument()) const history = syncHistoryWithStore(browserHistory, store) Meteor.startup(() => { render( <Provider store={store}> <Router history={history}> <Route path="/" component={AppView}/> </Router> </Provider>, document.getElementById('react-app') ) })
/** * Quill Editor */ import React, { Component } from 'react'; import ReactQuill from 'react-quill'; // page title bar import PageTitleBar from 'Components/PageTitleBar/PageTitleBar'; // intl messages import IntlMessages from 'Util/IntlMessages'; // rct card box import RctCollapsibleCard from 'Components/RctCollapsibleCard/RctCollapsibleCard'; const modules = { toolbar: [ [{ 'header': [1, 2, 3, 4, 5, 6, false] }], [{ 'font': [] }], ['bold', 'italic', 'underline', 'strike', 'blockquote'], [{ 'list': 'ordered' }, { 'list': 'bullet' }, { 'indent': '-1' }, { 'indent': '+1' }], ['link', 'image'], ['clean'], [{ 'align': [] }], ['code-block'] ], }; const formats = [ 'header', 'font', 'bold', 'italic', 'underline', 'strike', 'blockquote', 'list', 'bullet', 'indent', 'link', 'image', 'align', 'code-block' ]; class QuillEditor extends Component { constructor(props) { super(props) this.state = { text: '' } this.handleChange = this.handleChange.bind(this) } handleChange(value) { this.setState({ text: value }) } render() { return ( <div className="editor-wrapper"> <PageTitleBar title={<IntlMessages id="sidebar.quillEditor" />} match={this.props.match} /> <RctCollapsibleCard heading="Quill Editor"> <ReactQuill modules={modules} formats={formats} placeholder="Enter Your Message.." /> </RctCollapsibleCard> </div> ); } } export default QuillEditor;
exports.up = function (knex) { return knex.schema .createTable('user', project => { project.increments(); project.string('username', 100).notNullable(); project.text('password', 255).notNullable(); }) }; exports.down = function (knex) { return knex.schema .dropTableIfExists('user'); };
import React from 'react'; import ShoppingCartPage from './components/ShoppingCartPage' function App() { return ( <div> <ShoppingCartPage/> </div> ); } export default App;
import React from "react" import Layout from "../components/layouts/layout" import MainContent from "../components/MainContent/MainContent" import MindSetComponent from '../components/MindSetComponent/MindSetComponent' import SEO from "../components/seo" const MindSet = () => ( <Layout> <SEO title="mind set" /> <MainContent> <MindSetComponent title="Mind set"></MindSetComponent> </MainContent> </Layout> ) export default MindSet
class Player { static url = "https://riyutool.com/50yintuceshi/"; static mode = ""; constructor() { } static play(mp3) { return new Promise(async (resolve, reject) => { let audio = new Audio(); if(mp3.indexOf(",") > -1) { let arr = mp3.split(","); mp3 = arr[arr.length - 1]; } audio.src = Player.url + mp3 + ".mp3"; audio.autoplay = false; audio.addEventListener("loadstart", () => { Player.mode = "start"; // console.log("loadstart") }, true); audio.addEventListener("loadeddata", () => { // console.log("loadeddata") }, true); audio.addEventListener("canplay", () => { Player.mode = "playing"; audio.play(); }, true); audio.addEventListener("durationchange", () => { // console.log("durationchange") }, true); audio.addEventListener("timeupdate", () => { }, true); audio.addEventListener("ended", () => { // console.log("ended") setTimeout(() => { Player.mode = ""; resolve(); }, 1000); }, true); }); } static wait(sec) { return new Promise(async (resolve, reject) => { setTimeout(() => { resolve() }, 1000 * sec); }); } }
// Buharlaşarak kaybolan Div etiketi $(function () { $("#kaybol").on("click", function () { $("#kaybol").fadeToggle("slow", function () { $("#kaybol").fadeToggle("slow") }) }) }) /* Sayfa içerisinde bulunan olan paragraf etiketine ilk tıklandığında durum sınıfını ekleyen ikinci kez tıklandığında durum sınıfını çıkaran JQuery kod */ $(function () { $("p").on("click", function () { $("p").toggleClass("d"); alert($('span.d:first').text()) }) }) $(function () { $("p").prev().hide() });
// Description: // Selecciona al azar entre 29 buenas citas inspiradoras // // Dependencies: // None // // Configuration: // None // // Commands: // huemul una cita // // Author: // @jorgeepunan const citas = [ '> Lo bien hecho es mejor que lo bien dicho. *-Benjamin Franklin*', '> Un buen diseño es un buen negocio. *-Thomas Watson, Jr*', '> La actitud es una pequeña cosa que hace una gran diferencia. *-Winston Churchill*', '> Yo no soy un producto de mis circunstancias. Soy un producto de mis decisiones. *-Stephen Covey*', '> Cada niño es un artista. El problema es cómo seguir siendo artista una vez que se crece. *-Pablo Picasso*', '> Nunca se puede cruzar el océano hasta que tenga el coraje de perder de vista la costa. *-Cristóbal Colón*', '> He aprendido que la gente olvidará lo que dijiste, la gente olvidará lo que hiciste, pero las personas nunca olvidarán cómo los hiciste sentir. *-Maya Angelou*', '> Tanto si piensas que puedes o piensas que no puedes, tienes razón. *-Henry Ford*', '> Los dos días más importantes en su vida son los días que se nace y el día que se descubre por qué. *-Mark Twain*', '> Lo que puedas hacer o soñar, ponte a hacerlo. La osadía está llena de genialidad, poder y magia. *-Johann Wolfgang von Goethe*', '> La mejor venganza es el éxito masivo. *-Frank Sinatra*', '> La gente suele decir que la motivación no dura mucho. Bueno, tampoco lo hace la ducha -por eso la recomendamos a diario. *-Zig Ziglar*', '> La inspiración existe, pero tiene que encontrarte trabajando. *-Pablo Picasso*', '> Cualquiera que sea la mente del hombre puede concebir y creer, puede lograr. *-Napoleón Hill*', '> Su tiempo es limitado, así que no lo desperdicien viviendo la vida de otra persona. *-Steve Jobs*', '> Esfuérzate por no ser un éxito, sino más bien para ser de valor. *-Albert Einstein*', '> Dos caminos se bifurcaban en un bosque, y yo tomé el menos transitado, y eso ha hecho toda la diferencia. *-Robert Frost*', '> Si lo puedes soñar, lo puedes hacer. *-Walt Disney*', '> He fallado más de 9000 tiros en mi carrera. He perdido casi 300 juegos. He fallado una y otra y otra vez en mi vida. Y es por eso que tengo éxito. *-Michael Jordan*', '> Cada golpe me acerca a la próxima carrera de casa. *-Babe Ruth*', '> El propósito es el punto de partida de todo logro. *-W. Clement Stone*', '> La vida es lo que te pasa mientras estás ocupado haciendo otros planes. *-John Lennon*', '> Nos convertimos en lo que pensamos. *-Earl Nightingale*', '> Dentro de veinte años estarás más decepcionado por las cosas que no hiciste que por las que hiciste, así que suelta las amarras, vela lejos del puerto seguro y captura de los vientos alisios en tus velas. Explora, Sueña y descubre. *-Mark Twain*', '> La vida es 10% lo que me pasa y el 90% de cómo reacciono a ello. *-John Maxwell*', '> Si haces lo que siempre has hecho, obtendrás lo que siempre has conseguido. *-Tony Robbins*', '> La mente lo es todo. ¿En qué crees que te convertirás?. *-Buddha*', '> El mejor momento para plantar un árbol fue hace 20 años. El segundo mejor momento es ahora. *-Proverbio Chino*', '> No vale la pena vivir una vida poco examinada. *-Sócrates*', '> El ochenta por ciento del éxito está apareciendo. *-Woody Allen*', '> No espere. El tiempo nunca será justo. *-Napoleón Hill*', '> Ganar no lo es todo, pero el deseo de ganar si lo es. *-Vince Lombardi*' ]; module.exports = function(robot) { return robot.respond(/una cita/i, msg => msg.send( msg.random(citas) )); };
import Link from "next/link"; import React from "react"; import { AiFillGithub, AiFillInstagram, AiFillLinkedin, AiFillTwitterCircle, } from "react-icons/ai"; import { DiCssdeck } from "react-icons/di"; import { BiCodeCurly } from "react-icons/bi"; import { Container, Div1, Div2 as DivNavLink, Div3 as Social, NavLink, SocialIcons, } from "./HeaderStyles"; const Header = () => ( <> <Container> <Div1> <Link href="/"> <a style={{ display: "flex", alignItems: "center", color: "white", paddingBottom: 20, }} > <BiCodeCurly size="2rem" /> <span style={{ marginLeft: "1.5 rem", // paddingLeft: "2rem", padding: "0.5rem", fontSize: "2rem", }} > Pranjal Verma </span> </a> </Link> </Div1> <DivNavLink> <li> <Link href="#projects"> <NavLink>Projects</NavLink> </Link> </li> <li> <Link href="#tech"> <NavLink>Technologies</NavLink> </Link> </li> <li> <Link href="#about"> <NavLink>About</NavLink> </Link> </li> </DivNavLink> <Social> <SocialIcons href="https://github.com/pranjal-verma"> <AiFillGithub size="3rem" /> </SocialIcons> <SocialIcons href="https://www.linkedin.com/in/pranjal-verma-546b98168/"> <AiFillLinkedin size="3rem" /> </SocialIcons> <SocialIcons> <AiFillTwitterCircle size="3rem" /> </SocialIcons> </Social> </Container> </> ); export default Header;
import { put, call } from 'redux-saga/effects'; import { message } from 'antd'; import * as authService from 'services/auth'; import * as userApi from 'services/user'; export const state = { userMenus: [], user: {}, token: '' }; export const effects = { *syncApp() { try { yield put.resolve({ type: 'app/syncMenu' }); yield put.resolve({ type: 'app/fetchUserInfo' }); return true; } catch (error) { return false; } }, *syncMenu() { const res = yield call(authService.category); if (res) { yield put({ type: 'app/setState', payload: { userMenus: res.data } }); } else throw new Error('sync menu failed.'); }, *fetchUserInfo() { const res = yield call(userApi.getUserDetail); if (res) { yield put({ type: 'app/setState', payload: { user: res.data } }); return res.data; } else throw new Error('fetch user detail failed.'); }, }; export const reducers = { ['notify.success'](state, { payload }) { message.success(payload); return { ...state }; }, ['notify.warn'](state, { payload }) { message.warn(payload); return { ...state }; }, };
import React from 'react' import classes from './deal.module.css'; function Deal(props) { const discount = {...props.price} const amenities=discount.amenties.map((amen,index)=>{ return <ul key={index}><li><b>{amen}</b></li></ul> }) return ( <div className={classes.part}> <div className={classes.column2}> <span className={classes.price}>&#8377; {discount.original_fees}</span> <span className={classes.tagLobel}><small className={classes.tag}>{discount.discount}</small></span> </div> <div className={classes.dprice}> &#8377; {discount.discounted_fees} </div> <div> <br/> <small style={{color:'rgb(100,100,100)',float:'right'}}>{discount.fees_cycle}</small> </div> <div className={classes.free}>{amenities}</div> </div> ) } export default Deal
import { writeFileSync } from 'fs'; import Pokemon from 'pokemongo-json-pokedex/output/pokemon.json'; import PokedexEntry from 'pokemongo-json-pokedex/output/locales/en-US/pokemon.json'; const filteredPokemon = Pokemon.filter(pokemon => ( pokemon.id !== 'KECLEON' && pokemon.id !== 'GOREBYSS' )); const allEvolutions = []; filteredPokemon.forEach(pokemon => { if (pokemon.evolution.futureBranches && !pokemon.evolution.pastBranch) { allEvolutions[pokemon.family.id] = pokemon.evolution.futureBranches; } else if (!allEvolutions[pokemon.family.id]) { allEvolutions[pokemon.family.id] = {}; } }); // Solves problems with floating numbers const getPercentage = number => { let decimalString = (number * 100).toFixed(2).replace(/0+$/, ''); if (decimalString.slice(-1) === '.') { decimalString = decimalString.slice(0, -1); } return decimalString; }; const data = Pokemon.filter(pokemon => ( pokemon.id !== 'KECLEON' && pokemon.id !== 'GOREBYSS' )).map(pokemon => { const pokemonData = { id: pokemon.id, name: pokemon.name, maxCP: pokemon.maxCP, types: pokemon.types, stats: pokemon.stats, height: `${pokemon.height}m`, weight: `${pokemon.weight}kg`, pokedex: { entry: pokemon.dex, category: PokedexEntry[pokemon.id].category.toUpperCase(), description: PokedexEntry[pokemon.id].description, }, buddy: { size: pokemon.buddySize.name, distance: `${pokemon.kmBuddyDistance}km`, }, gender: { male: pokemon.encounter.gender ? `${getPercentage(pokemon.encounter.gender.malePercent)}%` : 'N/A', female: pokemon.encounter.gender ? `${getPercentage(pokemon.encounter.gender.femalePercent)}%` : 'N/A', }, evolutions: allEvolutions[pokemon.family.id], encounter: { attackProbability: `${getPercentage(pokemon.encounter.attackProbability)}%`, baseFleeRate: `${getPercentage(pokemon.encounter.baseFleeRate)}%`, baseCaptureRate: `${getPercentage(pokemon.encounter.baseCaptureRate)}%`, }, moves: { quickMoves: pokemon.quickMoves, cinematicMoves: pokemon.cinematicMoves, }, }; return pokemonData; }); writeFileSync('./src/assets/data/pokemon.json', JSON.stringify(data, null, 2));
import * as h from './support/helpers' import { assertBigNum } from './support/matchers' contract('Coordinator', () => { const sourcePath = 'Coordinator.sol' let coordinator, link beforeEach(async () => { link = await h.linkContract() coordinator = await h.deploy(sourcePath, link.address) }) it('has a limited public interface', () => { h.checkPublicABI(artifacts.require(sourcePath), [ 'EXPIRY_TIME', 'cancelOracleRequest', 'fulfillOracleRequest', 'getId', 'initiateServiceAgreement', 'onTokenTransfer', 'oracleRequest', 'serviceAgreements', 'withdraw', 'withdrawableTokens' ]) }) const endAt = h.sixMonthsFromNow() describe('#getId', () => { const agreedPayment = 1 const agreedExpiration = 2 const agreedOracles = [ '0x70AEc4B9CFFA7b55C0711b82DD719049d615E21d', '0xd26114cd6EE289AccF82350c8d8487fedB8A0C07' ] const requestDigest = '0x85820c5ec619a1f517ee6cfeff545ec0ca1a90206e1a38c47f016d4137e801dd' const args = [ agreedPayment, agreedExpiration, endAt, agreedOracles, requestDigest ] const expectedBinaryArgs = [ '0x', ...[agreedPayment, agreedExpiration, endAt].map(h.padNumTo256Bit), ...agreedOracles.map(h.pad0xHexTo256Bit), h.strip0x(requestDigest) ] .join('') .toLowerCase() it('matches the ID generated by the oracle off-chain', async () => { const expectedBinaryArgsSha3 = h.keccak(expectedBinaryArgs, { encoding: 'hex' }) const getIdArgs = h.constructStructArgs( ['payment', 'expiration', 'endAt', 'oracles', 'requestDigest'], args ) const result = await coordinator.getId.call(getIdArgs) assert.equal(result, expectedBinaryArgsSha3) }) }) describe('#initiateServiceAgreement', () => { let agreement before(async () => { agreement = await h.newServiceAgreement({ oracles: [h.oracleNode] }) }) context('with valid oracle signatures', () => { it('saves a service agreement struct from the parameters', async () => { let tx = await h.initiateServiceAgreement(coordinator, agreement) await h.checkServiceAgreementPresent(coordinator, agreement) }) it('returns the SAID', async () => { const sAID = await h.initiateServiceAgreementCall( coordinator, agreement ) assert.equal(sAID, agreement.id) }) it('logs an event', async () => { await h.initiateServiceAgreement(coordinator, agreement) const event = await h.getLatestEvent(coordinator) assert.equal(agreement.id, event.args.said) }) }) context('with an invalid oracle signatures', () => { let badOracleSignature, badRequestDigestAddr before(async () => { const sAID = h.calculateSAID(agreement) badOracleSignature = await h.personalSign(h.stranger, sAID) badRequestDigestAddr = h.recoverPersonalSignature( sAID, badOracleSignature ) assert.equal(h.stranger.toLowerCase(), h.toHex(badRequestDigestAddr)) }) it('saves no service agreement struct, if signatures invalid', async () => { await h.assertActionThrows(async () => { await h.initiateServiceAgreement( coordinator, Object.assign(agreement, { oracleSignatures: [badOracleSignature] }) ) }) await h.checkServiceAgreementAbsent(coordinator, agreement.id) }) }) context('Validation of service agreement deadlines', () => { it('Rejects a service agreement with an endAt date in the past', async () => { await h.assertActionThrows(async () => h.initiateServiceAgreement( coordinator, Object.assign(agreement, { endAt: 1 }) ) ) await h.checkServiceAgreementAbsent(coordinator, agreement.id) }) }) }) describe('#oracleRequest', () => { const fHash = h.functionSelector('requestedBytes32(bytes32,bytes32)') const to = '0x80e29acb842498fe6591f020bd82766dce619d43' let agreement before(async () => { agreement = await h.newServiceAgreement({ oracles: [h.oracleNode] }) }) beforeEach(async () => { await h.initiateServiceAgreement(coordinator, agreement) await link.transfer(h.consumer, h.toWei(1000)) }) context('when called through the LINK token with enough payment', () => { let tx beforeEach(async () => { const payload = h.executeServiceAgreementBytes( agreement.id, to, fHash, '1', '' ) tx = await link.transferAndCall( coordinator.address, agreement.payment, payload, { from: h.consumer } ) }) it('logs an event', async () => { const log = tx.receipt.rawLogs[2] assert.equal(coordinator.address, log.address) // If updating this test, be sure to update // services.ServiceAgreementExecutionLogTopic. (Which see for the // calculation of this hash.) const eventSignature = '0xd8d7ecc4800d25fa53ce0372f13a416d98907a7ef3d8d3bdd79cf4fe75529c65' assert.equal(eventSignature, log.topics[0]) assert.equal(agreement.id, log.topics[1]) const req = h.decodeRunRequest(tx.receipt.rawLogs[2]) assertBigNum( h.consumer, req.requester, "Logged consumer address doesn't match" ) assertBigNum( agreement.payment, req.payment, "Logged payment amount doesn't match" ) }) }) context( 'when called through the LINK token with not enough payment', () => { it('throws an error', async () => { const calldata = h.executeServiceAgreementBytes( agreement.id, to, fHash, '1', '' ) const underPaid = h .bigNum(agreement.payment) .sub(h.bigNum(1)) .toString() await h.assertActionThrows(async () => { await link.transferAndCall( coordinator.address, underPaid, calldata, { from: h.consumer } ) }) }) } ) context('when not called through the LINK token', () => { it('reverts', async () => { await h.assertActionThrows(async () => { await coordinator.oracleRequest( '0x0000000000000000000000000000000000000000', 0, agreement.id, to, fHash, 1, 1, '0x', { from: h.consumer } ) }) }) }) }) describe('#fulfillOracleRequest', () => { let agreement, mock, request beforeEach(async () => { agreement = await h.newServiceAgreement({ oracles: [h.oracleNode] }) const tx = await h.initiateServiceAgreement(coordinator, agreement) assert.equal(tx.logs[0].args.said, agreement.id) }) context('cooperative consumer', () => { beforeEach(async () => { mock = await h.deploy('examples/GetterSetter.sol') const fHash = h.functionSelector('requestedBytes32(bytes32,bytes32)') const payload = h.executeServiceAgreementBytes( agreement.id, mock.address, fHash, 1, '' ) const tx = await link.transferAndCall( coordinator.address, agreement.payment, payload, { value: 0 } ) request = h.decodeRunRequest(tx.receipt.rawLogs[2]) }) context('when called by a non-owner', () => { // Turn this test on when multiple-oracle response aggregation is enabled xit('raises an error', async () => { await h.assertActionThrows(async () => { await coordinator.fulfillOracleRequest( request.id, h.toHex('Hello World!'), { from: h.stranger } ) }) }) }) context('when called by an owner', () => { it('raises an error if the request ID does not exist', async () => { await h.assertActionThrows(async () => { await coordinator.fulfillOracleRequest( '0xdeadbeef', h.toHex('Hello World!'), { from: h.oracleNode } ) }) }) it('sets the value on the requested contract', async () => { await coordinator.fulfillOracleRequest( request.id, h.toHex('Hello World!'), { from: h.oracleNode } ) const mockRequestId = await mock.requestId.call() assert.equal(request.id, mockRequestId) const currentValue = await mock.getBytes32.call() assert.equal('Hello World!', h.toUtf8(currentValue)) }) it('does not allow a request to be fulfilled twice', async () => { await coordinator.fulfillOracleRequest( request.id, h.toHex('First message!'), { from: h.oracleNode } ) await h.assertActionThrows(async () => { await coordinator.fulfillOracleRequest( request.id, h.toHex('Second message!!'), { from: h.oracleNode } ) }) }) }) }) context('with a malicious requester', () => { const paymentAmount = h.toWei(1) beforeEach(async () => { mock = await h.deploy( 'examples/MaliciousRequester.sol', link.address, coordinator.address ) await link.transfer(mock.address, paymentAmount) }) xit('cannot cancel before the expiration', async () => { await h.assertActionThrows(async () => { await mock.maliciousRequestCancel( agreement.id, 'doesNothing(bytes32,bytes32)' ) }) }) it('cannot call functions on the LINK token through callbacks', async () => { await h.assertActionThrows(async () => { await mock.request( agreement.id, link.address, h.toHex('transfer(address,uint256)') ) }) }) context('requester lies about amount of LINK sent', () => { it('the oracle uses the amount of LINK actually paid', async () => { const tx = await mock.maliciousPrice(agreement.id) const req = h.decodeRunRequest(tx.receipt.rawLogs[3]) assertBigNum( paymentAmount, req.payment, [ 'Malicious data request tricked oracle into refunding more than', 'the requester paid, by claiming a larger amount', `(${req.payment}) than the requester paid (${paymentAmount})` ].join(' ') ) }) }) }) context('with a malicious consumer', () => { const paymentAmount = h.toWei(1) beforeEach(async () => { mock = await h.deploy( 'examples/MaliciousConsumer.sol', link.address, coordinator.address ) await link.transfer(mock.address, paymentAmount) }) context('fails during fulfillment', () => { beforeEach(async () => { const tx = await mock.requestData( agreement.id, h.toHex('assertFail(bytes32,bytes32)') ) request = h.decodeRunRequest(tx.receipt.rawLogs[3]) }) // needs coordinator withdrawal functionality to meet parity xit('allows the oracle node to receive their payment', async () => { await coordinator.fulfillOracleRequest( request.id, h.toHex('hack the planet 101'), { from: h.oracleNode } ) const balance = await link.balanceOf.call(h.oracleNode) assert.isTrue(balance.equals(0)) await coordinator.withdraw(h.oracleNode, paymentAmount, { from: h.oracleNode }) const newBalance = await link.balanceOf.call(h.oracleNode) assert.isTrue(paymentAmount.equals(newBalance)) }) it("can't fulfill the data again", async () => { await coordinator.fulfillOracleRequest( request.id, h.toHex('hack the planet 101'), { from: h.oracleNode } ) await h.assertActionThrows(async () => { await coordinator.fulfillOracleRequest( request.id, h.toHex('hack the planet 102'), { from: h.oracleNode } ) }) }) }) context('calls selfdestruct', () => { beforeEach(async () => { const tx = await mock.requestData( agreement.id, 'doesNothing(bytes32,bytes32)' ) request = h.decodeRunRequest(tx.receipt.rawLogs[3]) await mock.remove() }) // needs coordinator withdrawal functionality to meet parity xit('allows the oracle node to receive their payment', async () => { await coordinator.fulfillOracleRequest( request.id, h.toHex('hack the planet 101'), { from: h.oracleNode } ) const balance = await link.balanceOf.call(h.oracleNode) assert.isTrue(balance.equals(0)) await coordinator.withdraw(h.oracleNode, paymentAmount, { from: h.oracleNode }) const newBalance = await link.balanceOf.call(h.oracleNode) assert.isTrue(paymentAmount.equals(newBalance)) }) }) context('request is canceled during fulfillment', () => { beforeEach(async () => { const tx = await mock.requestData( agreement.id, h.toHex('cancelRequestOnFulfill(bytes32,bytes32)') ) request = h.decodeRunRequest(tx.receipt.rawLogs[3]) const mockBalance = await link.balanceOf.call(mock.address) assertBigNum(mockBalance, h.bigNum(0)) }) // needs coordinator withdrawal functionality to meet parity xit('allows the oracle node to receive their payment', async () => { await coordinator.fulfillOracleRequest( request.id, h.toHex('hack the planet 101'), { from: h.oracleNode } ) const mockBalance = await link.balanceOf.call(mock.address) assertBigNum(mockBalance, h.bigNum(0)) const balance = await link.balanceOf.call(h.oracleNode) assert.isTrue(balance.equals(0)) await coordinator.withdraw(h.oracleNode, paymentAmount, { from: h.oracleNode }) const newBalance = await link.balanceOf.call(h.oracleNode) assert.isTrue(paymentAmount.equals(newBalance)) }) it("can't fulfill the data again", async () => { await coordinator.fulfillOracleRequest( request.id, h.toHex('hack the planet 101'), { from: h.oracleNode } ) await h.assertActionThrows(async () => { await coordinator.fulfillOracleRequest( request.id, h.toHex('hack the planet 102'), { from: h.oracleNode } ) }) }) }) }) context('when aggregating answers', () => { let oracle1, oracle2, oracle3, request, strangerOracle beforeEach(async () => { strangerOracle = h.stranger oracle1 = h.oracleNode1 oracle2 = h.oracleNode2 oracle3 = h.oracleNode3 agreement = await h.newServiceAgreement({ oracles: [oracle1, oracle2, oracle3] }) let tx = await h.initiateServiceAgreement(coordinator, agreement) assert.equal(tx.logs[0].args.said, agreement.id) mock = await h.deploy('examples/GetterSetter.sol') const fHash = h.functionSelector('requestedUint256(bytes32,uint256)') const payload = h.executeServiceAgreementBytes( agreement.id, mock.address, fHash, 1, '' ) tx = await link.transferAndCall( coordinator.address, agreement.payment, payload, { value: 0 } ) request = h.decodeRunRequest(tx.receipt.rawLogs[2]) }) it('does not set the value with only one oracle', async () => { const tx = await coordinator.fulfillOracleRequest( request.id, h.toHex(17), { from: oracle1 } ) assert.equal(tx.receipt.rawLogs.length, 0) // No logs emitted = consuming contract not called }) it('sets the average of the reported values', async () => { await coordinator.fulfillOracleRequest(request.id, h.toHex(16), { from: oracle1 }) await coordinator.fulfillOracleRequest(request.id, h.toHex(17), { from: oracle2 }) const lastTx = await coordinator.fulfillOracleRequest( request.id, h.toHex(18), { from: oracle3 } ) assert.equal(lastTx.receipt.rawLogs.length, 1) const currentValue = await mock.getUint256.call() assertBigNum(h.bigNum(17), currentValue) }) context('when large values are provided in response', async () => { // (uint256(-1) / 2) - 1 const largeValue1 = '0x7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe' // (uint256(-1) / 2) const largeValue2 = '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff' // (uint256(-1) / 2) + 1 const largeValue3 = '0x8000000000000000000000000000000000000000000000000000000000000000' beforeEach(async () => { await coordinator.fulfillOracleRequest(request.id, largeValue1, { from: oracle1 }) await coordinator.fulfillOracleRequest(request.id, largeValue2, { from: oracle2 }) }) it('does not overflow', async () => { await coordinator.fulfillOracleRequest(request.id, largeValue3, { from: oracle3 }) }) it('sets the average of the reported values', async () => { await coordinator.fulfillOracleRequest(request.id, largeValue3, { from: oracle3 }) const currentValue = await mock.getUint256.call() assertBigNum(h.bigNum(largeValue2), currentValue) assert.notEqual(0, await mock.requestId.call()) // check if called }) }) it('successfully sets average when responses equal largest uint256', async () => { const largest = '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff' await coordinator.fulfillOracleRequest(request.id, largest, { from: oracle1 }) await coordinator.fulfillOracleRequest(request.id, largest, { from: oracle2 }) await coordinator.fulfillOracleRequest(request.id, largest, { from: oracle3 }) const currentValue = await mock.getUint256.call() assertBigNum(h.bigNum(largest), currentValue) assert.notEqual(0, await mock.requestId.call()) // check if called }) it('rejects oracles not part of the service agreement', async () => { await h.assertActionThrows(async () => { await coordinator.fulfillOracleRequest(request.id, h.toHex(18), { from: strangerOracle }) }) }) context('when an oracle reports multiple times', async () => { beforeEach(async () => { await coordinator.fulfillOracleRequest(request.id, h.toHex(16), { from: oracle1 }) await coordinator.fulfillOracleRequest(request.id, h.toHex(17), { from: oracle2 }) await h.assertActionThrows(async () => { await coordinator.fulfillOracleRequest(request.id, h.toHex(18), { from: oracle2 }) }) }) it('does not set the average', async () => { assert.equal(0, await mock.requestId.call()) // check if called }) it('still allows the other oracles to report', async () => { await coordinator.fulfillOracleRequest(request.id, h.toHex(18), { from: oracle3 }) const currentValue = await mock.getUint256.call() assertBigNum(h.bigNum(17), currentValue) assert.notEqual(0, await mock.requestId.call()) // check if called }) }) }) context('after aggregation', () => { let oracle1, oracle2, oracle3, request beforeEach(async () => { oracle1 = h.oracleNode1 oracle2 = h.oracleNode2 oracle3 = h.oracleNode3 agreement = await h.newServiceAgreement({ oracles: [oracle1, oracle2, oracle3] }) let tx = await h.initiateServiceAgreement(coordinator, agreement) assert.equal(tx.logs[0].args.said, agreement.id) mock = await h.deploy('examples/GetterSetter.sol') const fHash = h.functionSelector('requestedUint256(bytes32,uint256)') const payload = h.executeServiceAgreementBytes( agreement.id, mock.address, fHash, 1, '' ) tx = await link.transferAndCall( coordinator.address, agreement.payment, payload, { value: 0 } ) request = h.decodeRunRequest(tx.receipt.rawLogs[2]) await coordinator.fulfillOracleRequest(request.id, h.toHex(16), { from: oracle1 }) await coordinator.fulfillOracleRequest(request.id, h.toHex(17), { from: oracle2 }) await coordinator.fulfillOracleRequest(request.id, h.toHex(18), { from: oracle3 }) const currentValue = await mock.getUint256.call() assertBigNum(h.bigNum(17), currentValue) }) it('oracle balances are updated', async () => { // Given the 3 oracles from the SA, each should have the following balance after fulfillment const expected = h.bigNum('333333333333333333') const balance1 = await coordinator.withdrawableTokens.call(oracle1) assertBigNum(expected, balance1) }) }) context('withdraw', () => { let oracle1, oracle2, oracle3, request beforeEach(async () => { oracle1 = h.oracleNode1 oracle2 = h.oracleNode2 oracle3 = h.oracleNode3 agreement = await h.newServiceAgreement({ oracles: [oracle1, oracle2, oracle3] }) let tx = await h.initiateServiceAgreement(coordinator, agreement) assert.equal(tx.logs[0].args.said, agreement.id) mock = await h.deploy('examples/GetterSetter.sol') const fHash = h.functionSelector('requestedUint256(bytes32,uint256)') const payload = h.executeServiceAgreementBytes( agreement.id, mock.address, fHash, 1, '' ) tx = await link.transferAndCall( coordinator.address, agreement.payment, payload, { value: 0 } ) request = h.decodeRunRequest(tx.receipt.rawLogs[2]) await coordinator.fulfillOracleRequest(request.id, h.toHex(16), { from: oracle1 }) await coordinator.fulfillOracleRequest(request.id, h.toHex(17), { from: oracle2 }) await coordinator.fulfillOracleRequest(request.id, h.toHex(18), { from: oracle3 }) const currentValue = await mock.getUint256.call() assertBigNum(h.bigNum(17), currentValue) }) it('allows the oracle to withdraw their full amount', async () => { const coordBalance1 = await link.balanceOf.call(coordinator.address) const withdrawAmount = await coordinator.withdrawableTokens.call( oracle1 ) await coordinator.withdraw(oracle1, withdrawAmount.toString(), { from: oracle1 }) const oracleBalance = await link.balanceOf.call(oracle1) const afterWithdrawBalance = await coordinator.withdrawableTokens.call( oracle1 ) const coordBalance2 = await link.balanceOf.call(coordinator.address) const expectedCoordFinalBalance = coordBalance1.sub(withdrawAmount) assertBigNum(withdrawAmount, oracleBalance) assertBigNum(expectedCoordFinalBalance, coordBalance2) assertBigNum(h.bigNum(0), afterWithdrawBalance) }) it('rejects amounts greater than allowed', async () => { const oracleBalance = await coordinator.withdrawableTokens.call(oracle1) const withdrawAmount = oracleBalance.add(h.bigNum(1)) await h.assertActionThrows(async () => { await coordinator.withdraw(oracle1, withdrawAmount.toString(), { from: oracle1 }) }) }) }) }) })
//import React from 'react'; import React, { useState, useEffect } from 'react'; import { SafeAreaView, StyleSheet, ScrollView, TouchableOpacity, TextInput, View, Text, StatusBar, } from 'react-native'; //import React, { useState } from 'react'; import { Header, LearnMoreLinks, Colors, DebugInstructions, ReloadInstructions, } from 'react-native/Libraries/NewAppScreen'; import Svg, { Path } from "react-native-svg"; import { RadioButton } from 'react-native-paper'; const Otp = (props) => { console.log(props); const [otp, setOtp] = useState(new Array(6).fill("")); const handleChange = (element, index) => { if (isNaN(element.value)) return false; setOtp([...otp.map((d, idx) => (idx === index ? element.value : d))]); //Focus next input if (element.nextSibling) { element.nextSibling.focus(); } }; const VerifyOTP = () => { //alert("Entered OTP is " + otp.join(""),props.location.state.regObj.email) if(props.location.state.mobile==''){ conformCode( otp.join(""),props.location.state.email) }else{ console.log(otp.join(""),"+"+props.location.state.mobile); conformCode( otp.join(""),"+"+props.location.state.mobile) } // conformCode( otp.join(""),props.location.state.regObj.email) //conformCode( otp.join(""),props.location.state.regObj.Mobile) //this.props.history.push("/Body/Registration"); }; const GoToRegistration = () => { props.history.push("/Body/Registration"); //history.push("/Body/Registration"); //window.location.reload(false); } const conformCode=(code,user)=>{ console.log(code,user); Auth.confirmSignUp( user, code, "SMS_MFA" ) .then( data => console.log(data), alert("Registration Success"), props.history.push("/Profile/BasicInfo"), window.location.reload(false) ) .catch(err => console.log(err)); } const resendVerificationCode=()=>{ this.resendCode(this.state.username); } const resendCode=(username)=>{ Auth.resendSignUp( username ).then( console.log("success") ) .catch(console.log("fail")); } return ( <> <View style={{marginTop: 50}}> <View style={{ textAlign: "center" }}> <View className="OTPInputs"> {otp.map((data, index) => { return ( // <input // className="otp-field" // style={{width: "10%",margin:5,width: "10%",height: "50px",background: "#8048c1f5",borderRadius: "11px",color:"white",textAlign: "center",fontSize: "20px"}} // type="text" // name="otp" // maxLength="1" // key={index} // value={data} // onChange={e => handleChange(e.target, index)} // onFocus={e => e.target.select()} // /> <TextInput underlineColorAndroid="transparent" placeholder="" placeholderTextColor="grey" autoCapitalize="none" value={data} onChangeText={e => handleChange(e.target, index)} // onFocus={e => e.target.select()} /> ); })} </View> </View> </View> </> ); }; export default Otp;
var empData=[]; function storeData() { // take value from text field using id or name //we can store json object. but we have to convert // into string. console.log("Data store in local storage") var formData = readData(); empData.push(formData); localStorage.setItem("empInfo",JSON.stringify(empData)); console.log(empData); } function readData() { var formData={}; formData.clientName=document.getElementById("clientName").value; formData.name = document.getElementById("projectname").value; formData.budget = document.getElementById("budget").value; return formData; } function displayData() { var empObj = localStorage.getItem("empInfo"); var empJson = JSON.parse(empObj) console.log(empJson); console.log(empJson[0].clientName) var tableContent="" var startTable ="<table border=1><tr><th>Client Name</th><th>Project Name</th><th>Budget</th></tr>" for (let i = 0; i < empJson.length; i++) { tableContent +="<tr><td>"+empJson[i].clientName+"</td><td>"+empJson[i].name+"</td><td>"+empJson[i].budget+"</td></tr>" } var endTable="</table>" tableContent = startTable+tableContent+endTable document.getElementById("main").innerHTML=tableContent; } function goback(){ window.history.back(); }
const webpack = require('webpack'); const merge = require('webpack-merge'); const { productionEnvConfig } = require('../config/webpack.env'); function createProductionWebpackConfig(projectName) { if (!projectName) { throw `未传入projectName`; } // webpack公共配置 const webpackCommonConfig = require('./webpack.config.common.js')( projectName ); // webpack dev 配置 const webpackProductionConfig = { plugins: [new webpack.DefinePlugin({})], }; return merge( { mode: 'production' }, webpackProductionConfig, webpackCommonConfig ); } // output module.exports = createProductionWebpackConfig;
const spawn = require('cross-spawn'); const program = require('commander'); module.exports = async () => { const result = spawn.sync( 'node', [require.resolve('../src/start')].concat(program.args), { stdio: 'inherit' } ); process.exit(result.status); };
"use strict"; var _knockout = _interopRequireDefault(require("knockout")); var _icon = require("../../core/utils/icon"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // eslint-disable-next-line no-restricted-imports if (_knockout.default) { _knockout.default.bindingHandlers.dxControlsDescendantBindings = { init: function init(_, valueAccessor) { return { controlsDescendantBindings: _knockout.default.unwrap(valueAccessor()) }; } }; _knockout.default.bindingHandlers.dxIcon = { init: function init(element, valueAccessor) { var options = _knockout.default.utils.unwrapObservable(valueAccessor()) || {}; var iconElement = (0, _icon.getImageContainer)(options); _knockout.default.virtualElements.emptyNode(element); if (iconElement) { _knockout.default.virtualElements.prepend(element, iconElement.get(0)); } }, update: function update(element, valueAccessor) { var options = _knockout.default.utils.unwrapObservable(valueAccessor()) || {}; var iconElement = (0, _icon.getImageContainer)(options); _knockout.default.virtualElements.emptyNode(element); if (iconElement) { _knockout.default.virtualElements.prepend(element, iconElement.get(0)); } } }; _knockout.default.virtualElements.allowedBindings.dxIcon = true; }
const WID = 640; const HEI = 10; const HOR = 640 / WID; const VER = 400 / HEI; function WorkerWrapper(cvs, lx, ly) { var ctx = cvs.getContext('2d'); var myWorker = new Worker('./mandelbrot_www.js'); this.postMessage = function(x, y, scale, loop_max) { myWorker.postMessage([x + lx * WID * scale, y + ly * HEI * scale, scale, loop_max]); }; myWorker.onmessage = function(arg) { var imgData = ctx.createImageData(WID, HEI); imgData.data.set(arg.data); ctx.putImageData(imgData, WID * lx, HEI * ly); }; } function WorkerManager(cvs) { let ctx = cvs.getContext('2d'); let workerIndex = [] for (let y = 0; y < VER; y ++) { for (let x = 0; x < HOR; x ++) { workerIndex.push([x,y]); } } let workers = workerIndex.map(function(args) { return new WorkerWrapper(cvs, args[0], args[1]); }); this.postMessages = function(x, y, scale, loop_max) { ctx.clearRect(0, 0, 640, 400); workers.forEach(function(worker) { worker.postMessage(x, y, scale, loop_max); }); }; } function Scaler(manager) { let scale = 0.005; let centerX = -0.5; let centerY = 0; this.reload = function(loopMax) { manager.postMessages( centerX - 320 * scale, centerY - 200 * scale, scale, loopMax) } this.scaleUp = function(px, py, loopMax) { // px, py は640,400のCanvasサイズ centerX = centerX + (px - 320) * scale; centerY = centerY + (py - 200) * scale; scale = scale / 2; manager.postMessages( centerX - 320 * scale, centerY - 200 * scale, scale, loopMax); } this.scaleDown = function(px, py, loopMax) { // px, py は640,400のCanvasサイズ centerX = centerX + (px - 320) * scale; centerY = centerY + (py - 200) * scale; scale = scale * 8; manager.postMessages( centerX - 320 * scale, centerY - 200 * scale, scale, loopMax); } this.showPosition = function(cvs, px, py) { let x = centerX + (px - 320) * scale; let y = centerY + (py - 200) * scale; let ctx = cvs.getContext('2d'); let imageData = ctx.getImageData(px, py, 1, 1); let r = imageData.data[0]; let g = imageData.data[1]; let b = imageData.data[2]; return `[${r},${g},${b}]${scale}(${x}, ${y})` } } function onload() { var cvs = document.getElementById('c01'); var manager = new Scaler(new WorkerManager(cvs)); var loopMaxInput = document.getElementById('loop_max'); let statusBox = document.getElementById('status_box'); cvs.onclick = function(event) { var x = event.offsetX; var y = event.offsetY; manager.scaleUp(x, y, loopMaxInput.value); } cvs.ondblclick = function(event) { var x = event.offsetX; var y = event.offsetY; var button = event.button; manager.scaleDown(x, y, loopMaxInput.value); } cvs.onmousemove = function(event) { var x = event.offsetX; var y = event.offsetY; statusBox.value = manager.showPosition(cvs, x, y); } window.canvasGoGo = function() { var loop_max = loopMaxInput.value; manager.reload(loop_max); } }
import { gl, glPrintError, CGLExtObject } from "./glContext.js"; // import * as global from "./globalStorage.js" import * as sys from "./../System/sys.js" import { CModel } from "./glModel.js"; import { CMaterialParam, CMaterial } from "./glMaterial.js"; import { CShader, CShaderList } from "./glShader.js"; import { CTexture, CTextureList } from "./glTexture.js"; import { CBlendMode } from "./glBlendMode.js" import * as vMath from "../glMatrix/gl-matrix.js"; export class CModelAssembly extends CGLExtObject { constructor(slotID) { super(); this.id = ""; this.src = ""; this.models = []; } LoadAssemblyFromXML(asmid){ let lnk = document.getElementById(asmid); if(lnk == null) return false; this.src = lnk.src.replace('\\','/'); let folderPath = this.src.substr(0, this.src.lastIndexOf('/')+1); let parser = new DOMParser(); let xmlAsm = parser.parseFromString(lnk.text, "text/xml"); xmlAsm = xmlAsm.getElementsByTagName("assembly")[0]; xmlAsm.getElementsByTagNameImmediate = sys.utils.getElementsByTagNameImmediate; this.id = xmlAsm.id; let imgs = xmlAsm.getElementsByTagNameImmediate("img"); for(let i = 0; i < imgs.length; ++i){ let img = imgs[i]; let tx = CTextureList.getByName(folderPath + img.attributes.src.value); if(tx != null){ }else{ tx = new CTexture(-1); tx.CreateDelayed(folderPath + img.attributes.src.value, img.attributes.id.value); CTextureList.addTexture(tx); } img.value = tx; } let defaultMaterial = null; let globalMaterials = []; let xmlDefaultMaterials = xmlAsm.getElementsByTagNameImmediate("material"); if(xmlDefaultMaterials.length > 0){ for(let i = 0; i < xmlDefaultMaterials.length; ++i){ globalMaterials[i] = new CMaterial(); globalMaterials[i].LoadFromXMLDOM( xmlAsm.getElementsByTagNameImmediate("material")[i] ); } defaultMaterial = globalMaterials[0]; } let mdls = xmlAsm.getElementsByTagNameImmediate("model"); let matLinks = []; for(let i = 0; i < mdls.length; ++i){ let mdl = mdls[i]; mdl.getElementsByTagNameImmediate = sys.utils.getElementsByTagNameImmediate; let model = new CModel(0); model.DelayedImportFromPath(folderPath + mdl.attributes.src.value); let material = defaultMaterial; if( mdl.getElementsByTagNameImmediate("material").length > 0 ){ material = new CMaterial(); if(material.LoadFromXMLDOM( mdl.getElementsByTagNameImmediate("material")[0] ) == false)//if false it's material link matLinks[matLinks.length] = this.models.length; } model.setMaterial(material); let params = CMaterialParam.LoadParamsFromXMLDOM(mdl); model.setParams(params); this.models[this.models.length] = model; } //material linking for(let i = 0; i < matLinks.length; ++i){ let model = this.models[matLinks[i]]; let material = null; for(let m = 0; m < globalMaterials.length; ++m){ if(globalMaterials[m].id == model.material.id){ material = globalMaterials[m]; break; } } if(material == null) for(let m = 0; m < this.models.length; ++m){ if(m == matLinks[i]) continue; if(model.material.id == this.models[m].material.id && this.models[m].material.isMaterialLink() == false){ material = this.models[m].material; break; } } if(material === null){ alert("LoadAssemblyFromXML(): material link not found! <" + model.material.id + ">"); continue; } model.material.LinkFromMaterial(material); model.setMaterial(model.material); } } }
// Version 0.3.4 var mainInventoryURL = 'https://api.airtable.com/v0/appztwEDDxgAVCwxF/Main%20Inventory?api_key=keykbC2FwErK6UFom&view=Main%20View'; var mainInventoryHTML = ''; var mainInventoryDiv = $('.mainBody'); var counter = 0; var offsetcounter = 0; var renderMainInventory = function(data) { data.records.forEach(function(item) { if (item.fields['Serial Number / Asset Number']) { counter += 1; mainInventoryHTML += "<div class='itemContainer'>"; mainInventoryHTML += `<h4 class='id'>${item.id}</h4>` mainInventoryHTML += `<h4 class='SN'>${item.fields['Serial Number / Asset Number']}</h4>` mainInventoryHTML += "<div class='itemName'>"; mainInventoryHTML += '<h2>Serial Number/Asset Number: ' + '<span class="insertedText">' + item.fields['Serial Number / Asset Number'] + '</span></h2>'; mainInventoryHTML += '</div>'; // Add Hide to class mainInventoryHTML += "<div class='itemInfo hide'>"; mainInventoryHTML += '<p class="desktopModel">Desktop Model: '; if (item.fields['Desktop Model']) { mainInventoryHTML += '<span class="insertedText">' + item.fields['Desktop Model'] + '</span></p>'; } else { mainInventoryHTML += '</p>'; } mainInventoryHTML += '<p class="status">Status: '; if (item.fields['Status']) { mainInventoryHTML += '<span class="insertedText">' + item.fields['Status'] + '</span></p>'; } else { mainInventoryHTML += '</p>'; } mainInventoryHTML += '<p class="operatingSystem"> Operating System: '; if (item.fields['Operating System']) { mainInventoryHTML += '<span class="insertedText">' + item.fields['Operating System'] + '</span></p>'; } else { mainInventoryHTML += '</p>'; } mainInventoryHTML += '<p class="ram">Ram: '; if (item.fields['Ram GB']) { mainInventoryHTML += '<span class="insertedText">' + item.fields['Ram GB'] + '</span></p>'; } else { mainInventoryHTML += '</p>'; } mainInventoryHTML += '<p class= "storage">Storage: '; if (item.fields['Storage GB']) { mainInventoryHTML += '<span class="insertedText">' + item.fields['Storage GB'] + '</span></p>'; } else { mainInventoryHTML += '</p>'; } mainInventoryHTML += '<p class="cpu">CPU: ' if (item.fields['CPU']) { mainInventoryHTML += '<span class="insertedText">' + item.fields['CPU'] + '</span></p>'; } else { mainInventoryHTML += '</p>'; } mainInventoryHTML += '<div><form class="modifyRemove"><button class="mainButton remove" type="submit">Remove</button></form></div>'; mainInventoryHTML += '</div>'; mainInventoryHTML += '<hr /></div>'; } }); console.log(counter); // checks if there are more than 100 records if (data.offset) { var offsetmainInventoryURL = mainInventoryURL + '&offset=' + data.offset; $.getJSON(offsetmainInventoryURL, renderMainInventory); } else { mainInventoryDiv.append(mainInventoryHTML); var form = $('.modifyRemove'); console.log('i'); // Delete button function form.on('submit', function(d) { d.preventDefault(); var prompt = window.prompt("Please type 'DELETE' in order to continue .") var itemID = $(this).parents('.itemContainer'); itemID = itemID.children('.id'); itemID = itemID.text(); console.log(itemID); if (prompt === 'DELETE') { var link = `https://api.airtable.com/v0/appztwEDDxgAVCwxF/Main%20Inventory/${itemID}?api_key=keykbC2FwErK6UFom`; console.log(link); // Sends DELETE request to airtable $.ajax({ url: link, type: 'DELETE', success: function(result) { // Do something with the result console.log('Success'); window.location.reload(); } }); } }) } } // Search Bar var form2 = $('#searchbox'); var arrayholder = []; var results = 0; form2.on('submit', function(f) { f.preventDefault(); $('.noResults').remove(); results = 0; arrayholder.forEach(function(i) { // console.log(i); i.removeClass('hidden'); // console.log(i); }) var Search = search.value; if (!Search) { alert('No Serial Number Inserted') return } $('.SN').each(function(item) { var SN = $(this); SN = SN.text(); if (Search != SN) { var temp2 = $(this); temp2 = temp2.parent('.itemContainer') temp2.addClass('hidden'); arrayholder.push(temp2) } else { results += 1; } }) if (results === 0) { var insertWarning = '<div class="noResults"> No Results Found!</div>' mainInventoryDiv.prepend(insertWarning); return } // console.log(arrayholder) }) // Gets Airtable Data and renders it $.getJSON(mainInventoryURL, renderMainInventory); // Hides the descrition of item and toggles it $(document).on('click', '.itemName', function() { $(this).siblings('.itemInfo').toggleClass('hide'); }) // Shows Go to Top Button when user scrolls down 100 px window.onscroll = function() { scrollFunction() }; function scrollFunction() { if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) { document.getElementById("goTop").style.display = "block"; } else { document.getElementById("goTop").style.display = "none"; } } // Go to Top of page when user clicks on the Button function topFunction() { document.body.scrollTop = 0; // For Chrome, Safari and Opera document.documentElement.scrollTop = 0; // For IE and Firefox }
const metaDataDao = require('../dao/meta-data'); const utils = require('../../utils'); function toCamel(arr) { return arr.map(item => utils.toCamel(item)); } function getLocations(callback) { metaDataDao.getLocations(callback); } function getEnglishLevels(callback) { metaDataDao.getEnglishLevels(callback); } function getSkills(callback) { metaDataDao.getSkills((err, res) => { if (err) { throw err; } callback(err, toCamel(res)); }); } function getCandidateStatuses(callback) { metaDataDao.getCandidateStatuses(callback); } function getOtherSkills(callback) { metaDataDao.getOtherSkills(callback); } function getVacancyStatuses(callback) { metaDataDao.getVacancyStatuses(callback); } module.exports = { getEnglishLevels, getLocations, getSkills, getCandidateStatuses, getOtherSkills, getVacancyStatuses, };
/** * Task Status Filter * Used To Filter Todo List */ import React, { Component } from 'react'; import List from '@material-ui/core/List'; import ListItem from '@material-ui/core/ListItem'; import { connect } from 'react-redux'; import { Scrollbars } from 'react-custom-scrollbars'; import { withRouter } from 'react-router-dom'; // helpers import { getAppLayout } from 'Helpers/helpers'; // intl messages import IntlMessages from 'Util/IntlMessages'; // redux action import { getAllTodoAction, getCompletedTodosAction, getDeletedTodosAction, getStarredTodosAction, activateFilterAction } from 'Actions'; class TaskStatusFilter extends Component { /** * Function to filter the todo list with labels */ onFilterTodo(activeIndex) { this.props.activateFilterAction(activeIndex); } /** * Get Label Classes */ getLabelClasses(value) { let labelClasses = ''; switch (value) { case 1: labelClasses = 'ladgend bg-success'; return labelClasses; case 2: labelClasses = 'ladgend bg-primary'; return labelClasses; case 3: labelClasses = 'ladgend bg-info'; return labelClasses; case 4: labelClasses = 'ladgend bg-danger'; return labelClasses; default: return labelClasses; } } /** * Get Scroll Height */ getScrollHeight() { const { location } = this.props; const appLayout = getAppLayout(location) switch (appLayout) { case 'app': return 'calc(100vh - 288px)'; case 'agency': return 'calc(100vh - 416px)'; case 'boxed': return 'calc(100vh - 416px)'; case 'horizontal': return 'calc(100vh - 335px)'; default: break; } } render() { const { labels } = this.props; return ( <Scrollbars className="rct-scroll" autoHide style={{ height: this.getScrollHeight() }}> <div className="sidebar-filters-wrap"> <List className="filters"> <ListItem button onClick={() => this.props.getAllTodoAction()} > <span className="filter-title"><IntlMessages id="components.all" /></span> </ListItem> </List> <h6 className="sidebar-title px-20 pt-20">Filters</h6> <List className="filters list-unstyled"> <ListItem button onClick={() => this.props.getCompletedTodosAction()} > <i className="zmdi zmdi-check-square mr-3"></i> <span className="filter-title"><IntlMessages id="widgets.done" /></span> </ListItem> <ListItem button onClick={() => this.props.getDeletedTodosAction()} > <i className="zmdi zmdi-delete mr-3"></i> <span className="filter-title"><IntlMessages id="widgets.deleted" /></span> </ListItem> <ListItem button onClick={() => this.props.getStarredTodosAction()} > <i className="zmdi zmdi-star mr-3"></i> <span className="filter-title"><IntlMessages id="widgets.starred" /></span> </ListItem> </List> <h6 className="sidebar-title px-20 pt-20">Labels</h6> <List className="list-unstyled filters"> {labels.map((label, key) => ( <ListItem button onClick={() => this.onFilterTodo(label.value)} key={key} > <span className={this.getLabelClasses(label.value)}></span> <span className="filter-title"><IntlMessages id={label.name} /></span> </ListItem> ))} </List> </div> </Scrollbars> ); } } // map state to props const mapStateToProps = ({ todoApp, settings }) => { const { labels } = todoApp; return { labels, settings }; }; export default withRouter(connect(mapStateToProps, { getAllTodoAction, getCompletedTodosAction, getDeletedTodosAction, getStarredTodosAction, activateFilterAction })(TaskStatusFilter));
var prepareHeaders = function(hash) { result = {}; var re = /^AdminIt-/; $.each(hash, function(key, value) { if (!re.test(key)) { key = 'AdminIt-' + key.charAt(0).toUpperCase() + key.slice(1); } result[key] = value; }); return(result); } var initPartials = function() { $('[data-toggle="partial"][data-target]').on('click', function(evt) { var data = $(this).data(); var href = data.remote || $(this).attr('href'); if (href) { var options = { dataType: 'html', headers: prepareHeaders(data.params) } $.ajax(href).success(function(html) { $(data.target).innerHtml(html); }); evt.preventDefault(); } }); } var initDialogs = function() { /* $('[data-toggle="dialog"]').on('click', function(evt) { var data = $(this).data(); evt.preventDefault(); if (data.target) { $(data.target).modal('show'); } else if ($(this).attr('href')) });*/ } var initTiles = function() { $('.admin-tile') .mouseenter(function() { $(this).find('.admin-tile-actions').addClass('in'); }) .mouseleave(function() { $(this).find('.admin-tile-actions').removeClass('in'); }); $('.admin-tile-actions').each(function() { var $this = $(this); var $parent = $this.parent(); var pos = $parent.position(); $this.css({ position: 'absolute', top: pos.top + 10, left: pos.left + $parent.outerWidth() - $this.outerWidth() - 10 }); }); } var initPopups = function() { $('[data-toggle="popup"]') .mouseenter(function() { $(this).find('[data-toggle="popup-target"]').addClass('in'); }) .mouseleave(function() { $(this).find('[data-toggle="popup-target"]').removeClass('in'); }); } var initTabs = function() { $('[data-toggle="tab"]').on('shown.bs.tab', function(e) { $('[data-tab="' + $(e.relatedTarget).attr('href') + '"]').removeClass('in'); $('[data-tab="' + $(e.target).attr('href') + '"]').addClass('in'); $('form input[type="hidden"][name="section"]').val($(this).attr('href').substr(1)); initTiles(); }); var active = $('.active > [data-toggle="tab"]'); if (active.length > 0) { active = active.first().attr('href'); $('[data-tab="' + active + '"]').addClass('fade').addClass('in'); $('[data-tab][data-tab!="' + active + '"]').addClass('fade').removeClass('in'); $('form input[type="hidden"][name="section"]').val(active.substr(1)); } } var initLinks = function() { $('[data-link]').on('click', function(evt) { evt.preventDefault(); location = $(this).data().link; }); } var initImageUploads = function() { $('[data-toggle="file-upload"]').fileUpload({ success: function(el, response) { $(el.data('image')).attr('src', response.small_url); } }); } var initSelects = function() { $('.select2:not(.select2-container)').select2({ minimumResultsForSearch: -1 // disable search }); } var initGeoPickers = function() { $('[data-geo-picker]').each(function() { var $this = $(this); var $input = $($this.data('geoPicker')); var arr = $input.val().split(','); var lon = parseFloat(arr[0]); var lat = parseFloat(arr[1]); $this.geoLocationPicker({ gMapZoom: 13, gMapMapTypeId: google.maps.MapTypeId.ROADMAP, gMapMarkerTitle: 'Выбирите местоположение', showPickerEvent: 'click', defaultLat: lat || 55.751607, // center defaultLng: lon || 37.617159, // of Moscow defaultLocationCallback: function(lat, lon) { $input.val(lon + ', ' + lat); $input.parent().find('.x').text(lon); $input.parent().find('.y').text(lat); } }); }); } var initSwitches = function() { $('[data-toggle="switch"]').switch() } var initControls = function() { initImageUploads(); initSelects(); initGeoPickers(); initTiles(); initSwitches(); } $(document).on('ready page:load', function() { initPartials(); // initDialogs(); initTabs(); initPopups(); initLinks(); initControls(); // allow dialog content reloading $('.modal').on('hidden.bs.modal', function() { $(this).removeData(); }) .on('loaded.bs.modal', function() { var active = $('.active > [data-toggle="tab"]'); if (active.length > 0) { active = active.first().attr('href'); $('form input[type="hidden"][name="section"]').val(active.substr(1)); } var $form = $(this).find('form'); if ($form.length > 0) { $(this).find('button[type="submit"]').on('click', function(evt) { evt.preventDefault(); $form.submit(); }); } initControls(); }) });
import React, { useState } from 'react'; import './style.css' const NavBar = () => { const [click, setClick] = useState(false) const handleClick = () => setClick(!click); return( <nav> <div> <a href="#home" id="logo">CM</a> </div> <ul className={click ? "nav_menu active" : "nav_menu"}> <li className="nav_item"><a href="#home" onClick={handleClick}>Home</a></li> <li className="nav_item"><a href="#sobre" onClick={handleClick}>Sobre</a></li> <li className="nav_item"><a href="#projetos" onClick={handleClick}>Projetos</a></li> <li className="nav_item"><a href="#contato" onClick={handleClick}>Contato</a></li> </ul> <div onClick={handleClick} className="nav_icon"> <i className={click ? "fas fa-times" : "fas fa-bars"}></i> </div> </nav> ); } export default NavBar;
import React from 'react'; import { Chart } from "react-google-charts"; import './smallChart.css' const HistoricChart = (props) => { const priceOptions = { title: "Price Last Month", width:500, hAxis: { title: "Date"}, vAxis: { title: "Price" }, legend: "none" }; const mCapOptions = { title: "MarketCap Last Month", width:500, hAxis: { title: "Date"}, vAxis: { title: "MarketCap" }, legend: "none" }; const volumeOptions = { title: "Volume Last Month", width:500, hAxis: { title: "Date"}, vAxis: { title: "Volume" }, legend: "none" }; const chartPriceData = [['Date', 'Price'], ...props.historicData.prices]; const chartMCapData =[['Date', 'Cap'], ...props.historicData.marketCaps]; const chartVolumeData =[['Date', 'Volume'], ...props.historicData.totalVolumes]; const PriceChart = () => { return ( <Chart chartType="LineChart" data={chartPriceData} options={priceOptions} width="25%" height="250px" legendToggle /> ); }; const MarketCapChart = () => { return ( <Chart chartType="LineChart" data={chartMCapData} options={mCapOptions} width="25%" height="250px" legendToggle /> ); }; const VolumeChart = () => { return ( <Chart chartType="LineChart" data={chartVolumeData} options={volumeOptions} width="25%" height="250px" legendToggle /> ); }; if (!props.currency) return null; return( <div className="smallChart"> <PriceChart /> <MarketCapChart /> <VolumeChart /> </div> ) } export default HistoricChart;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var user_1 = require("./user"); exports.UserEntity = user_1.UserEntity; var user_account_1 = require("./user.account"); exports.UserAccountEntity = user_account_1.UserAccountEntity; var order_1 = require("./order"); exports.OrderEntity = order_1.OrderEntity; var order_item_1 = require("./order.item"); exports.OrderItemEntity = order_item_1.OrderItemEntity; var item_1 = require("./item"); exports.ItemEntity = item_1.ItemEntity; var category_1 = require("./category"); exports.CategoryEntity = category_1.CategoryEntity;
var SIZE = 40; var EDGE_SIZE = 3; var PADDING = 2; var colors = [ "yellow", "DarkOrange", "blue", "red", "green", "white" ]; function draw_cube() { var X_OFFSET = (canvas.width - 12 * SIZE - 3 * PADDING) / 2; var Y_OFFSET = (canvas.height - 9 * SIZE - 2 * PADDING) / 2 + 3 * SIZE; var PERSP = 1; var width = canvas.width - 2 * X_OFFSET; draw_side(X_OFFSET + 3 * SIZE + PADDING, Y_OFFSET - 3 * SIZE - PADDING, 0, 1); draw_side(X_OFFSET, Y_OFFSET, 1, 1); draw_side(X_OFFSET + 3 * SIZE + PADDING, Y_OFFSET, 2, 1); draw_side(X_OFFSET + 6 * SIZE + 2 * PADDING, Y_OFFSET, 3, 1); draw_side(X_OFFSET + 9 * SIZE + 3 * PADDING, Y_OFFSET, 4, 1); draw_side(X_OFFSET + 3 * SIZE + PADDING, Y_OFFSET + 3 * SIZE + PADDING, 5, 1); } function draw_one(x, y, size, idx) { ctx.beginPath(); ctx.rect(x + EDGE_SIZE, y + EDGE_SIZE, size - 2 * EDGE_SIZE, size - 2 * EDGE_SIZE); ctx.fillStyle = colors[cube[idx]]; ctx.fill(); } function draw_side(x, y, idx, p) { size = 3 * SIZE * p; ctx.beginPath(); ctx.rect(x, y, size, size); ctx.fillStyle = "black"; ctx.fill(); idx = idx * 9; size = SIZE * p; draw_one(x, y, size, idx++); draw_one(x + SIZE, y, SIZE, idx++); draw_one(x + 2 * SIZE, y, SIZE, idx++); draw_one(x, y + SIZE, size, idx++); draw_one(x + SIZE, y + SIZE, SIZE, idx++); draw_one(x + 2 * SIZE, y + SIZE, SIZE, idx++); draw_one(x, y + 2 * SIZE, size, idx++); draw_one(x + SIZE, y + 2 * SIZE, SIZE, idx++); draw_one(x + 2 * SIZE, y + 2 * SIZE, SIZE, idx++); }
var findRedundantConnection = function(edges) { let visited = new Set(); for (let i = 0; i < edges.length; i++) { let edge = edges[i] if (i === 0) { visited.add(edge[0]) visited.add(edge[1]) } else { if (visited.has(edge[0]) && visited.has(edge[1])) { return edge } else if (visited.has(edge[0])) { visited.add(edge[1]) } else if (visited.has(edge[1])) { visited.add(edge[0]) } else { visited.add(edge[0]); visited.add(edge[1]); } } } }; console.log(findRedundantConnection([[1,2], [1,3], [2,3]]))
const React = require('react'); const TileEditor = require('./TileEditor.jsx'); const Gridfunc = require('./Gridfunc.js'); const TileContent = require('./TileContent.jsx'); const Tile = React.createClass({ render: function () { if (this.props.position != this.props.editing) { //tile not being edited if (!(this.props.content.text || this.props.content.image)) { //empty tile return <div style={this.props.style} onDoubleClick={this.onDoubleClick} onClick={this.onClick} onDragStart={this.onDragStart} onDragEnter={this.onDragEnter} onDragEnd={this.onDragEnd} > <TileContent content={this.props.content}/> </div>; //tile has contents } else return <div style={this.props.style} onDoubleClick={this.onDoubleClick} onDragStart={this.onDragStart} onDragEnter={this.onDragEnter} onDragEnd={this.onDragEnd} > <TileContent content={this.props.content}/> </div>; //tile being edited } else return <div style={this.props.style} onDoubleClick={this.onDoubleClick} onDragStart={this.onDragStart} onDragEnter={this.onDragEnter} onDragEnd={this.onDragEnd} > <TileEditor editingContentType={this.props.editingContentType} editingColour={this.props.editingColour} columns={this.props.columns} gridSize={this.props.gridSize} editingText={this.props.editingText} editingImage={this.props.editingImage} editingTileSize={this.props.editingTileSize} userRequestsEdit={this.userRequestsEdit} position={this.props.position} onTextSubmit={this.props.onTextSubmit} content={this.props.content} changeTileText={this.props.changeTileText} userRequestsEditColour={this.props.userRequestsEditColour} changeTileColour={this.props.changeTileColour} userRequestsAddImage={this.props.userRequestsAddImage} changeImageURL={this.props.changeImageURL} userRequestsChangeTileSize={this.props.userRequestsChangeTileSize} changeTileSize={this.props.changeTileSize} userRequestsFill={this.props.userRequestsFill} /> </div>; }, onDoubleClick: function () { this.props.userRequestsEdit(this.props.position); }, onClick: function (e) { if (e.shiftKey === true) { this.props.tileSelected(this.props.position); } }, onDragStart: function () { this.props.logDragging(this.props.position); }, onDragEnter: function () { this.props.logDragTarget(this.props.position); }, onDragEnd: function () { this.props.swapPositions(this.props.position); } }); module.exports = Tile;
/* window.onload = function() { var menuImg = document.getElementsByClassName("menu-img")[0]; var listaMenu = document.getElementsByClassName("menu")[0].getElementsByTagName("ul")[0]; var muestraMenu = false; menuImg.onclick = function(){ if (muestraMenu) { muestraMenu = false; listaMenu.style.display = "none"; } else { muestraMenu = true; listaMenu.style.display = "block"; } } menuImg.onkeyup = function(){ if (muestraMenu) { muestraMenu = false; listaMenu.style.display = "none"; } else { muestraMenu = true; listaMenu.style.display = "block"; } } document.getElementsByTagName("body")[0].onresize = function(){ if (screen.width > 441) { listaMenu.style.display = "block"; } } }*/
exports = module.exports = function(io, db) { var playerpool = []; var currentgames = []; var index; var totalvictor = ""; io.sockets.on('connection', function (socket) { socket.on('join', function(data) { socket.join(data.user); socket.name = data.user; console.log("--------------"); console.log(data.user + " joined!"); console.log("SocketId: " + socket.id); console.log("--------------"); }) socket.on('disconnect', function() { console.log("--------------"); console.log(socket.name + " left!"); console.log("SocketId: " + socket.id); console.log("--------------"); if(currentgames.findIndex(x => x.player1==socket.name) != "-1") { index = currentgames.findIndex(x => x.player1==socket.name); userwin = currentgames[index].player2; db.query('UPDATE realtimeresults SET victor="' + userwin + '", timestamp=NOW() WHERE id=' + currentgames[index].id, function(err) { if (err) throw err; io.in(currentgames[index].player1).emit('RTDone', userwin); io.in(currentgames[index].player2).emit('RTDone', userwin); currentgames.splice(index, 1); console.log(currentgames); }) } else if(currentgames.findIndex(x => x.player2==socket.name) != "-1") { index = currentgames.findIndex(x => x.player2==socket.name); if(index != "-1") { userwin = currentgames[index].player1; db.query('UPDATE realtimeresults SET victor="' + userwin + '", timestamp=NOW() WHERE id=' + currentgames[index].id, function(err) { if (err) throw err; io.in(currentgames[index].player1).emit('RTDone', userwin); io.in(currentgames[index].player2).emit('RTDone', userwin); currentgames.splice(index, 1); console.log(currentgames); }) } } else { if(playerpool.findIndex(x => x.username==socket.name) != "-1") { playerpool.splice(playerpool.findIndex(x => x.username==socket.name), 1); } } }) socket.on('LeavePool', function(user) { playerpool.splice(playerpool.findIndex(x => x.username==user), 1); console.log("--------------"); console.log("Playerpool: " + playerpool.length); console.log("--------------"); }) socket.on('RTPlayerAdd', function (data) { var usernamein = data.username; var categoryin = data.category; if(playerpool.findIndex(x => x.username==usernamein) == "-1") { playerpool.push({username: usernamein, category: categoryin}); } else { playerindex = playerpool.findIndex(x => x.username==usernamein); playerpool[playerindex].category = categoryin; } console.log("--------------"); console.log("Playerpool: " + playerpool.length); console.log("--------------"); var playerpoolArr = playerpool.map(function(item){return item.category}); var isDuplicate = playerpoolArr.some(function(item, idx){ return playerpoolArr.indexOf(item) != idx }) if(isDuplicate == true) { var indexes = []; for (i = 0; i < playerpool.length; i++) { if (playerpool[i].category === categoryin) { indexes.push(i); } } db.query('INSERT INTO realtimeresults SET ?', {player1: playerpool[indexes[0]].username, player2: playerpool[indexes[1]].username, category: categoryin}, function(err, results, fields) { if(err) throw err; var gameId = results.insertId; var questionnumbers = []; db.query('SELECT COUNT(*) AS aantal FROM realtimequestions_' + categoryin, function(err, rows) { while(questionnumbers.length < 5) { var tempnumber = Math.floor((Math.random() * rows[0].aantal) + 1); if(!questionnumbers.includes(tempnumber)) { questionnumbers.push(tempnumber); } } var tempquery = 'SELECT question, answernr, ans1, ans2, uitleg FROM realtimequestions_' + categoryin + ' WHERE qsid IN (' + questionnumbers[0] + ', ' + questionnumbers[1] +', ' + questionnumbers[2] + ', ' + questionnumbers[3] +', ' + questionnumbers[4] + ') ORDER BY find_in_set(qsid, "' + questionnumbers[0] + ', ' + questionnumbers[1] +', ' + questionnumbers[2] + ', ' + questionnumbers[3] +', ' + questionnumbers[4] + '")'; db.query(tempquery, function(err,result) { console.log("GameId: " + gameId); currentgames.push({id: gameId, games: 0, player1: playerpool[indexes[0]].username, player1sec: 0, player1wins: 0, player1currentgame: 0, player2: playerpool[indexes[1]].username, player2sec: 0, player2wins: 0, player2currentgame: 0}); io.in(playerpool[indexes[0]].username).emit('RTPlayerAdd', [playerpool[indexes[0]].username, playerpool[indexes[1]].username, gameId, result]); io.in(playerpool[indexes[1]].username).emit('RTPlayerAdd', [playerpool[indexes[0]].username, playerpool[indexes[1]].username, gameId, result]); if(indexes[0] < indexes[1]) { playerpool.splice(indexes[0], 1); playerpool.splice(indexes[1] - 1, 1); } else { playerpool.splice(indexes[0], 1); playerpool.splice(indexes[1], 1); } }) }) }) } } ); socket.on('RTKillGame', function(playerwin) { index = currentgames.findIndex(x => x.player1==playerwin); var winnerplayer; if(index == "-1") { index = currentgames.findIndex(x => x.player2==playerwin); winnerplayer = currentgames[index].player2; } else { winnerplayer = currentgames[index].player1; } db.query('UPDATE realtimeresults SET victor="' + playerwin + '", timestamp=NOW() WHERE id=' + currentgames[index].id, function(err) { if (err) throw err; if(winnerplayer == currentgames[index].player1) { io.in(currentgames[index].player1).emit('RTDone', {winner: playerwin}); } else { io.in(currentgames[index].player2).emit('RTDone', {winner: playerwin}); } currentgames.splice(index, 1); console.log("Currentgames: " + currentgames); }) }) socket.on('DisconnectClient', function(user) { socket.disconnect(); }) socket.on('RTCompareResults', function(data) { index = currentgames.findIndex(x => x.id==data.gameId); curindex = currentgames[index]; if(curindex.player1 == data.player) { curindex.player1currentgame = data.secs; } else if(curindex.player2 == data.player) { curindex.player2currentgame = data.secs; } var victor = ""; if(curindex.player1currentgame != 0 && curindex.player2currentgame != 0) { if(curindex.player1currentgame == 999) { curindex.player1sec += 30; } else { curindex.player1sec += curindex.player1currentgame; } if(curindex.player2currentgame == 999) { curindex.player2sec += 30; } else { curindex.player2sec += curindex.player2currentgame; } if(curindex.player1currentgame == 999 && curindex.player2currentgame == 999) { curindex.player1currentgame = 0; curindex.player2currentgame = 0; victor = "Losers!"; } else if(curindex.player1currentgame > curindex.player2currentgame) { curindex.player2wins += 1; victor = curindex.player2; curindex.player1currentgame = 0; curindex.player2currentgame = 0; } else if(curindex.player1currentgame < curindex.player2currentgame) { curindex.player1wins += 1; curindex.player1currentgame = 0; curindex.player2currentgame = 0; victor = curindex.player1; } else { curindex.player1wins += 1; curindex.player2wins += 1; curindex.player1currentgame = 0; curindex.player2currentgame = 0; victor = "TIE!"; } curindex.games += 1; console.log("----------------------"); console.log("Game stats:"); console.log(curindex.player1 + ": " + curindex.player1wins + " (" + curindex.player1sec + " sec)"); console.log(curindex.player2 + ": " + curindex.player2wins + " (" + curindex.player2sec + " sec)"); console.log("Games: " + curindex.games); console.log("Winner: " + victor); console.log("----------------------"); if(curindex.games == 5) { if(curindex.player1wins < curindex.player2wins) { totalvictor = curindex.player2; } else if(curindex.player1wins > curindex.player2wins) { totalvictor = curindex.player1; } else { totalvictor = "none"; } if(totalvictor != "none") { db.query('UPDATE realtimeresults SET victor="' + totalvictor + '", timestamp=NOW() WHERE id=' + curindex.id, function(err) { if (err) throw err; io.in(curindex.player1).emit('RTDone', {winner: totalvictor, secs: curindex.player1sec}); io.in(curindex.player2).emit('RTDone', {winner: totalvictor, secs: curindex.player2sec}); currentgames.splice(index, 1); console.log("Currentgames: " + currentgames); }) db.query('UPDATE opdrachten_users SET score = score + 100 WHERE user = "' + totalvictor + '"', function(err) { if(err) throw err; }); } else { db.query('UPDATE realtimeresults SET timestamp=NOW() WHERE id=' + curindex.id, function(err) { if (err) throw err; io.in(curindex.player1).emit('RTDone', {winner: totalvictor, secs: curindex.player1sec}); io.in(curindex.player2).emit('RTDone', {winner: totalvictor, secs: curindex.player2sec}); currentgames.splice(index, 1); console.log("Currentgames: " + currentgames); }) } } else { io.in(curindex.player1).emit('RTNextRound', {victor: victor, scores: curindex}); io.in(curindex.player2).emit('RTNextRound', {victor: victor, scores: curindex}); } } }) }); }
function mes(mes) { let meses = ["num","janeiro","Fervereiro","março","Abril","Maio","junho","Julho","Agosto","setembro","outubro","Novembro","Desembro"] console.log( meses[mes]) } mes(2) //execicio 5 function elemento(soma,relativo) { let resultado = soma === relativo && soma >= relativo ? true : false console.log(resultado) } elemento(0,0) elemento(0,"0") elemento(5,1) //exercicio 6
// variables for current weather section // var city; // var lat; // var lon; var date; var iconCode; var iconImage; // var currentTemp; // var humidity; // var wind; // var UV; // variables for forecast section var currentDate; var FCiconCode; var FCiconImage; var FCtemp; var FChumidity; // new elements // var cityEl = $("<span>" + city + "</span>"); // var currentTempEl = $("<span>" + currentTemp + "</span>"); // var humidityEl = $("<span>" + humidity + "</span>"); // var windEl = $("<span>" + wind + "</span>"); // var UVEl = $("<span>" + UV + "</span>"); function createCurrentElements(apiCurrentResponse, UV) { var city = 'city: ' + apiCurrentResponse.name; var currentTemp = 'temp: ' + apiCurrentResponse.main.temp + 'F'; var humidity = 'humidity: ' +apiCurrentResponse.main.humidity + '%'; var wind = 'wind speed: ' + apiCurrentResponse.wind.speed + 'mph'; var UV = 'UV index: ' + apiUVResponse.value; console.log(UV); console.log(apiUVResponse.value); var cityEl = $("<span>" + city + "</span><br>"); var currentTempEl = $("<span>" + currentTemp + "</span><br>"); var humidityEl = $("<span>" + humidity + "</span><br>"); var windEl = $("<span>" + wind + "</span><br>"); var UVEl = $("<span>" + UV + "</span><br>"); $('#current').prepend(cityEl); $('#current').prepend(currentTempEl); $('#current').prepend(humidityEl); $('#current').prepend(windEl); $('#current').prepend(UVEl); }; $(document).ready(function(){ });
import Base from "./Base"; export default class Backend extends Base { static popular(query = {}) { return Base.get("/popular", query); } static movies(filter) { return Base.get(`/search_movies/${filter}`); } static movie(movieId) { return Base.get(`/movie/${movieId}`); } static credits(movieId) { return Base.get(`/movie/${movieId}/credits`); } static similarMovies(movieId) { return Base.get(`/movie/${movieId}/similar`); } static person(personId) { return Base.get(`/person/${personId}`); } static checkIn() { return Base.get("/check_in"); } static setApiKey(key) { return Base.post("/check_in", { key }); } }
export { InstallPopup } from './InstallPopup';
import map from 'lodash/map'; import enzymeListFull from '../../../../enzymeListFull.json'; import { connect } from 'react-redux' // import takaraEnzymeList from '../../../../enzymeListFull.json'; import takaraEnzymeList from '../../../../takaraEnzymeList.json'; // import {reduxForm, Field, formValueSelector} from 'redux-form' import RowItem from '../RowItem' import React from 'react' import './style.scss'; import Select from 'react-select'; import cutSequenceByRestrictionEnzyme from 've-sequence-utils/cutSequenceByRestrictionEnzyme'; import QuestionTooltip from '../../../components/QuestionTooltip'; import getReverseComplementSequenceString from 've-sequence-utils/getReverseComplementSequenceString'; import PrimaryButton from '../../../components/PrimaryButton'; import SecondaryButton from '../../../components/SecondaryButton'; class AddYourOwnEnzyme extends React.Component { render() { var paddingStart = '-------' var paddingEnd = '-------' var { // filteredRestrictionEnzymesAdd, // addRestrictionEnzyme, inputSequenceToTestAgainst= '', //pass this prop in! handleClose, seqName='Destination Vector', addYourOwnEnzyme, dispatch, invalid, stopAddingYourOwnEnzyme } = this.props addYourOwnEnzyme.chop_top_index = Number(addYourOwnEnzyme.chop_top_index) addYourOwnEnzyme.chop_bottom_index = Number(addYourOwnEnzyme.chop_bottom_index) var { sequence='', chop_top_index=0, chop_bottom_index=0, name='' } = addYourOwnEnzyme var regexString = bpsToRegexString(sequence) var enzyme = { name:name, site:sequence, forwardRegex:regexString, reverseRegex: getReverseComplementSequenceString(regexString), topSnipOffset:chop_top_index, bottomSnipOffset:chop_bottom_index, usForward:0, usReverse:0, color:'black' } var matches if (regexString.length === 0) { matches = [] } else { matches = cutSequenceByRestrictionEnzyme(inputSequenceToTestAgainst, true, enzyme) } var errors = validate(addYourOwnEnzyme) function onChange(updatedVal) { dispatch({ type: 'ADD_YOUR_OWN_ENZYME_UPDATE', payload: { ...addYourOwnEnzyme, ...updatedVal }, }) } var invalidOrNoMatches = invalid || matches.length < 1 var seqPlusPadding = paddingStart + sequence + paddingEnd return <div className={'createYourOwnEnzyme'}> <h2>Create your own enzyme</h2> <CustomInput error={errors['name']} value={name} onChange={onChange} name='name' label={'Name:'}/> <CustomInput error={errors['sequence']} value={sequence} onChange={onChange} name='sequence' label={ <div className='labelWithIcon'> <QuestionTooltip> <div className={'taLineHolder'}> <Line> Special Characters: </Line> <Line> R = G A (purine) </Line> <Line> Y = T C (pyrimidine) </Line> <Line> K = G T (keto) </Line> <Line> M = A C (amino) </Line> <Line> S = G C (strong bonds) </Line> <Line> W = A T (weak bonds) </Line> <Line> B = G T C (all but A) </Line> <Line> D = G A T (all but C) </Line> <Line> H = A C T (all but G) </Line> <Line> V = G C A (all but T) </Line> <Line> N = A G C T (any) </Line> </div> </QuestionTooltip> <span> Recognition sequence: </span> </div> } onInput={function (input) { var inputValue = input.target.value var cleanInput = inputValue.replace(/[^rykmswbdhvnagct]/ig, ''); input.target.value=cleanInput }} /> <CustomInput error={errors['chop_top_index']} value={chop_top_index} onChange={onChange} name='chop_top_index' label='Chop top index:' type="number"/> <CustomInput error={errors['chop_bottom_index']} value={chop_bottom_index} onChange={onChange} name='chop_bottom_index' label='Chop bottom index:' type="number"/> <RowItem { ...{ // width: 400, tickSpacing: 1, annotationVisibility: { cutsites: true, cutsiteLabels: false, axis: false, }, sequenceLength: seqPlusPadding.length, bpsPerRow: seqPlusPadding.length, row: { sequence: seqPlusPadding, start: 0, end: seqPlusPadding.length-1, cutsites: { 'fake1': { annotation: { recognitionSiteRange: { start: paddingStart.length, end: paddingStart.length + sequence.length - 1, }, topSnipBeforeBottom: chop_top_index < chop_bottom_index, bottomSnipPosition: paddingStart.length + chop_bottom_index, topSnipPosition: paddingStart.length + chop_top_index, id: 'fake1', restrictionEnzyme: { } } } }, }, } } /> <h3 className={'cutnumber ' + (matches.length === 0 && 'invalid') }> {matches.length > 10 ? `Cuts more than 10 times in your ${seqName}` : `Cuts ${matches.length} times in your ${seqName}` } </h3> <div className={'buttonHolder'}> <PrimaryButton className={' ta_useCutsite addYourOwnEnzymeBtn ' + (invalidOrNoMatches && 'disabled') } onClick={function () { if (invalidOrNoMatches) { return } dispatch({ type: 'ADD_RESTRICTION_ENZYME', payload: enzyme, meta: { EditorNamespace: ['MutagenesisEditor','SelectInsertEditor', 'ResultsEditor'] } }) dispatch({ type: 'FILTERED_RESTRICTION_ENZYMES_ADD', payload: { label: name, value: name, }, meta: { EditorNamespace: ['MutagenesisEditor','SelectInsertEditor', 'ResultsEditor'] } }) // addRestrictionEnzyme(enzyme) // filteredRestrictionEnzymesAdd({ // label: name, // value: name, // }) handleClose() }}> Use Enzyme</PrimaryButton> <SecondaryButton className={'addYourOwnEnzymeBtn'} onClick={stopAddingYourOwnEnzyme}> Back </SecondaryButton> </div> </div> } } // const selector = formValueSelector('customEnzymes') // AddYourOwnEnzyme = reduxForm({ // form: 'customEnzymes', // destroyOnUnmount: false, // initialValues: { // name: 'Example Enzyme', // sequence: 'ggatcc', // chop_top_index: 1, // chop_bottom_index: 5, // }, // validate // })(AddYourOwnEnzyme) AddYourOwnEnzyme = connect(function (state) { return {addYourOwnEnzyme: state.VectorEditor.addYourOwnEnzyme} })(AddYourOwnEnzyme) class AddAdditionalEnzymes extends React.Component { state = { addYourOwnEnzyme: false, enzymesToAdd: [], }; startAddingYourOwnEnzyme = () => { this.setState({addYourOwnEnzyme: true}); }; stopAddingYourOwnEnzyme = () => { this.setState({addYourOwnEnzyme: false}); }; render() { if (this.state.addYourOwnEnzyme) { return <AddYourOwnEnzyme {...this.props} stopAddingYourOwnEnzyme={this.stopAddingYourOwnEnzyme} ></AddYourOwnEnzyme> } var {dispatch, handleClose, inputSequenceToTestAgainst=''} = this.props var {enzymesToAdd} = this.state return <div className={'addYourOwnEnzyme'}> <h2>Add additional enzymes</h2> <span> Our default list only contains the most common enzymes. Search here to add less common ones: </span> <div className={'filterAndButton'}> <Select multi placeholder="Select cut sites..." options={map(enzymeListFull, function (enzyme) { return {label: enzyme.name, value: enzyme} })} onChange={(enzymesToAdd)=>{ this.setState({ enzymesToAdd: enzymesToAdd.map(function ({value}) { var times = cutSequenceByRestrictionEnzyme(inputSequenceToTestAgainst, true, value).length return { label: value.name + ` (Cuts ${times} time${times===1 ? '':'s'})`, value } }) }) }} value={enzymesToAdd} /> <PrimaryButton className={'addYourOwnEnzymeBtn'} onClick={function () { enzymesToAdd.forEach(function (enzyme) { dispatch({ type: 'ADD_RESTRICTION_ENZYME', payload: enzyme.value, meta: { EditorNamespace: ['MutagenesisEditor', 'SelectInsertEditor', 'ResultsEditor'] } }) dispatch({ type: 'FILTERED_RESTRICTION_ENZYMES_ADD', payload: { label: enzyme.label, value: enzyme.value.name, }, meta: { EditorNamespace: ['MutagenesisEditor', 'SelectInsertEditor', 'ResultsEditor'] } }) }) handleClose() }} disabled={this.state.enzymesToAdd && this.state.enzymesToAdd.length < 1}> Add Enzymes </PrimaryButton> </div> <div className={'createYourOwnButton'}> <span> Still not finding what you want? </span> <PrimaryButton className={'addYourOwnEnzymeBtn'} onClick={this.startAddingYourOwnEnzyme}> Create your own enzyme </PrimaryButton> </div> </div> } } function validate(values) { const errors = {} if (!values.name || values.name.trim() === '') { errors.name = 'Input cannot be blank' } else if (takaraEnzymeList[values.name.toLowerCase()]) { errors.name = `The name ${values.name} is already taken.` } if (!values.sequence || values.sequence.trim() === '' || values.sequence.trim().length < 4) { errors.sequence = 'Enzyme recognition sequence must be at least 4bps long' } if (values.sequence && values.sequence.replace(/[^atgcrykmswbdhvn]/ig, '').length !== values.sequence.length) { errors.sequence = 'Sequence must only contain valid bases' } if (!values.chop_top_index && values.chop_top_index !== 0) { errors.chop_top_index = 'Input cannot be blank' } if (!values.chop_bottom_index && values.chop_bottom_index !== 0) { errors.chop_bottom_index = 'Input cannot be blank' } return errors } AddAdditionalEnzymes = connect(function (state) { return {inputSequenceToTestAgainst: state.VectorEditor.addYourOwnEnzyme.inputSequenceToTestAgainst} })(AddAdditionalEnzymes) export default AddAdditionalEnzymes function bpsToRegexString(bps) { var regexString = '' if (typeof bps === 'string') { bps.split('').forEach(function (bp) { if (bp === 'r') { regexString+= '[ga]' } else if (bp === 'y') { regexString+= '[tc]' } else if (bp === 'k') { regexString+= '[gt]' } else if (bp === 'm') { regexString+= '[ac]' } else if (bp === 's') { regexString+= '[gc]' } else if (bp === 'w') { regexString+= '[at]' } else if (bp === 'b') { regexString+= '[gtc]' } else if (bp === 'd') { regexString+= '[gat]' } else if (bp === 'h') { regexString+= '[act]' } else if (bp === 'v') { regexString+= '[gca]' } else if (bp === 'n') { regexString+= '[agct]' } else { regexString += bp } }) } return regexString } // function CustomInput({name, type, label, onInput}) { // return <Field name={name} label={label} type={type} onInput={onInput} component={RenderInput} > // </Field> // } function CustomInput({name, value, onChange, onInput, label, error, type}) { return <div className={'inputHolder ' + (error && 'error')} > <div> <span> {label} </span> <input value={value} onChange={function (e) { onChange({ [name]: e.target.value }) }} onInput={onInput} type={type} /> </div> {error && <p className='errorMessage'>{error}</p>} </div> } function Line({children}) { return <div className={'taLine'} > {children}</div> }
import React, { useState, useEffect } from 'react' import { useParams } from 'react-router-dom' import axios from 'axios' import LoadingPage from '../ui/LoadingPage.jsx' export default function OneMovie() { const { id } = useParams() const [movie, setMovie] = useState([]) const [isLoading, setIsLoading] = useState(false) const [genres, setGenres] = useState([]) useEffect(() => { const fetchData = async () => { setIsLoading(true) const { data } = await axios.get(`/movie/${id}`) setGenres(Object.values(data.movie.genres)) setMovie(data.movie) setIsLoading(false) } fetchData() }, [id]) if (isLoading) return <LoadingPage /> return ( <> <h2> Movie: {movie.title} ({movie.year}) </h2> <div className="float-start"> <small>Rating: {movie.mpaa_rating}</small> </div> <div className="float-end"> {genres.map((m, index) => ( <span className="badge bg-secondary me-1">{m}</span> ))} </div> <table className="table table-compact table-striped"> <thead></thead> <tbody> <tr> <td> <strong>Title:</strong> </td> <td>{movie.title}</td> </tr> <tr> <td> <strong>Description:</strong> </td> <td>{movie.description}</td> </tr> <tr> <td> <strong>Run time:</strong> </td> <td>{movie.runtime} minutes</td> </tr> </tbody> </table> </> ) }
function dibujafondo(){ estrellasx -= 0.1 contexto.drawImage(estrellas,estrellasx,0) estrellas2x -= 0.1 estrellas2x -=Math.random()*2-1 contexto.drawImage(estrellas2,estrellas2x,0) } function dibujaestrellas(){ for(var i = 0;i<numeroestrellas;i++){ // para cada estrella estrellasx[i] -= velocidadestrellas[i]; // posicion de x disminuye en una velocidad aleatoria contexto.drawImage(estrellas,estrellasx[i],estrellasy[i]); // se dibuja la estrella en posiciones x e y diferentes } } function dibujarnebulosas(){ for(var i = 0;i<numeronebulosas;i++){ //para cada nebulosa nebulosasx[i] -= velocidadnebulosas[i]; //posicion de X de la nebulosa disminuye en velocidad aleatoria contexto.drawImage(nebulosas,nebulosasx[i],nebulosasy[i]); //se dibuja la nebulosa en X e Y posiciones diferentes } } function dibujarnebulosas2(){ for(var i = 0;i<numeronebulosas2;i++){ //para cada nebulosa nebulosas2x[i] -= velocidadnebulosas2[i]; //posicion de X de la nebulosa disminuye en velocidad aleatoria contexto.drawImage(nebulosas2,nebulosas2x[i],nebulosas2y[i]); //se dibuja la nebulosa en X e Y posiciones diferentes } } function gestionenemigo(){ for(var i = 0; i < numeroenemigos;i++){ enemigox[i]--; //se desplaza en X en negativo a velocidad constante enemigoy[i]+= Math.random()*4-2; //se desplaza Y aleatoriamente dentro de un rango contexto.drawImage(enemigo[tipoenemigo[i]],enemigox[i],enemigoy[i]); //se dibujo al enemigo en posiciones Y y X aleatoriamente //contexto.drawImage(enemigo,enemigox[i],enemigoy[i]); } } function balas(){ // repasamos las balas contexto.fillStyle = "red"; for(var i = 0;i < cuentabalas ;i++){ //para cada bala balax[i]+= velocidadbala; //posicion de X aumenta segun la velocidad de la bala contexto.drawImage(imgdisparo,balax[i],balay[i]) //se dibuja la bala en X y Y diferente } // compruebo si alguna de las balas llega al HITBOX for(var i=0;i < cuentabalas ;i++){ //para cada bala for(var j = 0;j <numeroenemigos;j++){ // para cada enemigo if(Math.abs(balax[i] - enemigox[j]) < enemigoanchura && Math.abs(balay[i] - enemigoy[j]) < enemigoaltura-90){ //console.log("colisiona") enemigox.splice(j,1) //desaparece enemigo en x enemigoy.splice(j,1) //desaparece enemigo en y balax.splice(i,1) //desaparece la bala con que impacto balay.splice(i,1) //desaparece la bala con que impacto numeroenemigos--; //la cantidad de enemigos va disminuyendo $("#contieneaudio").append('<audio id="musica" src ="audio/boom1.mp3" autoplay controls="true"></audio>') //cuando colisiona con el enemigo se ejecuta el audio puntuacion++; } } } } function dispara(){ balax[cuentabalas] = navex; //la bala aparece en X + anchura de la nave balay[cuentabalas] = navey+(navealtura/2); //la bala aparece en Y + altura/2 de la nave cuentabalas++; //el contador de balas aumenta } function personaje(){ if(movimientopersonajey == "abajo"){velocidady++;navey+= velocidady;} if(movimientopersonajey == "arriba"){velocidady--;navey+= velocidady;} if(movimientopersonajex == "derecha"){velocidadx++;navex+= velocidadx;} if(movimientopersonajex == "izquierda"){velocidadx--;navex+= velocidadx;} contexto.drawImage(nave,navex,navey); } function gestionteclas(){ $(document).keydown(function(event){ if(event.which == 40){movimientopersonajey = "abajo";} // se mueve abajo if(event.which == 39){movimientopersonajex = "derecha";} // se mueve a la derecha if(event.which == 38){movimientopersonajey = "arriba";} // se mueve arriba if(event.which == 37){movimientopersonajex = "izquierda";} // se mueve a la izquierda if(event.which == 32){ // se dispara con espacio dispara(); } }) $(document).keyup(function(event){ if(event.which == 40){movimientopersonajey = 0} // suelto abajo y deja de moverse if(event.which == 39){movimientopersonajex = 0} // suelto derecha y deja de moverse if(event.which == 38){movimientopersonajey = 0} // suelto arriba y deja de moverse if(event.which == 37){movimientopersonajex = 0} // suelto izquierda y deja de moverse }) } function gestionsensible(){ $("#arriba").mousedown(function(){movimientopersonajey = "arriba"}) $("#abajo").mousedown(function(){movimientopersonajey = "abajo"}) $("#derecha").mousedown(function(){movimientopersonajex = "derecha"}) $("#izquierda").mousedown(function(){movimientopersonajex = "izquierda"}) $("#disparo").click(function(){dispara();}) // Al soltar /*$("#arriba").mouseup(function(){movimientopersonajey = 0}) $("#abajo").mouseup(function(){movimientopersonajey = 0}) $("#derecha").mouseup(function(){movimientopersonajex = 0}) $("#izquierda").mouseup(function(){movimientopersonajex = 0}) */ $(document).mouseup(function(){ movimientopersonajex = 0; movimientopersonajey = 0; }) } function muevemouse(){ $("#lienzo").mousemove(function(event){ //navex = event.clientX; //navey = event.clientY; if(ratonpulsado == true){ navex = event.clientX - tempx; navey = event.clientY - tempy; } $("#lienzo").mousedown(function(){ ratonpulsado = true; tempx = event.clientX - navex; tempy = event.clientY - navey; }) }) $("#lienzo").mouseup(function (){ratonpulsado = false;}) } function movpersonaje(){ if(movimientopersonajex == 0){ if(velocidadx > 0){velocidadx--;} if(velocidadx < 0){velocidadx++;} navex += velocidadx; } if(movimientopersonajey == 0){ if(velocidady > 0){velocidady--;} if(velocidady < 0){velocidady++;} navey += velocidady; } } function eliminabalas(){ //for(var i = 0; i < cuentabalas ; i++){ for(var numnave in balax){ if(balax[numnave]>anchuraventana){ //si la bala en x es mayor a la anchura de la ventana cuentabalas--; //las balas disminuyen balax.splice(numnave,1); //bala desaparece en x balay.splice(numnave,1); //bala desaparece en y } } } function mantenmeadentro(){ if(navex > anchuraventana){navex = anchuraventana} if(navex < 0){navex = 0} if(navey > 800){navey = 800} if(navey < 0){navey = 0} } function gestioonamusica(){ var musica = document.getElementById("musica") //llamo al elemento musica musica.volume = 0.05; //volumen de musica en 0.5 musica.play(); //la musica comienza en play } function eliminaaudio(){ $("#contieneaudio").html(""); } function ganaste(){ if(puntuacion == 10){ //si la puntuacion es igual a 10 $('#ganaste').html("HAS GANADO"); //aparece has ganado setTimeout("location.reload()",4000); //luego de 4 segundos se recarga la pagina } } function perdiste(){ if(vidas == 0){ //si la vida llega a 0 $('#perdiste').html("HAS PERDIDO"); //aparece has perdido setTimeout("location.reload()",4000); //luego de 4 segundos recarga la pagina } } function pierdesvidas(){ for(var numglobo in enemigox){ if(enemigox[numglobo]<0){ //si enemigo de x es menor a 0 vidas--; //disminuye vida enemigox.splice(numglobo,1); //desaparece el enemigo en x enemigox.splice(numglobo,1); // desaparece el enemigo en y } } }
import styled from 'styled-components' import { useState } from "react" import SideNav from './SideNav'; const BurgerMenu = () => { const [open, setOpen] = useState(false) return ( <Nav> <Burger open={open} onClick={() => setOpen(!open)}> <div /> <div /> <div /> </Burger> <SideNav open={open} setOpen={setOpen}/> </Nav> ) }; const Nav = styled.nav` display: none; @media (min-width: 320px) and (max-width: 768px) { display: flex; align-items: flex-end; justify-content: space-between; } ` const Burger = styled.div` display: none; @media (min-width: 320px) and (max-width: 768px) { width: 5rem; height: 2.5rem; position: fixed; top: 5vh; right: 5vh; z-index: 20; display: flex; justify-content: space-around; flex-flow: column nowrap; div { width: 3.5rem; height: 0.35rem; background-color: ${({ open }) => open ? 'lightgreen' : 'whitesmoke'}; opacity: 0.6; border-radius: 15px; transform-origin: 1px; transition: all 0.3s linear; &:nth-child(1) { transform: ${({ open }) => open ? 'rotate(45deg)' : 'rotate(0)'}; } &:nth-child(2) { transform: ${({ open }) => open ? 'translateX(100%)' : 'translateX(0)'}; opacity: ${({ open }) => open ? 0 : 1}; } &:nth-child(3) { transform: ${({ open }) => open ? 'rotate(-45deg)' : 'rotate(0)'}; }} } ` export default BurgerMenu;
setInterval(function() { $.get("/get", function (data) { console.log(data); obj = JSON.parse(data); if(obj.loading) { $("#loading").show(); $("#text").hide(); } else { $("#text").text(obj.text); $("#loading").hide(); $("#text").show(); } }) }, 1000);
import React from "react"; import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; import NavBarSection from "./NavBarSection"; import NavagationList from "./NavagationList"; import AboutList from "./AboutList"; import FeaturesSection from "./FeaturesSection"; import HomePackageSection from "./HomePackageSection"; import StorySectionList from "./StorySectionList"; import BookList from "./BookList"; import FooterList from "./FooterList"; import PopUpList from "./PopupList" import { library } from "@fortawesome/fontawesome-svg-core"; import { faSearch } from "@fortawesome/free-solid-svg-icons"; import { faFighterJet } from "@fortawesome/free-solid-svg-icons"; import { faMicrochip } from "@fortawesome/free-solid-svg-icons"; import { faDesktop } from "@fortawesome/free-solid-svg-icons"; import { faHeartbeat } from "@fortawesome/free-solid-svg-icons"; library.add(faSearch); library.add(faFighterJet); library.add(faMicrochip); library.add(faDesktop); library.add(faHeartbeat); //trying to nest feature component into features session so i get four across so far accomplised horizontal elements only class App extends React.Component { state = {}; render() { return ( <div className=""> <Router> <Switch> <Route exact path="/" Component={NavBarSection} /> </Switch> <NavagationList /> <NavBarSection /> <AboutList /> <FeaturesSection /> <HomePackageSection /> <StorySectionList/> <BookList /> <FooterList /> <PopUpList /> </Router> </div> ); } } export default App;
import React from "react"; import { createAppContainer, createSwitchNavigator, SwitchNavigator } from 'react-navigation'; import { SafeAreaView, StyleSheet, ScrollView, View, Text, StatusBar, } from 'react-native'; import { NavigationContainer } from "@react-navigation/native"; import Splash from "./Swipe"; import LandingPage22 from "./Deside" import Login from "./Login"; import Signupp from "./SignUp" const Switch = createSwitchNavigator({ Swipe : Splash, Deside : LandingPage22, Login : Login, SignUp : Signupp }, { initialRouteName:'Swipe' } ); AppContainer = createAppContainer(Switch); class SwitchNav extends React.Component { constructor(props) { super(props); this.state = { } } render() { return ( <NavigationContainer> {/* <Switch.Navigator> <Switch.Screen name="Swipe" component={Splash} /> <Switch.Screen name="Deside" component={LandingPage22} /> <Switch.Screen name="Login" component={Login} /> <Switch.Screen name="SignUp" component={Signupp} /> </Switch.Navigator> */} <AppContainer/> </NavigationContainer> ); } } export default SwitchNav;
import React, { Component, PropTypes } from 'react'; import s from "./HeaderPortrait.css"; import Button from "../Button"; import Icon from "../Icon" import Boutiquer from "../boutiquer" import withStyles from 'isomorphic-style-loader/lib/withStyles'; import className from 'classnames'; import defaultPic from "./images/pic.png"; import {imageCDN} from "../../imgCDN"; class HeaderPortrait extends Component { constructor(props) { super(props); this.state = {} } static propTypes = { headerPic: PropTypes.string, jumpPersonInfo:PropTypes.func, pic_type:PropTypes.string, nickname:PropTypes.string, commitTime:PropTypes.string, textStyle:PropTypes.string, } jumpPersonInfo(e){ e.stopPropagation(); !!this.props.jumpPersonInfo && this.props.jumpPersonInfo(); } render() { let direction = this.props.direction || false; let textDirection = direction ? s.text_right : s.text_left; let comment = this.props.comment && <p className={ className([s.comment,textDirection]) }>{this.props.comment}</p>; let nickname = this.props.nickname && <div className={className([s.nickname,s[this.props.textStyle] || s.color2])}><span className={s.nicknameText}>{this.props.nickname} { !!this.props.butiquer && <Boutiquer /> }</span><span>{this.props.commitTime}</span></div>; let vip = this.props.isVip>0 && <em className={s.vipPos}> <Icon type="vip"></Icon> </em>; let headerPic; if(typeof window !== "undefined"){ headerPic = this.props.headerPic ? (this.props.headerPic.indexOf("http://") > -1 ? this.props.headerPic : window._imgCDN + this.props.headerPic) : defaultPic; }else { headerPic = this.props.headerPic ? (this.props.headerPic.indexOf("http://") > -1 ? this.props.headerPic : imageCDN + this.props.headerPic) : defaultPic; } return( <div> <div className={className([s.HPic,direction?s.right_pic:s.left_pic])}> <div onClick={(e)=>this.jumpPersonInfo(e)} className={className([s.headerPic,s[this.props.pic_type] || s.s_Pic])}> <img className={s[this.props.pic_type] || s.s_Pic } src={headerPic} alt=""/> {vip} </div> { nickname } </div> { comment } </div> ) } } export default withStyles(s)(HeaderPortrait);
import React from 'react' import { storiesOf } from '@storybook/react' import { text, boolean, number, select } from '@storybook/addon-knobs/react' import { withInfo } from '@storybook/addon-info' import { colorList } from '../colors' import { Button } from '../buttons' import { Icon } from '../icons' let colorSelect = { none: '' } colorList.forEach(color => { Object.assign(colorSelect, { [color]: color }) }) const props = () => ({ a: boolean('a', false), display: select( 'display', { block: 'block', 'inline-block': 'inline-block' }, 'inline-block' ), color: select('color', colorSelect, 'black'), round: boolean('round', false), children: text('children', 'Hello') }) storiesOf('Buttons', module) .add( 'Button', withInfo(` something here `)(() => <Button {...props()} />) ) .add( 'Button w/ Icon', withInfo(` something here `)(() => ( <Button a round color={select('button color', colorSelect, 'black')}> <Icon color={text('icon color', 'white')} /> </Button> )) )
import { takeLatest, put } from 'redux-saga/effects'; import { Auth } from 'aws-amplify'; import log from '../../common/libs/logger'; import { LOGIN_IN_PROGRESS } from '../actions/types'; import { loggedInSet, photoFavGetMany } from '../actions'; export function* login({ payload }) { log.info('login fired...', payload); try { const result = yield Auth.signIn(payload.email, payload.password); if (result) { yield put(loggedInSet(true)); yield put(photoFavGetMany()); } } catch (e) { yield log.error('Exception occurred: ', e); } } export function* watchLogin() { log.info('watchLogin starting'); yield takeLatest(LOGIN_IN_PROGRESS, login); }
// ==UserScript== // @name 百度经验纯净版 // @namespace https://saltzmanalaric.github.io // @version 1.0.0 // @description BaiduJingyanClear // @author Saltzman // @license MIT // @date 2020-05-21 // @modified 2020-05-21 // @match *://jingyan.baidu.com/*/* // @run-at document-end // @noframes // @icon https://saltzmanalaric.github.io/favicon.ico // ==/UserScript== (function() { 'use strict'; var children = [ document.getElementsByClassName("clearfix feeds-video-box")[0], document.getElementsByClassName("f-light feeds-video-one-view")[0], document.getElementsByClassName("wgt-income-money")[0], document.getElementById("fresh-share-exp-e"), document.getElementById("w-share"), document.getElementById("w-favor"), document.getElementById("wgt-like") ]; for (var child of children) { if (child) { child.parentNode.removeChild(child); } } })();
let courses = ["javascript", "java", "python"]; exports.save = (courseParam) => { const course = courseParam.toLowerCase(); let existingCourse = courses.includes(course) ? true : false; if (!existingCourse) { courses.push(course); console.log(course, "foi salvo "); return courses; } else { return `${course} já existe`; } }; exports.update = (oldCourseParam, newCourseParam) => { const oldCourse = oldCourseParam.toLowerCase(); const newCourse = newCourseParam.toLowerCase(); let coursesIndex = courses.indexOf(oldCourse); courses[coursesIndex] = newCourse; console.log(`curso: ${oldCourse} foi atualizado para: ${newCourse}`); return courses; }; exports.delete = (courseParam) => { const course = courseParam.toLowerCase(); let coursesIndex = courses.indexOf(course); delete courses[coursesIndex]; console.log(`${course} deletado`); return courses; }; exports.getCourses = () => { return courses; };
TOOL = //取得已知_id之user之nick {'getUserNick' : function(user) { user = Meteor.users.findOne(user); if (user) { return user.profile.nick; } else { return '不明人物'; } } //轉換timeStamp為中文時間 ,'convertTimeToChinese' : function(time) { time = parseInt(time, 10); if (time) { return moment(time).format('[(]YYYY/MM/DD HH:mm:ss[)]'); } else { return '(????/??/?? ??:??:??)' } } //判斷目前使用者是否為目前房間之管理者 ,'userIsAdm' : function() { var RouterParams = Session.get('RouterParams') , room = DB.room.findOne(RouterParams.room) , id = Meteor.userId() ; if (RouterParams.room === TRPG.public.id) { return true; } return (id && (id == TRPG.adm || (room && _.indexOf(room.adm, id) !== -1) )); } //判斷目前使用者是否為目前房間之玩家 ,'userIsPlayer' : function() { var RouterParams = Session.get('RouterParams') , room = DB.room.findOne(RouterParams.room) , id = Meteor.userId() ; if (RouterParams.room === TRPG.public.id) { return true; } return ( id && (id == TRPG.adm || ( room && (_.indexOf(room.adm, id) !== -1 || _.indexOf(room.player, id) !== -1) ) ) ); } //判斷一個物件的各key是否undefined ,'keyIsUndefined' : function() { var undefined , i ; for (i in arguments) { if (this[ arguments[ i ] ] !== undefined) { return false; } } return true; } };
console.log("Tushar"); console.log("Chauhan");
import {get} from '../../../utils/http'; import {getLocale} from '../../../i18n/utils'; import {REDUCERS_GROUP_PREFIX, ENDPOINT_ACCOUNT} from './constants'; const REDUCER_NAME = `${REDUCERS_GROUP_PREFIX}/info`; const GET_ACCOUNT_INFO_SUCCESS = `${REDUCER_NAME}/GET_ACCOUNT_INFO_SUCCESS`; const GET_ACCOUNT_INFO_ERROR = `${REDUCER_NAME}/GET_ACCOUNT_INFO_ERROR`; const initState = { info: { email: '', name: '', gender: '', avatar: '', createdAt: 0, updatedAt: 0 }, language: getLocale().toUpperCase(), loading: true }; export default (state = initState, action) => { switch (action.type) { case GET_ACCOUNT_INFO_SUCCESS: return {...state, info: action.info, language: getLocale().toUpperCase(), loading: false}; case GET_ACCOUNT_INFO_ERROR: return {...state, errorMessage: action.error, errors: action.errors, loading: false}; default: return state; } }; export const getAccountInfo = () => { return dispatch => { get(ENDPOINT_ACCOUNT).then(response => { dispatch({type: GET_ACCOUNT_INFO_SUCCESS, info: response}); }).catch(response => { dispatch({type: GET_ACCOUNT_INFO_ERROR, error: response.data.message}); }); } };
import React, {Component} from 'react'; import {Modal, Radio, Select, Button, message, Input, Col} from 'antd'; import E from 'wangeditor' import {articleSave, articleUpdate} from '../../requests/http-req.js' import history from '../../history.js' const RadioGroup = Radio.Group; const Option = Select.Option; export default class ArticleEditPage extends Component { constructor(props) { super(props); this.state = { content: '', title: '', showClient: 3, keyWords: null, language: 'zh', status: 0, type: null }; }; saveArticle = () => { const {content, title, showClient, keyWords, language, status, type} = this.state //console.log(this.state) if (content == '' || title == '' || keyWords == '' || type == '') { message.warning('空') return } let temObj = { articleResource: 'articleResource', content: content, keyWords: keyWords, language: language, showClient: showClient, status: status, title: title, type: type } if (this.itemData) { temObj.id = this.itemData.id this.coArticleUpdata(JSON.stringify(temObj)) } else { this.articleSave(JSON.stringify(temObj)) } } type = [] coArticleUpdata = (data) => { articleUpdate(data).then(req => { //console.log(req) message.success('更新ok') }) } articleSave = (data) => { articleSave(data).then(req => { //console.log(req) message.success('新建ok') }) } componentWillReceiveProps(props) { } componentWillMount() { // let {itemData, type} = this.props.location.data //console.log(this.props.location.data) this.itemData = this.props.location && this.props.location.data ? this.props.location.data.itemData : null if (this.itemData) { this.state.content = this.itemData.content this.state.title = this.itemData.title this.state.showClient = this.itemData.showClient this.state.keyWords = this.itemData.keyWords this.state.language = this.itemData.language this.state.status = this.itemData.status this.state.type = this.itemData.type } this.type = this.props.location && this.props.location.data ? this.props.location.data.type : null } componentDidMount() { if (this.refs.editorElem) { this.initEdit() } } editor = null initEdit = () => { const elem = this.refs.editorElem this.editor = new E(elem) this.editor.customConfig.zIndex = 100 // 使用 onchange 函数监听内容的变化,并实时更新到 state 中 this.editor.customConfig.onchange = html => { this.state.content = html; } this.editor.create() this.editor.txt.html(this.itemData ? this.itemData.content : "") } onChangeRadioGroup = (e) => { this.setState({ showClient: e.target.value }) } render() { return ( <div className='center-user-list'> <div className='edit-view-center'> <div style={{display: 'flex', flexDirection: 'row', width: '100%'}}> <div className='edit-row' style={{width: '600px'}}> <div style={{width: '100px'}}>文章标题:</div> <Input style={{width: '300px'}} value={this.state.title} onChange={(e) => this.setState({title: e.target.value})}/> </div> <div className='edit-row' style={{marginLeft: '35px'}}> <div style={{width: '100px'}}>关键字:</div> <Input style={{width: '300px'}} value={this.state.keyWords} onChange={(e) => this.setState({keyWords: e.target.value})}/> </div> </div> <div style={{display: 'flex', flexDirection: 'row', width: '100%',margin: '15px 0 0'}}> <div className='edit-row' style={{width: '600px'}}> <div style={{width: '100px'}}> 显示客户端: </div> <RadioGroup value={ parseInt(this.state.showClient) } onChange={this.onChangeRadioGroup}> <Radio value={1}>手机端</Radio> <Radio value={2}>PC端</Radio> <Radio value={3}>所有端</Radio> </RadioGroup> </div> <div className='edit-row' style={{marginLeft: '35px'}}> <div style={{width: '100px'}}>语言:</div> <RadioGroup onChange={(e) => this.setState({language: e.target.value})} value={this.state.language}> <Radio value={'zh'}>中文</Radio> <Radio value={'en'}>英文</Radio> </RadioGroup> </div> </div> <div style={{display: 'flex', flexDirection: 'row',margin: '15px 0 0'}}> <div className='edit-row' style={{width: '600px'}}> <div style={{width: '100px'}}>状态:</div> <RadioGroup onChange={(e) => this.setState({status: e.target.value}, () => { //console.log(this.state.status) })} value={parseInt(this.state.status)}> <Radio value={1}>停用</Radio> <Radio value={0}>启用</Radio> </RadioGroup> </div> <div className='edit-row' style={{marginLeft: '35px'}}> <div style={{width: '100px'}}>类型:</div> <Select onChange={(e) => { //console.log(e) this.state.type = e }} defaultValue={this.state.type} style={{width: '300px'}} placeholder="文章类型" > { this.type && this.type.map((item, index) => { return <Option key={index} value={item.typeName}>{item.typeName}</Option> }) } </Select> </div> </div> </div> <div ref="editorElem"></div> <div style={{display: 'flex', flexDirection: 'row'}}> <Button onClick={this.saveArticle} style={{width: '100px'}}>{this.itemData ? '更新' : '保存'}</Button> <Button onClick={() => { history.go(-1) }} style={{width: '100px'}}>返回</Button> </div> {this.state.hiddenEdit && <div style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>选择你要操作的文件,或者选择新建文章</div>} </div> ) } }
import ConMoveNav from './src/ConMoveNav' /* istanbul ignore next */ ConMoveNav.install = function(Vue) { Vue.component(ConMoveNav.name, ConMoveNav); }; export default ConMoveNav;
var AchieveRateWidget = function (trelloClient, selector) { this.client = trelloClient; this.selector = selector; }; AchieveRateWidget.prototype.calcRate = function (doneList, lists) { var self = this; var achieveCardCnt = self.client.findList(lists, doneList).cards.length; var allCardCnt = lists.reduce(function (prev, list) { return prev + list.cards.length; }, 0); return (Math.round(10000 * (achieveCardCnt / allCardCnt))) / 100; }; AchieveRateWidget.prototype.displayRate = function (rate) { $(this.selector).append('<span class="achieve_rate_rate">' + rate + '%</span>'); };
'use strict'; app.controller('autoPartListController', function($rootScope, $scope, $state, utils) { var data = null; $scope.init = function(){ utils.getData("base/autoPartAction!listAutoPart.action", function callback(dt){ $rootScope.tableData=dt; data = dt; console.info(dt); if(dTable){ dTable.fnDestroy(); initTable(); }else{ initTable(); } }); }; $scope.init(); function formatData(data) { var keys = ['parent', 'creator', 'onDutyTime', 'offDutyTime', 'createTime', 'lastModifyTime']; var len = keys.length, l = data.length; for (var i = 0; i < len; i++) { switch (i) { case 0: var dt = []; for (var n = 0; n < l; n++) { if (data[n][keys[i]]) dt.push(data[n][keys[i]]); } app.utils.getData(url, dt, function(d){}); default: break; } } return data; } //var ids = [], obj; $rootScope.ids = [], $rootScope.obj; function clicked(target, that){ var classname = 'rowSelected', id; target.click(function(e){ var evt = e || window.event; //evt.preventDefault(); evt.stopPropagation(); if(!that){ that = $(this).parents('tr'); } $rootScope.details = $rootScope.obj = app.utils.getDataByKey(data, 'id', that.data('id')); id = $rootScope.obj['id']; if(!$(this)[0].checked){ var idx = $rootScope.ids.indexOf(id); if(idx !== -1 ) $rootScope.ids.splice(idx, 1); //that.removeClass(classname); }else{ $rootScope.ids.push(id); //that.addClass(classname); } $scope.setBtnStatus(); }); } // 初始化表格 jQuery datatable var autoPartList, dTable; function initTable() { autoPartList = $('#autoPartList'); console.info(autoPartList); dTable = autoPartList.dataTable({ // "serverSide": true, // "ajax": { // "url": app.url.org.subUnits, // "type": 'POST', // "data": { // "id": $scope.item_id // } // }, //"bFilter": true, "data": data, "sAjaxDataProp": "dataList", "oLanguage": { "sLengthMenu": "每页 _MENU_ 条", "sZeroRecords": "没有找到符合条件的数据", "sProcessing": "&lt;img src=’./loading.gif’ /&gt;", "sInfo": "当前第 _START_ - _END_ 条,共 _TOTAL_ 条", "sInfoEmpty": "没有记录", "sInfoFiltered": "(从 _MAX_ 条记录中过滤)", "sSearch": "搜索", "oPaginate": { "sFirst": "<<", "sPrevious": "<", "sNext": ">", "sLast": ">>" } }, "fnCreatedRow": function(nRow, aData, iDataIndex){ $(nRow).attr('data-id', aData['id']); }, "drawCallback": function( settings ) { var input = autoPartList.find('thead .i-checks input'); var inputs = autoPartList.find('tbody .i-checks input'); var len = inputs.length, allChecked = true; for(var i=0; i<len; i++){ if(!inputs.eq(i)[0].checked){ allChecked = false; break; } } if(allChecked){ input[0].checked = true; }else{ input[0].checked = false; } input.off().click(function(){ for(var i=0; i<len; i++){ if(!inputs.eq(i)[0].checked || !$(this)[0].checked){ clicked(inputs.eq(i).off()); inputs.eq(i).trigger('click'); } } }); }, "aoColumns": [{ "orderable": false, "render": function(param){ return '<label class="i-checks"><input type="checkbox"><i></i></label>'; } }, { "mDataProp": "partCode", },{ "mDataProp":"partName" },{ "mDataProp":"brandName" },{ "mDataProp":"spec" },{ "mDataProp":"model" },{ "mDataProp":"sunitPrice" },{ "mDataProp":"eunitPrice" },{ "mDataProp":"yunitPrice" },{ "mDataProp":"useState", "render":function(param){ //0=初始化、1=待审核、2=发布(审核通过)、3=停止/下架、4=强制下架(违规) switch(param){ case 0: return "初始化";break; case 1: return "待审核";break; case 2: return "发布(审核通过)";break; case 3: return "停止/下架";break; case 4: return "强制下架(违规)";break; default: return "";break; }} },{ "mDataProp":"isActivity", "render":function(param){ //0=不参加(默认),1=参加 switch(param){ case 0: return "不参加";break; case 1: return "参加";break; default: return "";break; }} },{ "mDataProp":"stock" },{ "mDataProp":"updateTime" },{ "mDataProp":"partSource" },{ "mDataProp":"memo" }] }); var id; // 表格行事件 dTable.$('tr').dblclick(function(e, settings) { $scope.seeDetails($(this).data('id')); }).click(function(e) { var evt = e || window.event; var target = event.target || event.srcElement; evt.preventDefault(); //evt.stopPropagation(); var ipt = $(this).find('.i-checks input'); clicked(ipt.off(), $(this)); ipt.trigger('click'); var input = autoPartList.find('thead .i-checks input'); var inputs = autoPartList.find('tbody .i-checks input'); var len = inputs.length, allChecked = true; for(var i=0; i<len; i++){ if(!inputs.eq(i)[0].checked){ allChecked = false; break; } } if(allChecked){ input[0].checked = true; }else{ input[0].checked = false; } }); } });
import React from 'react'; import PropTypes from 'prop-types'; import Total from '../../components/Total/Total'; import './TotalsView.css'; const TotalsView = ({ dataHelper }) => ( <section className="flex-center totals-view"> <h2>Totals</h2> <div className="totals-wrapper flex-center"> <Total dataHelper={dataHelper} channelSet="millisecondOffset" /> <Total dataHelper={dataHelper} channelSet="distance" /> <Total dataHelper={dataHelper} channelSet="elevation" /> </div> </section> ); export default TotalsView; TotalsView.propTypes = { dataHelper: PropTypes.shape({ originalData: PropTypes.shape({}), minuteData: PropTypes.arrayOf(PropTypes.shape({})), channels: PropTypes.arrayOf(PropTypes.string), GPSCoords: PropTypes.arrayOf(PropTypes.shape({})), }).isRequired, };
import React from "react"; import { Link } from "react-router-dom"; import { Button } from "./Button"; import "./Footer.css"; function Footer() { return ( <div className="footer-container"> <section className="footer-subscription"> <p className="footer-subscription-heading"> Join the Sailor Nomad newsletter to receive the best vacation options </p> <p className="footer-subscription-text"> You may unsubscribe at any time </p> <div className="input-areas"> <form> <input type="email" name="email" placeholder="Your Email:" className="footer-input" /> <Button buttonStyle="btn--outline">Subscribe</Button> </form> </div> </section> <div class="footer-links"> <div className="footer-link-wrapper"> <div class="footer-link-items"> <h2>About Us</h2> <Link to="/sign-up">How it works</Link> <Link to="/">Terms of Service</Link> </div> <div class="footer-link-items"> <h2>Contact Us</h2> <Link to={{pathname:"https://github.com/aldogutierrez"}} target="_blank">Contact</Link> <Link to={{pathname:"https://github.com/aldogutierrez/sailor_nomad"}} target="_blank">Support</Link> <Link to="/">Destinations</Link> </div> </div> <div className="footer-link-wrapper"> <div class="footer-link-items"> <h2>Social Media</h2> <Link to={{ pathname:'https://instagram.com' }} target="_blank">Instagram</Link> <Link to={{ pathname:'https://facebook.com' }} target="_blank">Facebook</Link> <Link to={{ pathname:'https://youtube.com' }} target="_blank">YouTube</Link> <Link to={{ pathname:'https://twitter.com' }} target="_blank">Twitter</Link> </div> </div> </div> <section class="social-media"> <div class="social-media-wrap"> <div class="footer-logo"> <Link to="/" className="social-logo"> Sailor Nomad <i className="fas fa-passport"/> </Link> </div> <small class="website-rights">Sailor Nomad © 2020</small> <div class="social-icons"> <Link class="social-icon-link facebook" to={{ pathname:'https://facebook.com' }} target="_blank" aria-label="Facebook"> <i class="fab fa-facebook-f" /></Link> <Link class="social-icon-link instagram" to={{ pathname:'https://instagram.com' }} target="_blank" aria-label="Instagram"><i class="fab fa-instagram" /></Link> <Link class="social-icon-link youtube" to={{ pathname:'https://youtube.com' }} target="_blank" aria-label="YouTube"><i class="fab fa-youtube" /></Link> <Link class="social-icon-link twitter" to={{ pathname:'https://twitter.com' }} target="_blank" aria-label="Twitter"><i class="fab fa-twitter" /></Link> </div> </div> </section> </div> ); } export default Footer;
/*<input type="radio" name="lesson" value="java" onclick="changeImage(this)">Java <input type="radio" name="lesson" value="oracle" onclick="changeImage(this)">oracle <input type="radio" name="lesson" value="xml" onclick="changeImage(this)">xml <input type="radio" name="lesson" value="html" onclick="changeImage(this)">html <input type="radio" name="lesson" value="javascript" onclick="changeImage(this)">javascript*/ function changeImage(obj){ console.log(obj.value); var fd=document.getElementById("fd"); fd.style.display='inline'; switch (obj.value) { case 'java': fd.innerHTML="<img src=\"/web/imgBook/02KCAT2001.jpg\" width=200 height=200>"; break; case 'oracle': fd.innerHTML="<img src=\"/web/imgBook/03HYSC2004.jpg\" width=200 height=200>"; break; case 'xml': fd.innerHTML="<img src=\"/web/imgBook/04SAED1907.jpg\" width=200 height=200>"; break; case 'html': fd.innerHTML="<img src=\"/web/imgBook/21LSMT2015.jpg\" width=200 height=200>"; break; case 'javascript': fd.innerHTML="<img src=\"/web/imgBook/25ESG02020.jpg\" width=200 height=200>"; break; default: break; } }
export default /* glsl */` void getTBN(vec3 tangent, vec3 binormal, vec3 normal) { vec3 B = cross(normal, vObjectSpaceUpW); vec3 T = cross(normal, B); if (dot(B,B)==0.0) // deal with case when vObjectSpaceUpW normal are parallel { float major=max(max(normal.x, normal.y), normal.z); if (normal.x == major) { B=cross(normal, vec3(0,1,0)); T=cross(normal, B); } else if (normal.y == major) { B=cross(normal, vec3(0,0,1)); T=cross(normal, B); } else if (normal.z == major) { B=cross(normal, vec3(1,0,0)); T=cross(normal, B); } } dTBN = mat3(normalize(T), normalize(B), normalize(normal)); } `;
/** * Created by Daniel on 02.11.2015. */ import page from 'page' import * as pages from './pages.js' page('/', '/home') page('/results', pages.results) page('/constructors', pages.constructors) //page('/constructors/:constructor', pages.constructor) page('/drivers', pages.drivers) page('/driver/:id', pages.driver) page('/chart', pages.chart) //page('/drivers/:driver', pages.driver) page('/home', pages.home) page('/contact', pages.contact) page('*', pages.notFound) page()
/*** * Project: MDL * Author: Sudaraka Jayashanka * Module: login services */ 'use strict'; var serviceName = 'mdl.mobileweb.service.notification' angular.module('newApp').service(serviceName,['$http','$cookieStore','$location','settings','mdl.mobileweb.service.login', function($http, $cookieStore, $location,settings,loginService) { var vm = this; vm.webApiBaseUrl = settings.webApiBaseUrl; vm.getNewNotificationCount = function(callback){ var token = loginService.getAccessToken(); var body ={"getnewnotificationpulse":{ "token":token }}; //console.log(body); var authEndpoint = vm.webApiBaseUrl+'services/getnewnotificationpulse'; $http.post(authEndpoint,body,{headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }}) .success(function (response) { // success //console.log(response); callback(response); }) .error(function (errResponse) { console.log(" Error returning from " + authEndpoint); callback(errResponse); }); } vm.getTopNotifications = function(callback){ var token = loginService.getAccessToken(); var body ={"gettopnotifications":{ "token":token }}; var authEndpoint = vm.webApiBaseUrl+'services/gettopnotifications'; $http.post(authEndpoint,body,{headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }}) .success(function (response) { // success callback(response); }) .error(function (errResponse) { console.log(" Error returning from " + authEndpoint); callback(errResponse); }); } vm.getAllNotifications = function(callback){ /* * Post: Get all Notification (on notification -> see all page ) */ var token = loginService.getAccessToken(); var body = {"getallnotifications ":{ "token":token } }; var authEndpoint = vm.webApiBaseUrl+'services/getallnotifications'; $http.post(authEndpoint,body,{headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }}) .success(function (response) { // success callback(response); }) .error(function (errResponse) { console.log(" Error returning from " + authEndpoint); callback(errResponse); }); } vm.confirmNotifications = function(notification_id, callback){ /* * Post: Acknowledge a given notification */ var token = loginService.getAccessToken(); var body = {"readnotification":{ "token":token, "notification_id": notification_id } }; console.log(body); var authEndpoint = vm.webApiBaseUrl+'services/readnotification'; $http.post(authEndpoint,body,{headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }}) .success(function (response) { // success callback(response); }) .error(function (errResponse) { console.log(" Error returning from " + authEndpoint); callback(errResponse); }); } } ]);
'use strict'; const { DataTypes, Model } = require('sequelize'); class Product extends Model { getProductCode() { return this.code } } module.exports.class = Product; module.exports.columns = { id: { type: DataTypes.INTEGER, allowNull: false, autoIncrement: true, primaryKey: true, }, code: { type: DataTypes.STRING, allowNull: false, unique: true }, barcode: { type: DataTypes.STRING, allowNull: false, unique: true }, manufacturer_id: { type: DataTypes.INTEGER, allowNull: true }, quantity: { type: DataTypes.INTEGER, allowNull: true, defaultValue: 0 }, price: { type: DataTypes.FLOAT, allowNull: true, defaultValue: 0 }, tax_id: { type: DataTypes.INTEGER, allowNull: true }, image: { type: DataTypes.TEXT, allowNull: true }, out_of_stock_status_id: { type: DataTypes.INTEGER, allowNull: true }, date_available: { type: DataTypes.DATE, allowNull: true, defaultValue: DataTypes.NOW }, status: { type: DataTypes.BOOLEAN, allowNull: true, defaultValue: 1 } } module.exports.config = { hasTimestamps: true, tableName: 'products' }
import React from 'react'; import Product from '../Components/Product'; import Michelob1 from './michelob-photos/michelob1.jpg'; import Michelob2 from './michelob-photos/michelob2.jpeg'; import Michelob3 from './michelob-photos/michelob3.jpeg'; import Michelob4 from './michelob-photos/michelob4.jpeg'; const Michelob = (props) => { return ( <div id='michelob'> <div className='container text-center'> <h3 className='pt-4 pb-2'>Michelob Ultra</h3> <div className='row'> <div className='col-lg-3'> <Product img={Michelob1} name='Michelob Ultra 25 oz' price={Number(2).toFixed(2)}cartState={props.cartState} totalState={props.totalState} setTotal={props.setTotal} setCartState={props.setCartState}> </Product> </div> <div className='col-lg-3'> <Product img={Michelob2} name='Michelob Ultra 6 pack' price={Number(5).toFixed(2)} cartState={props.cartState} totalState={props.totalState} setTotal={props.setTotal} setCartState={props.setCartState}> </Product> </div> <div className='col-lg-3'> <Product img={Michelob3} name='Michelob Ultra 25 oz' price={Number(2).toFixed(2)} cartState={props.cartState} totalState={props.totalState} setTotal={props.setTotal} setCartState={props.setCartState}> </Product> </div> <div className='col-lg-3'> <Product img={Michelob4} name='Michelob Ultra 12 pack' price={Number(22).toFixed(2)} cartState={props.cartState} totalState={props.totalState} setTotal={props.setTotal} setCartState={props.setCartState}> </Product> </div> </div> </div> </div> ) } export default Michelob;
var fs = require('fs'), http = require('http'), connect = require('connect'), parse = require('url').parse, join = require('path').join; // Response prototype. var res = module.exports = { __proto__: http.ServerResponse.prototype }; // **render** map the express res.render api. Render a `view` with the // given `data` and optional callback. When a callback is given a // reponse will not be made automatically, otherwise a response with // statusCode 200 and `text/html` is given. res.render = function(view, data, cb) { var self = this, app = this.app, req = this.req; data = data || {}; self.locals = self.locals || []; // support callback function as second arg if(typeof data === 'function') cb = data, data = {}; // default callback to respond cb = cb || function(err, str){ if (err) return self.next(err); self.end(str); }; var filters = [].concat(app.viewFilters); (function next(filter) { if(!filter) return app.render(view, data, cb); filter(req, self, function(e) { if(e) return cb(e); // merge response locals data.locals = self.locals; next(filters.shift()); }); })(filters.shift()); }; // **json** send json response. res.json = function json(data) { var spaces = this.app.get('json spaces') || 2, body = JSON.stringify(data, null, spaces); this.charset = this.charset || 'utf-8'; this.setHeader('Content-Type', 'application/json'); return this.end(body); }; // **redirect** to the gien `url` with optional response `status` res.redirect = function redirect(url) { var app = this.app, req = this.req, headers = req.headers, status = 302, route = app.route, path = parse(req.url).pathname, host = req.headers.host, protocol = req.connection.encrypted ? 'https' : 'http'; // allow status / url if (arguments.length === 2) status = url, url = arguments[1]; // perform redirect if we get special `back` path url = url === 'back' ? (headers.referrer || headers.referer || '/') : url; var rel = !~url.indexOf('://'); // relative? if(rel) { // relative to path if(url.indexOf('./') === 0 || url.indexOf('..') === 0) url = path + '/' + url; // relative to mount point else if(url[0] === '/') url = route + '/' + url; // normalize url path, replacing any `//` by a single `/` and // reverting back `\` sepearator to be unix-like on windows url = join(url).replace(/\\/g, '/'); url = protocol + '://' + host + url; } var body = req.method === 'HEAD' ? null : '<p>Redirecting to <a href=":url">:url</a></p>'.replace(/:url/g, url); this.statusCode = status; this.setHeader('Content-Type', 'text/html'); this.setHeader('Location', url); this.end(body); };
import sTheme from "../../src/styledTheme"; import { NextSeo } from "next-seo"; import { makeStyles } from "@material-ui/core/styles"; import sizes from "../../src/sizes"; import { faStarOfLife } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import CostCalculator from "../../components/CostCalculator"; import Button from "@material-ui/core/Button"; import clsx from "clsx"; import Form from "../../components/Form"; import DentalImplantsInIstanbul from "../../components/DentalImplantsInIstanbul"; import WhyChooseIsc from "../../components/WhyChooseIsc"; import HowAreWeAffordable from "../../components/HowAreWeAffordable"; import Layout from "../../components/Layout"; const useStyles = makeStyles((theme) => ({ fontAwesomeIcon: { fontSize: "3rem", marginRight: ".5rem", color: theme.palette.third.dark, [sizes.down("lg")]: { fontSize: "2.8rem" }, [sizes.down("md")]: { fontSize: "2.5rem" } }, fontAwesomeIconCheck: { fontSize: "2.5rem", position: "relative", top: "3px", marginRight: "1rem", color: theme.palette.third.dark, [sizes.down("lg")]: { fontSize: "2.3rem" }, [sizes.down("md")]: { fontSize: "2rem" } }, regularButton: { borderRadius: "20px", fontSize: "1.5rem", backgroundColor: theme.palette.third.dark, letterSpacing: "1px", padding: "10px 25px", position: "relative", zIndex: 100, fontWeight: "bold", "&::before": { borderRadius: "inherit", content: "close-quote", backgroundImage: "linear-gradient(to right, rgba(26,59,112,1) 0%, rgba(40,85,130,1) 52%, rgba(0,164,189,1) 100%)", position: "absolute", top: 0, left: 0, opacity: 0, width: "100%", height: "100%", zIndex: -100, transition: "opacity 250ms cubic-bezier(0.4, 0, 0.2, 1) 0ms", display: "block" }, "&:hover": { // backgroundColor: theme.palette.primary.main, // background: // "linear-gradient(to right, rgba(26,59,112,1) 0%, rgba(40,85,130,1) 52%, rgba(0,164,189,1) 100%)", "&::before": { opacity: 1 }, color: theme.palette.secondary.main } }, pricesButton: { marginRight: "auto", marginLeft: "50%", transform: "translateX(-50%)", padding: "1rem 6rem" } })); const treatmentTemplate = (props) => { const classes = useStyles(); const handleChat = () => { if (typeof Tawk_API !== "undefined") { Tawk_API.maximize(); } }; const { open, handleCallbackClose, handleCallbackOpen } = props; return ( <Layout openCallback={open} handleCallbackOpen={handleCallbackOpen} handleCallbackClose={handleCallbackClose}> <NextSeo title="Dentures in Istanbul, Turkey - Dental Cost Calculator | Istanbul Smile Center" description="Calculate your denture/dental prosthesis treatment cost with our dental cost calculator. We provide high quality and affordable denture treatments. Learn more about our easy denture treatment process." openGraph={{ url: "https://www.istanbulsmilecenter.co/dentures", title: "Dentures in Istanbul, Turkey - Dental Cost Calculator | Istanbul Smile Center", description: "Calculate your denture/dental prosthesis treatment cost with our dental cost calculator. We provide high quality and affordable denture treatments. Learn more about our easy denture treatment process." }} /> <section className="treatment-img-section"> <div className="treatment-img-div" /> </section> <section className="treatment-section"> <div className="treatment-header"> <h1 className="treatment-header-text">Dentures</h1> </div> <section className="treatment-paragraph-section"> <DentalImplantsInIstanbul treatmentName="Dentures" /> </section> <section className="treatment-paragraph-section"> <WhyChooseIsc treatmentName="" /> </section> <section className="our-prices-section cost-calculator-section"> <div className="our-prices-header"> <h2 className="our-prices-header-text">Dental Cost Calculator</h2> <p className="our-prices-header-paragraph-text"> We even provide you a cost calculator to calculate the dental cost by yourself for your convenience. If you got your teeth checked up by a doctor and know your exact treatment needs or you need an estimated cost, feel free to use our calculator. </p> </div> <div className="cost-calculator-wrapper"> <CostCalculator /> </div> <div className="dental-treatments-buttons-div"> <Button variant="contained" color="primary" className={clsx(classes.regularButton, classes.pricesButton)} onClick={handleChat} > Chat&nbsp;Now </Button> </div> </section> <section className="treatment-paragraph-section"> <div className="treatment-paragraph-img-div-div"> <div className="treatment-paragraph-img-div treatment-paragraph-img-2" /> </div> <div className="treatment-general-text-div treatment-general-text-div-double treatment-general-text-div-double-extra "> <div className="treatment-general-text-side-div"> <h2 className="treatment-paragraph-header"> <FontAwesomeIcon className={classes.fontAwesomeIcon} icon={faStarOfLife} /> What Are Dentures/Prosthetic Teeth? </h2> <p className="treatment-paragraph"> Artificial teeth placed in order to complete dental deficiencies due to different reasons and to ensure oral integrity are referred to as prostheses. Deficiencies and disruption of oral health can be solved by prosthetic teeth. </p> <p className="treatment-paragraph"> There are fixed dentures and removable dentures. Fixed dentures are applied by the bonding method. Crowns, bridges or similar applications form fixed dentures. These dentures can be worn and removed by dentists because they are fixed in the structural context and do not show mobility. Methods such as zirconium or porcelain tooth coating may be preferred for fixed dentures. </p> <p className="treatment-paragraph"> Removable prostheses, on the other hand, can be easily removed and worn by the patient. There are total prosthesis, partial prosthesis, sensitive prosthesis and overdentures in this category of prostheses. </p> <h2 className="treatment-paragraph-header"> <FontAwesomeIcon className={classes.fontAwesomeIcon} icon={faStarOfLife} /> How Is The Treatment Process? </h2> <p className="treatment-paragraph"> In the first stage of treatment, the dentist takes the measurements. Three-dimensional digital scanning methods are used in the measurements performed in Istanbul Smile Center. With these methods, the process is made comfortable and fast. After the measurement, the color tone is selected and modeling occurs. In order to observe the harmony of the model in the mouth, a test is performed first. Some corrections can be made according to the result of the test. Prostheses bonded with special adhesives become ready for use. </p> <p className="treatment-paragraph"> In the treatment of removable prosthesis, measurement procedures are done first. Following the measurement procedures, dental samples formed by special methods are placed in the patient to observe the harmony in the mouth. If there are no problems, prostheses are created. Finally, the integration process is done. </p> </div> <div className="treatment-general-text-side-div"> <h2 className="treatment-paragraph-header"> <FontAwesomeIcon className={classes.fontAwesomeIcon} icon={faStarOfLife} /> Who Needs Dentures? </h2> <p className="treatment-paragraph"> Denture Treatment can be applied to anyone who has missing teeth. Fixed dentures are applied to patients who have partial teeth loss. Removable dentures are made in case of loss of all teeth. </p> <h2 className="treatment-paragraph-header"> <FontAwesomeIcon className={classes.fontAwesomeIcon} icon={faStarOfLife} /> What Are The Features of Dentures? </h2> <p className="treatment-paragraph"> Dental deficiencies in the mouth can cause damage not only in the region where they are located but also in the surrounding areas. The absence of teeth in a region also affects the teeth on the right and left of the cavity to a large extent. Teeth positioned next to the cavity will bend over time. In addition, if regular maintenance is not done, inflammation will occur, and this inflammation will spread to the adjacent teeth. The inflammation of the teeth and gums causes further problems. </p> <p className="treatment-paragraph"> The main advantage of prosthetic teeth includes the protection of adjacent teeth. The displacement, slipping or inclination of natural teeth can be prevented by a prosthesis. The deficiencies in the teeth make it difficult to chew, prevent speech, and extend the grinding process. With these prosthesis applications, these problems are completely eliminated. Missing teeth also cause some psychological problems in daily life. In some cases, providing a good appearance and aesthetic smile is possible with prosthesis. </p> </div> <div className="dental-treatments-buttons-div"> <Button variant="contained" color="primary" className={clsx(classes.regularButton, classes.pricesButton)} onClick={handleChat} > Chat&nbsp;Now </Button> </div> </div> </section> <section className="treatment-paragraph-section"> <HowAreWeAffordable /> </section> <section className="our-prices-section form-section"> <div className="our-prices-header"> <h2 className="our-prices-header-text">Get A Free Quote</h2> <p className="our-prices-header-paragraph-text"> Contacting us through live chat or WhatsApp is always the fastest way, but you may prefer sending us a good old form. Tell us your dental needs, and don't forget to attach at least the pictures of your teeth to the form. If you have an X-Ray or CT Scan, it's even better and crucial for most patients; this will help our doctors to make the right dental plan for you. It will also help us in giving you a more accurate quote for your treatment. Go ahead and fill out the form! Let's make your smile perfect! </p> </div> <div className="form-wrapper"> <Form /> </div> </section> </section> <style jsx>{` .treatment-img-section { width: 100%; } :global(.webp) .treatment-img-div { background-image: url(${require("../../public/treatments/dentures-page/dentures-intro-img.webp")}); } :global(.no-webp) .treatment-img-div { background-image: url(${require("../../public/treatments/dentures-page/dentures-intro-img.jpg")}); } .treatment-img-div { width: 100%; height: 65vh; background-repeat: no-repeat; background-size: cover; background-position: left 45% bottom 30%; clip-path: ellipse(100% 100% at 50% 0%); } .treatment-section { display: flex; align-items: center; flex-direction: column; padding: 2rem 1rem; } .treatment-header { display: flex; justify-content: center; flex-direction: column; align-items: center; width: 100%; text-align: center; } .treatment-process-header { width: 100%; text-align: center; margin-bottom: 1rem; } .treatment-header-text { font-family: ${sTheme.typography.serif}; color: ${sTheme.palette.primary.main}; font-size: 4rem; } .treatment-paragraph-section { width: 100%; display: flex; flex-direction: column; align-items: center; margin-top: 2rem; } .treatment-paragraph-img-div-div { width: 65%; } .treatment-paragraph-img-div { height: 300px; border-top-left-radius: 20px; border-top-right-radius: 20px; background-repeat: no-repeat; background-size: cover; background-position: left 50% bottom 80%; background-color: ${sTheme.palette.secondary.main}; } :global(.webp) .treatment-paragraph-img-2 { background-image: url(${require("../../public/treatments/dentures-page/dentures-set-img.webp")}); } :global(.no-webp) .treatment-paragraph-img-2 { background-image: url(${require("../../public/treatments/dentures-page/dentures-set-img.jpg")}); } .treatment-paragraph-img-2 { max-height: 750px; height: 35vmax; background-position: left 50% bottom 80%; } .treatment-general-text-div { width: 65%; border: 0px solid ${sTheme.palette.primary.main}; border-bottom-left-radius: 20px; border-bottom-right-radius: 20px; border-top: none; padding: 3rem; background-color: ${sTheme.palette.secondary.main}; margin-top: 0; } .treatment-general-text-div-single { border-radius: 20px; } .treatment-general-text-div-double { display: flex; justify-content: space-between; flex-wrap: wrap; } .treatment-general-text-div-double-extra { align-items: center; } .treatment-general-text-div-multiple { flex-wrap: wrap; border-radius: 20px; align-items: center; } .treatment-general-text-side-div { width: 48%; } .treatment-paragraph-header { font-size: 3rem; color: ${sTheme.palette.primary.main}; font-family: ${sTheme.typography.serif}; } .treatment-paragraph { font-size: 2rem; font-weight: normal; margin-bottom: 1rem; } .treatment-paragraph-small-header { color: ${sTheme.palette.primary.main}; font-family: ${sTheme.typography.serif}; font-weight: bold; } .our-prices-section { display: flex; justify-content: center; flex-wrap: wrap; margin-top: -5px; padding-bottom: 4rem; width: 100%; } .our-prices-header { display: flex; justify-content: center; flex-direction: column; align-items: center; width: 100%; text-align: center; } .our-prices-header-text { font-family: ${sTheme.typography.serif}; color: ${sTheme.palette.primary.main}; font-size: 4rem; } .our-prices-header-paragraph-text { color: ${sTheme.palette.secondary.dark}; font-size: 2rem; width: 50%; } .cost-calculator-section { margin-top: 2rem; } .cost-calculator-wrapper { width: 70%; } @media (max-width: ${sizes.sizes.xl}) { .cost-calculator-wrapper { width: 80%; } } @media (max-width: ${sizes.sizes.lg}) { .cost-calculator-wrapper { width: 90%; } } @media (max-width: ${sizes.sizes.md}) { .cost-calculator-wrapper { width: 95%; } } .dental-treatments-buttons-div { display: flex; justify-content: flex-start; width: 100%; align-items: baseline; margin: 0 auto; margin-top: 4rem; } .form-section { margin-top: 2rem; } .form-wrapper { width: 97%; } .guarantees-div { margin: 1rem 0 2rem 0; } .guarantees-div .treatment-paragraph { font-weight: bold; color: ${sTheme.palette.primary.main}; } @media (max-width: ${sizes.sizes.xl}) { .treatment-paragraph-img-div-div, .treatment-general-text-div { width: 70%; } .our-prices-header-paragraph-text { width: 60%; } } @media (max-width: ${sizes.sizes.lg}) { .treatment-paragraph-img-div-div, .treatment-general-text-div { width: 80%; } .our-prices-header-paragraph-text { width: 70%; font-size: 1.8rem; } .our-prices-header-text { font-size: 3.5rem; } .treatment-header-text { font-size: 3.5rem; } .treatment-paragraph-header { font-size: 2.5rem; } .treatment-paragraph { font-size: 1.8rem; } } @media (max-width: ${sizes.sizes.md}) { .treatment-img-div { height: 50vh; } .treatment-paragraph-img-div-div, .treatment-general-text-div { width: 90%; } .our-prices-header-paragraph-text { width: 80%; font-size: 1.6rem; } .our-prices-header-text { font-size: 3rem; } .treatment-header-text { font-size: 3rem; } .treatment-paragraph-header { font-size: 2.2rem; } .treatment-paragraph { font-size: 1.6rem; } } @media (max-width: ${sizes.sizes.mdsm}) { .treatment-paragraph-img-div-div, .treatment-general-text-div { width: 100%; } .treatment-paragraph-img-1 { height: 250px; } } @media (max-width: ${sizes.sizes.sm}) { .treatment-general-text-div { padding: 2.5rem; } } @media (max-width: ${sizes.sizes.xs}) { .treatment-img-div { height: 40vh; } .treatment-paragraph-img-1 { height: 200px; } .treatment-general-text-side-div { width: 100%; } .treatment-general-text-div-double-extra { flex-wrap: wrap; } .treatment-general-text-div { text-align: center; } } @media (max-width: ${sizes.sizes.xxs}) { .treatment-general-text-div { padding: 2rem; } } `}</style> </Layout> ); }; export default treatmentTemplate;
import Comment from '../entities/CommentClass'; import fetchJsonp from 'fetch-jsonp'; class CommentService { getComment(id) { return fetchJsonp(`https://hacker-news.firebaseio.com/v0/item/${id}.json?print=pretty`) .then(response => response.json()) .then(data => new Comment(data)) } } const commentData = new CommentService(); export default commentData;
function onMouseMove(e) {} function onMouseDown(e) { //console.log(getMousePos(e)); if(menu == "start") { ball = new Ball("red"); player1 = new Player("blue"); player2 = new Player("green"); player2.x = 40; if(buttonStartVsComputer.isClicked(getMousePos(e))) { menu = "game"; mode = "vscomputer"; } if(buttonStartVsPlayer.isClicked(getMousePos(e))) { menu = "game"; mode = "vsplayer"; } } if(menu == "game") { if(buttonBackToMenu.isClicked(getMousePos(e))) { menu = "start"; } } } function onMouseUp(e) {} function onMouseOut(e) {} function getMousePos(e) { var rect = canvas.getBoundingClientRect(); return { x: Math.round((e.clientX - rect.left)/(rect.right - rect.left)*canvas.width), y: Math.round((e.clientY - rect.top)/(rect.bottom - rect.top)*canvas.height) }; } function onKeyDown(e) { //console.log(e.keyCode); if(menu == "game") { if(e.keyCode == 38) player1.goUp(); if(e.keyCode == 40) player1.goDown(); if(mode == "vsplayer") { if(e.keyCode == 87) player2.goUp(); if(e.keyCode == 83) player2.goDown(); } } }
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { View, Text, Image, StyleSheet, TouchableWithoutFeedback } from 'react-native'; import Card from './common/Card'; import CardSection from './common/CardSection'; import Stars from './common/Stars'; import WaitTime from './common/WaitTime'; import TotalTime from './common/TotalTime'; class RestaurantDisplay extends Component { render() { const { name, price, rating, image_url, popular_times } = this.props.restaurantData; return ( <TouchableWithoutFeedback onPress={this.props.onItemPressed}> <View> <Card> <CardSection> <View style={styles.thumbnailContainerStyle}> <Image style={styles.thumbnailStyle} source={{ uri: image_url }} /> </View> <View style={styles.contentStyle}> <Text style={styles.headerTextStyle}>{name}</Text> <WaitTime times={popular_times} /> <TotalTime times={popular_times} /> </View> <View style={styles.starStyle}> <Text>{price}</Text> <Stars votes={rating} /> </View> </CardSection> </Card> </View> </TouchableWithoutFeedback> ); } } const styles = StyleSheet.create({ contentStyle: { flexDirection: 'column', justifyContent: 'space-around', }, headerTextStyle: { fontSize: 15, fontWeight: 'bold' }, thumbnailContainerStyle: { justifyContent: 'center', alignItems: 'center', marginLeft: 10, marginRight: 10 }, thumbnailStyle: { height: 60, width: 60 }, starStyle: { flex: 1, flexDirection: 'column', justifyContent: 'flex-end', alignItems: 'flex-end' } }); RestaurantDisplay.propTypes = { restaurantData: PropTypes.object.isRequired, onItemPressed: PropTypes.func } export default RestaurantDisplay;
import moment from 'moment' const now = moment() export const addIdToObj = ( thecontacts ) => { for( let id in thecontacts ) { thecontacts[ id ].id = id } return thecontacts } export const makeObjAndArray = ( thecontacts ) => { // Fb results are objects like: { 'id': { name: 'Potato' } // Make the results array const contactarray = [] for ( let id in thecontacts ) { contactarray.push( { ...thecontacts[id], id: id } ) } // Return both the array and object for for easy access return { array: contactarray, object: thecontacts } } export const makeArrayMeetingsArray = contacts => { if ( !contacts ) return contacts contacts.array = contacts.array.map( contact => { contact.meetings = makeObjAndArray( contact.meetings ) return contact } ) return contacts } export const makeObjectMeetingsArray = contacts => { for ( let id in contacts.object ) { // Copy the meetings to new variable const oldmeetings = { ...contacts.object[id].meetings } // Empty the meetings key contacts.object[id].meetings = {} if ( !oldmeetings ) contacts.object[id].meetings = { array: [], object: {} } contacts.object[id].meetings = makeObjAndArray( oldmeetings ) } return contacts } export const addLastMeeting = contacts => { contacts.array = contacts.array.map( contact => { // If no meetings are registered, assume the last touch point was 1 year ago if ( contact.meetings.array.length == 0 ) { return { ...contact, lastmeeting: 365, priority: 365 } } // Add the lastmeetingm. The ... is because .min only takes parameters but not arrays contact.lastmeeting = Math.min( ...contact.meetings.array.map( meeting => now.diff( moment( meeting.date, 'DD-MM-YYYY' ), 'days' ) ) ) // How many days have passed since you should have contacted them? contact.priority = contact.lastmeeting - contact.frequency return contact } ) return contacts }
document.writeln('<ul> <li> <a href="#SEC681">Index</a></ul>');
function reduce(arr, callback, initialValue) { if (initialValue !== undefined) { previousValue = callback(initialValue, arr[0], 0, arr); } else { previousValue = arr[0]; } for (let i = 1; i < arr.length; i++) { previousValue = callback(previousValue, arr[i], i, arr); } return previousValue; } module.exports = reduce;
const List = ({ list, check, query }) => { const completed = (check) => (list) => list.completed === check; // function completed(check){ // return function(list){ // list.completed === check; // } // } // query const byQuery = (query) => (list) => list.title.toLowerCase().includes(query.toLowerCase()); let filteredList= []; if(check){ filteredList = list.filter(completed(check)).filter(byQuery(query)); }else{ filteredList = list.filter(byQuery(query)); } return ( <> {filteredList.map((item) => ( <div> <h2>{item.title}</h2> {item.completed ? <p style={{ textDecoration: "line-through" }}>Completed</p> : <p>Completed</p>} </div> ))} </> ) } export default List;
import { useDispatch } from "react-redux"; import loginUser from "../../Actions/user_actions"; import { connect } from "react-redux"; import { Typography, TextField, Button, createTheme, ThemeProvider, Stack, } from "@mui/material"; import "./LogIn.css"; import { React, useState, useContext } from "react"; import { useHistory } from "react-router"; import { AuthContext } from "../../Context/AuthContext"; import { loginCall } from "../../apiCalls"; const theme = createTheme({ palette: { facebook: { main: "var(--darkblue)", }, google: { main: "var(--light)", }, twitter: { main: "var(--sblue)", }, ASKGAMBLERS: { main: "var(--sred)", }, button_color: { main: "var(--ored)", }, }, }); function Login({ user }) { const { isFetching, dispatch } = useContext(AuthContext); const [field, setField] = useState({}); const history = useHistory(); const handleSubmit = async (e) => { console.log(field); loginCall( { username: field.username, password: field.password, }, dispatch ); if (!isFetching) { history.push("/playQuiz"); } else { alert("error"); } }; const handleOnChange = (e) => { const name = e.target.name; setField((prev) => ({ ...prev, [name]: e.target.value, })); }; return ( <div className="signupContainer"> <div className="signupWrapper"> <div className="header__wrapper"> <div className="heading_login"> <h2 className="header__title"> <div className="quiz__icon"> <img style={{ maxWidth: "50px" }} src="https://s3.eu-west-2.amazonaws.com/quizando-dev-images/question_images/977ce665-17c6-477d-9e24-8e919db7f468.jpeg" alt="" /> </div> <span style={{ fontFamily: "Paytone One" }}> Login to Quizando </span> </h2> </div> </div> <div className="SignupInput"> <div> <Typography variant="h5"> Login to Quizando with your social media account or email address </Typography> </div> <div className="outbuttonContainer"> <div className=""> <ThemeProvider theme={theme}> <Button className="signupButton facebook" color="facebook" fullWidth variant="contained" > <i class="fa fa-facebook-f"></i> <h5 className="h5__title">Sign in with Facebook</h5> </Button> <Button className="signupButton " fullWidth color="google" variant="contained" > <i className="fa fa-google"></i>{" "} <h5 className="h5__title">Sign in with Google</h5> </Button> <Button className="signupButton facebook" fullWidth color="twitter" variant="contained" > <i className="fa fa-twitter"></i>{" "} <h5 className="h5__title">Sign in with Twitter</h5> </Button> <Button className="signupButton facebook" fullWidth color="ASKGAMBLERS" variant="contained" > <Typography variant="h5">Sign in with ASKGAMBLERS</Typography> </Button> </ThemeProvider> </div> </div> <Stack direction="column" spacing={2}> {[ { displayName: " Username", Name: "username", }, { displayName: "Password", Name: "password", }, ].map((item, val) => { return ( <TextField id="outlined-basic" label={item.displayName} fullWidth name={item.Name} onChange={handleOnChange} variant="outlined" key={val} /> ); })} </Stack> <p style={{ margin: "1em 0 0 0", fontSize: "1.6em" }}> New to Quizando? Click here to{" "} <span style={{ color: "var(--cyan)" }}> <a className="anchor" href="/signup"> Sign up. </a> </span> </p> <ThemeProvider theme={theme}> <Button className="signin__button" fullWidth variant="contained" color="button_color" onClick={handleSubmit} > Login </Button> </ThemeProvider> <Typography> By signing in, you agree to Quizando's <span>Privacy Policy</span> &{" "} <span>Terms & Conditions.</span> </Typography> </div> </div> </div> ); } export default Login;
import React, { useEffect } from 'react' import { List } from 'semantic-ui-react' export default function Listattrsbook({ product }) { return ( <List size='big' divided verticalAlign='middle'> <List.Item style={{marginBottom:"5px"}}> {product.paPublishers ? ( product.paPublishers.nodes.map(item => ( <List.Content floated='right'>{item.name}</List.Content> )) ) : ('')} <List.Content>{`نشر`}</List.Content> </List.Item> <List.Item style={{marginBottom:"5px"}}> {product.paWriters ? ( product.paWriters.nodes.map(item => ( <List.Content floated='right'>{item.name}</List.Content> )) ) : ('')} <List.Content>{`نویسنده`}</List.Content> </List.Item> <List.Item style={{marginBottom:"5px"}}> {product.paTranslators ? ( product.paTranslators.nodes.map(item => ( <List.Content floated='right'>{item.name}</List.Content> )) ) : ('')} <List.Content>{`مترجم`}</List.Content> </List.Item> <List.Item style={{marginBottom:"5px"}}> {product.paBookCodes ? ( product.paBookCodes.nodes.map(item => ( <List.Content floated='right'>{item.name}</List.Content> )) ) : ('')} <List.Content>{`کد کتاب`}</List.Content> </List.Item> <List.Item style={{marginBottom:"5px"}}> {product.paBookPrintSeries ? ( product.paBookPrintSeries.nodes.map(item => ( <List.Content floated='right'>{item.name}</List.Content> )) ) : ('')} <List.Content>{`سری چاپ`}</List.Content> </List.Item> <List.Item style={{marginBottom:"5px"}}> {product.paBookSizes ? ( product.paBookSizes.nodes.map(item => ( <List.Content floated='right'>{item.name}</List.Content> )) ) : ('')} <List.Content>{`اندازه کتاب`}</List.Content> </List.Item> <List.Item style={{marginBottom:"5px"}}> {product.paCoverTypes ? ( product.paCoverTypes.nodes.map(item => ( <List.Content floated='right'>{item.name}</List.Content> )) ) : ('')} <List.Content>{`نوع جلد`}</List.Content> </List.Item> <List.Item style={{marginBottom:"5px"}}> {product.paIsbns ? ( product.paIsbns.nodes.map(item => ( <List.Content floated='right'>{item.name}</List.Content> )) ) : ('')} <List.Content>{`شابک`}</List.Content> </List.Item> <List.Item style={{marginBottom:"5px"}}> {product.paNumberPages ? ( product.paNumberPages.nodes.map(item => ( <List.Content floated='right'>{item.name}</List.Content> )) ) : ('')} <List.Content>{`تعداد صفحه`}</List.Content> </List.Item> <List.Item style={{marginBottom:"5px"}}> {product.paAdPublishDates ? ( product.paAdPublishDates.nodes.map(item => ( <List.Content floated='right'>{item.name}</List.Content> )) ) : ('')} <List.Content>{`تاریخ انتشار به میلادی`}</List.Content> </List.Item> <List.Item> {product.paSolarPublishDates ? ( product.paSolarPublishDates.nodes.map(item => ( <List.Content floated='right'>{item.name}</List.Content> )) ) : ('')} <List.Content>{`تاریخ انتشار به شمسی`}</List.Content> </List.Item> </List> ) }
/* * Defines observable model for location which has coordinates, description etc. Also stores google location, marker and infoWindow */ var Location = function(googleLoc, marker, infoWindow) { var location = this; this.mapData = googleLoc; this.marker = marker; this.infoWindow = infoWindow; this.title = ko.observable(googleLoc.name); this.address = ko.observable(googleLoc.formatted_address); this.photo = ko.observable(); /* * This data is initially empty but will be populated when it is loaded from * yelp on first click */ this.yelpData = ko.observable('Loading additional data...'); this.yelpImage = ko.observable(); if (googleLoc.photos) { this.photo(googleLoc.photos[0].getUrl({ maxWidth : 100, maxHeight : 100 })); } this.visible = ko.pureComputed({ read : function() { return marker.isVisible(); }, write : function(visible) { marker.setVisible(visible); infoWindow.close(); } }); };
/** *@author: RXK *@date:2018/11/3 9:47 *@version: V1.0.0 *@Des: 列表首页的按钮组件 **/ import React from 'react' import {Button} from 'antd' class ButtonList extends React.Component{ onChange = (item) =>{ console.log("传送的item是:", item); this.props.action(item); }; render(){ return( <div style={{background: 'rgb(190, 200, 200)', padding: '26px 16px 16px',textAlign:'justify'}}> {this.props.data.map((item) => <Button type="primary" ghost className="button-list" onClick={() => this.onChange(item)}> <p>{item.title}</p><p>{item.value}</p> </Button> )} </div> ); } } export default ButtonList
import { configureStore } from "@reduxjs/toolkit"; import emailsReducer from "../features/emails/emailsSlice"; import authReducer from "../features/auth/AuthSlice"; import appReducer from "./appSlice"; const store = configureStore({ reducer: { auth: authReducer, emails: emailsReducer, app: appReducer } }); export default store;
function Car( name ){ this.x = 0; this.y = 0; this.steeringAngle = 0; this.maxSterringAngle = 0.3; this.heading = 0; this.speed = 5; this.length = 15; this.width = 10; this.tireWidth = 2.5; this.tireLength = 5; this.name = name; this.active = false; this.autoReset = false; //track this.corners = []; this.corner; this.section = 0; this.cornerIndex = 0; this.change = 0.5; this.changeOffset = 50; //target this.minDistToTarget = 50; this.target = createVector(this.x+this.minDistToTarget*2,this.y); this.targetTimer = 0; //DATA this.data = { frames: 100000, times: [], steeringSum: 0, steeringSums: [], } this.firstlap = true; this.last = 0; this.end = function(){ if( !this.firstlap ){ this.last = this.data.times[0]; } }; this.endLap = function(){ var time = this.data.frames; var dist = sqrt( pow(this.x-this.target.x,2) + pow(this.y-this.target.y,2) ); var subframe = 1-(this.minDistToTarget - dist)/this.speed; var time = this.data.frames + subframe; this.data.times.unshift( time ); this.data.steeringSums.unshift( this.data.steeringSum ); this.end(); if( this.firstlap ) this.firstlap = false; this.data.frames = 0; } this.nextTarget = function(){ this.targetTimer = 0; this.section++; if( this.section >= this.corner.points.length ){ this.section = 0; this.track.evolve(); this.cornerIndex++; if( this.cornerIndex >= this.track.corners.length ){ this.cornerIndex = 0; this.endLap(); } this.corner = this.track.corners[ this.cornerIndex ]; } var point = this.corner.points[ this.section ]; this.target.x = point.x; this.target.y = point.y; } this.reset = function(){ this.section = 0; this.cornerIndex = 0; this.corner = this.track.corners[ 0 ]; this.x = this.corner.points[0].x; this.y = this.corner.points[0].y; this.nextTarget(); this.heading = atan2( this.target.y-this.y, this.target.x-this.x ); this.data.frames = 0; this.data.steeringSum = 0; this.active = true; } this.addTrack = function( track ){ this.track = new AITrack( track ); this.reset(); return this.track; } this.update = function(){ if( this.active ){ this.data.frames++; this.targetTimer++; if( this.targetTimer > 100 ){ this.active = false; this.end(); } var targetAngle = atan2( this.target.y-this.y, this.target.x-this.x ); var dif = angleDifference( this.heading, targetAngle ); this.steeringAngle = -constrain( dif, -this.maxSterringAngle, this.maxSterringAngle ); var sv = createVector( this.length-this.speed, 0 ); sv.x += cos(this.steeringAngle)*this.speed; sv.y += sin(this.steeringAngle)*this.speed; this.heading += sv.heading(); sv.normalize(); sv.rotate( this.heading ); this.x += sv.x*this.speed; this.y += sv.y*this.speed; this.data.steeringSum += pow(this.steeringAngle,2); do{ var dist = sqrt( pow(this.x-this.target.x,2) + pow(this.y-this.target.y,2) ) if( dist <= this.minDistToTarget ){ this.nextTarget(); } }while( dist <= this.minDistToTarget && this.active==true ); } } this.drawTrack = false; this.offset = 0; this.marked = false; this.draw = function(){ //if( this.drawTrack ) this.track.draw(); //draw time fill(255);noStroke(); textSize(20); text( this.name, 200,200+this.offset ); var time = (this.last/60).toFixed(3)+"s"; text( time, 240,200+this.offset ); stroke(255);strokeWeight(1);fill(255,50); if( this.drawTrack ){ fill(0,255,0,50); stroke(0,255,0 ); } var x = this.x; var y = this.y; var l = this.length; var w = this.width; var s = sin( this.heading ); var c = cos( this.heading ); if( this.drawTrack) //ellipse( this.target.x, this.target.y, 20, 20 ); if( this.drawTrack ){ fill(0,255,0); stroke(100,255,100 ); } //Body arc( x+c*l/2, y+s*l/2, w/4, w/4, this.heading+PI/2, this.heading-PI/2 ); beginShape( ); vertex( x-c*l/2+s*w/2, y-s*l/2-c*w/2 ); vertex( x-c*l/2-s*w/2, y-s*l/2+c*w/2 ); vertex( x+c*l/2-s*w/2, y+s*l/2+c*w/2 ); vertex( x+c*l/2+s*w/2, y+s*l/2-c*w/2 ); endShape( CLOSE ); //tires var tw = this.tireWidth; var tl = this.tireLength; var tx = x-c*(l/2)+s*(w/2); var ty = y-s*(l/2)-c*(w/2); beginShape( ); vertex( tx-c*tl/2+s*tw/2, ty-s*tl/2-c*tw/2 ); vertex( tx-c*tl/2-s*tw/2, ty-s*tl/2+c*tw/2 ); vertex( tx+c*tl/2-s*tw/2, ty+s*tl/2+c*tw/2 ); vertex( tx+c*tl/2+s*tw/2, ty+s*tl/2-c*tw/2 ); endShape( CLOSE ); tx = x-c*(l/2)-s*(w/2); ty = y-s*(l/2)+c*(w/2); beginShape( ); vertex( tx-c*tl/2+s*tw/2, ty-s*tl/2-c*tw/2 ); vertex( tx-c*tl/2-s*tw/2, ty-s*tl/2+c*tw/2 ); vertex( tx+c*tl/2-s*tw/2, ty+s*tl/2+c*tw/2 ); vertex( tx+c*tl/2+s*tw/2, ty+s*tl/2-c*tw/2 ); endShape( CLOSE ); var ts = sin( this.heading+this.steeringAngle ); var tc = cos( this.heading+this.steeringAngle ); tx = x+c*(l/2)+s*(w/2); ty = y+s*(l/2)-c*(w/2); beginShape( ); vertex( tx-tc*tl/2+ts*tw/2, ty-ts*tl/2-tc*tw/2 ); vertex( tx-tc*tl/2-ts*tw/2, ty-ts*tl/2+tc*tw/2 ); vertex( tx+tc*tl/2-ts*tw/2, ty+ts*tl/2+tc*tw/2 ); vertex( tx+tc*tl/2+ts*tw/2, ty+ts*tl/2-tc*tw/2 ); endShape( CLOSE ); tx = x+c*(l/2)-s*(w/2); ty = y+s*(l/2)+c*(w/2); beginShape( ); vertex( tx-tc*tl/2+ts*tw/2, ty-ts*tl/2-tc*tw/2 ); vertex( tx-tc*tl/2-ts*tw/2, ty-ts*tl/2+tc*tw/2 ); vertex( tx+tc*tl/2-ts*tw/2, ty+ts*tl/2+tc*tw/2 ); vertex( tx+tc*tl/2+ts*tw/2, ty+ts*tl/2-tc*tw/2 ); endShape( CLOSE ); } }
(function () { 'use strict' window.GOVUK = window.GOVUK || {} var organisationsForm = { init: function init (params) { $().ready(function ($) { organisationsForm.hideClosedAtFields() organisationsForm.hideSupersededByField() organisationsForm.toggleCustomLogoField() }) }, hideClosedAtFields: function hideClosedAtFields () { var $closedFields = $('.js-closed-organisation-field') var $govUkStatusField = $('#organisation_govuk_status') $govUkStatusField.change(enableClosedOrgFieldsIfClosed) enableClosedOrgFieldsIfClosed() function enableClosedOrgFieldsIfClosed () { if ($govUkStatusField.val() === 'closed') { enableClosedOrgFields() organisationsForm.hideSupersededByField() } else { disableClosedOrgFields() } } function enableClosedOrgFields () { $closedFields.show() $('input, select', $closedFields).removeAttr('disabled') } function disableClosedOrgFields () { $closedFields.hide() $('input, select', $closedFields).attr('disabled', true) } }, hideSupersededByField: function hideSupersededByField () { var $supersededField = $('.js-superseded-organisation-field') var $govUkClosedStatusField = $('#organisation_govuk_closed_status') $govUkClosedStatusField.change(enableSupersededOrgFieldIfClosed) enableSupersededOrgFieldIfClosed() function enableSupersededOrgFieldIfClosed () { var supersededOrgFields = ['replaced', 'split', 'merged', 'changed_name', 'devolved'] if (supersededOrgFields.indexOf($govUkClosedStatusField.val()) > -1) { enableSupersededOrgField() } else { disabledSupersededOrgField() } } function enableSupersededOrgField () { $supersededField.show() $('input, select', $supersededField).removeAttr('disabled') } function disabledSupersededOrgField () { $supersededField.hide() $('input, select', $supersededField).val('') $('.search-choice', $supersededField).remove() $('input, select', $supersededField).attr('disabled', true) } }, toggleCustomLogoField: function toggleCustomLogoField () { var $logoSelector = $('#organisation_organisation_logo_type_id') var valueForCustomLogo = '14' $logoSelector.chosen().change(function (event) { if ($(this).val() === valueForCustomLogo) { $('.organisation-custom-logo').slideDown() } else { $('.organisation-custom-logo').slideUp() } }) } } window.GOVUK.organisationsForm = organisationsForm }())
$.testsEnabled=false;
import { useEffect, useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { useHistory, useParams } from 'react-router-dom' import { fetchOneListing } from '../../store/listings'; import { fetchCreateBooking } from '../../store/bookings'; import { findDuration } from '../../date-repository'; import './ListingPage.css'; const ListingPage = ({ theListing }) => { const dispatch = useDispatch(); const history = useHistory(); const {id} = useParams(); const listingId = id; const sessionUser = useSelector(state => state.session.user); const currentListing = useSelector(state => state.listings); const [startDate, setStartDate] = useState(''); const [endDate, setEndDate] = useState(''); const [errors, setErrors] = useState([]); const handleClick = async() => { const newErrors = []; if (!startDate || !endDate){ newErrors.push( 'Please select a start date and an end date to check availability.'); } if (startDate > endDate){ newErrors.push( 'Please choose an end date after your chosen start date.'); } if (!sessionUser){ newErrors.push('Please login or sign up to check availability.'); } if (newErrors.length === 0){ const duration = findDuration(startDate, endDate) ; const newBooking = await dispatch(fetchCreateBooking({ listingId: listingId, userId: sessionUser.id, startDay: startDate, endDay: endDate, status: "pending", duration: duration })); if (newBooking){ const bookingId = newBooking.id; history.push(`/listings/${listingId}/bookings/${bookingId}`); return null }else{ console.log("booked") newErrors.push('This ride is booked for one or more of those days. Please try another date or another ride.') } } setErrors(newErrors) } useEffect( () => { dispatch(fetchOneListing(id)); }, [dispatch,id]); return( <> <div className="listing-page-header" id="listing-page-header"> <h2> {currentListing.title} </h2> <p> {currentListing.nearestCity} </p> </div> <div className="listing-page-gallery"> <div id="listing-page-primary"> <img id="listing-page-primary_1" alt="bike" src={currentListing.Pictures && currentListing.Pictures[0].url}/> </div> <div className="listing-page-gallery-images"> {currentListing.Pictures && currentListing.Pictures.map((pic, i) => { if (i>0) { return( <div className="listing-page-tile" id={`listing-page-gallery_${i}`} key={`listing-page-gallery_${i}`} > <img className="listing-page-img" alt="bike" src={pic.url} /> </div> ) } else return null; })} </div> </div> <div className="listing-page-properties"> <div className="listing-page-properties_2"> <div className="listing-page-properties_2_1"> {`$${currentListing.pricePerDay/100} / day`} </div> {errors.map((error, idx) => <li key={`listing-page-error_${idx}`}>{error}</li>)} <div className="listing-page-properties_2_2"> <div className="listing-page-dates"> <div className="listing-page-dates_start"> <label>Start Date</label> <input type="date" value={startDate} onChange={(e) => setStartDate(e.target.value)} /> </div> <div className="listing-page-dates_end"> <label>End Date</label> <input type="date" min={startDate} value={endDate} onChange={(e) => setEndDate(e.target.value)} /> </div> </div> </div> <button className="button" id="reserve-button" onClick={handleClick} > Check Availability </button> </div> <div className="listing-page-properties_1"> <div className="listing-page-properties_1_1"> <h3> {currentListing.BikeType && `${currentListing.BikeType.type} bike offered by ${currentListing.User.username}`} </h3> </div> <hr /> <div className="listing-page-properties_1_2"> {currentListing.description} </div> <div className="listing-page-properties_1_3"> Size: {currentListing.BikeSize && currentListing.BikeSize.name} </div> </div> </div> </> ) } export default ListingPage;