text
stringlengths
7
3.69M
import React, { useState } from 'react'; import { connect } from 'react-redux'; import './Login.scss'; import Button from '../Button/Button'; import InputField from '../InputField/InputField'; import { loginUser } from '../../store/actions/auth'; const Login = ({ history, loginUser, isAuth }) => { const [data, setData] = useState({ username: '', password: '' }); const {username, password} = data; const dataHandler = e => { setData({ ...data, [e.target.name]: e.target.value }); }; const submitHandler = async e => { e.preventDefault(); const body = { username, password }; try { if (!isAuth) { const result = await loginUser(body); if(!result){ alert('Invalid Credentials') }else { alert('User was logging in'); history.push('/'); } } else { alert('User already loaded'); } } catch (err) { console.error('Unable to authorize'); } } return ( <form className='form__container' onSubmit={submitHandler}> <InputField name='username' type='text' onChange={dataHandler} /> <InputField name='password' type='password' onChange={dataHandler} /> <Button type='submit' text='Login' /> </form> ); }; const mapStateToProps = state => { return { isAuth: state.auth.isAuthenticated }; }; export default connect(mapStateToProps, { loginUser })(Login);
/* * @lc app=leetcode id=121 lang=javascript * * [121] Best Time to Buy and Sell Stock */ // @lc code=start /** * @param {number[]} prices * @return {number} */ var maxProfit = function(prices) { if (!prices.length) return 0; const dp = new Array(prices.length).fill(0); let min = prices[0]; for (let i = 1; i < prices.length; i++) { if (prices[i] < min) { min = prices[i]; dp[i] = dp[i - 1]; } else dp[i] = Math.max(dp[i - 1], prices[i] - min); } return dp[dp.length - 1]; }; // @lc code=end
import Types from "sequelize"; import props from "../settings/props.js"; const { DataTypes } = Types; const Todos = props.sequelize.define( "todo_list", { todo_id: { type: DataTypes.INTEGER, primaryKey: true }, todo_title: DataTypes.STRING, todo_body: DataTypes.STRING, }, { freezeTableName: true, } ); export default Todos;
import React, { Component } from "react"; import { connect } from "react-redux"; import { createDogList } from "../../actions/dogActions"; import PropTypes from "prop-types"; import TextInput from "../common/TextInput"; import SelectOnce from "../common/SelectOnce"; import M from "materialize-css/dist/js/materialize.min.js"; export class NewDog extends Component { state = { name: "", sex: "", dateofbirth: "", primarycolor: "", secondarycolor: "", breed: "", errors: {} }; componentDidMount() { var elem = document.querySelectorAll("select"); M.FormSelect.init(elem, { classes: "", dropdownOptions: {} }); } componentWillReceiveProps(nextProps) { if (nextProps.errors) { this.setState({ errors: nextProps.errors }); } } onChange = e => { this.setState({ [e.target.name]: e.target.value }); }; onSubmit = e => { e.preventDefault(); const newDog = { name: this.state.name, sex: this.state.sex, dateofbirth: this.state.dateofbirth, primarycolor: this.state.primarycolor, secondarycolor: this.state.secondarycolor, breed: this.state.breed }; this.props.createDogList(newDog, this.props.history); }; render() { const sexOption = [ { label: "ระบุเพศของสุนัข", value: 0 }, { label: "เพศผู้", value: "เพศผู้" }, { label: "เพศเมีย", value: "เพศเมีย" } ]; const colorOption = [ { label: "ระบุสีขนของสุนัข", value: 0 }, { label: "สีขาว", value: "สีขาว" }, { label: "สีดำ", value: "สีดำ" }, { label: "สีเทา", value: "สีเทา" }, { label: "สีน้ำตาลแดง", value: "สีน้ำตาลแดง" }, { label: "สีน้ำตาล", value: "สีน้ำตาล" }, { label: "สีน้ำตาลอ่อน", value: "สีน้ำตาลอ่อน" } ]; const breedOption = [ { label: "ระบุสายพันธุ์ของสุนัข", value: 0 }, { label: "Labrador Retriever", value: "Labrador Retriever" }, { label: "German Shepherd", value: "German Shepherd" }, { label: "Golden Retriever", value: "Golden Retriever" }, { label: "Bulldog", value: "Bulldog" }, { label: "Beagle", value: "Beagle" }, { label: "French Bulldog", value: "French Bulldog" }, { label: "Yorkshire Terrier", value: "Yorkshire Terrier" }, { label: "Poodle", value: "Poodle" }, { label: "Rottweiler", value: "Rottweiler" }, { label: "Boxer", value: "Boxer" }, { label: "German Shorthaired Pointer", value: "German Shorthaired Pointer" }, { label: "Siberian Husky", value: "Siberian Husky" }, { label: "Dachshund", value: "Dachshund" }, { label: "Doberman Pinscher", value: "Doberman Pinscher" }, { label: "Great Dane", value: "Great Dane" }, { label: "Miniature Schnauzer", value: "Miniature Schnauzer" }, { label: "Australian Shepherd", value: "Australian Shepherd" }, { label: "Cavalier King Charles Spaniel", value: "Cavalier King Charles Spaniel" }, { label: "Shih Tzu", value: "Shih Tzu" }, { label: "Pembroke Welsh Corgi", value: "Pembroke Welsh Corgi" }, { label: "Pomeranian", value: "Pomeranian" }, { label: "Boston Terrier", value: "Boston Terrier" }, { label: "Shetland Sheepdog", value: "Shetland Sheepdog" }, { label: "Havanese", value: "Havanese" }, { label: "Mastiff", value: "Mastiff" }, { label: "Brittany", value: "Brittany" }, { label: "English Springer Spaniel", value: "English Springer Spaniel" }, { label: "Chihuahua", value: "Chihuahua" }, { label: "Bernese Mountain Dog", value: "Bernese Mountain Dog" }, { label: "Cocker Spaniel", value: "Cocker Spaniel" }, { label: "Maltese", value: "Maltese" }, { label: "Vizsla", value: "Vizsla" }, { label: "Pug", value: "Pug" }, { label: "Weimaraner", value: "Weimaraner" }, { label: "Cane Corso", value: "Cane Corso" }, { label: "Collie", value: "Collie" }, { label: "Newfoundland", value: "Newfoundland" }, { label: "Border Collie", value: "Border Collie" }, { label: "Basset Hound", value: "Basset Hound" }, { label: "Rhodesian Ridgebacks", value: "Rhodesian Ridgebacks" }, { label: "West Highland White Terrier", value: "West Highland White Terrier" }, { label: "Chesapeake Bay Retrievers", value: "Chesapeake Bay Retrievers" }, { label: "Bullmastiff", value: "Bullmastiff" }, { label: "Bichon Frise", value: "Bichon Frise" }, { label: "Shiba Inu", value: "Shiba Inu" }, { label: "Akita", value: "Akita" }, { label: "Soft Coated Wheaten Terrier", value: "Soft Coated Wheaten Terrier" }, { label: "Papillon", value: "Papillon" }, { label: "Bloodhound", value: "Bloodhound" }, { label: "St. Bernard", value: "St. Bernard" }, { label: "Thai Bangkaew", value: "Thai Bangkaew" }, { label: "Thai Ridgeback", value: "Thai Ridgeback" } ]; const { errors } = this.state; return ( <div className="container-register container"> <div className="row"> <div className="col s12 center"> <h1>สร้างรายชื่อสุนัขของคุณ</h1> </div> <form className="col s12" onSubmit={this.onSubmit} noValidate> <TextInput type="text" id="name" name="name" value={this.state.name} onChange={this.onChange} label="ชื่อสุนัข" error={errors.name} /> <SelectOnce id="sex" name="sex" value={this.state.sex} onChange={this.onChange} label="เพศ" error={errors.sex} options={sexOption} /> <TextInput type="date" id="dateofbirth" name="dateofbirth" value={this.state.dateofbirth} onChange={this.onChange} label="วัน/เดือน/ปี เกิดสุนัข" error={errors.dateofbirth} /> <SelectOnce id="primarycolor" name="primarycolor" value={this.state.primarycolor} onChange={this.onChange} label="สีหลักของสุนัข" error={errors.primarycolor} options={colorOption} /> <SelectOnce id="secondarycolor" name="secondarycolor" value={this.state.secondarycolor} onChange={this.onChange} label="สีรองของสุนัข" error={errors.secondarycolor} options={colorOption} /> <SelectOnce id="breed" name="breed" value={this.state.breed} onChange={this.onChange} label="สายพันธุ์" error={errors.breed} options={breedOption} /> <div className="col s12 center"> <button type="submit" className="waves-effect waves-light btn-large pink"> สร้างรายชื่อสุนัข </button> </div> </form> </div> </div> ); } } NewDog.propTypes = { createDogList: PropTypes.func.isRequired, errors: PropTypes.object }; const stateToProps = state => ({ errors: state.errors }); export default connect( stateToProps, { createDogList } )(NewDog);
function printShirt() { // Change the colour of the t-shirt var colList = document.getElementById("js-colour-list"); document.getElementById("js-tShirt").style.backgroundColor = colList.options[colList.selectedIndex].value; // if nothing has been selected then change the picture if (document.getElementById("pictureList").value !== 'null') { document.getElementById("pic").src = document.getElementById("pictureList").value; document.getElementById("pic").style.visibility = 'visible'; } else { document.getElementById("pic").style.visibility = "hidden"; } // Apply font text and colour var shirtText = document.getElementById("js-shirt-text"); shirtText.innerHTML = document.getElementById("shirtTextBox").value; shirtText.style.color = document.getElementById("fontColourList").value; shirtText.style.font = document.getElementById("fontSizeList").value + "px " + document.getElementById("fontList").value; } function validateAddress() { // If the boxes are not empty if (document.getElementById("nameBox").value === "" || document.getElementById("l1Box").value === "" || document.getElementById("l2Box").value === "" || document.getElementById("postCode").value === "" || document.getElementById("county").value === "") { return false; } else { return true; } } function validateQuan(value) { if (value === "") { return "0"; } else { return value; } } function validateOrder() { // Make sure the order has all the correct information entered if (document.getElementById("smallQuan").value === "0" && document.getElementById("mediumQuan").value === "0" && document.getElementById("largeQuan").value === "0" && document.getElementById("vlargeQuan").value === "0") { window.alert("Please enter a Quantity."); return false; } else { if (validateAddress() === true) { return true; } else { window.alert("Please enter a valid address."); return false; } } }
/** * Created by Joey on 2015/12/14. */ var preStat = ""; var preList = []; var NOTIFY = Notify(); var interval_id; var intF = function (start) { if (interval_id) window.clearInterval(interval_id); if (!start) { return; } interval_id = window.setInterval(function () { refresh(); }, 5000) }; var refresh = function () { var listChange = false; ARIA2.getGlobalStat(function (re) { var curStat = "" + re.numActive + "," + re.numWaiting + "," + re.numStopped; if (curStat !== preStat) { listChange = true; preStat = curStat; localStorage.preStat = preStat; } if (listChange) ARIA2.refresh(function (list) { var stateC = []; $.each(list, function (ni, nn) { var found = false; $.each(preList, function (pi, pn) { if (pn.gid == nn.gid) { found = true; if (pn.status != nn.status) if (nn.status.match(/(complete|error)/)) stateC.push(nn); } }); if (!found) { stateC.push(nn); } }); preList = []; $.extend(preList, list); localStorage.preList = JSON.stringify(preList); if (stateC.length) { var tore = []; $.each(stateC, function (i, task) { var smsg = { title: task.title, message: task.status.match(/(complete|error)/) ? task.status : "Added" }; tore.push(smsg); if (!globalSettings.inShortMsg) { NOTIFY.basic(smsg.title, smsg.message); } }); if (globalSettings.inShortMsg) NOTIFY.list("Download Task", "A", tore); } }); }); }; chrome.extension.onConnect.addListener(function (port) { port.onMessage.addListener(function (msg) { mag = JSON.parse(msg); intF(msg.notification); console.log(msg); }); }); intF(globalSettings.notification); if (chrome.downloads.setShelfEnabled) chrome.downloads.setShelfEnabled(false);
function checkCashRegister(price, cash, cid) { var currencyCent = { 'ONE HUNDRED': 10000, 'TWENTY': 2000, 'TEN': 1000, 'FIVE': 500, 'ONE': 100, 'QUARTER': 25, 'DIME': 10, 'NICKEL': 5, 'PENNY': 1 }; var currencyKeys = Object.keys(currencyCent); var changeDueCent = (cash - price) * 100; var changeStructured = []; if (changeDueCent === cidTotalCent(cid)) { return 'Closed'; } for (var i = 0; i < currencyKeys.length; i += 1) { var key = currencyKeys[i]; var amountCent = changeDueCent - (changeDueCent % currencyCent[key]); var chargedFromCidCent = chargeCID(key, amountCent, cid); if (chargedFromCidCent === false) { return 'Insufficient Funds'; } if (changeDueCent >= currencyCent[key]) { changeStructured.push([key, chargedFromCidCent / 100]); changeDueCent -= chargedFromCidCent; } } return changeStructured; } function chargeCID(currency, dueCent, cid) { for (var i = 0; i < cid.length; i += 1) { if (cid[i][0] === currency) { if (cid[i][1] >= dueCent / 100) { return dueCent; } else if (currency === 'PENNY') { return false; } return cid[i][1] * 100; } } return false; } function cidTotalCent(cid) { var total = 0; for (var i = 0; i < cid.length; i += 1) { total += cid[i][1] * 100; } return total; } module.exports = checkCashRegister;
angular.module('nemesisApp').controller('userController', function ($scope, $mdSidenav, $rootScope, $location, $http, $mdDialog) { $scope.user = {} $scope.refresh = () => { $http.get('/api/usuario') .then(res => { $scope.users = res.data }, err => { console.log(err) }) } $scope.refresh() $scope.remove = (user) => { // Appending dialog to document.body to cover sidenav in docs app var confirm = $mdDialog.confirm() .title('Remover usuário ?') .textContent(user.email) .ariaLabel('Lucky day') .ok('Sim') .cancel('Não'); $mdDialog.show(confirm).then(() => { $http.delete('api/usuario/' + user.id) .then((response) => { const errors = response.data.errors if (errors) { $mdDialog.show( $mdDialog.alert() .clickOutsideToClose(true) .title(errors[0]) .ariaLabel('Alert Dialog Demo') .ok('OK') ) } else $scope.refresh() }) }) } $scope.openModal = (user) => { let callback = $scope.refresh $mdDialog.show({ clickOutsideToClose: false, templateUrl: 'App/templates/editUser.html', controller: function ($scope, $mdDialog, $http) { $scope.close = () => { $mdDialog.hide() } $scope.user = user ? angular.copy(user) : {} if ($scope.user.tipo) $scope.user.tipo = $scope.user.tipo.toLowerCase() $scope.validate = () => { $scope.errors = [] if ($scope.user.password && $scope.user.password != $scope.user.confirm) $scope.errors.push('A senhas não coincidem') return $scope.errors.length == 0 } $scope.save = () => { if (!$scope.validate()) return if ($scope.user.id > 0) { $http.put('api/usuario/', $scope.user) .then((response) => { $scope.errors = response.data.errors if (!$scope.errors) { callback() $mdDialog.hide() } }); } else { $http.post('api/usuario/', $scope.user) .then((response) => { $scope.errors = response.data.errors if (!$scope.errors) { callback() $mdDialog.hide() } }); } } } }) } })
import React from 'react'; import axios from 'axios'; import { Link } from 'react-router-dom' const DisplayQuizs = ({quizs}) => { return ( <ul> {quizs.map((quiz, i) => { return ( <li key={i}> {quiz.name}, {quiz.type} <span><Link to={`/${quiz.id}`}>view</Link></span> </li> ) })} </ul> ) } class Quizs extends React.Component { constructor(props){ super(props); this.state = { quizs: [] }; } componentDidMount(){ axios.get('https://quiz-321.herokuapp.com/quiz') .then(res => {this.setState({quizs: res.data}) }) .catch(error => { console.log(error) }) } render() { const { quizs } = this.state return ( <div> <DisplayQuizs quizs={quizs}/> </div> ) } } export default Quizs;
/*zoomGraph.js : class defining zoom behavior on the graph zoom in and zoom out on x and y axis by scrolling mouse wheel peak intensity is also adjusted by ctrl + mouse wheel */ class GraphZoom { scrollTimer;//detect if scroll has ended or not constructor(){} adjustPeakHeight = (scaleFactor) => { let peaks = Graph.scene.getObjectByName("plotGroup"); let dataGroup = Graph.scene.getObjectByName("dataGroup"); let oriScale = dataGroup.scale.y; dataGroup.scale.set(dataGroup.scale.x, oriScale * scaleFactor, dataGroup.scale.z); if (scaleFactor > 1){ GraphControl.adjustIntensity(peaks.children, oriScale * scaleFactor); } GraphRender.renderImmediate(); } onZoom = (e) => { e.preventDefault();//disable scroll of browser window.clearTimeout( this.scrollTimer ); this.scrollTimer = setTimeout(() => { let axis = GraphUtil.findObjectHover(e, Graph.axisGroup);//axis is null if cursor is not on axis if (axis == null){ //check if cursor is inside the graph plane if (GraphUtil.findObjectHover(e, Graph.gridGroup)) { if (e.ctrlKey){//if control key is pressed --> intensity zoom let scaleFactor = 0; if (e.deltaY > 0) { scaleFactor = 0.75; this.adjustPeakHeight(scaleFactor); } else if (e.deltaY < 0){ scaleFactor = 1.5; this.adjustPeakHeight(scaleFactor); } } else{ this.onZoomFromEventListener(e, "both"); } } } else{ if (axis.name == "xAxis"){ this.onZoomFromEventListener(e, "mz"); } else if(axis.name == "yAxis"){ this.onZoomFromEventListener(e, "rt"); } } }, 5); } onZoomFromEventListener = (e, axisName) => { //zoom action detected by event listener in each axis let scaleFactor = 0; let mousePos = GraphUtil.getMousePosition(e); let newmzrange = Graph.viewRange.mzrange; let newrtrange = Graph.viewRange.rtrange; let curmz = mousePos.x * Graph.viewRange.mzrange + Graph.viewRange.mzmin;//current mz and rt that has a cursor pointed to let currt = mousePos.z * Graph.viewRange.rtrange + Graph.viewRange.rtmin; //reset view range based on scroll up or down if (e.deltaY < 0) { scaleFactor = 0.8; } else{ scaleFactor = 1.2; } //figure out where the cursor is (near x axis, y axis) if (axisName == "rt"){ newrtrange = Graph.viewRange.rtrange * scaleFactor; } else if (axisName == "mz"){//mz range adjust newmzrange = Graph.viewRange.mzrange * scaleFactor; } else if (axisName == "both"){//if adjusting both newrtrange = Graph.viewRange.rtrange * scaleFactor; newmzrange = Graph.viewRange.mzrange * scaleFactor; } else{ return; } let mzscale = (curmz - Graph.viewRange.mzmin)/(Graph.viewRange.mzmax - Graph.viewRange.mzmin);//find relative pos of current mz currrent rt let rtscale = (currt - Graph.viewRange.rtmin)/(Graph.viewRange.rtmax - Graph.viewRange.rtmin); let newmzmin = curmz - (mzscale * newmzrange);//the closer curmz or currt is to the minmz and minrt, the less change in min value let newrtmin = currt - (rtscale * newrtrange); let newRange = GraphControl.constrainBoundsZoom(newmzmin, newmzrange, newrtmin, newrtrange); GraphData.updateGraph(newRange.mzmin, newRange.mzmax, newRange.rtmin, newRange.rtmax, Graph.curRT); } main(){ Graph.renderer.domElement.addEventListener('wheel', this.onZoom, false); } }
var wrapper; wrapper = document.getElementById('main-slider'); wrapper.children[0].style.height = window.innerWidth + 'px'; wrapper.style.height = window.innerWidth + 'px'; // items.json 파일의 json 형식에 문제가 있어 수정했습니다. function loadJSON(jsonfile, callback) { var xobj = new XMLHttpRequest(); xobj.overrideMimeType("application/json"); xobj.open('GET', jsonfile, true); // Replace 'my_data' with the path to your file xobj.onreadystatechange = function () { if (xobj.readyState == 4 && xobj.status == "200") { // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode callback(xobj.responseText); } }; xobj.send(null); } function init() { loadJSON('./js/items.json',function(response) { var buildings = JSON.parse(response); var img = document.createElement("img"); img.src = buildings.datas[0].building.img; var name = document.createTextNode(buildings.datas[0].building.name); var address = document.createTextNode(buildings.datas[0].building.address1 + " " + buildings.datas[0].building.address2 + " " + buildings.datas[0].building.address3); var floor = document.createTextNode(buildings.datas[0].building.floor); var rooms = document.createTextNode(buildings.datas[0].building.rooms); var established = document.createTextNode(buildings.datas[0].building.established); document.getElementById("building-image").appendChild(img); document.getElementById("building-name").appendChild(name); document.getElementById("building-address").appendChild(address); document.getElementById("building-floor").appendChild(floor); document.getElementById("building-rooms").appendChild(rooms); document.getElementById("building-established").appendChild(established); }); } init(); var mapContainer = document.getElementById('map'), // 지도를 표시할 div mapOption = { center: new daum.maps.LatLng(33.450701, 126.570667), // 지도의 중심좌표 level: 3 // 지도의 확대 레벨 }; var map = new daum.maps.Map(mapContainer, mapOption); // 지도를 생성합니다 // 지도에 표시할 원을 생성합니다 var circle = new daum.maps.Circle({ center : new daum.maps.LatLng(33.450701, 126.570667), // 원의 중심좌표 입니다 radius: 50, // 미터 단위의 원의 반지름입니다 strokeWeight: 0, // 선의 두께입니다 strokeColor: '#75B8FA', // 선의 색깔입니다 strokeOpacity: 0, // 선의 불투명도 입니다 1에서 0 사이의 값이며 0에 가까울수록 투명합니다 strokeStyle: 'solid', // 선의 스타일 입니다 fillColor: '#ffa409', // 채우기 색깔입니다 fillOpacity: 0.7 // 채우기 불투명도 입니다 }); // 지도에 원을 표시합니다 circle.setMap(map);
/** * Created by caoguangyao on 2014/11/4 0004. */ var apiIp ='http://v2.api.njnetting.cn/';//全局的接口地址 function GetQueryString(name){ //获取浏览器的参数 var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if(r!=null)return decodeURIComponent(r[2]); return null; } function GetAppStyle(){//获取设备类型 无法区别 android平板和android手机 var platform; var userAgentT = navigator.userAgent; if ((userAgentT.match(/(Android)/i))) { platform = 'Android'; } else { if ((userAgentT.match(/(iPhone|iPod|ios|iPad)/i))) { if(userAgentT.match(/(iPhone|iPod|ios)/i)){ platform = 'iPhone'; }else{ platform = 'iPad'; } } else { if ((userAgentT.match(/(Windows phone)/i))){ platform = 'Windows phone'; } else { platform = 'pc browser'; } } } return platform; }
import './style.css'; //creating contructor for ball object class Ball{ constructor(top,left,height){ this.top=top; this.left=left; this.high=1.6; this.speed=5; this.direction=1; this.kick=false; this.scoreText=false; } } //creating initial starting point for theball const initialX=40; const initialY=245; //creating the ball obj let ball4 = new Ball(initialY,initialX,0); //creating main component with all html elements function component() { //main div const element = document.createElement('div'); element.classList.add('wrapper'); // main button const button = document.createElement('button'); button.classList.add('main_button'); button.innerHTML='PLAY A NEW GAME'; button.addEventListener('click',startPlaying); element.appendChild(button); //score table const scoreText = document.createElement('div'); scoreText.classList.add('scoreText'); scoreText.innerHTML='Score: '+0; element.appendChild(scoreText); //changing speed parameter in case of screen,s different width if(window.innerWidth>700){ ball4.speed=5; } else if(window.innerWidth>450){ ball4.speed=8; } else { ball4.speed=9; } return element; } //action triggered when main button clicked function startPlaying(){ //removing button const child = document.getElementsByClassName('main_button'); const parent = child[0].parentNode; parent.removeChild(child[0]); //setting score to 0 ball4.scoreText=0; //if ball already exist we just add kickBall event to it otherwise we create a new ball element const ballEl =document.getElementsByClassName('ball_wrapper'); if(ballEl.length>0){ ballEl[0].addEventListener('click',kickBall); } else{ parent.appendChild(createBall()); }; //if the gameOverText exist remove it const gameOverText =document.getElementsByClassName('gameOverText'); if(gameOverText.length>0){ const gameOverTextParent = gameOverText[0].parentNode; gameOverTextParent.removeChild(gameOverText[0]); }; //now we can trigger main action kickBall(false) } //each time ball is kicked the score is incrementing function incrementScore(val){ ball4.scoreText=val?ball4.scoreText+1:0; const scoreText = document.getElementsByClassName('scoreText'); scoreText[0].innerHTML=`Score: ${ball4.scoreText}`; } //main function triggered when ball is kisked function kickBall(val){ //triggering increment function incrementScore(val); //creating var and changing val of kick in order to disable previous setinterval const kick = ball4.kick; ball4.kick= !ball4.kick //random direction (left or right) each time ball is kicked ball4.direction= Math.random()-0.5<=0?-1:1; //grabbing ball element to change attributes of left and top later on const child = document.getElementsByClassName('ball_wrapper'); //saving in const initial value of top const ballYAngle = ball4.top; //random x value for the sinus function const xlengthOnCCS = Math.floor(window.innerWidth*((Math.random()*0.5)+0.2)); //seting x value for the sinus function based on x value const ylengthOnCCS= ball4.high*xlengthOnCCS/Math.PI; //changing pixels of x value to PI in order to add it xInPiForSinFn each time the ball moves const xlengthOnCCSinPI = Math.PI/xlengthOnCCS; //setting initial value of x in Pi to pass it to sinus function let xInPiForSinFn=0; //starting intervals const id = setInterval(movingBall,ball4.speed); //main function in interval function movingBall(){ //changing dirction if the ball hits wall if(child[0].offsetLeft+281>=window.innerWidth||child[0].offsetLeft<=-70){ ball4.direction = ball4.direction*(-1); } //disable interval in case the ball is kicked one more time if(ball4.kick===kick){ clearInterval(id); } else if(ball4.top<window.innerHeight-228){ //moving ball verticallly ball4.left = ball4.left + ball4.direction; //moving ball horizontally ball4.top = ballYAngle-(ylengthOnCCS*sinThirdGrade(xInPiForSinFn)); //setting ne top and left values child[0].setAttribute("style",`left:${ball4.left}px;top:${ball4.top}px;`); //incrementing x in PI value passed to sinus function in Y xInPiForSinFn=xInPiForSinFn+xlengthOnCCSinPI; //in case the ball falls down game over } else{ clearInterval(id); showGameOverInfo(); } }// end of movingBall } //setting sinus value function sinThirdGrade(x){ return x-(Math.pow(x,3)/strong(3))-(Math.pow(x,5)/strong(5)) } //stting strong value function strong(n) { if ((n == 0) || (n == 1)) return 1 else { let result = (n * strong(n-1) ); return result } } //function triggered when game is over function showGameOverInfo(){ //creating game over info and adding it to the main el const element = document.getElementsByClassName('wrapper'); const gameOverText = document.createElement('p'); gameOverText.classList.add('gameOverText'); gameOverText.innerText=`Game over. Your score is ${ball4.scoreText}`; element[0].appendChild(gameOverText); // creating main btn createStartBtn(); } //function which creates main btn function createStartBtn(){ // creating main btn and adding it to the main el const element = document.getElementsByClassName('wrapper'); const button = document.createElement('button'); button.classList.add('main_button'); button.innerHTML='START'; button.addEventListener('click',startPlaying); element[0].appendChild(button); //removing the main event from the ball const ball = document.getElementsByClassName('ball_wrapper'); ball[0].removeEventListener('click',kickBall); // settin initial values of the ball in case player wants to play one more time ball4.top=initialY; ball4.left=initialX; } //a funtion which creates the ball function createBall() { const ball = document.createElement('div'); ball.addEventListener('click',kickBall); ball.classList.add('ball_wrapper'); ball.setAttribute("style",`left:${ball4.left}px;top:${ball4.top}px;`) const innerBall = document.createElement('div'); innerBall.classList.add("inner-ball_wrapper"); ball.appendChild(innerBall); return ball; } document.body.appendChild(component());
/*! * Basic postMessage Support * * Copyright (c) 2013-2016 Dave Olsen, http://dmolsen.com * Licensed under the MIT license * * Handles the postMessage stuff in the pattern, view-all, and style guide templates. * */ // alert the iframe parent that the pattern has loaded assuming this view was loaded in an iframe if (self != top) { // handle the options that could be sent to the parent window // - all get path // - pattern & view all get a pattern partial, styleguide gets all // - pattern shares lineage var path = window.location.toString(); var parts = path.split('?'); var options = { event: 'patternLab.pageLoad', path: parts[0], }; patternData = document.getElementById('pl-pattern-data-footer').innerHTML; patternData = JSON.parse(patternData); options.patternpartial = patternData.patternPartial !== undefined ? patternData.patternPartial : 'all'; if (patternData.lineage !== '') { options.lineage = patternData.lineage; } var targetOrigin = window.location.protocol == 'file:' ? '*' : window.location.protocol + '//' + window.location.host; parent.postMessage(options, targetOrigin); // find all links and add an onclick handler for replacing the iframe address so the history works var aTags = document.getElementsByTagName('a'); for (var i = 0; i < aTags.length; i++) { aTags[i].onclick = function(e) { var href = this.getAttribute('href'); var target = this.getAttribute('target'); if (target !== undefined && (target == '_parent' || target == '_blank')) { // just do normal stuff } else if (href && href !== '#') { e.preventDefault(); window.location.replace(href); } else { e.preventDefault(); return false; } }; } } // watch the iframe source so that it can be sent back to everyone else. function receiveIframeMessage(event) { // does the origin sending the message match the current host? if not dev/null the request if ( window.location.protocol != 'file:' && event.origin !== window.location.protocol + '//' + window.location.host ) { return; } var path; var data = {}; try { data = typeof event.data !== 'string' ? event.data : JSON.parse(event.data); } catch (e) {} if (data.event !== undefined && data.event == 'patternLab.updatePath') { if (patternData.patternPartial !== undefined) { // handle patterns and the view all page var re = /(patterns|snapshots)\/(.*)$/; path = window.location.protocol + '//' + window.location.host + window.location.pathname.replace(re, '') + data.path + '?' + Date.now(); window.location.replace(path); } else { // handle the style guide path = window.location.protocol + '//' + window.location.host + window.location.pathname.replace( 'styleguide/html/styleguide.html', '' ) + data.path + '?' + Date.now(); window.location.replace(path); } } else if (data.event !== undefined && data.event == 'patternLab.reload') { // reload the location if there was a message to do so window.location.reload(); } } window.addEventListener('message', receiveIframeMessage, false); // jshint ignore: start /*! * clipboard.js v1.7.1 * https://zenorocha.github.io/clipboard.js * * Licensed MIT © Zeno Rocha */ !(function(t) { if ('object' == typeof exports && 'undefined' != typeof module) module.exports = t(); else if ('function' == typeof define && define.amd) define([], t); else { var e; (e = 'undefined' != typeof window ? window : 'undefined' != typeof global ? global : 'undefined' != typeof self ? self : this), (e.Clipboard = t()); } })(function() { var t, e, n; return (function t(e, n, o) { function i(a, c) { if (!n[a]) { if (!e[a]) { var l = 'function' == typeof require && require; if (!c && l) return l(a, !0); if (r) return r(a, !0); var s = new Error("Cannot find module '" + a + "'"); throw ((s.code = 'MODULE_NOT_FOUND'), s); } var u = (n[a] = { exports: {} }); e[a][0].call( u.exports, function(t) { var n = e[a][1][t]; return i(n || t); }, u, u.exports, t, e, n, o ); } return n[a].exports; } for ( var r = 'function' == typeof require && require, a = 0; a < o.length; a++ ) i(o[a]); return i; })( { 1: [ function(t, e, n) { function o(t, e) { for (; t && t.nodeType !== i; ) { if ('function' == typeof t.matches && t.matches(e)) return t; t = t.parentNode; } } var i = 9; if ('undefined' != typeof Element && !Element.prototype.matches) { var r = Element.prototype; r.matches = r.matchesSelector || r.mozMatchesSelector || r.msMatchesSelector || r.oMatchesSelector || r.webkitMatchesSelector; } e.exports = o; }, {}, ], 2: [ function(t, e, n) { function o(t, e, n, o, r) { var a = i.apply(this, arguments); return ( t.addEventListener(n, a, r), { destroy: function() { t.removeEventListener(n, a, r); }, } ); } function i(t, e, n, o) { return function(n) { (n.delegateTarget = r(n.target, e)), n.delegateTarget && o.call(t, n); }; } var r = t('./closest'); e.exports = o; }, { './closest': 1 }, ], 3: [ function(t, e, n) { (n.node = function(t) { return void 0 !== t && t instanceof HTMLElement && 1 === t.nodeType; }), (n.nodeList = function(t) { var e = Object.prototype.toString.call(t); return ( void 0 !== t && ('[object NodeList]' === e || '[object HTMLCollection]' === e) && 'length' in t && (0 === t.length || n.node(t[0])) ); }), (n.string = function(t) { return 'string' == typeof t || t instanceof String; }), (n.fn = function(t) { return '[object Function]' === Object.prototype.toString.call(t); }); }, {}, ], 4: [ function(t, e, n) { function o(t, e, n) { if (!t && !e && !n) throw new Error('Missing required arguments'); if (!c.string(e)) throw new TypeError('Second argument must be a String'); if (!c.fn(n)) throw new TypeError('Third argument must be a Function'); if (c.node(t)) return i(t, e, n); if (c.nodeList(t)) return r(t, e, n); if (c.string(t)) return a(t, e, n); throw new TypeError( 'First argument must be a String, HTMLElement, HTMLCollection, or NodeList' ); } function i(t, e, n) { return ( t.addEventListener(e, n), { destroy: function() { t.removeEventListener(e, n); }, } ); } function r(t, e, n) { return ( Array.prototype.forEach.call(t, function(t) { t.addEventListener(e, n); }), { destroy: function() { Array.prototype.forEach.call(t, function(t) { t.removeEventListener(e, n); }); }, } ); } function a(t, e, n) { return l(document.body, t, e, n); } var c = t('./is'), l = t('delegate'); e.exports = o; }, { './is': 3, delegate: 2 }, ], 5: [ function(t, e, n) { function o(t) { var e; if ('SELECT' === t.nodeName) t.focus(), (e = t.value); else if ('INPUT' === t.nodeName || 'TEXTAREA' === t.nodeName) { var n = t.hasAttribute('readonly'); n || t.setAttribute('readonly', ''), t.select(), t.setSelectionRange(0, t.value.length), n || t.removeAttribute('readonly'), (e = t.value); } else { t.hasAttribute('contenteditable') && t.focus(); var o = window.getSelection(), i = document.createRange(); i.selectNodeContents(t), o.removeAllRanges(), o.addRange(i), (e = o.toString()); } return e; } e.exports = o; }, {}, ], 6: [ function(t, e, n) { function o() {} (o.prototype = { on: function(t, e, n) { var o = this.e || (this.e = {}); return (o[t] || (o[t] = [])).push({ fn: e, ctx: n }), this; }, once: function(t, e, n) { function o() { i.off(t, o), e.apply(n, arguments); } var i = this; return (o._ = e), this.on(t, o, n); }, emit: function(t) { var e = [].slice.call(arguments, 1), n = ((this.e || (this.e = {}))[t] || []).slice(), o = 0, i = n.length; for (o; o < i; o++) n[o].fn.apply(n[o].ctx, e); return this; }, off: function(t, e) { var n = this.e || (this.e = {}), o = n[t], i = []; if (o && e) for (var r = 0, a = o.length; r < a; r++) o[r].fn !== e && o[r].fn._ !== e && i.push(o[r]); return i.length ? (n[t] = i) : delete n[t], this; }, }), (e.exports = o); }, {}, ], 7: [ function(e, n, o) { !(function(i, r) { if ('function' == typeof t && t.amd) t(['module', 'select'], r); else if (void 0 !== o) r(n, e('select')); else { var a = { exports: {} }; r(a, i.select), (i.clipboardAction = a.exports); } })(this, function(t, e) { 'use strict'; function n(t) { return t && t.__esModule ? t : { default: t }; } function o(t, e) { if (!(t instanceof e)) throw new TypeError('Cannot call a class as a function'); } var i = n(e), r = 'function' == typeof Symbol && 'symbol' == typeof Symbol.iterator ? function(t) { return typeof t; } : function(t) { return t && 'function' == typeof Symbol && t.constructor === Symbol && t !== Symbol.prototype ? 'symbol' : typeof t; }, a = (function() { function t(t, e) { for (var n = 0; n < e.length; n++) { var o = e[n]; (o.enumerable = o.enumerable || !1), (o.configurable = !0), 'value' in o && (o.writable = !0), Object.defineProperty(t, o.key, o); } } return function(e, n, o) { return n && t(e.prototype, n), o && t(e, o), e; }; })(), c = (function() { function t(e) { o(this, t), this.resolveOptions(e), this.initSelection(); } return ( a(t, [ { key: 'resolveOptions', value: function t() { var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}; (this.action = e.action), (this.container = e.container), (this.emitter = e.emitter), (this.target = e.target), (this.text = e.text), (this.trigger = e.trigger), (this.selectedText = ''); }, }, { key: 'initSelection', value: function t() { this.text ? this.selectFake() : this.target && this.selectTarget(); }, }, { key: 'selectFake', value: function t() { var e = this, n = 'rtl' == document.documentElement.getAttribute('dir'); this.removeFake(), (this.fakeHandlerCallback = function() { return e.removeFake(); }), (this.fakeHandler = this.container.addEventListener( 'click', this.fakeHandlerCallback ) || !0), (this.fakeElem = document.createElement('textarea')), (this.fakeElem.style.fontSize = '12pt'), (this.fakeElem.style.border = '0'), (this.fakeElem.style.padding = '0'), (this.fakeElem.style.margin = '0'), (this.fakeElem.style.position = 'absolute'), (this.fakeElem.style[n ? 'right' : 'left'] = '-9999px'); var o = window.pageYOffset || document.documentElement.scrollTop; (this.fakeElem.style.top = o + 'px'), this.fakeElem.setAttribute('readonly', ''), (this.fakeElem.value = this.text), this.container.appendChild(this.fakeElem), (this.selectedText = (0, i.default)(this.fakeElem)), this.copyText(); }, }, { key: 'removeFake', value: function t() { this.fakeHandler && (this.container.removeEventListener( 'click', this.fakeHandlerCallback ), (this.fakeHandler = null), (this.fakeHandlerCallback = null)), this.fakeElem && (this.container.removeChild(this.fakeElem), (this.fakeElem = null)); }, }, { key: 'selectTarget', value: function t() { (this.selectedText = (0, i.default)(this.target)), this.copyText(); }, }, { key: 'copyText', value: function t() { var e = void 0; try { e = document.execCommand(this.action); } catch (t) { e = !1; } this.handleResult(e); }, }, { key: 'handleResult', value: function t(e) { this.emitter.emit(e ? 'success' : 'error', { action: this.action, text: this.selectedText, trigger: this.trigger, clearSelection: this.clearSelection.bind(this), }); }, }, { key: 'clearSelection', value: function t() { this.trigger && this.trigger.focus(), window.getSelection().removeAllRanges(); }, }, { key: 'destroy', value: function t() { this.removeFake(); }, }, { key: 'action', set: function t() { var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : 'copy'; if ( ((this._action = e), 'copy' !== this._action && 'cut' !== this._action) ) throw new Error( 'Invalid "action" value, use either "copy" or "cut"' ); }, get: function t() { return this._action; }, }, { key: 'target', set: function t(e) { if (void 0 !== e) { if ( !e || 'object' !== (void 0 === e ? 'undefined' : r(e)) || 1 !== e.nodeType ) throw new Error( 'Invalid "target" value, use a valid Element' ); if ( 'copy' === this.action && e.hasAttribute('disabled') ) throw new Error( 'Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute' ); if ( 'cut' === this.action && (e.hasAttribute('readonly') || e.hasAttribute('disabled')) ) throw new Error( 'Invalid "target" attribute. You can\'t cut text from elements with "readonly" or "disabled" attributes' ); this._target = e; } }, get: function t() { return this._target; }, }, ]), t ); })(); t.exports = c; }); }, { select: 5 }, ], 8: [ function(e, n, o) { !(function(i, r) { if ('function' == typeof t && t.amd) t( [ 'module', './clipboard-action', 'tiny-emitter', 'good-listener', ], r ); else if (void 0 !== o) r( n, e('./clipboard-action'), e('tiny-emitter'), e('good-listener') ); else { var a = { exports: {} }; r(a, i.clipboardAction, i.tinyEmitter, i.goodListener), (i.clipboard = a.exports); } })(this, function(t, e, n, o) { 'use strict'; function i(t) { return t && t.__esModule ? t : { default: t }; } function r(t, e) { if (!(t instanceof e)) throw new TypeError('Cannot call a class as a function'); } function a(t, e) { if (!t) throw new ReferenceError( "this hasn't been initialised - super() hasn't been called" ); return !e || ('object' != typeof e && 'function' != typeof e) ? t : e; } function c(t, e) { if ('function' != typeof e && null !== e) throw new TypeError( 'Super expression must either be null or a function, not ' + typeof e ); (t.prototype = Object.create(e && e.prototype, { constructor: { value: t, enumerable: !1, writable: !0, configurable: !0, }, })), e && (Object.setPrototypeOf ? Object.setPrototypeOf(t, e) : (t.__proto__ = e)); } function l(t, e) { var n = 'data-clipboard-' + t; if (e.hasAttribute(n)) return e.getAttribute(n); } var s = i(e), u = i(n), f = i(o), d = 'function' == typeof Symbol && 'symbol' == typeof Symbol.iterator ? function(t) { return typeof t; } : function(t) { return t && 'function' == typeof Symbol && t.constructor === Symbol && t !== Symbol.prototype ? 'symbol' : typeof t; }, h = (function() { function t(t, e) { for (var n = 0; n < e.length; n++) { var o = e[n]; (o.enumerable = o.enumerable || !1), (o.configurable = !0), 'value' in o && (o.writable = !0), Object.defineProperty(t, o.key, o); } } return function(e, n, o) { return n && t(e.prototype, n), o && t(e, o), e; }; })(), p = (function(t) { function e(t, n) { r(this, e); var o = a( this, (e.__proto__ || Object.getPrototypeOf(e)).call(this) ); return o.resolveOptions(n), o.listenClick(t), o; } return ( c(e, t), h( e, [ { key: 'resolveOptions', value: function t() { var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}; (this.action = 'function' == typeof e.action ? e.action : this.defaultAction), (this.target = 'function' == typeof e.target ? e.target : this.defaultTarget), (this.text = 'function' == typeof e.text ? e.text : this.defaultText), (this.container = 'object' === d(e.container) ? e.container : document.body); }, }, { key: 'listenClick', value: function t(e) { var n = this; this.listener = (0, f.default)(e, 'click', function( t ) { return n.onClick(t); }); }, }, { key: 'onClick', value: function t(e) { var n = e.delegateTarget || e.currentTarget; this.clipboardAction && (this.clipboardAction = null), (this.clipboardAction = new s.default({ action: this.action(n), target: this.target(n), text: this.text(n), container: this.container, trigger: n, emitter: this, })); }, }, { key: 'defaultAction', value: function t(e) { return l('action', e); }, }, { key: 'defaultTarget', value: function t(e) { var n = l('target', e); if (n) return document.querySelector(n); }, }, { key: 'defaultText', value: function t(e) { return l('text', e); }, }, { key: 'destroy', value: function t() { this.listener.destroy(), this.clipboardAction && (this.clipboardAction.destroy(), (this.clipboardAction = null)); }, }, ], [ { key: 'isSupported', value: function t() { var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : ['copy', 'cut'], n = 'string' == typeof e ? [e] : e, o = !!document.queryCommandSupported; return ( n.forEach(function(t) { o = o && !!document.queryCommandSupported(t); }), o ); }, }, ] ), e ); })(u.default); t.exports = p; }); }, { './clipboard-action': 7, 'good-listener': 4, 'tiny-emitter': 6 }, ], }, {}, [8] )(8); }); /*! * URL Handler * * Copyright (c) 2013-2014 Dave Olsen, http://dmolsen.com * Licensed under the MIT license * * Helps handle the initial iFrame source. Parses a string to see if it matches * an expected pattern in Pattern Lab. Supports Pattern Lab's fuzzy pattern partial * matching style. * */ var urlHandler = { // set-up some default vars skipBack: false, targetOrigin: window.location.protocol == 'file:' ? '*' : window.location.protocol + '//' + window.location.host, /** * get the real file name for a given pattern name * @param {String} the shorthand partials syntax for a given pattern * @param {Boolean} with the file name should be returned with the full rendered suffix or not * * @return {String} the real file path */ getFileName: function(name, withRenderedSuffix) { var baseDir = 'patterns'; var fileName = ''; if (name === undefined) { return fileName; } if (withRenderedSuffix === undefined) { withRenderedSuffix = true; } if (name == 'all') { return 'styleguide/html/styleguide.html'; } else if (name == 'snapshots') { return 'snapshots/index.html'; } var paths = name.indexOf('viewall-') != -1 ? viewAllPaths : patternPaths; var nameClean = name.replace('viewall-', ''); // look at this as a regular pattern var bits = this.getPatternInfo(nameClean, paths); var patternType = bits[0]; var pattern = bits[1]; if ( paths[patternType] !== undefined && paths[patternType][pattern] !== undefined ) { fileName = paths[patternType][pattern]; } else if (paths[patternType] !== undefined) { for (var patternMatchKey in paths[patternType]) { if (patternMatchKey.indexOf(pattern) != -1) { fileName = paths[patternType][patternMatchKey]; break; } } } if (fileName === '') { return fileName; } var regex = /\//g; if ( name.indexOf('viewall-') !== -1 && name.indexOf('viewall-') === 0 && fileName !== '' ) { fileName = baseDir + '/' + fileName.replace(regex, '-') + '/index.html'; } else if (fileName !== '') { fileName = baseDir + '/' + fileName.replace(regex, '-') + '/' + fileName.replace(regex, '-'); if (withRenderedSuffix) { var fileSuffixRendered = config.outputFileSuffixes !== undefined && config.outputFileSuffixes.rendered !== undefined ? config.outputFileSuffixes.rendered : ''; fileName = fileName + fileSuffixRendered + '.html'; } } return fileName; }, /** * break up a pattern into its parts, pattern type and pattern name * @param {String} the shorthand partials syntax for a given pattern * @param {Object} the paths to be compared * * @return {Array} the pattern type and pattern name */ getPatternInfo: function(name, paths) { var patternBits = name.split('-'); var i = 1; var c = patternBits.length; var patternType = patternBits[0]; while (paths[patternType] === undefined && i < c) { patternType += '-' + patternBits[i]; i++; } var pattern = name.slice(patternType.length + 1, name.length); return [patternType, pattern]; }, /** * search the request vars for a particular item * * @return {Object} a search of the window.location.search vars */ getRequestVars: function() { // the following is taken from https://developer.mozilla.org/en-US/docs/Web/API/window.location var oGetVars = new function(sSearch) { if (sSearch.length > 1) { for ( var aItKey, nKeyId = 0, aCouples = sSearch.substr(1).split('&'); nKeyId < aCouples.length; nKeyId++ ) { aItKey = aCouples[nKeyId].split('='); this[unescape(aItKey[0])] = aItKey.length > 1 ? unescape(aItKey[1]) : ''; } } }(window.location.search); return oGetVars; }, /** * push a pattern onto the current history based on a click * @param {String} the shorthand partials syntax for a given pattern * @param {String} the path given by the loaded iframe */ pushPattern: function(pattern, givenPath) { var data = { pattern: pattern, }; var fileName = urlHandler.getFileName(pattern); var path = window.location.pathname; path = window.location.protocol === 'file' ? path.replace('/public/index.html', 'public/') : path.replace(/\/index\.html/, '/'); var expectedPath = window.location.protocol + '//' + window.location.host + path + fileName; if (givenPath != expectedPath) { // make sure to update the iframe because there was a click var obj = JSON.stringify({ event: 'patternLab.updatePath', path: fileName, }); document .querySelector('.pl-js-iframe') .contentWindow.postMessage(obj, urlHandler.targetOrigin); } else { // add to the history var addressReplacement = window.location.protocol == 'file:' ? null : window.location.protocol + '//' + window.location.host + window.location.pathname.replace('index.html', '') + '?p=' + pattern; if (history.pushState !== undefined) { history.pushState(data, null, addressReplacement); } document.getElementById('title').innerHTML = 'Pattern Lab - ' + pattern; // Open in new window link if (document.querySelector('.pl-js-open-new-window') !== undefined) { // Set value of href to the path to the pattern document .querySelector('.pl-js-open-new-window') .setAttribute('href', urlHandler.getFileName(pattern)); } } }, /** * based on a click forward or backward modify the url and iframe source * @param {Object} event info like state and properties set in pushState() */ popPattern: function(e) { var patternName; var state = e.state; if (state === null) { this.skipBack = false; return; } else if (state !== null) { patternName = state.pattern; } var iFramePath = ''; iFramePath = this.getFileName(patternName); if (iFramePath === '') { iFramePath = 'styleguide/html/styleguide.html'; } var obj = JSON.stringify({ event: 'patternLab.updatePath', path: iFramePath, }); document .querySelector('.pl-js-iframe') .contentWindow.postMessage(obj, urlHandler.targetOrigin); document.getElementById('title').innerHTML = 'Pattern Lab - ' + patternName; document .querySelector('.pl-js-open-new-window') .setAttribute('href', urlHandler.getFileName(patternName)); }, }; /** * handle the onpopstate event */ window.onpopstate = function(event) { urlHandler.skipBack = true; urlHandler.popPattern(event); }; /*! * Panels Util * For both styleguide and viewer * * Copyright (c) 2013-16 Dave Olsen, http://dmolsen.com * Licensed under the MIT license * * @requires url-handler.js * */ var panelsUtil = { /** * Add click events to the template that was rendered * @param {String} the rendered template for the modal * @param {String} the pattern partial for the modal */ addClickEvents: function(templateRendered, patternPartial) { var els = templateRendered.querySelectorAll('.pl-js-tab-link'); for (var i = 0; i < els.length; ++i) { els[i].onclick = function(e) { e.preventDefault(); var patternPartial = this.getAttribute('data-patternpartial'); var panelID = this.getAttribute('data-panelid'); panelsUtil.show(patternPartial, panelID); }; } return templateRendered; }, /** * Show a specific modal * @param {String} the pattern partial for the modal * @param {String} the ID of the panel to be shown */ show: function(patternPartial, panelID) { var els; // turn off all of the active tabs els = document.querySelectorAll( '#pl-' + patternPartial + '-tabs .pl-js-tab-link' ); for (i = 0; i < els.length; ++i) { els[i].classList.remove('pl-is-active-tab'); } // hide all of the panels els = document.querySelectorAll( '#pl-' + patternPartial + '-panels .pl-js-tab-panel' ); for (i = 0; i < els.length; ++i) { els[i].classList.remove('pl-is-active-tab'); } // add active tab class document .getElementById('pl-' + patternPartial + '-' + panelID + '-tab') .classList.add('pl-is-active-tab'); // show the panel document .getElementById('pl-' + patternPartial + '-' + panelID + '-panel') .classList.add('pl-is-active-tab'); }, }; /*! * Modal for the Styleguide Layer * For both annotations and code/info * * Copyright (c) 2016 Dave Olsen, http://dmolsen.com * Licensed under the MIT license * * @requires panels-util.js * @requires url-handler.js * */ var modalStyleguide = { // set up some defaults active: [], targetOrigin: window.location.protocol === 'file:' ? '*' : window.location.protocol + '//' + window.location.host, /** * initialize the modal window */ onReady: function() { // go through the panel toggles and add click event to the pattern extra toggle button var els = document.querySelectorAll('.pl-js-pattern-extra-toggle'); for (var i = 0; i < els.length; ++i) { els[i].onclick = function(e) { var patternPartial = this.getAttribute('data-patternpartial'); modalStyleguide.toggle(patternPartial); }; } }, /** * toggle the modal window open and closed based on clicking the pip * @param {String} the patternPartial that identifies what needs to be toggled */ toggle: function(patternPartial) { if ( modalStyleguide.active[patternPartial] === undefined || !modalStyleguide.active[patternPartial] ) { var el = document.getElementById('pl-pattern-data-' + patternPartial); modalStyleguide.collectAndSend(el, true, false); } else { modalStyleguide.highlightsHide(); modalStyleguide.close(patternPartial); } }, /** * open the modal window for a view-all entry * @param {String} the patternPartial that identifies what needs to be opened * @param {String} the content that should be inserted */ open: function(patternPartial, content) { // make sure templateRendered is modified to be an HTML element var div = document.createElement('div'); div.innerHTML = content; content = document .createElement('div') .appendChild(div) .querySelector('div'); // add click events content = panelsUtil.addClickEvents(content, patternPartial); // make sure the modal viewer and other options are off just in case modalStyleguide.close(patternPartial); // note it's turned on in the viewer modalStyleguide.active[patternPartial] = true; // make sure there's no content div = document.getElementById('pl-pattern-extra-' + patternPartial); if (div.childNodes.length > 0) { div.removeChild(div.childNodes[0]); } // add the content document .getElementById('pl-pattern-extra-' + patternPartial) .appendChild(content); // show the modal document .getElementById('pl-pattern-extra-toggle-' + patternPartial) .classList.add('pl-is-active'); document .getElementById('pl-pattern-extra-' + patternPartial) .classList.add('pl-is-active'); }, /** * close the modal window for a view-all entry * @param {String} the patternPartial that identifies what needs to be closed */ close: function(patternPartial) { // note that the modal viewer is no longer active modalStyleguide.active[patternPartial] = false; // hide the modal, look at info-panel.js document .getElementById('pl-pattern-extra-toggle-' + patternPartial) .classList.remove('pl-is-active'); document .getElementById('pl-pattern-extra-' + patternPartial) .classList.remove('pl-is-active'); }, /** * get the data that needs to be send to the viewer for rendering * @param {Element} the identifier for the element that needs to be collected * @param {Boolean} if the refresh is of a view-all view and the content should be sent back * @param {Boolean} if the text in the dropdown should be switched */ collectAndSend: function(el, iframePassback, switchText) { var patternData = JSON.parse(el.innerHTML); if (patternData.patternName !== undefined) { patternMarkupEl = document.querySelector( '#' + patternData.patternPartial + ' > .pl-js-pattern-example' ); patternData.patternMarkup = patternMarkupEl !== null ? patternMarkupEl.innerHTML : document.querySelector('body').innerHTML; modalStyleguide.patternQueryInfo(patternData, iframePassback, switchText); } }, /** * hide the annotation highlights */ highlightsHide: function(patternPartial) { var patternPartialSelector = patternPartial !== undefined ? '#' + patternPartial + ' > ' : ''; elsToHide = document.querySelectorAll( patternPartialSelector + '.pl-has-annotation' ); for (i = 0; i < elsToHide.length; i++) { elsToHide[i].classList.remove('pl-has-annotation'); } elsToHide = document.querySelectorAll( patternPartialSelector + '.pl-c-annotation-tip' ); for (i = 0; i < elsToHide.length; i++) { elsToHide[i].style.display = 'none'; } }, /** * return the pattern info to the top level * @param {Object} the content that will be sent to the viewer for rendering * @param {Boolean} if the refresh is of a view-all view and the content should be sent back * @param {Boolean} if the text in the dropdown should be switched */ patternQueryInfo: function(patternData, iframePassback, switchText) { // send a message to the pattern try { var obj = JSON.stringify({ event: 'patternLab.patternQueryInfo', patternData: patternData, iframePassback: iframePassback, switchText: switchText, }); parent.postMessage(obj, modalStyleguide.targetOrigin); } catch (e) {} }, /** * toggle the comment pop-up based on a user clicking on the pattern * based on the great MDN docs at https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage * @param {Object} event info */ receiveIframeMessage: function(event) { var i; // does the origin sending the message match the current host? if not dev/null the request if ( window.location.protocol !== 'file:' && event.origin !== window.location.protocol + '//' + window.location.host ) { return; } var data = {}; try { data = typeof event.data !== 'string' ? event.data : JSON.parse(event.data); } catch (e) {} // see if it got a path to replace if (data.event !== undefined && data.event == 'patternLab.patternQuery') { var els, iframePassback, patternData, patternMarkupEl; // find all elements related to pattern info els = document.querySelectorAll('.pl-js-pattern-data'); iframePassback = els.length > 1; // send each up to the parent to be read and compiled into panels for (i = 0; i < els.length; i++) { modalStyleguide.collectAndSend(els[i], iframePassback, data.switchText); } } else if ( data.event !== undefined && data.event == 'patternLab.patternModalInsert' ) { // insert the previously rendered content being passed from the iframe modalStyleguide.open(data.patternPartial, data.modalContent); } else if ( data.event !== undefined && data.event == 'patternLab.annotationsHighlightShow' ) { var elsToHighlight, j, item, span; // go over the supplied annotations for (i = 0; i < data.annotations.length; i++) { item = data.annotations[i]; elsToHighlight = document.querySelectorAll(item.el); if (elsToHighlight.length > 0) { for (j = 0; j < elsToHighlight.length; j++) { elsToHighlight[j].classList.add('pl-has-annotation'); span = document.createElement('span'); span.innerHTML = item.displayNumber; span.classList.add('pl-c-annotation-tip'); if ( window .getComputedStyle(elsToHighlight[j], null) .getPropertyValue('max-height') == '0px' ) { span.style.display = 'none'; } annotationTip = document.querySelector( item.el + ' > span.pl-c-annotation-tip' ); if (annotationTip === null) { elsToHighlight[j].insertBefore( span, elsToHighlight[j].firstChild ); } else { annotationTip.style.display = 'inline'; } elsToHighlight[j].onclick = (function(item) { return function(e) { e.preventDefault(); e.stopPropagation(); var obj = JSON.stringify({ event: 'patternLab.annotationNumberClicked', displayNumber: item.displayNumber, }); parent.postMessage(obj, modalStyleguide.targetOrigin); }; })(item); } } } } else if ( data.event !== undefined && data.event == 'patternLab.annotationsHighlightHide' ) { modalStyleguide.highlightsHide(); } else if ( data.event !== undefined && data.event == 'patternLab.patternModalClose' ) { var keys = []; for (var k in modalStyleguide.active) { keys.push(k); } for (i = 0; i < keys.length; i++) { var patternPartial = keys[i]; if (modalStyleguide.active[patternPartial]) { modalStyleguide.close(patternPartial); } } } }, }; // when the document is ready make sure the modal is ready modalStyleguide.onReady(); window.addEventListener('message', modalStyleguide.receiveIframeMessage, false); // Copy to clipboard functionality var clipboard = new Clipboard('.pl-js-code-copy-btn'); clipboard.on('success', function(e) { var copyButton = document.querySelectorAll('.pl-js-code-copy-btn'); for (i = 0; i < copyButton.length; i++) { copyButton[i].innerText = 'Copy'; } e.trigger.textContent = 'Copied'; });
var dir________________________________07c2df013bb20677b8e65a9f18968d2c________________8js________8js____8js__8js_8js = [ [ "dir________________07c2df013bb20677b8e65a9f18968d2c________8js____8js__8js_8js", "dir________________________________07c2df013bb20677b8e65a9f18968d2c________________8js________8js____8js__8js_8js.html#a2bad7e21cc6f94429bef479487d2499d", null ] ];
/* Toggle between adding and removing the "responsive" class to topnav when the user clicks on the icon */ function myFunction() { var x = document.getElementById("tn"); if (x.className === "top-nav") { x.className += " responsive"; } else { x.className = "top-nav"; } } // When the user scrolls down 20px from the top of the document, slide down the navbar // When the user scrolls to the top of the page, slide up the navbar (50px out of the top view) window.onscroll = function() {scrollFunction()}; function scrollFunction() { if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) { document.getElementById("tn").style.top = "0"; } else { document.getElementById("tn").style.top = "-50px"; } }
const weatherForm = document.querySelector('form') const search = document.querySelector('input') const msgError = document.querySelector('#message-1') const msgTemperature = document.querySelector('#message-2') const msgAddress = document.querySelector('#message-3') const msgTimezone = document.querySelector('#message-4') const url = '/weather?address=' weatherForm.addEventListener('submit' ,(e)=>{ e.preventDefault() const location = search.value // console.log(location) // console.log(url) msgError.textContent = 'Loading...' msgTemperature.textContent = '' msgAddress.textContent = '' msgTimezone.textContent = '' fetch(url+location).then((response) => { response.json().then((data) => { if(data.error){ console.log(data.error) msgError.textContent = data.error }else{ msgTemperature.textContent = data.forecast + " " + data.temperature + ". Highest Temperature on this day is " + data.highTemperature + " : Low Temperature on this day is " + data.lowTemperature msgTimezone.textContent = data.timezone msgAddress.textContent = data.address msgError.textContent = '' // console.log(data.forecast) // console.log(data.timezone) // console.log(data.address) // console.log(data.temperature) } }) }) })
import * as React from 'react' import Picture from '../../images/Picture.jpg' import { InfoBox, SmallAboutContainer, StyledTitle, StyledParagraph, StyledLink } from './smallAbout-style'; export default function SmallAbout({lang}) { const translatedData = { pt: { aboutTitle: "SOBRE MIM", aboutParagraph: "Meu nome é Wander e eu sou desenvolvedor Web. Atualmente estou estudando React.js e Gatsby.", callPortfolio: "Veja meu Portfólio", altText: "Picture" }, en: { aboutTitle: "ABOUT ME", aboutParagraph: "My name is Wander and I am a Web developer. I have currently focused my studies on React and Gatsby.", callPortfolio: "See my portfolio" } }; return ( <SmallAboutContainer> <StyledTitle>{translatedData[lang].aboutTitle}</StyledTitle> <InfoBox> <img src={Picture} alt={translatedData[lang].altText}/> <StyledParagraph>{translatedData[lang].aboutParagraph}</StyledParagraph> <p>{translatedData[lang].callPortfolio}</p> <StyledLink href="https://wandercruz.com.br">www.wandercruz.com.br</StyledLink> </InfoBox> </SmallAboutContainer> ) }
var app = angular.module('executUpload', ['toastr']); app.controller('executUploadCtrl', function($scope, executSer,$stateParams,$state,toastr){ $scope.showed=true var infoData ={id: $stateParams.id}; //获取ID executSer.exectId(infoData).then(function(response){ if(response.data.code== 0){ $scope.edit = response.data.data; }else{ toastr.error( response.data.msg, '温馨提示'); } }); //编辑点击提交 $scope.openEditFun = function(){ $scope.edit={ id:$stateParams.id, delay:$scope.edit.delay, delayType:$scope.edit.delayType, reportReason:$scope.edit.reportReason, delayTime:$scope.edit.delayTime1 } executSer.exectUpload($scope.edit).then(function(response){ if(response.data.code == 0){ $state.go('root.allocation.execution.list[12]'); toastr.success( "编辑成功", '温馨提示'); }else{ toastr.error( response.data.msg, '温馨提示'); } }); }; });
const config = require('./app/config/config'); var rimraf = require('rimraf'); if (!config.testOnRinkeby) { rimraf.sync('./db'); console.log("Cleared DB"); } const express = require('express'); const app = express(); const https = require('https') const Router = require('named-routes'); var router = new Router(); router.extendExpress(app); router.registerAppHelpers(app); const bodyParser = require('body-parser'); app.use(bodyParser.json()); const comp = require('./compile'); const assert = require('assert'); const moment = require('moment'); const coinstring = require('coinstring'); const fs = require("fs"); const solc = require('solc'); const Artifactor = require("truffle-artifactor"); const async = require("async"); const TruffleContract = require('truffle-contract'); var TestRPC = require("ethereumjs-testrpc"); const Web3 = require("web3"); const BN = Web3.utils.BN; const util = require('util'); const ethUtil = require('ethereumjs-util'); const PlasmaTransaction = require('./lib/Tx/tx'); const Block = require('./lib/Block/block'); const fromBtcWif = coinstring.createDecoder(0x80); const levelup = require('levelup') const leveldown = require('leveldown') const levelDB = levelup(leveldown('./db')) let lastBlock; let lastBlockHash; let blockMiningTimer; const {blockNumberLength} = require("./lib/dataStructureLengths"); const plasmaOperatorPrivKeyHex = config.plasmaOperatorPrivKeyHex; const plasmaOperatorPrivKey = ethUtil.toBuffer(plasmaOperatorPrivKeyHex); const plasmaOperatorAddress = config.plasmaOperatorAddress; const testPrivKeys = config.testPrivKeys; const port = config.port; let sendAsyncPromisified; let PlasmaContract; let DeployedPlasmaContract; let Web3PlasmaContract; let web3; async function startVM(){ if (config.testOnRinkeby) { web3 = new Web3(config.provider); let unlocked = await web3.eth.personal.unlockAccount(config.plasmaOperatorAddress, config.plasmaOperatorPassword, 0); let provider = web3.currentProvider; sendAsyncPromisified = util.promisify(provider.send).bind(provider); return; } let provider = TestRPC.provider({ total_accounts: 10, time:new Date(), verbose:false, gasPrice: 0, accounts:[ {secretKey:"0x" + plasmaOperatorPrivKey.toString('hex'), balance: 4.2e18}, {secretKey:"0x" + testPrivKeys[0].toString('hex'), balance: 4.2e18}, {secretKey:"0x" + testPrivKeys[1].toString('hex'), balance: 4.2e18} ], mnemonic: "42" // , // logger: console }); web3 = new Web3(provider); sendAsyncPromisified = util.promisify(provider.sendAsync).bind(provider); } async function deployContracts() { PlasmaContract = new TruffleContract(require("./build/contracts/PlasmaParent.json")); if (config.testOnRinkeby) { if (config.deployedPlasmaContract == "") { Web3PlasmaContract = new web3.eth.Contract(PlasmaContract.abi, {from: config.plasmaOperatorAddress, gasPrice: 35e9}); DeployedPlasmaContract = await Web3PlasmaContract.deploy({data: PlasmaContract.bytecode}).send({from: config.plasmaOperatorAddress, gas: 6e6}); console.log("Deployed at "+ DeployedPlasmaContract._address); return; } DeployedPlasmaContract = new web3.eth.Contract(PlasmaContract.abi, config.deployedPlasmaContract,{from: config.plasmaOperatorAddress, gasPrice: 35e9}); console.log("Deployed at "+ DeployedPlasmaContract._address); return; } Web3PlasmaContract = new web3.eth.Contract(PlasmaContract.abi, {from: config.plasmaOperatorAddress}); DeployedPlasmaContract = await Web3PlasmaContract.deploy({data: PlasmaContract.bytecode}).send({from: plasmaOperatorAddress, gas: 6e6}); console.log("Deployed at "+ DeployedPlasmaContract._address); } function jump(duration) { return async function() { var params = duration.split(" "); params[0] = parseInt(params[0]) var seconds = moment.duration.apply(moment, params).asSeconds(); await sendAsyncPromisified({ jsonrpc: "2.0", method: "evm_increaseTime", params: [seconds], id: new Date().getTime() }); } } app.jump = jump; async function prepareOracle(){ await startVM(); await comp(); await deployContracts(); try{ lastBlock = await levelDB.get('lastBlockNumber'); } catch(error) { lastBlock = ethUtil.setLengthLeft(ethUtil.toBuffer(new BN(0)),blockNumberLength) await levelDB.put('lastBlockNumber', lastBlock); } try{ lastBlockHash = await levelDB.get('lastBlockHash'); } catch(error) { lastBlockHash = ethUtil.sha3('bankex.com') await levelDB.put('lastBlockHash', lastBlockHash); } app.txQueueArray = []; app.DeployedPlasmaContract = DeployedPlasmaContract; const processDepositEvent = require('./app/helpers/processDepositEvent')(app, levelDB, web3); const processExpressWithdrawMakeEvent = require('./app/helpers/processExpressWithdrawMadeEvent')(app, levelDB, web3); app.processDepositEvent = processDepositEvent; app.processExpressWithdrawMakeEvent = processExpressWithdrawMakeEvent; require('./app/miner')(app, levelDB, web3); // require('./app/endpoints/fundPlasma')(app, levelDB, web3); // require('./app/endpoints/acceptAndSignTransaction')(app, levelDB, web3); require('./app/endpoints/createTransactionToSign')(app,levelDB,web3); require('./app/endpoints/acceptSignedTX')(app, levelDB, web3); require('./app/endpoints/getBlockByNumber')(app, levelDB, web3); require('./app/endpoints/getTxByNumber')(app, levelDB, web3); require('./app/endpoints/getUTXOsForAddress')(app, levelDB, web3); require('./app/endpoints/getTXsForAddress')(app, levelDB, web3); require('./app/endpoints/getWithdrawsForAddress')(app, levelDB, web3); // require('./app/endpoints/withdraw')(app, levelDB, web3); require('./app/endpoints/auxilary')(app, levelDB, web3); require('./app/endpoints/prepareProofForExpressWithdraw')(app, levelDB, web3); } prepareOracle().then(async (result) => { if (config.useSSL) { const privateKey = fs.readFileSync( 'privatekey.pem' ); const certificate = fs.readFileSync( 'certificate.pem' ); await https.createServer({ key: privateKey, cert: certificate }, app).listen(port); console.log("Live using SSL") console.log('We are live on ' + port); // console.log(config.testAccounts[0]) // console.log(config.testAccounts[1]) console.log("Operator address = " + config.plasmaOperatorAddress); app._router.stack.forEach(function(r){ if (r.name && r.name == 'bound dispatch'){ console.log(r.route.path) } }) } else { app.listen(port, async () => { console.log('We are live on ' + port); // console.log(config.testAccounts[0]) // console.log(config.testAccounts[1]) console.log("Operator address = " + config.plasmaOperatorAddress); app._router.stack.forEach(function(r){ if (r.name && r.name == 'bound dispatch'){ console.log(r.route.path) } }) }) } } )
import React, { PropTypes } from 'react'; import ReactDOM from 'react-dom'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './EditPage.less'; import { getObject } from '../../../../common/common'; import {SuperForm, SuperToolbar, SuperTable2, ModalWithDrag,Title} from '../../../../components'; const TOOLBAR_EVENTS = ['onClick']; const TABLE2_EVENTS = ['onCheck', 'onContentChange']; const defaultSize = 'small'; const props = { title: PropTypes.string, config: PropTypes.object, controls: PropTypes.array, value: PropTypes.object, valid: PropTypes.bool, size: PropTypes.oneOf(['small', 'middle', 'large']), onCancel: PropTypes.func, onOk: PropTypes.func, onChange: PropTypes.func, onSearch: PropTypes.func, onExitValid: PropTypes.func, }; /** * onChange:内容改变时触发,原型func(key, value) * onSearch: search组件搜索时触发,原型为(key, value) */ class EditPage extends React.Component { static propTypes = props; static PROPS = Object.keys(props); getWidth = () => { const {size} = this.props; if (size === 'small') { return 416; } else if (size === 'middle') { return 700; } else if (size === 'large') { return 910; } else { return 520; } }; getProps = () => { const {title, config, onOk, onCancel,isShow} = this.props; let visible = typeof isShow !== 'undefined' ? isShow : true; return { title, onOk, onCancel, width: this.getWidth(), visible: typeof isShow !== 'undefined' ? isShow : true, maskClosable: false, okText: config.ok, cancelText: config.cancel, getContainer: () => ReactDOM.findDOMNode(this).firstChild }; }; getColNumber = () => { if (this.props.size === 'middle' || this.props.size === 'large') { return 3; } else { return 2; } }; // 显示标题 toTitle = (title) => ( <div role={'title'} className={`ant-modal-header ${s.toTitle}`} > <span className={`ant-modal-title ${s.title}`}>{title}</span> </div> ); render() { const {buttons, tableCols, tableItems} = this.props; const subTitle = '通知信息'; const toolbarProps = { buttons, option: {bsSize: 'small'}, callback: getObject(this.props, TOOLBAR_EVENTS) }; const tableProps = { cols: tableCols, items: tableItems, callback: getObject(this.props, TABLE2_EVENTS) }; return ( <div> <div /> <ModalWithDrag {...this.getProps()} > <SuperForm {...this.props} size={defaultSize} colNum={this.getColNumber()} /> <div className={s.root}> <Title title="通知信息"/> <SuperToolbar {...toolbarProps} /> <SuperTable2 {...tableProps} /> </div> </ModalWithDrag> </div> ); } } export default withStyles(s)(EditPage);
import { SET_QUERY, SAVE_QUERY, SEARCH_RESULT_OVERVIEW, SEARCH_LOADING } from "../actions/types"; const initialState = { hotelQuery: { results: [] }, // all the hotels that match searchQuery: null, // the search arguments loading: true }; // ...state = current state export default function(state = initialState, action) { switch (action.type) { case SEARCH_LOADING: return { ...state, loading: true }; case SET_QUERY: return { ...state, hotelQuery: action.payload, loading: false }; case SAVE_QUERY: return { ...state, searchQuery: action.payload, loading: false }; case SEARCH_RESULT_OVERVIEW: //falls to default as we want to return the entire state default: return state; } }
import React from 'react' import renderer from 'react-test-renderer' import { StyleRoot } from '@instacart/radium' import Row from '../Row' it('renders Row correctly', () => { const tree = renderer .create( <StyleRoot> <div> <Row /> </div> </StyleRoot> ) .toJSON() expect(tree).toMatchSnapshot() }) it('renders Row with styles passed in correctly', () => { const tree = renderer .create( <StyleRoot> <div> <Row style={{ color: '#ccc', width: '100%' }} /> </div> </StyleRoot> ) .toJSON() expect(tree).toMatchSnapshot() }) it('renders Row with maxColumns correctly', () => { const tree = renderer .create( <StyleRoot> <div> <Row maxColumns={1} /> <Row maxColumns={2} /> <Row maxColumns={3} /> <Row maxColumns={4} /> <Row maxColumns={5} /> <Row maxColumns={6} /> <Row maxColumns={7} /> <Row maxColumns={8} /> <Row maxColumns={9} /> <Row maxColumns={10} /> <Row maxColumns={11} /> <Row maxColumns={12} /> <Row maxColumns={13} /> <Row maxColumns={14} /> </div> </StyleRoot> ) .toJSON() expect(tree).toMatchSnapshot() }) it('renders Row with styles and maxColumns passed in correctly', () => { const tree = renderer .create( <StyleRoot> <div> <Row maxColumns={1} style={{ color: '#ccc', width: '100%' }} /> <Row maxColumns={6} style={{ color: '#ccc', width: '100%' }} /> <Row maxColumns={10} style={{ color: '#ccc', width: '100%' }} /> </div> </StyleRoot> ) .toJSON() expect(tree).toMatchSnapshot() }) it('renders Row with styles, maxColumns and forceFullPage passed in correctly', () => { const tree = renderer .create( <StyleRoot> <div> <Row forceFullPage maxColumns={8} /> <Row forceFullPage style={{ color: '#ccc', width: '100%' }} /> <Row forceFullPage maxColumns={10} style={{ color: '#ccc', width: '100%' }} /> </div> </StyleRoot> ) .toJSON() expect(tree).toMatchSnapshot() })
import React, { useEffect } from 'react' import { BrowserRouter, Switch, Route } from 'react-router-dom' import LoginPage from '../Pages/Login' import { useSelector, useDispatch } from 'react-redux' import MainView from '../Pages/MainView' import DashboardPage from '../Pages/Dashboard' import OffersPage from '../Pages/History/OffersPage' import api from '../Services/api' import { notification } from 'antd' import Cookie from 'js-cookie' import TradesPage from '../Pages/History/TradesPage' import UpdatersSettingsPage from '../Pages/Settings/UpdatersSettings' import FeesSettingsPage from '../Pages/Settings/FeesSettings' import WatsonSettingsPage from '../Pages/Settings/WatsonSettings' const Routes = () => { const userData = useSelector(state => state.User) const dispatch = useDispatch() const changeUserData = data => { dispatch({ type: 'CHANGE_USER_DATA', User: data }) } const checkLogged = () => { if (userData.loading === true) api .get('/users/me') .then(() => { if (window.location.pathname === '/') window.location.replace('/dashboard') notification.success({ message: 'You were already logged in!' }) changeUserData({ ...userData, loading: false, logged: true }) }) .catch(() => { Cookie.remove('jwt-token') if (window.location.pathname !== '/login') window.location.replace('/login') changeUserData({ ...userData, loading: false, logged: false }) }) } useEffect(checkLogged, []) return ( <BrowserRouter> <Switch> {userData.logged ? ( <MainView> <Route exact path='/dashboard' component={DashboardPage} /> <Route exact path='/history/offers' component={OffersPage} /> <Route exact path='/history/trades' component={TradesPage} /> <Route exact path='/settings/updaters' component={UpdatersSettingsPage} /> <Route exact path='/settings/fees' component={FeesSettingsPage} /> <Route exact path='/settings/ibm-watson' component={WatsonSettingsPage} /> </MainView> ) : ( <Route exact path='/login' component={LoginPage} /> )} </Switch> </BrowserRouter> ) } export default Routes
import React from "react"; import ReactDOM from "react-dom"; class Layout extends React.Component { constructor (props) { super(props); this.state = { joke: [] }; } fetchMusic () { fetch('https://api.chucknorris.io/jokes/random?category=music') .then(results => { return results.json(); }) .then(data => { let music = [<p>{data.value}</p>]; this.setState({music:music}); }); } fetchMovie () { fetch('https://api.chucknorris.io/jokes/random?category=movie') .then(results => { return results.json(); }) .then(data => { let movie = [<p>{data.value}</p>]; this.setState({movie:movie}); }); } fetchCelebrity () { fetch('https://api.chucknorris.io/jokes/random?category=celebrity') .then(results => { return results.json(); }) .then(data => { let celebrity = [<p>{data.value}</p>]; this.setState({celebrity:celebrity}); }); } fetchScience () { fetch('https://api.chucknorris.io/jokes/random?category=science') .then(results => { return results.json(); }) .then(data => { let science = [<p>{data.value}</p>]; this.setState({science:science}); }); } fetchSport () { fetch('https://api.chucknorris.io/jokes/random?category=sport') .then(results => { return results.json(); }) .then(data => { let sport = [<p>{data.value}</p>]; this.setState({sport:sport}); }); } fetchFashion () { fetch('https://api.chucknorris.io/jokes/random?category=fashion') .then(results => { return results.json(); }) .then(data => { let fashion = [<p>{data.value}</p>]; this.setState({fashion:fashion}); }); } fetchMoney () { fetch('https://api.chucknorris.io/jokes/random?category=money') .then(results => { return results.json(); }) .then(data => { let money = [<p>{data.value}</p>]; this.setState({money:money}); }); } fetchCareer () { fetch('https://api.chucknorris.io/jokes/random?category=career') .then(results => { return results.json(); }) .then(data => { let career = [<p>{data.value}</p>]; this.setState({career:career}); }); } fetchAnimal () { fetch('https://api.chucknorris.io/jokes/random?category=animal') .then(results => { return results.json(); }) .then(data => { let animal = [<p>{data.value}</p>]; this.setState({animal:animal}); }); } fetchTravel () { fetch('https://api.chucknorris.io/jokes/random?category=travel') .then(results => { return results.json(); }) .then(data => { let travel = [<p>{data.value}</p>]; this.setState({travel:travel}); }); } fetchPolitical () { fetch('https://api.chucknorris.io/jokes/random?category=political') .then(results => { return results.json(); }) .then(data => { let politic = [<p>{data.value}</p>]; this.setState({politic:politic}); }); } fetchRandom () { fetch('https://api.chucknorris.io/jokes/random') .then(results => { return results.json(); }) .then(data => { let joke = [<p>{data.value}</p>]; this.setState({joke:joke}); }); } render () { return ( <div className="container-fluid"> <div className="row top"> <div className="col-md-12 text-center "> <h2>{this.state.joke}{this.state.music}{this.state.politic}{this.state.travel}{this.state.animal}{this.state.career}{this.state.money}{this.state.fashion}{this.state.sport}{this.state.science}{this.state.celebrity}{this.state.movie}</h2> </div> </div> <div className="row "> <div className="col-md-2"> <button onClick={() => this.fetchMusic()} className="button red"><p>Music</p> <span className="button2">Click Me!</span> </button> </div> <div className="col-md-2"> <button onClick={() => this.fetchRandom()} className="button red"><p>Random</p> <span className="button2">Click Me!</span> </button> </div> <div className="col-md-2"> <button onClick={() => this.fetchMovie()} className="button red"><p>Movies</p> <span className="button2">Click Me!</span> </button> </div> <div className="col-md-2"> <button onClick={() => this.fetchCelebrity()} className="button red"><p>Celebrity</p> <span className="button2">Click Me!</span> </button> </div> <div className="col-md-2"> <button onClick={() => this.fetchScience()} className="button red"><p>Science</p> <span className="button2">Click Me!</span> </button> </div> <div className="col-md-2"> <button onClick={() => this.fetchSport()} className="button red"><p>Sport</p> <span className="button2">Click Me!</span> </button> </div> </div> <div className="row mt"> <div className="col-md-2"> <button onClick={() => this.fetchFashion()} className="button red"><p>Fashion</p> <span className="button2">Click Me!</span> </button> </div> <div className="col-md-2"> <button onClick={() => this.fetchMoney()} className="button red"><p>Money</p> <span className="button2">Click Me!</span> </button> </div> <div className="col-md-2"> <button onClick={() => this.fetchCareer()} className="button red"><p>Career</p> <span className="button2">Click Me!</span> </button> </div> <div className="col-md-2"> <button onClick={() => this.fetchAnimal()} className="button red"><p>Animal</p> <span className="button2">Click Me!</span> </button> </div> <div className="col-md-2"> <button onClick={() => this.fetchTravel()} className="button red"><p>Travel</p> <span className="button2">Click Me!</span> </button> </div> <div className="col-md-2"> <button onClick={() => this.fetchPolitical()} className="button red"><p>Political</p> <span className="button2">Click Me!</span> </button> </div> </div> </div> ); } } const app = document.getElementById('app'); ReactDOM.render(<Layout />, app);
import React from 'react'; const FeaturesModal = ({ modal, modalTitle }) => ( <div className="modal fade" id="modalCenter" tabIndex="-1" role="dialog" aria-labelledby="modalCenterTitle" aria-hidden="true"> <div className="modal-dialog modal-dialog-centered modal-lg" role="document"> <div className="modal-content rounded-0 bg-dark text-light shadow"> <div className="modal-header border-bottom border-danger"> <h5 className="modal-title text-uppercase font-weight-light" id="modalCenterTitle">{modalTitle}</h5> <button type="button" className="close text-light" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div className="modal-body"> <img className="img-fluid" src={modal} alt="##" /> </div> </div> </div> </div> ); export default FeaturesModal;
import { Card, Button, Form } from 'react-bootstrap' export const EditDemo = () => { return ( <Card> <Card.Body> <Card.Title>Edit Demo</Card.Title> <Card.Text> <Form> <Form.Group className="mb-3" controlId="formBasicName"> <Form.Label>Name</Form.Label> <Form.Control type="email" placeholder="Enter name" /> <Form.Text className="text-muted"> Demo stuff :) </Form.Text> </Form.Group> <Button variant="primary"> Submit </Button> </Form> </Card.Text> </Card.Body> </Card> ) }
const express = require("express"); const router = express.Router(); /** * Express router for /toppic * * Render a toppic task configure web page back to user */ const toppic = router.get('/toppic', function (req, res) { if (req.session.passport === undefined) { res.write("Please log in first to use topic for your projecct"); res.end(); } else { // console.log(req.session.passport); // console.log(req.query.projectCode); let projectCode = req.query.projectCode; if (!projectCode) { res.write("No project selected for this topic task."); return; } else { res.render('pages/topicTask', { projectCode }); } } }); module.exports = toppic;
// pages/note/note.js Page({ /** * 页面的初始数据 */ data: { list:[], }, properties: { // list: { // type: Object, // value: [] // }, }, detail:function(e){ console.log(JSON.stringify(e.currentTarget.dataset)) wx.navigateTo({ url: './detail?id=' + e.currentTarget.dataset.id, }) }, isEmpty(str){ return str==null || str==undefined || str==''; }, getMinString(str, min){ let dot = ''; if(str.length>min){ dot = '...'; } return this.isEmpty(str) ? '' : str.substring(0, min) + dot; }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { this.selectComponent('#list').init(this.getList) // this.getList(); }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, getList(currentPage, pageCount) { var tmpList = []; tmpList.push({ id: 0, title: '又会从后台进入前台又会从后台进入前台又会从后台进入前台又会从后台进入前台又会从后台进入前台', content: '又会从后台进入前台又会从后台进入前台又会从后台进入前台又会从后台进入前台', date: '2018年02月07日', folder: '好长好长的笔记本好长好长的笔记本', }); let tmp = this.data.list.length == 0 ? 10 : 5; console.log(tmp) for (let i = 1; i < tmp;i++){ tmpList.push({ id: i, title: 't' + i, content: 'c' + i, date: 'd' + i, folder: 'f' + i, }) } tmpList.forEach((element) => { element.tempTitle = this.getMinString(element.title, 9); element.tempContent = this.getMinString(element.content, 32); element.tempFolder = this.getMinString(element.folder, 11); }) //this.data.list.length == 0 ? tmpList : this.data.list.concat(tmpList) this.setData({ list: currentPage == 1 ? tmpList : this.data.list.concat(tmpList) }); console.log(this.data.list) this.selectComponent('#list').loadSuccess({ total: 15, currentSize: this.data.list.length, nextPage: 2 }) }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { console.log("onPullDownRefresh", this.selectComponent('#list')) this.selectComponent('#list').refresh() }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { console.log("onReachBottom", this.selectComponent('#list')) this.selectComponent('#list').loadMore() }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })
var dom = localStorage.getItem("dom"); document.getElementById("status").textContent = dom;
import { render, screen, cleanup, act, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import axios from "axios"; import DeleteTodoBtn from "../../components/DeleteTodoBtn"; describe("DeleteTodoBtn", () => { beforeEach(() => { axios.delete = jest.fn((url, body) => { return Promise.resolve({ data: { success: false, message: "Invalid id" }, }); }); }); afterEach(cleanup); it("Should render with proper styling", () => { render(<DeleteTodoBtn />); const deleteBtn = screen.getByRole("button"); expect(deleteBtn).toBeInTheDocument(); expect(deleteBtn.innerHTML).toMatch("X"); expect(deleteBtn).toHaveClass("bg-red-500 hover:bg-red-600 button"); }); it("Should call api delete on click", () => { for (let i = 1; i <= 5; i++) { render(<DeleteTodoBtn id={i} />); let deleteBtn = screen.getByRole("button"); act(() => { userEvent.click(deleteBtn); }); expect(axios.delete).toBeCalledTimes(i); expect(axios.delete.mock.calls[i - 1][0]).toBe(`/api/v1/todos/${i}`); cleanup(); } }); it("Should call API only once after excessive clicking", () => { render(<DeleteTodoBtn id={1} />); let deleteBtn = screen.getByRole("button"); act(() => { for (let i = 0; i < 5; i++) { userEvent.dblClick(deleteBtn); } }); expect(axios.delete).toBeCalledTimes(1); expect(axios.delete.mock.calls[0][0]).toBe(`/api/v1/todos/${1}`); }); });
jest.dontMock('../List.react'); describe('List Component', function() { it('counts up or down in increments of 1 or 5', function() { var React = require('react/addons'); var ListComponent = require('../List.react'); var TestUtils = React.addons.TestUtils; var initItems = ['Welcome', 'to', 'React']; var list = TestUtils.renderIntoDocument( <ListComponent items={initItems} /> ); // Test list exists var ul = TestUtils.findRenderedDOMComponentWithTag(list, 'ul'); expect(ul).toBeDefined() // Test each item in items is appened to DOM initItems.forEach(function(item) { var node = TestUtils.findRenderedDOMComponentWithClass(list, item); expect(node.getDOMNode().textContent).toEqual(item); }); }); });
const chart = (state=[], action) => action.type === `SET_CHART` ? action.payload : state; export default chart;
import React, { Component } from "react" import Playlist from "./Playlist.jsx" import NewPlaylistModal from './NewPlaylistModal.jsx' import './playlist.css' export default class PlaylistsView extends Component { render() { return ( <React.Fragment> <div className="d-flex playlistTitle sticky-top"> <h1 className="display-4" >Playlists</h1> {/* Modal */} <NewPlaylistModal addPlaylist={this.props.addPlaylist} handleFieldChange={this.props.handleFieldChange}/> </div> {this.props.playlists.map(playlist =>{ return <Playlist key={playlist.id} passedState = {this.props.passedState} playlist = {playlist} songsIds = {playlist.songs_playlists} songs={this.props.songs} addSongToPlaylist={this.props.addSongToPlaylist} removeSongFromPlaylist={this.props.removeSongFromPlaylist} removePlaylist={this.props.removePlaylist} editTitleButton={this.props.editTitleButton} editTitleBackButton={this.props.editTitleBackButton} editPlaylistTitle={this.props.editPlaylistTitle} handleFieldChange={this.props.handleFieldChange} displayStringAsHTML={this.props.displayStringAsHTML} moveSongUp = {this.props.moveSongUp} moveSongDown = {this.props.moveSongDown} deleteSongFromPlaylist={this.props.deleteSongFromPlaylist}/> })} </React.Fragment> ) } }
var $document = $(document); $document.ready(function() { initClipboard() $('.btn-down:contains(百度离线)').on('click',function(){ var self = this var toURL= 'http://pan.baidu.com/disk/home' doCopy() openPage(toURL) // initTour() }) $('.btn-down:contains(百度云盘)').on('click',function(){ var self = this var toURL= $('#link').val() if($('#btn-copy:contains("复制密码")').size() > 0){ doCopy() window.open(toURL) } else { window.location.href = toURL } }) $('.btn-down:contains(迅雷离线)').on('click',function(){ var self = this var toURL= 'http://lixian.xunlei.com/xl9/space.html' doCopy() openPage(toURL) }) $('.btn-down:contains(迅雷下载)').on('click',function(){ var self = this var toURL= $('#link').val() var toURL = urlcodesc.encode(toURL, "thunder"); window.location.href = toURL }) $('.btn-down:contains(磁力播放)').on('click',function(){ var self = this var $postVideo = $('#post-video'); if ($postVideo.attr('class') == 'post-video-display') { $postVideo.attr('class', 'post-video') $postVideo.click() $('#loading').show(); // var scriptEle = document.createElement("script"); // scriptEle.src = "/assets/js/btstream.js" // $("#post-video").append(scriptEle) } }) if(/\/movie\/torrent\/b[0-9]+\.html$/.test(location.pathname) && $('#btn-copy:contains("复制密码")').size() < 1){ $('.btn-down:contains(百度云盘)').click() } }); function openPage(toURL){ if (isMobile()) { window.location.href = toURL } else { window.open(toURL) } } function isMobile(){ return /^\/m\/movie/.test(location.pathname) } function doCopy(){ $('#btn-copy').select().click() } function initClipboard(){ var btnClips = document.querySelectorAll('.btn-clipboard'); for (var i = 0; i < btnClips.length; i++) { btnClips[i].addEventListener('mouseleave', clearTooltip); btnClips[i].addEventListener('blur', clearTooltip); } function clearTooltip(e) { if(!e.currentTarget) { return false } var target = e.currentTarget; var sLabel = target.getAttribute('aria-label') if(!sLabel) { return false } var sCls = target.getAttribute('class') sCls = sCls.replace(/tooltipped[-a-zA-Z]*/g,'') e.currentTarget.setAttribute('class', sCls); e.currentTarget.removeAttribute('aria-label'); } function showTooltip(elem, msg) { elem.setAttribute('class', 'btn-clipboard tooltipped tooltipped-s'); elem.setAttribute('aria-label', msg); } var tClipboard = new Clipboard('.btn-clipboard'); tClipboard.on('success', function(e) { e.clearSelection(); showTooltip(e.trigger, '复制成功'); }); tClipboard.on('error', function(e) { e.clearSelection(); showTooltip(e.trigger, '复制失败'); }); } function initTour(){ var tour = new Tour({ name: "tour", steps: [], container: "body", smartPlacement: true, keyboard: true, storage: window.localStorage, debug: false, backdrop: false, backdropContainer: 'body', backdropPadding: 0, redirect: true, orphan: false, duration: false, delay: false, basePath: "", template: '<div class="popover tour-tour tour-tour-1 fade top in" role="tooltip" id="step-1" style="top: 334.85px; left: 502px; display: block;"> <div class="arrow" style="left: 50%;"></div><div class="popover-content">Easy is better, right? The tour is up and running with just a few options and steps.</div> <div class="popover-navigation"> <div class="btn-group"> <button class="btn btn-sm btn-default" data-role="prev">« Prev</button> <button class="btn btn-sm btn-default" data-role="next">Next »</button> </div> <button class="btn btn-sm btn-default" data-role="end">End tour</button> </div> </div>', afterGetState: function (key, value) {}, afterSetState: function (key, value) {}, afterRemoveState: function (key, value) {}, onStart: function (tour) {}, onEnd: function (tour) {}, onShow: function (tour) {}, onShown: function (tour) {}, onHide: function (tour) {}, onHidden: function (tour) {}, onNext: function (tour) {}, onPrev: function (tour) {}, onPause: function (tour, duration) {}, onResume: function (tour, duration) {}, onRedirectError: function (tour) {} }); tour.addStep({ element: "#btn-copy", placement: "right", title: "第一步", content: "①复制资源链接" }) tour.addStep({ element: "#btn-list", placement: "bottom", title: "第二步", content: "②获取资源" }) console.log('init.......') // Initialize the tour tour.init(); console.log('start.......') // Start the tour tour.start(true); }
describe('standard.lang', () => { test.todo('Atributo value retorna a lang corrente') test.todo('Metodo setValue define uma nova linguagem') })
var os = require('os'), getIP = require('external-ip')(), ip = '127.0.0.1', accounts = {}; var stats = { setAccounts: function (accs) { accounts = accs; }, sendStats: function (socket) { if (ip == '127.0.0.1') { setTimeout(function () { stats.sendStats(socket); }, 100); return; } socket.emit('server.update', { uid: os.hostname()+"@"+ip, ip: ip, hostname: os.hostname(), freemem: os.freemem(), totalmem: os.totalmem(), usedmem: os.totalmem() - os.freemem(), loadavg: os.loadavg(), accounts: accounts }); }, getUID: function (callback) { if (ip == '127.0.0.1') { setTimeout(function () { stats.getUID(callback); }, 100); return; } callback(stats.getUIDSync()); }, getUIDSync: function () { return os.hostname()+"@"+ip; } }; getIP(function (err, ip2) { if (err) { throw err; } ip = ip2; }); module.exports = stats;
import styled from "styled-components"; const CalendarTitleStyled = styled.h3` font-family: Montserrat; font-style: normal; font-weight: 600; font-size: 16px; line-height: 24px; text-align: center; color: #5b5b5b; `; const CalendarWrapper = styled.div` display:flex; flex-direction:row; justify-content: space-between; align-items: center; `; export {CalendarTitleStyled ,CalendarWrapper};
import React from 'react'; import { useHistory } from 'react-router-dom'; import styled from 'styled-components'; const StyledDiv = styled.div` color: red; padding: 20px; `; const BackButton = styled.button` display: flex; align-self: baseline; padding: 5px; background: transparent; border: 1px solid #ccc; border-radius: 3px; `; const NotFoundPage = () => { const history = useHistory(); return ( <> <BackButton onClick={() => history.push('/teams')}>Back to Table</BackButton> <StyledDiv>Page Not Found</StyledDiv> </> ) }; export default NotFoundPage;
// Generated by CoffeeScript 1.10.0 (function() { var PDFDocument, doc; PDFDocument = require('pdfkit'); doc = new PDFDocument; doc.pipe(fs.createWriteStream('output.pdf')); doc.font('fonts/PalatinoBold.ttf').fontSize(25).text('Some text with an embedded font!', 100, 100); doc.addPage().fontSize(25).text('Here is some vector graphics...', 100, 100); doc.save().moveTo(100, 150).lineTo(100, 250).lineTo(200, 250).fill("#FF3300"); doc.scale(0.6).translate(470, -380).path('M 250,75 L 323,301 131,161 369,161 177,301 z').fill('red', 'even-odd').restore(); doc.addPage().fillColor("blue").text('Here is a link!', 100, 100).underline(100, 100, 160, 27, { color: "#0000FF" }).link(100, 100, 160, 27, 'http://google.com/'); doc.end(); }).call(this);
import React, { Component } from 'react' import axios from 'axios' import Pagination from '../Pagination/Pagination'; import Rating from '../../Rating/Rating' import { connect } from 'react-redux' import { addCpu } from '../../../Ducks/Reducer' import { withRouter,Link } from 'react-router-dom' class CpuTable extends Component { constructor(props){ super(props) this.state = { cpu:[], currentCpus:[], filteredCpus:[], currentPage:null, totalPages:null, asc: 'desc', } } componentDidMount(){ axios.get('/api/cpu').then(res=>{ this.setState({cpu:res.data}) }) } onPageChanged = data => { const {cpu} = this.state const { currentPage, totalPages, pageLimit} = data const offSet = (currentPage - 1) * pageLimit const currentCpus = cpu.slice(offSet, offSet + pageLimit) this.setState({currentPage, currentCpus, totalPages}) } compareValues(key, order='asc') { return function(a, b) { if(!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) { // property doesn't exist on either object return 0; } const varA = (typeof a[key] === 'string') ? a[key].toUpperCase() : a[key]; const varB = (typeof b[key] === 'string') ? b[key].toUpperCase() : b[key]; let comparison = 0; if (varA > varB) { comparison = 1; } else if (varA < varB) { comparison = -1; } return ( (order === 'desc') ? (comparison * -1) : comparison ); }; } compareNums(key,order = 'asc'){ return function(a,b){ let comparison = 0; let varA = parseInt(a[key]) ? parseInt(a[key]) : 0 let varB = parseInt(b[key]) ? parseInt(b[key]) : 0 if(varA > varB){ comparison = 1; }else if(varA < varB){ comparison = -1 } return ( (order === 'desc') ? (comparison * -1) : comparison ) } } sortBy(key, type) { let arrayCopy = [...this.state.currentCpus]; arrayCopy.sort(this.compareValues(key, type)); this.state.asc === 'asc' ? this.setState({asc:'desc'}) : this.setState({asc:'asc'}) this.setState({currentCpus: arrayCopy}); } sortByNum(key, type){ let arrayCopy = [...this.state.currentCpus] arrayCopy.sort(this.compareNums(key, type)) this.state.asc === 'asc' ? this.setState({asc:'desc'}) : this.setState({asc:'asc'}) this.setState({currentCpus: arrayCopy}) } addCpu(id){ this.props.addCpu(id) this.props.history.push('/list') } componentDidUpdate(prevProps){ console.log(prevProps, this.props.cores) if(prevProps.cores !== this.props.cores){ this.setState({filteredCpus:this.state.cpu.filter(e=>e.cores === this.props.cores)}) } } render() { console.log(this.state.filteredCpus) const { cpu, } = this.state; const totalCpus = cpu.length; if (totalCpus === 0) return null; return ( <div> <table className='table'> <thead className='table-head'> <tr> <th>&nbsp;</th> <th className='table-th' onClick={()=>this.sortBy('cpuname', this.state.asc)}> <p>CPU</p> <div> <span className='fa fa-angle-down angle-down'></span> <span className='fa fa-angle-up angle-up'></span> </div> </th> <th onClick={()=>this.sortBy('operatingfrequency', this.state.asc)}> <p>Speed</p> <div> <span className='fa fa-angle-down angle-down'></span> <span className='fa fa-angle-up angle-up'></span> </div> </th> <th onClick={()=>this.sortByNum('cores', this.state.asc)}> <p>Cores</p> <div> <span className='fa fa-angle-down angle-down'></span> <span className='fa fa-angle-up angle-up'></span> </div> </th> <th onClick={()=>this.sortByNum('thermaldesignpower', this.state.asc)}> <p>TDP</p> <div> <span className='fa fa-angle-down angle-down'></span> <span className='fa fa-angle-up angle-up'></span> </div> </th> <th> <p>Rating</p> <div> <span className='fa fa-angle-down angle-down'></span> <span className='fa fa-angle-up angle-up'></span> </div></th> <th> <p>Price</p> <div> <span className='fa fa-angle-down angle-down'></span> <span className='fa fa-angle-up angle-up'></span> </div></th> <th>&nbsp;</th> </tr> </thead> <tbody className='table-body'> { this.props.cores !== undefined ? this.state.filteredCpus.map(e=>{ return ( <tr key={e.cpu_id}> <td><input type="checkbox"/></td> <td> <Link to={`cpu/${e.cpu_id}`}> {e.cpuname} </Link> </td> <td>{e.operatingfrequency}</td> <td>{e.cores}</td> <td>{e.thermaldesignpower}</td> <td> <Rating/> </td> <td> </td> <td> <button onClick={()=>this.addCpu(e.cpu_id)}>Add</button> </td> </tr> ) }) : this.state.currentCpus.map(e=>{ return ( <tr key={e.cpu_id}> <td><input type="checkbox"/></td> <td> <Link to={`cpu/${e.cpu_id}`}> {e.cpuname} </Link> </td> <td>{e.operatingfrequency}</td> <td>{e.cores}</td> <td>{e.thermaldesignpower}</td> <td> <Rating/> </td> <td> </td> <td> <button onClick={()=>this.addCpu(e.cpu_id)}>Add</button> </td> </tr> ) }) } </tbody> </table> <div> <Pagination totalRecords={totalCpus} pageLimit={50} pageNeighbours={1} onPageChanged={this.onPageChanged} /> </div> </div> ) } } function mapState(state){ let {list} = state return { list } } export default withRouter(connect(mapState, {addCpu})(CpuTable))
let webpack = require('webpack'); //let deepScope = require('webpack-deep-scope-plugin').default; let path = require('path'); let package = require('./package.json'); module.exports = (env, argv) => { let nodeTarget = { target: "node", entry: "./src/index.ts", mode: argv.mode || 'development', output: { path: path.resolve(__dirname, 'dist'), filename: 'pouchdb.relational-pouch.node.js', libraryTarget: 'commonjs2', libraryExport: 'default', }, externals: Object.keys(package.dependencies), plugins: [ ], module: { rules: [ { test: /\.m?[jt]s$/, exclude: /(node_modules|bower_components)/, use: [ { loader: 'babel-loader', options: { presets: [ ['@babel/preset-env', { "targets": { "node": "10" }, "modules": false, useBuiltIns: "usage", corejs: 3, }], ], }, }, { loader: 'ts-loader', options: { transpileOnly: true, experimentalWatchApi: true, }, }, ], } ] }, resolve: { extensions: ['tsx', '.ts', '.js', '.json'], }, // externals: [ // function(context, request, callback) { // if (/^http-debug$/.test(request)){ // return callback(null, 'commonjs ' + request); // } // callback(); // }, // ], }; let webTarget = { target: "web", entry: "./src/browser.ts",//TODO: this file could be exluded in tsc to not generate dist/browser.* mode: argv.mode || 'development', // stats: 'verbose', output: { path: path.resolve(__dirname, 'dist'), filename: 'pouchdb.relational-pouch.browser.js', libraryTarget: 'umd', }, plugins: [ ], module: { rules: [ { test: /\.m?[jt]s$/, exclude: /(node_modules|bower_components)/, use: [ { loader: 'babel-loader', options: { presets: [ ['@babel/preset-env', { "targets": ">2%, not ie 11", "modules": false, useBuiltIns: "usage", corejs: 3, }], ], }, }, { loader: 'ts-loader', options: { transpileOnly: true, experimentalWatchApi: true, }, }, ], } ] }, resolve: { extensions: ['tsx', '.ts', '.js', '.json'], }, // externals: [ // function(context, request, callback) { // if (/^http-debug$/.test(request)){ // return callback(null, 'commonjs ' + request); // } // callback(); // }, // ], }; var doSourcemapping = argv.mode != 'production';//also needs a change in run.js if (doSourcemapping) { webTarget.devtool = 'source-map';//'inline-source-map', nodeTarget.devtool = 'source-map'; } return [webTarget, nodeTarget,]; };
import { AsyncStorage } from "react-native"; import Orientation from 'react-native-orientation'; import React, { Component } from 'react'; import { AppRegistry, Image, StatusBar } from "react-native"; import { Button, Text, Container, List, ListItem, Content, Icon, Left, Body, Right } from "native-base"; const routes = ["خانه","موزه چندرسانه ای","پیام ها","درباره ما","اطلاعات","خروج"]; const pages = ["Homeindex","QRcamera2","mynews","aboutUs","myProfile","Login"]; const num = ["0","1","2","3","4","5"]; const icons = ["home","md-qr-scanner","megaphone","ios-contacts","person","ios-arrow-back"] export default class Side333Bar extends React.Component { componentDidMount() { Orientation.lockToPortrait(); } render() { return ( <Container> <Content> <Image style={{ height: 120, width: "100%", alignSelf: "stretch", position: "absolute" }} source={{uri : "https://khaterat.mobi/js/cover.png"}} /> <Image square style={{ height: 80, width: 70, position: "absolute", alignSelf: "center", top: 20 }} source={{uri : 'https://khaterat.mobi/js/web/TextLogo.png'}} /> <List dataArray={num} contentContainerStyle={{ marginTop: 120 }} renderRow={num => { return ( <ListItem style = {{ height:80 , alignContent:"flex-end",justifyContent:"flex-end",textAlign:"right",alignItems:"flex-end"}} button onPress={() => {if(pages[num] =="Login"){ try { AsyncStorage.setItem('key:Token',''); } catch (error) { // Error saving data } }this.props.navigation.navigate(pages[num])}} > <Left><Icon style = {{justifyContent:"flex-start",textAlign:"left",alignItems:"flex-start"}} name={icons[num]}/></Left> <Right><Text style = {{justifyContent:"flex-end",textAlign:"right",alignItems:"flex-end" , width: 120}}>{routes[num]}</Text></Right> </ListItem> ); }} /> </Content> </Container> ); } }
const sizes = { phoneMini: '320px', phoneSmall: '360px', phone: '375px', phoneWide: '384px', phablet: '414px', tabletSmall: '480px', tablet: '640px', tabletWide: '750px', desktop: '900px', desktopWide: '1200px', } export const media = { phone: `(min-width: ${sizes.phoneMini}`, phoneMini: `(min-width: ${sizes.phoneMini})`, phoneSmall: `(min-width: ${sizes.phoneSmall})`, phoneWide: `(min-width: ${sizes.phoneWide})`, phablet: `(min-width: ${sizes.phablet})`, tablet: `(min-width: ${sizes.tabletSmall})`, tabletSmall: `(min-width: ${sizes.tabletSmall})`, tabletWide: `(min-width: ${sizes.tabletWide})`, desktop: `(min-width: ${sizes.desktop})`, desktopWide: `(min-width: ${sizes.desktopWide})`, }
function startTimer(duration, display) { var timer = duration, minutes, seconds; setInterval(function () { minutes = parseInt(timer / 60, 10); seconds = parseInt(timer % 60, 10); minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds; document.getElementById("timer").innerHTML = "Dirija-se ao caixa em no máximo "+minutes+" : "+seconds; if (--timer < 0) { window.location="timeout.html"; } }, 1000); } window.onload = function () { var time = 60 * 1, display = document.querySelector('#time'); startTimer(time, display); }; var chave = parent.document.URL.substring(parent.document.URL.indexOf('myVar=') + 6, parent.document.URL.length); firebase.database().ref('/').once("value") .then(function(snapshot) { var firstName = snapshot.child("caixas/caixa_1/caixa").val(); // "Ada" var firstname2 = snapshot.child("caixas/caixa_2/caixa").val(); // "Ada" var caixa1 = snapshot.child("caixas/caixa_1/itemKey").val(); if (caixa1 == chave){ document.getElementById("caixa").innerHTML = 1; }else{ document.getElementById("caixa").innerHTML = 2; } }); function verificarUserNoCaixa (snapshot) { var valorFila; var pertence = true; var caixa1; var caixa2; var id; var userDict; firebase.database().ref('caixas/').once("value", function(snapshot) { userDict = snapshot.val(); console.log(userDict); caixa1 = Object.keys(userDict)[0]; id = snapshot.child(caixa1).val().itemKey; // "Ada" if (chave != id){ pertence = false; } console.log(caixa1 + id); }); firebase.database().ref('caixas/').once("value", function(snapshot) { userDict = snapshot.val(); console.log(userDict); caixa2 = Object.keys(userDict)[1]; id = snapshot.child(caixa1).val().itemKey; // "Ada" console.log(caixa2 + id); if (chave != id){ pertence = false } }); if (pertence == false){ window.location="filaclientefim.html"; console.log("sai da fila"); } else { console.log("to na fila ainda"); } } firebase.database().ref('caixas/').on('child_changed', verificarUserNoCaixa);
var React = require('react'); module.exports = () => ( <div> <h1 className="text-center page-title">About</h1> <div className="callout"> <p> This is a weather application build on React. I have build it for <b>The Complete React Web App Developer Course</b>. </p> <p> Here are a some of the tools is used: </p> </div> <div className="stacked button-group"> <a href="https://github.com/polakj/ReactWeather" className="button">GitHub project page</a> <a href="https://facebook.github.io/react/" className="button">React documentation</a> <a href="http://foundation.zurb.com/index.html" className="button">Foundation documentation</a> <a href="http://openweathermap.org/" className="button">OpenWeatherMap </a> </div> </div> );
const setTime = (val) => { var y = val.split('-')[0]; var m = val.split('-')[1]; var dhms = val.split('-')[2]; var d = dhms.split('T')[0]; return( y+'/'+m+'/'+'/'+d ) }; export { setTime };
import React from "react"; import styled from "styled-components"; import Title from "../../atoms/Title/Title"; import ProductInfo from "../../molecules/ProductInfo/ProductInfo"; const StyledWrapper = styled.div` padding: 2rem 0.5rem; @media (min-width: 768px) { padding: 2rem 4rem; } `; const StyledFlexWrapper = styled.div` display: flex; flex-wrap: wrap; @media (min-width: 1280px) { margin: 3rem 0; flex-wrap: nowrap; justify-content: space-between; } `; const StyledImg = styled.img` width: 100%; border: 2px solid grey; @media (min-width: 1280px) { width: 40%; height: 60vh; } `; const StyledProductInfo = styled(ProductInfo)` margin: 3rem 0; `; const ProductDetails = ({ category, name, price, img, description, productID, }) => ( <StyledWrapper> <Title small>{name}</Title> <StyledFlexWrapper> <StyledImg src={`data:image/jpeg;base64,${img}`}></StyledImg> <StyledProductInfo category={category} name={name} price={price} img={img} description={description} productID={productID} /> </StyledFlexWrapper> </StyledWrapper> ); export default ProductDetails;
`use strict`; const tabsNav = document.querySelector('.tabs-nav'); const tabsContent = document.querySelector('.tabs-content'); const tabClone = tabsNav.firstElementChild.cloneNode(true); tabsNav.removeChild(tabsNav.firstElementChild); const articles = Array.from(document.getElementsByTagName('article')); for(let article of articles) { let newTab = tabClone.cloneNode(true); newTab.firstElementChild.classList.add(`${article.dataset.tabIcon}`); newTab.firstElementChild.textContent = article.dataset.tabTitle; tabsNav.appendChild(newTab); } let items = Array.from(tabsContent.children); let currentItem = items[0]; for(let item of items) { if(item !== currentItem) { item.classList.add('hidden'); } } const tabs = Array.from(tabsNav.getElementsByTagName('li')); let currentTab = tabs[0]; currentTab.classList.add('ui-tabs-active'); for(let tab of tabs) { tab.addEventListener('click', function() { currentTab.classList.remove('ui-tabs-active'); currentTab = tab; currentTab.classList.add('ui-tabs-active'); if(!tab.firstElementChild.classList.contains(`${currentItem.dataset.tabIcon}`)) { currentItem.classList.add('hidden'); for(item of items) { if(tab.firstElementChild.classList.contains(`${item.dataset.tabIcon}`)) { currentItem = item; currentItem.classList.remove('hidden'); } } } }) }
Citations.insert = function(userId, citation, auteur) { var set = { citation: citation, auteur: auteur, user_id: userId, date: new Date() }; Citations.log.trace("Citations.insert", set); return CitationsCollection.insert(set); }
export const bekahAgain = { "name": "bekah likes gifs", "skills": "gif hunting", "gif": "https://media.giphy.com/media/cFdHXXm5GhJsc/giphy.gif" } export default bekahAgain
import Head from 'next/head' export default ({title = 'This is the default title' }) => ( <Head> <title>{ title }</title> <meta charSet='utf-8' /> <link rel='stylesheet' href='/static/react-md.amber-teal.min.css' /> <link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Roboto:300,400,500' /> <link rel='stylesheet' href='/static/styles/tailwind.css' /> <link rel='stylesheet' href='/static/styles.css' /> <meta name='viewport' content='initial-scale=1.0, width=device-width' /> </Head> )
import React, { Component } from 'react'; import { composeWithTracker } from 'react-komposer'; function composer(props, onData) { const subscription = Meteor.subscribe('getSolutions',props.taskId); if (subscription.ready()) { console.log(Solutions.find().fetch()); const data = { ready: true, tasks: Solutions.find().fetch() }; onData(null, data); } else { onData(null, {ready: false}); } } const MySolutions = React.createClass({ render() { return ( <div className="container"> <h1>My Solutions</h1> </div> ); } }); export default composeWithTracker(composer)(MySolutions);
export default class IndexController { /** * For API testing * * @param {Object} req * @param {Object} res */ ping(req, res) { res.json({ status: 200 }); } /** * Renders home page * * @param {Object} req * @param {Object} res */ index(req, res) { res.render('index'); } }
// import { xianRequest } from './xianRequest' // import commonTip from './common' // export default { // xianRequest, // commonTip // }
window.addEventListener("DOMContentLoaded", function(){ jQuery(function($) { /** * zoom: "5", * data_x: null, * data_y: null, * text: "Yandex Maps", * code: "45035" */ console.log(mapObj); ymaps.ready(WPYML_init); function WPYML_init () { var myMap = new ymaps.Map("yandex-map-"+mapObj.code, { center: [54.83, 37.11], zoom: 5 }), myPlacemark = new ymaps.Placemark([+mapObj.data_x, +mapObj.data_y], { // Чтобы балун и хинт открывались на метке, необходимо задать ей определенные свойства. balloonContentHeader: mapObj.header, balloonContentBody: mapObj.body, balloonContentFooter: mapObj.footer, hintContent: mapObj.hint }); myMap.geoObjects.add(myPlacemark); } }); });
// theme.js export const lightTheme = { body: '#E2E2E2', text: '#363537', link: { normal: 'slateblue', hover: 'cornflowerblue', }, border: '1px solid #363537', } export const darkTheme = { body: '#111', text: 'GhostWhite', link: { normal: 'royalblue', hover: 'blue', }, border: '1px solid GhostWhite', }
import Footer from '../components/Footer'; import Whatsapp from '../img/whatsapp-clone.jpg'; import Hulu from '../img/hulu-clone.jpg'; import Google from '../img/google-clone.jpg' import GitHub from '../img/github-project.jpg'; import MealFinder from '../img/meal-finder-project.jpg'; import OmniFood from '../img/omni-food.png' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faSearchPlus } from '@fortawesome/free-solid-svg-icons'; import { PopupboxManager, PopupboxContainer } from 'react-popupbox'; import 'react-popupbox/dist/react-popupbox.css' import MiniProjects from '../components/MiniProjects' import Contact from '../pages/Contact' import '../style/projects.css' const Projects = () => { //Whatsapp Clone const popupboxWhatsapp = () => { const content = ( <> <img className='project__image__popup pb-3' src={Whatsapp} alt='Whatsapp Clone (Coming Soon)'/> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Duis convallis convallis tellus id. Dolor sit amet consectetur adipiscing elit.</p> <b>Demo: <p>Coming Soon</p> {/*</b><a href='https://clone-3d506.web.app/' className='hyper__link' onClick={"https://clone-3d506.web.app/"}>Whatsapp Clone</a><br />*/} <b>GitHub: </b><a href="https://github.com/BlakeACollins/whatsapp-clone" className='hyper__link' onClick={"https://github.com/BlakeACollins/whatsapp-clone"}>Whatsapp Clone Project</a> </> ) PopupboxManager.open({ content }); PopupboxManager.update({ content, config: { titleBar: { text: "Whatsapp Clone with Next.js (Coming Soon)", }, }, }); } const popupboxConfigWhatsapp = { titleBar: { enable: true, }, fadeIn: true, fadeInSpeed: 600 } //Hulu Clone const popupboxHuluClone = () => { const content = ( <> <img className='project__image__popup pb-3' src={Hulu} alt='Hulu Clone project with next'/> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Duis convallis convallis tellus id. Dolor sit amet consectetur adipiscing elit.</p> <b>Demo: </b><a href="https://hulu-ui-clone-eta.vercel.app/" className='hyper__link' onClick={"https://hulu-ui-clone-eta.vercel.app/"}>Hulu Clone</a><br /> <b>GitHub: </b><a href='https://github.com/BlakeACollins/amazon-clone' className='hyper__link' onClick={"https://github.com/BlakeACollins/amazon-clone"}>Hulu Clone Project</a> </> ) PopupboxManager.open({ content }); PopupboxManager.update({ content, config: { titleBar: { text: "Hulu Clone with Next.js", }, }, }); } const popupboxConfigHulu = { titleBar: { enable: true, }, fadeIn: true, fadeInSpeed: 600 } //GitHub Profile Finder const popupboxGitHub = () => { const content = ( <> <img className='project__image__popup pb-3' src={GitHub} alt='GitHub profile finder project with JavaScript'/> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Duis convallis convallis tellus id. Dolor sit amet consectetur adipiscing elit.</p> <b>Demo: </b><a href="https://gallant-varahamihira-b81efc.netlify.app/" className='hyper__link' onClick={"https://gallant-varahamihira-b81efc.netlify.app/"}>GitHub Finder</a><br /> <b>GitHub: </b><a href="https://github.com/BlakeACollins/github-finder" className='hyper__link' onClick={"https://github.com/BlakeACollins/github-finder"}>GitHub Profile Finder</a> </> ) PopupboxManager.open({ content }); PopupboxManager.update({ content, config: { titleBar: { text: "GitHub Profile Finder with JavaScript", }, }, }); } const popupboxConfigGitHub = { titleBar: { enable: true, }, fadeIn: true, fadeInSpeed: 600 } //MealFinder App const popupboxMealFinder = () => { const content = ( <> <img className='project__image__popup pb-3' src={MealFinder} alt='Meal Finder app'/> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Duis convallis convallis tellus id. Dolor sit amet consectetur adipiscing elit.</p> <b>Demo: </b><a href="https://blakeacollins.github.io/mealFinder/" className='hyper__link' onClick={"https://blakeacollins.github.io/mealFinder/"}>Meal Finder</a><br /> <b>GitHub: </b><a href="https://github.com/BlakeACollins/mealFinder" className='hyper__link' onClick={"https://github.com/BlakeACollins/mealFinder"}>Meal Finder Project</a> </> ) PopupboxManager.open({ content }); PopupboxManager.update({ content, config: { titleBar: { text: "Meal Finder App with JavaScript", }, }, }); } const popupboxConfigMealFinder = { titleBar: { enable: true, }, fadeIn: true, fadeInSpeed: 600 } //Google UI Clone const popupboxGoogleClone = () => { const content = ( <> <img className='project__image__popup pb-3' src={Google} alt='Google UI Clone with search function'/> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Duis convallis convallis tellus id. Dolor sit amet consectetur adipiscing elit.</p> <b>Demo: </b><a href="https://google-ui-clone.vercel.app/" className='hyper__link' onClick={"https://google-ui-clone.vercel.app/"}>Google Clone</a><br /> <b>GitHub: </b><a href="https://github.com/BlakeACollins/google-UI-clone" className='hyper__link' onClick={"https://github.com/BlakeACollins/google-UI-clone"}>Google Clone Project</a> </> ) PopupboxManager.open({ content }); PopupboxManager.update({ content, config: { titleBar: { text: "Google Clone with Next.js", }, }, }); } const popupboxConfigGoogleClone = { titleBar: { enable: true, }, fadeIn: true, fadeInSpeed: 600 } //TBD const popupboxGmail = () => { const content = ( <> <img className='project__image__popup pb-3' src={MealFinder} alt='Gmail Clone'/> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Duis convallis convallis tellus id. Dolor sit amet consectetur adipiscing elit.</p> <b>Demo: </b><a href='https://clone-3d506.web.app/' className='hyper__link' onClick={"https://clone-3d506.web.app/"}>Gmail Clone</a><br /> <b>GitHub: </b><a href='https://github.com/BlakeACollins/amazon-clone' className='hyper__link' onClick={"https://github.com/BlakeACollins/amazon-clone"}>Gmail Clone Project</a> </> ) PopupboxManager.open({ content }); PopupboxManager.update({ content, config: { titleBar: { text: "TBD", }, }, }); } const popupboxConfigGmail = { titleBar: { enable: true, }, fadeIn: true, fadeInSpeed: 600 } //Web Shop const popupboxWebShop = () => { const content = ( <> <img className='project__image__popup pb-3' src={MealFinder} alt='Web Shop E-commerce app'/> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Duis convallis convallis tellus id. Dolor sit amet consectetur adipiscing elit.</p> <b>Demo: </b><a href='https://clone-3d506.web.app/' className='hyper__link' onClick={"https://clone-3d506.web.app/"}>Web Shop E-Commerce Store</a><br /> <b>GitHub: </b><a href='https://github.com/BlakeACollins/amazon-clone' className='hyper__link' onClick={"https://github.com/BlakeACollins/amazon-clone"}>Web Shop Project</a> </> ) PopupboxManager.open({ content }); PopupboxManager.update({ content, config: { titleBar: { text: "TBD", }, }, }); } const popupboxConfigWebShop = { titleBar: { enable: true, }, fadeIn: true, fadeInSpeed: 600 } //Omni Food UI const popupboxOmniFood = () => { const content = ( <> <img className='project__image__popup pb-3' src={OmniFood} alt='Omni Food Delivery Front End'/> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Duis convallis convallis tellus id. Dolor sit amet consectetur adipiscing elit.</p> <b>Demo: </b><a href="https://blakeacollins.github.io/OmniFood/" className='hyper__link' onClick={"https://blakeacollins.github.io/OmniFood/"}>Omni Food Delivery</a><br /> <b>GitHub: </b><a href="https://github.com/BlakeACollins/OmniFood" className='hyper__link' onClick={"https://github.com/BlakeACollins/OmniFood"}>Omni Food Project</a> </> ) PopupboxManager.open({ content }); PopupboxManager.update({ content, config: { titleBar: { text: "Omni Food Delivery UI", }, }, }); } const popupboxConfigOmniFood = { titleBar: { enable: true, }, fadeIn: true, fadeInSpeed: 600 } return ( <> <div id='projects' className='project__wrapper'> <div className='container'> <h1 className='text-uppercase text-center py-5' >projects</h1> <div className='image__box__wrapper row justify-content-center'> <div className='project__image__box' onClick={popupboxWhatsapp}> <h5 className='text-center mb-3'>Whatsapp Clone</h5> <img className='project__image' src={Whatsapp} alt=''/> <div className='overflow'></div> <FontAwesomeIcon className='project__icon' icon={faSearchPlus} /> </div> {/* - */} <div className='project__image__box' onClick={popupboxHuluClone}> <h5 className='text-center mb-3'>Hulu Clone</h5> <img className='project__image' src={Hulu} alt=''/> <div className='overflow'></div> <FontAwesomeIcon className='project__icon' icon={faSearchPlus} /> </div> {/* - */} <div className='project__image__box' onClick={popupboxGitHub}> <h5 className='text-center mb-3'>GitHub Finder</h5> <img className='project__image' src={GitHub} alt=''/> <div className='overflow'></div> <FontAwesomeIcon className='project__icon' icon={faSearchPlus} /> </div> </div> </div> <PopupboxContainer {...popupboxConfigWhatsapp} /> <PopupboxContainer {...popupboxConfigHulu} /> <PopupboxContainer {...popupboxConfigGitHub} /> <PopupboxContainer {...popupboxConfigMealFinder} /> <div className='container mt-3'> <div className='image__box__wrapper row justify-content-center'> {/* <div className='project__image__box' onClick={popupboxWebShop}> <h5 className='text-center mb-3'>TDB</h5> <img className='project__image' src={GitHub} alt='Web Shop E-Commerce'/> <div className='overflow'></div> <FontAwesomeIcon className='project__icon' icon={faSearchPlus} /> </div> {/* <div className='project__image__box' onClick={popupboxGmail}> <h5 className='text-center mb-3'>TBD</h5> <img className='project__image' src={Hulu} alt=''/> <div className='overflow'></div> <FontAwesomeIcon className='project__icon' icon={faSearchPlus} /> </div> */} <div className='project__image__box' onClick={popupboxGoogleClone}> <h5 className='text-center mb-3'>Google UI Clone</h5> <img className='project__image' src={Google} alt=''/> <div className='overflow'></div> <FontAwesomeIcon className='project__icon' icon={faSearchPlus} /> </div> {/* - */} <div className='project__image__box' onClick={popupboxMealFinder}> <h5 className='text-center mb-3'>Meal Finder</h5> <img className='project__image' src={MealFinder} alt=''/> <div className='overflow'></div> <FontAwesomeIcon className='project__icon' icon={faSearchPlus} /> </div> {/* - */} <div className='project__image__box' onClick={popupboxOmniFood}> <h5 className='text-center mb-3'>Omni Food</h5> <img className='project__image' src={OmniFood} alt=''/> <div className='overflow'></div> <FontAwesomeIcon className='project__icon' icon={faSearchPlus} /> </div> <PopupboxContainer {...popupboxConfigGoogleClone} /> <PopupboxContainer {...popupboxConfigGmail} /> <PopupboxContainer {...popupboxConfigWebShop} /> <PopupboxContainer {...popupboxConfigOmniFood} /> </div> </div> </div> <div> <MiniProjects /> <Contact /> <Footer /> </div> </> ) } export default Projects;
(function($) { // Сохраняем функции, которые описаны в файле misc/ajax.js. // beforeSend подготавливает AJAX запрос перед его отправкой. // success вызывается после успешного выполнения AJAX. // error вызывается после неудачного выполения AJAX. var beforeSend = Drupal.ajax.prototype.beforeSend; var success = Drupal.ajax.prototype.success; var error = Drupal.ajax.prototype.error; /** * Prepare the Ajax request before it is sent. */ Drupal.ajax.prototype.beforeSend = function(xmlhttprequest, options) { // Вызываем код, который описан в Drupal.ajax.prototype.beforeSend в файле misc/ajax.js, // что бы не нарушить работу AJAX. beforeSend.call(this, xmlhttprequest, options); if (this.progress.type == "example_progress" && $(this.element).attr("type") == "submit") { // Сохраняем оригинальное название кнопки, это необходимо для того, что бы после завершения работы AJAX, // изменять название кнопки назад. this.progress.submitValue = $(this.element).attr("value"); // Присваиваем новое название кнопки. $(this.element).attr("value", Drupal.t("Loading...")); } }; /** * Handler for the form redirection completion. */ Drupal.ajax.prototype.success = function(xmlhttprequest, options) { success.call(this, xmlhttprequest, options); // Востанавливаем значение кнопки на оригинальное. if (this.progress.submitValue) { $(this.element).attr("value", this.progress.submitValue); } }; /** * Handler for the form redirection error. */ Drupal.ajax.prototype.error = function (response, uri) { error.call(this, xmlhttprequest, options); if (this.progress.submitValue) { $(this.element).attr("value", this.progress.submitValue); } }; })(jQuery);
module.exports = { stylist_username: '<...>', stylist_password: '<...>', oauth_consumer_key: '<...>', oauth_consumer_secret: '<...>', grant_type: 'client_credentials', site_url: 'https://pos.shortcutssoftware.com/site/<...>' };
var controls = { key: function(value) { game.numbers.click(value); }, reset: function() { }, help: function() { view.animate.move_screen(-1920); game.reset(); }, play: function() { view.animate.move_screen(-960); game.reset(); }, about: function() { view.animate.move_screen(0); game.timer.pause(); }, back: function() { view.animate.move_screen(-480); game.timer.pause(); }, highscores: function() { view.animate.move_screen(-1440); game.timer.pause(); }, }
// Copyright 2012 Dmitry Monin. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. goog.provide('morning.fx.WindowScroll'); goog.require('morning.fx.dom.PredefinedEffect'); /** * Creates an animation object that will scroll an element from A to B. * * Start and End should be 2 dimensional arrays * * @param {Element|Window} element Dom Node to be used in the animation. * @param {Array.<number>} start 2D array for start scroll left and top. * @param {Array.<number>} end 2D array for end scroll left and top. * @param {number} time Length of animation in milliseconds. * @param {Function=} opt_acc Acceleration function, returns 0-1 for inputs 0-1. * @extends {morning.fx.dom.PredefinedEffect} * @constructor */ morning.fx.WindowScroll = function(element, start, end, time, opt_acc) { if (start.length != 2 || end.length != 2) { throw Error('Start and end points must be 2D'); } morning.fx.dom.PredefinedEffect.apply(this, arguments); }; goog.inherits(morning.fx.WindowScroll, morning.fx.dom.PredefinedEffect); /** * Animation event handler that will set the scroll posiiton of an element * @protected * @override */ morning.fx.WindowScroll.prototype.updateStyle = function() { window.scrollTo(this.coords[0], this.coords[1]); };
let cursos = ['Programacion','MKT','UX','Data Science','Python'] //destructuracion array let [programacion,mkt] = cursos; //console.log(cursos); //console.log(programacion); //console.log(mkt); //desctructuracion objeto let persona = { nombre: "Carli", edad: 24, domicilio: "Congreso 1661 6A" } let {nombre, edad} = persona console.log(persona); console.log(nombre); console.log(edad);
import React from 'react'; import './App.css'; import Layout from './components/Layout.js' function App() { document.title = "Stat Roller"; return ( <div className="container"> <Layout/> </div> ); } export default App;
(function(){ 'use strict'; angular.module('app.consultorios', [ 'app.consultorios.controller', 'app.consultorios.services', 'app.consultorios.router', 'app.consultorios.directivas' ]); })();
export const SET_INGREDIENTS = 'SET_INGREDIENTS'; export const LOAD_RECIPES = 'LOAD_RECIPES';
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsSwapVert = { name: 'swap_vert', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M16 17.01V10h-2v7.01h-3L15 21l4-3.99h-3zM9 3L5 6.99h3V14h2V6.99h3L9 3z"/></svg>` };
/* Generated from Java with JSweet 3.0.0-SNAPSHOT - http://www.jsweet.org */ var quickstart; (function (quickstart) { /** * Classe contente il main per la generazione della pagina home.html * @author miche * @class */ class Home { static main(args) { let divBar = Home.createDivBar(); $(divBar).css("float", "clear"); let start = Home.getStarter(); $("body").css("text-align", "center"); $("body").append(start); $("body").append(divBar); $("body").css("margin", "2% 1.5%"); } /** * La funzione ritorna un bottone per avviare il sistema * @return {HTMLInputElement} bottone start * @private */ /*private*/ static getStarter() { return quickstart.Builder.createButtonRandomLink(Home.STARTER_TEXT); } /** * La funzione ritorna un element HTMLDivElement contente il link per uscire * dal propro account * @return {HTMLDivElement} HTMLDivElement contente il link a .logout.jsp * @private */ /*private*/ static createDivBar() { let signUpLink = quickstart.Builder.getLink("Esci", "./logout.jsp"); $(signUpLink).css("margin", "0% 1.5%"); $(signUpLink).css("float", "right"); let divBar = quickstart.Builder.createDiv(); $(divBar).append(signUpLink); $(divBar).css("margin", "0% 1.5%"); return divBar; } } Home.STARTER_TEXT = "Inizia"; quickstart.Home = Home; Home["__class"] = "quickstart.Home"; })(quickstart || (quickstart = {})); quickstart.Home.main(null);
class Player { constructor(name, type, x, y, size = 30) { this.name = name; this.type = type; this.size = size; this.arrows = type == "Police" ? [65, 68, 87, 83] : [37, 39, 38, 40]; this.color = type == "Police" ? "red" : "black"; this.x = x; this.y = y; } draw(ctx) { ctx.beginPath(); ctx.fillStyle = this.color; ctx.arc(this.x, this.y, this.size, (0 * Math.PI) / 180, 2 * Math.PI); ctx.fill(); } move(ctx) { this.x = this.x + -speed; this.y = this.y + -speed; } } class Game { constructor(canvas, width, height) { this.canvas = canvas; this.width = width; this.height = height; canvas.width = width; canvas.height = height; this.ctx = canvas.getContext("2d"); this.players = this.createPlayers(2); document.addEventListener("keydown", this.keyPress.bind(this)); } createPlayers(num) { let players = []; for (let i = 0; i < num; i++) { let type = i < num / 2 ? "Police" : "Thief"; let name = type + " " + ((i % num) / 2 + 1); let x = Math.floor(Math.random() * this.width); let y = Math.floor((Math.random() * this.height) / 3) + (type == "Thief") ? (2 * this.height) / 3 : 0; let player = new Player(name, type, x, y); players.push(player); } return players; } play() { this.ctx.clearRect(0, 0, this.width, this.height); // just clear the whole game area this.players.forEach(player => { player.draw(this.ctx); }); requestAnimationFrame(this.play.bind(this)); } keyPress(e) { console.log(e.keyCode); let keys = e.keyCode; // this.players.filter(pressed => { // if (pressed.type == "Police" && pressed.arrows == 40) { // console.log("press"); // } // }); this.players.filter(x => { return console.log("yay"); }); // let red = this.players[0]; // let black = this.players[1]; // What is the key , // I will adjust the x, y value of thief and police // [-x,+x,-y,+y] // if (keys == 40) { // console.log(this.players[0].name, this.players[1].name); // this.players.filter(x => ); // } // this.players[0].y = this.players[0].x = -1; // switch (keys) { // case 40: // red.y += 3; // break; // case 38: // red.y -= 3; // break; // case 39: // red.x += 3; // break; // case 37: // red.x -= 3; // break; // case 83: // black.y += 3; // break; // case 87: // black.y -= 3; // break; // case 68: // black.x += 3; // break; // case 65: // black.x -= 3; // break; // } // this.players.filter(police); // function police(x ) // this.players // .filter(x => x == "Police") // .map(v => console.log(this.players[0].y)); } } function initGame() { // alert("Onload"); let canvas = document.getElementById("game"); //jquery // let canvas = $("#game")[0]; let game = new Game(canvas, 400, 300); // console.log(game); game.play(); } // document.onload = function(){ initGame(); // }
function a() { console.log(this); this.newvariable = 'hello'; } var b = function() { console.log(this); } a(); console.log(newvariable); // not good! b(); var c = { name: 'The c object', log: function() { var self = this; self.name = 'Updated c object'; console.log(self); var setname = function(newname) { self.name = newname; } setname('Updated again! The c object'); console.log(self); } } c.log(); //==================================================== function a() { console.log(this);//global this.newvariable = 'hello';//creates new variable //in the global namespace } var b = function() { console.log(this); } //"this" is global windows object a(); console.log(newvariable); b(); //============================================== var c = { name: 'The c object', log: function() { this.name = 'Updated c object'; console.log(this); var setname = function(newname) { this.name = newname;//"this" points //to the global object } setname('Updated again! The c object'); console.log(this); } } c.log(); //to avoid this pointing to the global object //we can do as it is shown down //============================================== var c = { name: 'The c object', log: function() { var self = this; self.name = 'Updated c object'; console.log(self); var setname = function(newname) { self.name = newname; } setname('Updated again! The c object'); console.log(self); } } c.log();
import React from 'react'; import './Enrolled.css' const Enrolled = (props) => { const addClasses = props.addClasses; console.log(addClasses) let total=0; for (let i = 0; i < addClasses.length; i++) { const course = addClasses[i]; total = total+course.price; } return ( <div className="enroll-cart"> <h2> Purchase Summery</h2> <h2>Total Purchase : {addClasses.length} </h2> <h3>Total $ : {total} </h3> </div> ); }; export default Enrolled;
var url = require('url') var websocket = require('websocket-stream') var MuxDemux = require('mux-demux') var Model = require('scuttlebutt/model') var duplexEmitter = require('duplex-emitter') window.socket = websocket('ws://' + url.parse(window.location.href).host) var emitter var connected = false var mdm = MuxDemux() mdm.on('connection', function (stream) { if (stream.meta === "emitter") { window.emitter = emitter = duplexEmitter(stream) connected = true emitter.on('id', function(id) { console.log('id', id) playerID = id }) emitter.on('settings', function(settings) { window.game = game = createGame(settings) //emitter.emit('generated', Date.now()) }) } // if (stream.meta === "voxels") { // var voxels = new Model() // voxels.on('update', function(data, value) { // var val = data[1] // var pos = data[0].split('|') // var ckey = pos.splice(0,3).join('|') // pos = {x: +pos[0], y: +pos[1], z: +pos[2]} // var set = voxelAtChunkIndexAndVoxelVector(ckey, pos, val) // game.showChunk(game.voxels.chunks[ckey]) // }) // // stream.pipe(voxels.createStream()).pipe(stream) //} }) socket.pipe(mdm).pipe(socket) socket.on('end', function() { connected = false }) function createGame(options) { var game = require('voxel-hello-world') var voxelEl = document.querySelector('#voxel') var chunkEl = document.querySelector('#chunk') game.voxelRegion.on('change', function(pos) { voxelEl.innerHTML = JSON.stringify(pos) }) game.chunkRegion.on('change', function(pos) { chunkEl.innerHTML = JSON.stringify(pos) }) }
/** MODULOS EXPRESS **/ let logger = require(process.cwd() + '/utils/logger.js'); //gerador de logs let express = require('express'); let Router = express.Router(); let security = require('../utils/security'); let utilsFunctions = require('../utils/functions'); /** CONEXAO DB **/ let db = require('../config/connect'); let mysql = require('mysql'); let Connection = mysql.createPool(db.config); /** METODOS DO CONTROLLER **/ Router.route('/:empresa') //LIST .get(function (req, res, next) { //EXECULTA CONSULTA logger.info('Iniciando pesquisa de atendente'); Connection.getConnection(function (err, sql) { if(err){ let msg = `Erro na conexão com o banco de dados, se o problema persistir consulte o suporte ténico!`; logger.warn(msg); res.status(400).json(msg); }else{ sql.query(`SELECT id, sts AS status, name AS nome, user AS usuario, email, phone AS fone, CONCAT(square_init, ' - ', square_finish) AS praca FROM atendentes WHERE user_id = '${req.params.empresa}' ORDER BY name ASC`, function (error, rows, fields) { sql.release(); if (error) { let msg = `Erro na execução da consulta, se o problema persistir consulte o suporte técnico!`; logger.warn(msg); res.status(400).json(msg); }else { if (rows && rows.length > 0) { logger.info('Atendentes carregados'); let Itens = []; rows.forEach(item => { (item.praca === '0 - 0')?item.praca = '---------':item.praca = item.praca; Itens.push(item); }); res.status(200).send(Itens); }else { logger.info('Lista de atendentes vazia'); res.status(200).send([]); } } }); } }); }) //POST .post(function (req, res, next) { logger.info('Iniciando inclusão de atendente'); if(JSON.stringify(req.body) === '{}'){ let msg = `Nenhum dado foi enviado para inclusão`; logger.warn(msg); res.status(400).json(msg); }else{ //VERIFICANDO SE ITEM JA FOI CADASTRADO Connection.getConnection(function (err, sql) { if(err){ let msg = `Erro na conexão com o banco de dados, se o problema persistir consulte o suporte ténico!`; logger.warn(msg); res.status(400).json(msg); }else{ sql.query(`SELECT name FROM atendentes WHERE user_id = '${req.params.empresa}' AND name = '${req.body.nome}' LIMIT 1`, function (error, rows, fields) { if (error) { sql.release(); let msg = `Erro na execução da consulta, se o problema persistir consulte o suporte técnico!`; logger.warn(msg); res.status(400).json(msg); }else { //SE NAO EXISTIR REGISTRO, INSERE if (rows.length === 0) { logger.info('Gerando senha de acesso'); let senha = '123'; let pass_user; pass_user = security.passGenerate(senha + security.passSegredo()); logger.info('Gerando nome de usuário'); let nomeUser = req.body.nome; nomeUser = nomeUser.match(/\b(\w)/g); nomeUser = nomeUser.join(''); nomeUser = `${nomeUser}${Math.floor((Math.random() * 99999) + 100)}`; let CAMPOS = { user_id: req.params.empresa, name: req.body.nome.toUpperCase(), email: req.body.email, phone: req.body.fone, user: nomeUser.toUpperCase(), pass: pass_user, square_init: (req.body.praca_init === undefined || req.body.praca_init === null || req.body.praca_init === '')?0:req.body.praca_init, square_finish: (req.body.praca_finish === undefined || req.body.praca_finish === null || req.body.praca_finish === '')?0:req.body.praca_finish, created: utilsFunctions.getMoment('ymdh', Date.now()), updated: utilsFunctions.getMoment('ymdh', Date.now()) }; sql.query(`INSERT INTO atendentes SET ?`, [CAMPOS], function (error, rows, fields) { sql.release(); if (error) { let msg = `Erro ao inserir item, se o problema persistir consulte o suporte técnico!`; logger.error(msg); res.status(400).json(msg); }else { let msg = `O atendente ${req.body.nome.toUpperCase()} foi cadastrado com sucesso!`; logger.info(msg); res.status(200).json(msg); } }); }else { sql.release(); let msg = `O item ${req.body.nome.toUpperCase()} já foi cadastrado!`; logger.warn(msg); res.status(200).json({message: msg}); } } }); } }); } }); //ID Router.route('/:id/:empresa') .get(function (req, res, next) { //EXECULTA CONSULTA logger.info(`Iniciando pesquisa de atendente: (${req.params.id})`); Connection.getConnection(function (err, sql) { if(err){ let msg = `Erro na conexão com o banco de dados, se o problema persistir consulte o suporte ténico!`; logger.warn(msg); res.status(400).json(msg); }else{ sql.query(`SELECT * FROM atendentes WHERE user_id = '${req.params.empresa}' AND id = '${req.params.id}' LIMIT 1`, function (error, rows, fields) { sql.release(); if (error) { let msg = `Erro na execução da consulta, se o problema persistir consulte o suporte técnico!`; logger.warn(msg); res.status(400).json(msg); }else { if (rows) { logger.info(`Atendente carregado`); res.status(200).send(rows[0]); }else { let msg = `Atendente não encontrado!`; logger.info(msg); res.status(200).json(msg); } } }); } }); }) .put(function (req, res, next) { if(JSON.stringify(req.body) === '{}'){ let msg = `Nenhum dado foi enviado para inclusão`; logger.warn(msg); res.status(400).json(msg); }else{ logger.info(`Iniciando atualização de atendente: (${req.params.id})`); let CAMPOS = { name: req.body.nome.toUpperCase(), email: req.body.email, phone: req.body.fone, square_init: (req.body.praca_init === undefined || req.body.praca_init === null || req.body.praca_init === '')?0:req.body.praca_init, square_finish: (req.body.praca_finish === undefined || req.body.praca_finish === null || req.body.praca_finish === '')?0:req.body.praca_finish, updated: utilsFunctions.getMoment('ymdh', Date.now()) }; //EXECULTA CONSULTA Connection.getConnection(function (err, sql) { if(err){ let msg = `Erro na conexão com o banco de dados, se o problema persistir consulte o suporte ténico!`; logger.warn(msg); res.status(400).json(msg); }else{ sql.query(`UPDATE atendentes SET ? WHERE user_id = '${req.params.empresa}' AND id = '${req.params.id}' LIMIT 1`, [CAMPOS], function (error, rows, fields) { sql.release(); if (error) { let msg = `Erro na execução da consulta, se o problema persistir consulte o suporte técnico!`; logger.warn(msg); res.status(400).json(msg); }else { let msg = `O atendente ${req.body.nome.toUpperCase()} foi atualizado com sucesso!`; logger.info(msg); res.status(200).json(msg); } }); } }); } }) .delete(function (req, res, next) { //EXECULTA CONSULTA logger.info(`Iniciando exclusão de atendente: (${req.params.id})`); Connection.getConnection(function (err, sql) { if(err){ let msg = `Erro na conexão com o banco de dados, se o problema persistir consulte o suporte ténico!`; logger.warn(msg); res.status(400).json(msg); }else{ //HARD DELETE sql.query(`DELETE FROM atendentes WHERE user_id = '${req.params.empresa}' AND id = '${req.params.id}' LIMIT 1`, //SOFT DELETE //sql.query(`UPDATE atendentes SET sts = 'INATIVO', deleted = true WHERE user_id = '${req.params.empresa}' AND id = '${req.params.id}' LIMIT 1`, function (error, rows, fields) { sql.release(); if (error) { let msg = `Erro na execução da consulta, se o problema persistir consulte o suporte técnico!`; logger.warn(msg); res.status(400).json(msg); }else { let msg = `O item foi excluído com sucesso!`; logger.info(msg); res.status(200).json(msg); } }); } }); }); //DESATIVAR ITEM Router.route('/:id/deactivate/:empresa') .get(function (req, res, next) { //EXECULTA CONSULTA logger.info(`Iniciando bloqueio de atendente: (${req.params.id})`); Connection.getConnection(function (err, sql) { if(err){ let msg = `Erro na conexão com o banco de dados, se o problema persistir consulte o suporte ténico!`; logger.warn(msg); res.status(400).json(msg); }else{ sql.query(`UPDATE atendentes SET sts = 'INATIVO' WHERE user_id = '${req.params.empresa}' AND id = '${req.params.id}' LIMIT 1`, function (error, rows, fields) { sql.release(); if (error) { let msg = `Erro na execução da consulta, se o problema persistir consulte o suporte técnico!`; logger.warn(msg); res.status(400).json(msg); }else { let msg = `O item foi bloqueado com sucesso!`; logger.info(msg); res.status(200).json(msg); } }); } }); }); //REATIVANDO ITEM Router.route('/:id/activate/:empresa') .get(function (req, res, next) { //EXECULTA CONSULTA logger.info(`Iniciando reativação de atendente: (${req.params.id})`); Connection.getConnection(function (err, sql) { if(err){ let msg = `Erro na conexão com o banco de dados, se o problema persistir consulte o suporte ténico!`; logger.warn(msg); res.status(400).json(msg); }else{ sql.query(`UPDATE atendentes SET sts = 'ATIVO', deleted = false WHERE user_id = '${req.params.empresa}' AND id = '${req.params.id}' LIMIT 1`, function (error, rows, fields) { sql.release(); if (error) { let msg = `Erro na execução da consulta, se o problema persistir consulte o suporte técnico!`; logger.warn(msg); res.status(400).json(msg); }else { let msg = `O item foi reativado com sucesso!`; logger.info(msg); res.status(200).json(msg); } }); } }); }); //LOGAR Router.route('/auth/user') .post(function (req, res, next) { //EXECULTA CONSULTA logger.info(`Iniciando autenticação de atendente`); Connection.getConnection(function (err, sql) { if(err){ let msg = `Erro na conexão com o banco de dados, se o problema persistir consulte o suporte ténico!`; logger.warn(msg); res.status(503).json(msg); }else{ sql.query(`SELECT * FROM atendentes WHERE user = '${req.body.usuario}' AND sts = 'ATIVO' AND deleted = false AND count_connect <= 10 LIMIT 1`, function (error, rows, fields) { sql.release(); if (error) { let msg = `Erro na execução da consulta, se o problema persistir consulte o suporte técnico!`; logger.warn(msg); res.status(503).json(msg); }else { if (rows && rows.length > 0) { logger.info(`Validando senha do atendente`); isValid = security.passValid(req.body.senha + security.passSegredo(), rows[0].pass); if(isValid){ logger.info(`Atendente logado`); res.status(200).send(rows[0]); }else{ let msg = `Senha inválida!`; logger.warn(msg); res.status(503).json(msg); } }else { let msg = `Atendente não encontrado ou sem permissão de acesso!`; logger.warn(msg); res.status(503).json(msg); } } }); } }); }); //LOGAR Router.route('/auth/token/:token') .get(function (req, res, next) { //EXECULTA CONSULTA logger.info(`Iniciando autenticação de atendente por token`); Connection.getConnection(function (err, sql) { if(err){ let msg = `Erro na conexão com o banco de dados, se o problema persistir consulte o suporte ténico!`; logger.warn(msg); res.status(400).json(msg); }else{ sql.query(`SELECT id FROM atendentes WHERE id = '${req.params.token}' AND sts = 'ATIVO' AND deleted = false AND count_connect <= 10 LIMIT 1`, function (error, rows, fields) { sql.release(); if (error) { let msg = `Erro na execução da consulta, se o problema persistir consulte o suporte técnico!`; logger.warn(msg); res.status(400).json(msg); }else { if (rows && rows.length > 0) { logger.info(`Token de atendente válido`); res.status(200).send(true); }else{ logger.warn(`Token de atendente inválido`); res.status(200).send(false); } } }); } }); }); module.exports = Router;
const DBF = require('stream-dbf'); const createCsvWriter = require('csv-writer').createObjectCsvWriter; const parseAddrObj = (filename) => new Promise((resolve, reject) => { const FILE_NAME = filename; let data = []; let index = 0; const parser = new DBF(`./files/fias_dbf/${FILE_NAME}`, {encoding: 'cp866', /*withMeta: false, lowercase: true , */}); const stream = parser.stream; stream.on('data', async function(record) { data.push(record); index = record["@sequenceNumber"]; if (index%10000 == 0) { console.log(`============= Читаем запись ${record["@sequenceNumber"]} из файла ${FILE_NAME} =============`); } }); stream.on('error', reject); stream.on('end', () => { console.log('finished'); const csvWriter = createCsvWriter({ path: `./files/csv/addrobj/${FILE_NAME}.csv`, header: [ { id: 'AOGUID', title: 'AOGUID' }, { id: 'FORMALNAME', title: 'FORMALNAME'}, { id: 'REGIONCODE', title: 'REGIONCODE'}, { id: 'AUTOCODE', title: 'AUTOCODE'}, { id: 'AREACODE', title: 'AREACODE'}, { id: 'CITYCODE', title: 'CITYCODE'}, { id: 'CTARCODE', title: 'CTARCODE'}, { id: 'PLACECODE', title: 'PLACECODE'}, { id: 'PLANCODE', title: 'PLANCODE'}, { id: 'STREETCODE', title: 'STREETCODE'}, { id: 'EXTRCODE', title: 'EXTRCODE'}, { id: 'SEXTCODE', title: 'SEXTCODE'}, { id: 'OFFNAME', title: 'OFFNAME'}, { id: 'POSTALCODE', title: 'POSTALCODE'}, { id: 'IFNSFL', title: 'IFNSFL'}, { id: 'IFNSUL', title: 'IFNSUL'}, { id: 'TERRIFNSUL', title: 'TERRIFNSUL'}, { id: 'OKATO', title: 'OKATO'}, { id: 'OKTMO', title: 'OKTMO'}, { id: 'UPDATEDATE', title: 'UPDATEDATE'}, { id: 'SHORTNAME', title: 'SHORTNAME'}, { id: 'AOLEVEL', title: 'AOLEVEL'}, { id: 'PARENTGUID', title: 'PARENTGUID'}, { id: 'AOID', title: 'AOID'}, { id: 'PREVID', title: 'PREVID'}, { id: 'NEXTID', title: 'NEXTID'}, { id: 'CODE', title: 'CODE'}, { id: 'PLAINCODE', title: 'PLAINCODE'}, { id: 'ACTSTATUS', title: 'ACTSTATUS'}, { id: 'LIVESTATUS', title: 'LIVESTATUS'}, { id: 'CENTSTATUS', title: 'CENTSTATUS'}, { id: 'OPERSTATUS', title: 'OPERSTATUS'}, { id: 'CURRSTATUS', title: 'CURRSTATUS'}, { id: 'STARTDATE', title: 'STARTDATE'}, { id: 'ENDDATE', title: 'ENDDATE'}, { id: 'NORMDOC', title: 'NORMDOC'}, { id: 'CADNUM', title: 'CADNUM'}, { id: 'DIVTYPE', title: 'DIVTYPE'}, { id: 'TERRIFNSFL', title: 'TERRIFNSFL'}, ] }); csvWriter .writeRecords(data) .then(() => console.log("csv file created")) resolve(index); }); }); module.exports = parseAddrObj;
import React from 'react' import { BrowserRouter, Switch } from 'react-router-dom' import css from './styles.css' import Navigation from '../Navigation' const Router = (props) => { return ( <div> <BrowserRouter> <main> <Navigation /> <Switch> {props.children} </Switch> </main> </BrowserRouter> </div> ) } export default Router
app.controller('main', [ '$scope', '$rootScope', '$http', '$routeParams', function ($scope, $rootScope, $http, $routeParams) { var api = $rootScope.site_url; $scope.loaderInit = () => { //Total cart contents and Total Cart Price $http.post(api + '/cart/fetchJson').then(function (response) { $scope.cart = response.data; $('#cartTotal1').html(response.data.rows); $('#cartTotal2').html(response.data.rows); }); $http.post(api + '/cart/view').then(function (response) { $scope.cartItem = response.data; // console.log($scope.cartItem); }); //User Details $http.post(api + '/users/view').then(function (response) { // console.log(response.data[0]); $scope.user = response.data[0]; }); // Address Details $http.get(api + '/users/viewAddress').then(function (response) { $scope.address = response.data; $scope.addr = $scope.address[0]; console.log($scope.address); }); }; $scope.loaderInit(); }, ]);
require("../common/vendor.js"), (global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/packageA/map/_price_select" ], { "0d90": function(t, e, a) { a.r(e); var n = a("9295"), c = a.n(n); for (var r in n) [ "default" ].indexOf(r) < 0 && function(t) { a.d(e, t, function() { return n[t]; }); }(r); e.default = c.a; }, "404c": function(t, e, a) { a.d(e, "b", function() { return n; }), a.d(e, "c", function() { return c; }), a.d(e, "a", function() {}); var n = function() { var t = this; t.$createElement; t._self._c; }, c = []; }, 9295: function(t, e, a) { Object.defineProperty(e, "__esModule", { value: !0 }), e.default = void 0; var n = { water: [ { text: "不限", value: "" }, { text: "50万以下", value: "0-500000" }, { text: "50-100万", value: "500000-1000000" }, { text: "100-150万", value: "1000000-1500000" }, { text: "150-200万", value: "1500000-2000000" }, { text: "200-250万", value: "2000000-2500000" }, { text: "250-300万", value: "2500000-3000000" } ], square: [ { text: "不限", value: "" }, { text: "6000元/㎡以下", value: "0-6000" }, { text: "6000元-8000元/㎡", value: "6000-8000" }, { text: "8000元-10000元/㎡", value: "8000-10000" }, { text: "10000元-15000元/㎡", value: "10000-15000" }, { text: "15000元-20000元/㎡", value: "15000-20000" }, { text: "20000元-30000元/㎡", value: "20000-30000" } ] }, c = { data: function() { return { selected: "", selected_tx: "不限", tabs: [ { text: "总价", value: "water" }, { text: "单价", value: "square" } ], type: "water", start: "", end: "" }; }, onUnload: function() { this.type = "water", this.start = "", this.end = "", this.selected = ""; }, computed: { opts: function() { return n[this.type]; }, input_tip_start: function() { return "water" === this.type ? "最低总价" : "最低单价"; }, input_tip_end: function() { return "water" === this.type ? "最高总价" : "最高单价"; } }, methods: { changeType: function(t) { this.type = t.currentTarget.dataset.type, this.start = "", this.end = ""; }, onSelect: function(t) { this.selected = t.currentTarget.dataset.value, this.selected_tx = t.currentTarget.dataset.text; }, changeStart: function(t) { this.start = t.target.value; }, changeEnd: function(t) { this.end = t.target.value; }, confirm: function() { var t = this.start, e = this.end, a = this.selected_tx; this.start && this.end && ("water" === this.type ? (a = "".concat(t, "万-").concat(e, "万"), t *= 1e4, e *= 1e4) : a = "".concat(t, "元-").concat(e, "元/㎡"), this.selected_tx = a), "water" === this.type && this.start && this.end && (t *= 1e4, e *= 1e4); var n = "" != t && "" != e ? "".concat(t, "-").concat(e) : this.selected; n || !t && !e ? this.$emit("change", this.type, n, a) : wx.showToast({ title: "请选择或填写价格", icon: "none" }); } }, props: { show: { type: Boolean } } }; e.default = c; }, a60c: function(t, e, a) {}, e6f1: function(t, e, a) { var n = a("a60c"); a.n(n).a; }, f870: function(t, e, a) { a.r(e); var n = a("404c"), c = a("0d90"); for (var r in c) [ "default" ].indexOf(r) < 0 && function(t) { a.d(e, t, function() { return c[t]; }); }(r); a("e6f1"); var s = a("f0c5"), u = Object(s.a)(c.default, n.b, n.c, !1, null, "c7fa7f4e", null, !1, n.a, void 0); e.default = u.exports; } } ]), (global.webpackJsonp = global.webpackJsonp || []).push([ "pages/packageA/map/_price_select-create-component", { "pages/packageA/map/_price_select-create-component": function(t, e, a) { a("543d").createComponent(a("f870")); } }, [ [ "pages/packageA/map/_price_select-create-component" ] ] ]);
'use strict'; const skeleton = require('./../skeletons/url'); module.exports = { up: (queryInterface, Sequelize) => queryInterface.createTable(skeleton.name, skeleton.skeleton, skeleton.options), down: (queryInterface, Sequelize) => queryInterface.dropTable('url') };
const FORM_PRIMITIVE = 0; function decode(buffer) { let bytesRead = 0; let tag = buffer.readUInt8(bytesRead); bytesRead += 1; const cls = tag >> 6; const form = tag >> 5 & 1; let tagCode = tag & 0b11111; if (tagCode === 0b11111) { tagCode = 0; let byte; do { byte = buffer.readUInt8(bytesRead); bytesRead += 1; tagCode = (tagCode << 7) | (byte & 0x7f); } while (byte & 0x80); } let elementLength = buffer.readUInt8(bytesRead); bytesRead += 1; if (tag === 0 && elementLength === 0) { // End-of-contents indicator return { element: null, bytesRead }; } if (elementLength < 128) { // Short form length, do nothing } else if (elementLength === 128) { elementLength = undefined; } else { const lengthLength = elementLength & 127; elementLength = buffer.readUIntBE(bytesRead, lengthLength); bytesRead += lengthLength; } const element = { cls, form, tagCode }; if (form === 0) { // Primitive const value = elementLength ? buffer.slice(bytesRead, bytesRead + elementLength) : Buffer.from([]); bytesRead += elementLength; element.value = value; } else { const elements = []; while (!elementLength || bytesRead - 2 < elementLength) { const result = decode(buffer.slice(bytesRead)); bytesRead += result.bytesRead; if (result.element === null) { // End-of-contents indicator reached break; } elements.push(result.element); } element.elements = elements; } return { element, bytesRead }; } function encode(element) { function enc(element, buffer, offset) { let bytesWritten = 0; function writeLength(length) { if (length < 128) { buffer.writeUInt8(length, offset + bytesWritten); bytesWritten += 1; } else if (!length) { throw new Error('Encoding of indefinite length elements is not supported'); // buffer.writeUInt8(128, bytesWritten); // bytesWritten += 1; } else { const lengthLength = Math.ceil(Math.log2(length) / 8); buffer.writeUInt8(0x80 | lengthLength, offset + bytesWritten); bytesWritten += 1; buffer.writeUIntBE(length, offset + bytesWritten, lengthLength); bytesWritten += lengthLength; } } if (element.tagCode > 0b11110) { throw new Error('Extended tags are not supported'); } const tag = element.cls << 6 | element.form << 5 | element.tagCode; buffer.writeUInt8(tag, offset + bytesWritten); bytesWritten += 1; if (element.form === FORM_PRIMITIVE) { writeLength(element.value.length); buffer.write(element.value.toString('binary'), offset + bytesWritten, element.value.length, 'binary'); bytesWritten += element.value.length; } else { const tmpBuffer = Buffer.allocUnsafe(1024); const tmpBytesWritten = element.elements.reduce((bytesWritten, element) => bytesWritten + enc(element, tmpBuffer, bytesWritten), 0); writeLength(tmpBytesWritten); buffer.write(tmpBuffer.slice(0, tmpBytesWritten).toString('binary'), offset + bytesWritten, tmpBytesWritten, 'binary'); bytesWritten += tmpBytesWritten; } return bytesWritten; } const buffer = Buffer.allocUnsafe(1024); const bytesWritten = enc(element, buffer, 0); return buffer.slice(0, bytesWritten); } module.exports = Object.freeze({ decode: (buffer) => decode(buffer).element, encode });
window.esdocSearchIndex = [ [ "parexgram-js/src/alternation.js~alternation", "class/src/alternation.js~Alternation.html", "<span>Alternation</span> <span class=\"search-result-import-path\">parexgram-js/src/alternation.js</span>", "class" ], [ "parexgram-js/src/charset.js~charset", "class/src/charset.js~CharSet.html", "<span>CharSet</span> <span class=\"search-result-import-path\">parexgram-js/src/charset.js</span>", "class" ], [ "parexgram-js/src/feed.js~feed", "class/src/feed.js~Feed.html", "<span>Feed</span> <span class=\"search-result-import-path\">parexgram-js/src/feed.js</span>", "class" ], [ "parexgram-js/src/matcher.js~matcher", "class/src/matcher.js~Matcher.html", "<span>Matcher</span> <span class=\"search-result-import-path\">parexgram-js/src/matcher.js</span>", "class" ], [ "parexgram-js/src/pattern.js~pattern", "class/src/pattern.js~Pattern.html", "<span>Pattern</span> <span class=\"search-result-import-path\">parexgram-js/src/pattern.js</span>", "class" ], [ "parexgram-js/src/quantifier.js~quantifier", "class/src/quantifier.js~Quantifier.html", "<span>Quantifier</span> <span class=\"search-result-import-path\">parexgram-js/src/quantifier.js</span>", "class" ], [ "parexgram-js/src/range.js~range", "class/src/range.js~Range.html", "<span>Range</span> <span class=\"search-result-import-path\">parexgram-js/src/range.js</span>", "class" ], [ "parexgram-js/src/sequence.js~sequence", "class/src/sequence.js~Sequence.html", "<span>Sequence</span> <span class=\"search-result-import-path\">parexgram-js/src/sequence.js</span>", "class" ], [ "", "test-file/test/alternation.js.html#lineNumber8", "Alternation", "test" ], [ "", "test-file/test/alternation.js.html#lineNumber12", "Alternation #parse", "test" ], [ "", "test-file/test/alternation.js.html#lineNumber16", "Alternation #parse should return an Array if a matcher returns an Array", "test" ], [ "", "test-file/test/alternation.js.html#lineNumber31", "Alternation #parse should return an String if a matcher returns a String", "test" ], [ "", "test-file/test/alternation.js.html#lineNumber68", "Alternation #parse should return the other matches if the previous matches fails", "test" ], [ "", "test-file/test/alternation.js.html#lineNumber42", "Alternation #parse should return undefined if there are no matchers", "test" ], [ "", "test-file/test/alternation.js.html#lineNumber53", "Alternation #parse should return undefined if there are no matchers", "test" ], [ "", "test-file/test/charset.js.html#lineNumber5", "CharSet", "test" ], [ "", "test-file/test/charset.js.html#lineNumber9", "CharSet #parse", "test" ], [ "", "test-file/test/charset.js.html#lineNumber13", "CharSet #parse should return a String", "test" ], [ "", "test-file/test/charset.js.html#lineNumber22", "CharSet #parse should return a String equal to the CharSet if successful", "test" ], [ "", "test-file/test/charset.js.html#lineNumber40", "CharSet #parse should return a undefined if a non-Feed is received", "test" ], [ "", "test-file/test/charset.js.html#lineNumber31", "CharSet #parse should return a undefined if unsuccessful", "test" ], [ "", "test-file/test/feed.js.html#lineNumber8", "Feed", "test" ], [ "", "test-file/test/feed.js.html#lineNumber39", "Feed #eat", "test" ], [ "", "test-file/test/feed.js.html#lineNumber43", "Feed #eat should return a Boolean", "test" ], [ "", "test-file/test/feed.js.html#lineNumber65", "Feed #eat should return false if the given string is not a prefix of the Feed.", "test" ], [ "", "test-file/test/feed.js.html#lineNumber54", "Feed #eat should return true if the given string is a prefix of the Feed.", "test" ], [ "", "test-file/test/feed.js.html#lineNumber12", "Feed #peek", "test" ], [ "", "test-file/test/feed.js.html#lineNumber16", "Feed #peek should return a String", "test" ], [ "", "test-file/test/feed.js.html#lineNumber27", "Feed #peek should return the correct string", "test" ], [ "", "test-file/test/feed.js.html#lineNumber77", "Feed #revert", "test" ], [ "", "test-file/test/feed.js.html#lineNumber81", "Feed #revert should revert successfully.", "test" ], [ "", "test-file/test/feed.js.html#lineNumber94", "Feed #size", "test" ], [ "", "test-file/test/feed.js.html#lineNumber98", "Feed #size should return a Number", "test" ], [ "", "test-file/test/feed.js.html#lineNumber122", "Feed #size should return the correct size if #eat is not called.", "test" ], [ "", "test-file/test/feed.js.html#lineNumber109", "Feed #size should return the size equal to the received string of the Feed, if #eat is not called.", "test" ], [ "", "test-file/test/pattern.js.html#lineNumber5", "Pattern", "test" ], [ "", "test-file/test/pattern.js.html#lineNumber6", "Pattern it should match correctly given a RegExp", "test" ], [ "", "test-file/test/pattern.js.html#lineNumber9", "Pattern it should match correctly given a String", "test" ], [ "", "test-file/test/pattern.js.html#lineNumber31", "Pattern it should return undefined if RegExp match fails", "test" ], [ "", "test-file/test/pattern.js.html#lineNumber37", "Pattern it should return undefined if RegExp matches but is not a prefix", "test" ], [ "", "test-file/test/pattern.js.html#lineNumber24", "Pattern it should return undefined if there is a no valid RegExp", "test" ], [ "", "test-file/test/pattern.js.html#lineNumber12", "Pattern it should return undefined if there is a non-Feed", "test" ], [ "", "test-file/test/quantifier.js.html#lineNumber8", "Quantifier", "test" ], [ "", "test-file/test/quantifier.js.html#lineNumber12", "Quantifier #parse", "test" ], [ "", "test-file/test/quantifier.js.html#lineNumber16", "Quantifier #parse should return a undefined if a non-Feed is received", "test" ], [ "", "test-file/test/quantifier.js.html#lineNumber31", "Quantifier #parse should return a undefined if there is no matcher", "test" ], [ "", "test-file/test/quantifier.js.html#lineNumber45", "Quantifier #parse should return an empty array if Quantifier(match, 0) matches no result", "test" ], [ "", "test-file/test/quantifier.js.html#lineNumber37", "Quantifier #parse should return the correct sequence", "test" ], [ "", "test-file/test/quantifier.js.html#lineNumber52", "Quantifier #parse should return undefiend if the required matches is not met", "test" ], [ "", "test-file/test/range.js.html#lineNumber5", "Range", "test" ], [ "", "test-file/test/range.js.html#lineNumber6", "Range #parse", "test" ], [ "", "test-file/test/range.js.html#lineNumber7", "Range #parse should return a String", "test" ], [ "", "test-file/test/range.js.html#lineNumber16", "Range #parse should return a String equal to the CharSet if successful", "test" ], [ "", "test-file/test/range.js.html#lineNumber34", "Range #parse should return a undefined if a non-Feed is received", "test" ], [ "", "test-file/test/range.js.html#lineNumber25", "Range #parse should return a undefined if unsuccessful", "test" ], [ "", "test-file/test/sequence.js.html#lineNumber6", "Sequence", "test" ], [ "", "test-file/test/sequence.js.html#lineNumber10", "Sequence #parse", "test" ], [ "", "test-file/test/sequence.js.html#lineNumber14", "Sequence #parse should return an Array", "test" ], [ "", "test-file/test/sequence.js.html#lineNumber23", "Sequence #parse should return an Array equal to the Matchers if successful", "test" ], [ "", "test-file/test/sequence.js.html#lineNumber36", "Sequence #parse should return undefined if no matchers were passed", "test" ], [ "", "test-file/test/sequence.js.html#lineNumber46", "Sequence #parse should return undefined if one of the matchers fails", "test" ], [ "src/.external-ecmascript.js~array", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array", "src/.external-ecmascript.js~Array", "external" ], [ "src/.external-ecmascript.js~arraybuffer", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer", "src/.external-ecmascript.js~ArrayBuffer", "external" ], [ "src/.external-ecmascript.js~boolean", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean", "src/.external-ecmascript.js~Boolean", "external" ], [ "src/.external-ecmascript.js~dataview", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView", "src/.external-ecmascript.js~DataView", "external" ], [ "src/.external-ecmascript.js~date", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date", "src/.external-ecmascript.js~Date", "external" ], [ "src/.external-ecmascript.js~error", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error", "src/.external-ecmascript.js~Error", "external" ], [ "src/.external-ecmascript.js~evalerror", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError", "src/.external-ecmascript.js~EvalError", "external" ], [ "src/.external-ecmascript.js~float32array", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array", "src/.external-ecmascript.js~Float32Array", "external" ], [ "src/.external-ecmascript.js~float64array", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array", "src/.external-ecmascript.js~Float64Array", "external" ], [ "src/.external-ecmascript.js~function", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function", "src/.external-ecmascript.js~Function", "external" ], [ "src/.external-ecmascript.js~generator", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator", "src/.external-ecmascript.js~Generator", "external" ], [ "src/.external-ecmascript.js~generatorfunction", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/GeneratorFunction", "src/.external-ecmascript.js~GeneratorFunction", "external" ], [ "src/.external-ecmascript.js~infinity", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity", "src/.external-ecmascript.js~Infinity", "external" ], [ "src/.external-ecmascript.js~int16array", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array", "src/.external-ecmascript.js~Int16Array", "external" ], [ "src/.external-ecmascript.js~int32array", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array", "src/.external-ecmascript.js~Int32Array", "external" ], [ "src/.external-ecmascript.js~int8array", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array", "src/.external-ecmascript.js~Int8Array", "external" ], [ "src/.external-ecmascript.js~internalerror", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/InternalError", "src/.external-ecmascript.js~InternalError", "external" ], [ "src/.external-ecmascript.js~json", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON", "src/.external-ecmascript.js~JSON", "external" ], [ "src/.external-ecmascript.js~map", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map", "src/.external-ecmascript.js~Map", "external" ], [ "src/.external-ecmascript.js~nan", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN", "src/.external-ecmascript.js~NaN", "external" ], [ "src/.external-ecmascript.js~number", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number", "src/.external-ecmascript.js~Number", "external" ], [ "src/.external-ecmascript.js~object", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object", "src/.external-ecmascript.js~Object", "external" ], [ "src/.external-ecmascript.js~promise", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise", "src/.external-ecmascript.js~Promise", "external" ], [ "src/.external-ecmascript.js~proxy", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy", "src/.external-ecmascript.js~Proxy", "external" ], [ "src/.external-ecmascript.js~rangeerror", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError", "src/.external-ecmascript.js~RangeError", "external" ], [ "src/.external-ecmascript.js~referenceerror", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError", "src/.external-ecmascript.js~ReferenceError", "external" ], [ "src/.external-ecmascript.js~reflect", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect", "src/.external-ecmascript.js~Reflect", "external" ], [ "src/.external-ecmascript.js~regexp", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp", "src/.external-ecmascript.js~RegExp", "external" ], [ "src/.external-ecmascript.js~set", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set", "src/.external-ecmascript.js~Set", "external" ], [ "src/.external-ecmascript.js~string", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String", "src/.external-ecmascript.js~String", "external" ], [ "src/.external-ecmascript.js~symbol", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol", "src/.external-ecmascript.js~Symbol", "external" ], [ "src/.external-ecmascript.js~syntaxerror", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError", "src/.external-ecmascript.js~SyntaxError", "external" ], [ "src/.external-ecmascript.js~typeerror", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError", "src/.external-ecmascript.js~TypeError", "external" ], [ "src/.external-ecmascript.js~urierror", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError", "src/.external-ecmascript.js~URIError", "external" ], [ "src/.external-ecmascript.js~uint16array", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array", "src/.external-ecmascript.js~Uint16Array", "external" ], [ "src/.external-ecmascript.js~uint32array", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array", "src/.external-ecmascript.js~Uint32Array", "external" ], [ "src/.external-ecmascript.js~uint8array", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array", "src/.external-ecmascript.js~Uint8Array", "external" ], [ "src/.external-ecmascript.js~uint8clampedarray", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray", "src/.external-ecmascript.js~Uint8ClampedArray", "external" ], [ "src/.external-ecmascript.js~weakmap", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap", "src/.external-ecmascript.js~WeakMap", "external" ], [ "src/.external-ecmascript.js~weakset", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet", "src/.external-ecmascript.js~WeakSet", "external" ], [ "src/.external-ecmascript.js~boolean", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean", "src/.external-ecmascript.js~boolean", "external" ], [ "src/.external-ecmascript.js~function", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function", "src/.external-ecmascript.js~function", "external" ], [ "src/.external-ecmascript.js~null", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null", "src/.external-ecmascript.js~null", "external" ], [ "src/.external-ecmascript.js~number", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number", "src/.external-ecmascript.js~number", "external" ], [ "src/.external-ecmascript.js~object", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object", "src/.external-ecmascript.js~object", "external" ], [ "src/.external-ecmascript.js~string", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String", "src/.external-ecmascript.js~string", "external" ], [ "src/.external-ecmascript.js~undefined", "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined", "src/.external-ecmascript.js~undefined", "external" ], [ "src/alternation.js", "file/src/alternation.js.html", "src/alternation.js", "file" ], [ "src/alternation.js~alternation#constructor", "class/src/alternation.js~Alternation.html#instance-constructor-constructor", "src/alternation.js~Alternation#constructor", "method" ], [ "src/alternation.js~alternation#matchers", "class/src/alternation.js~Alternation.html#instance-member-matchers", "src/alternation.js~Alternation#matchers", "member" ], [ "src/alternation.js~alternation#parse", "class/src/alternation.js~Alternation.html#instance-method-parse", "src/alternation.js~Alternation#parse", "method" ], [ "src/charset.js", "file/src/charset.js.html", "src/charset.js", "file" ], [ "src/charset.js~charset#constructor", "class/src/charset.js~CharSet.html#instance-constructor-constructor", "src/charset.js~CharSet#constructor", "method" ], [ "src/charset.js~charset#parse", "class/src/charset.js~CharSet.html#instance-method-parse", "src/charset.js~CharSet#parse", "method" ], [ "src/feed.js", "file/src/feed.js.html", "src/feed.js", "file" ], [ "src/feed.js~feed#constructor", "class/src/feed.js~Feed.html#instance-constructor-constructor", "src/feed.js~Feed#constructor", "method" ], [ "src/feed.js~feed#eat", "class/src/feed.js~Feed.html#instance-method-eat", "src/feed.js~Feed#eat", "method" ], [ "src/feed.js~feed#peek", "class/src/feed.js~Feed.html#instance-method-peek", "src/feed.js~Feed#peek", "method" ], [ "src/feed.js~feed#revert", "class/src/feed.js~Feed.html#instance-method-revert", "src/feed.js~Feed#revert", "method" ], [ "src/feed.js~feed#size", "class/src/feed.js~Feed.html#instance-get-size", "src/feed.js~Feed#size", "member" ], [ "src/index.js", "file/src/index.js.html", "src/index.js", "file" ], [ "src/matcher.js", "file/src/matcher.js.html", "src/matcher.js", "file" ], [ "src/matcher.js~matcher#parse", "class/src/matcher.js~Matcher.html#instance-method-parse", "src/matcher.js~Matcher#parse", "method" ], [ "src/pattern.js", "file/src/pattern.js.html", "src/pattern.js", "file" ], [ "src/pattern.js~pattern#constructor", "class/src/pattern.js~Pattern.html#instance-constructor-constructor", "src/pattern.js~Pattern#constructor", "method" ], [ "src/pattern.js~pattern#parse", "class/src/pattern.js~Pattern.html#instance-method-parse", "src/pattern.js~Pattern#parse", "method" ], [ "src/quantifier.js", "file/src/quantifier.js.html", "src/quantifier.js", "file" ], [ "src/quantifier.js~quantifier#constructor", "class/src/quantifier.js~Quantifier.html#instance-constructor-constructor", "src/quantifier.js~Quantifier#constructor", "method" ], [ "src/quantifier.js~quantifier#parse", "class/src/quantifier.js~Quantifier.html#instance-method-parse", "src/quantifier.js~Quantifier#parse", "method" ], [ "src/range.js", "file/src/range.js.html", "src/range.js", "file" ], [ "src/range.js~range#constructor", "class/src/range.js~Range.html#instance-constructor-constructor", "src/range.js~Range#constructor", "method" ], [ "src/range.js~range#parse", "class/src/range.js~Range.html#instance-method-parse", "src/range.js~Range#parse", "method" ], [ "src/sequence.js", "file/src/sequence.js.html", "src/sequence.js", "file" ], [ "src/sequence.js~sequence#constructor", "class/src/sequence.js~Sequence.html#instance-constructor-constructor", "src/sequence.js~Sequence#constructor", "method" ], [ "src/sequence.js~sequence#matchers", "class/src/sequence.js~Sequence.html#instance-member-matchers", "src/sequence.js~Sequence#matchers", "member" ], [ "src/sequence.js~sequence#parse", "class/src/sequence.js~Sequence.html#instance-method-parse", "src/sequence.js~Sequence#parse", "method" ], [ "src/utils.js", "file/src/utils.js.html", "src/utils.js", "file" ], [ "test/alternation.js", "test-file/test/alternation.js.html", "test/alternation.js", "testFile" ], [ "test/charset.js", "test-file/test/charset.js.html", "test/charset.js", "testFile" ], [ "test/feed.js", "test-file/test/feed.js.html", "test/feed.js", "testFile" ], [ "test/pattern.js", "test-file/test/pattern.js.html", "test/pattern.js", "testFile" ], [ "test/quantifier.js", "test-file/test/quantifier.js.html", "test/quantifier.js", "testFile" ], [ "test/range.js", "test-file/test/range.js.html", "test/range.js", "testFile" ], [ "test/sequence.js", "test-file/test/sequence.js.html", "test/sequence.js", "testFile" ] ]
process.chdir(__dirname); const fs = require("fs"); const { rollup } = require("rollup"); const { bundleSize } = require("../lib/rollup-plugin-bundle-size.cjs"); const consoleLogMock = jest.fn(); global.console = { ...global.console, log: consoleLogMock }; beforeEach(() => { consoleLogMock.mockClear(); }); function testFixtures(dir, testName) { test(testName, async () => { const options = { input: `fixtures/${dir}/main.js`, plugins: [bundleSize()], }; const build = await rollup(options); await build.generate({ format: "cjs" }); expect(consoleLogMock.mock.calls.length).toBe(1); }); } for (const dir of fs.readdirSync(`./fixtures`)) { testFixtures(dir, `${dir}`); }
const path = require("path"); module.exports = { entry: ["./js/index.js"], output: { path: path.resolve(__dirname, "out"), //output directory filename: "out.js", //output file (merge all JS-files will into one out.js file) publicPath: "out" }, module: { rules: [ //scripts rule (*.js) { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", options: { presets: [ [ "env", { targets: { browsers: ["> 1%", "last 2 versions"] // browsers: ['Chrome 49'] } } ] ] } } }, { test: /\.scss$/, use: [ "style-loader", // creates style nodes from JS strings "css-loader", // translates CSS into CommonJS "sass-loader" // compiles Sass to CSS ] }, { test: /\.(woff(2)?|ttf|eot|otf|svg)(\?v=\d+\.\d+\.\d+)?$/, use: [ { loader: "file-loader", options: { name: "[name].[ext]", outputPath: "/fonts/" } } ] }, { test: /\.(html)$/, use: { loader: "html-loader", options: { attrs: false } } }, { test: /\.(jpe?g|png|gif|svg)$/i, use: [ { loader: "file-loader", options: { name: "[name].[ext]", outputPath: "/images/" } } ] } ] }, devServer: { filename: "./js/out.js" }, plugins: [], watch: true, mode: "development", devtool: "source-map" };
const path = require('path') module.exports = { mode: 'none', entry: './src/main.js', output: { filename: 'bundle.js', path: path.join(__dirname, 'dist'), publicPath: 'dist/' }, module: { rules: [ { test: /.jpg$/, use: { loader: 'url-loader', options: { limit: 10 * 1024 // 10 kb } } }, { test: /\.(html)$/, use: { loader: 'html-loader', options: { // attrs: ['img:src', 'a:href'] // 这个怎么会报错啊? attributes: { list: [ { tag: 'a', attribute: 'href', type: 'src' }, { tag: 'img', attribute: 'src', type: 'src' } ] } } } } ] } }
// В HTML есть пустой список ul#ingredients. // < ul id = "ingredients" ></ > // В JS есть массив строк. // const ingredients = [ // 'Картошка', // 'Грибы', // 'Чеснок', // 'Помидоры', // 'Зелень', // 'Приправы', // ]; // Напиши скрипт, который для каждого элемента массива ingredients // создаст отдельный li, после чего вставит все li за одну операцию // в список ul.ingredients. // Для создания DOM - узлов используй document.createElement(). const ingredients = [ "Картошка", "Грибы", "Чеснок", "Помидоры", "Зелень", "Приправы" ]; const ulEl = document.getElementById('ingredients') const createLiElements = ingredients.map(ingredient => { const liEl = document.createElement('li'); liEl.textContent = ingredient; return liEl; }); ulEl.append(...createLiElements);
const http = require("http"); const url = require("url"); const PORT = 8080; let counter = 8999; const routeHandlers = { GET: { "/": (req, res) => res.end("Hello, World!"), "/goodbye": (req, res) => res.end("Goodbye, World!") }, POST: { "/counter": (req, res) => { counter++; res.end(counter.toString()); } } }; const server = http.createServer((req, res) => { const method = req.method; const path = url.parse(req.url).path; console.log(`Processing request: ${method} ${path}`); if (routeHandlers[method][path]) { routeHandlers[method][path](req, res); } else { res.statusCode = 404; res.end("Not Found"); } }); server.listen(PORT, () => { console.log("Server is listening at http://localhost:8080"); });
$(function () { //***************************************************** // グルーバル変数 //***************************************************** var mode = ""; var checkNum = ""; var groupNo = ""; //20200323 ADD ? //var SubmitMode = ""; //20200317 ADD 詳細・見積追加 var CheckNum = ""; //results[1] var SalesPersonName = ""; //results[2] var Title = ""; //results[3] var CustomerCode = ""; //results[4] var CustomerName = ""; //results[5] //20200323 ADD const MaxDispLine = 20; var NowDispMax; //リスト・検索 var GroupNoArr = {}; var rGroupNameArr = {}; var SalesPersonNameArr = {}; //詳細 //var GroupNoArr = {}; //var rGroupNameArr = {}; var LeaderNameArr = {}; var rGroupCycleArr = {}; var CheckNumArr = {}; //var SalesPersonNameArr = {}; var LeaderFlagArr = {}; var TitleArr = {}; var CustomerCodeArr = {}; var CustomerNameArr = {}; //20200407 ADD var EditFlagArr = {}; var NewCheckNumFlagArr = {}; //***************************************************** ////20200313 MOVE ////一覧へ戻る //$('#BtnBack').click(function () { // //parent.$.closeDialog(); //ok // location.href = "./PopGroup.aspx?mode=list"; //グループ管理 リストへ戻る //}); ////20200313 ADD test reloadDialog //$('#BtnTest').click(function () { // parent.$.reloadDialog(); //ok //}); //───────────────────────────────────── //機能: グループ管理画面Load時イベント //引数: //戻値: //補足: //───────────────────────────────────── $(document).ready(function () { //test //alert("$(#SubmitMode).val()=" + $("#SubmitMode").val()); //alert("$(#sGroupNo).val()=" + $("#sGroupNo").val()); //alert("sGroupNo=" + sGroupNo); //test2 //var querystr = window.location.search; // GET変数が存在する場合 //if (querystr) { //alert("PopGroup.js - querystr=" + querystr); //} //***************************************************** //test1 //var url = "./Pages/PopGroup/PopGroup.aspx/GetJsonTestData"; //var data = JSON.stringify({ test: 'TEST' }); //var result = parent.$.getAjaxData(url, data); //var esData = JSON.parse(result); ////if (result.indexOf('エラー:') != -1) { //if (result.match(/エラー:/)) { // alert(esData); // return false; //} //alert(esData["DT1"][0]["A"] + ':' + esData["DT1"][0]["B"] + ':' + esData["DT1"][0]["C"]); //alert(esData["DT2"][0]["A"]); //***************************************************** var querystr = window.location.search; //TODO:検索条件の値は持ち回る←保留 // GET変数が存在する場合 mode = ""; checkNum = ""; groupNo = ""; if (querystr) { if (!querystr.match(/&/)) { //querystrに含む場合の処理 if (querystr.split('=')[0].match(/mode/)) { mode = querystr.split('=')[1]; } //if (querystr.split('=')[0].match(/test/) && querystr.split('=')[1].match(/on/)) { // TestMode = true; //} else if (querystr.split('=')[0].match(/test/) && querystr.split('=')[1].match(/off/)) { // TestMode = false; //} if (querystr.split('=')[0].match(/cno/)) { checkNum = querystr.split('=')[1]; } if (querystr.split('=')[0].match(/gno/)) { groupNo = querystr.split('=')[1]; } } else { // ?を取り除くため、1から始める。keyと値に分割。 array = querystr.slice(1).split('&'); qsarr = new Array(); // GET変数を順に処理 $.each(array, function (index, elem) { if (elem.split('=')[0].match(/mode/)) { mode = elem.split('=')[1]; } //if (elem.split('=')[0].match(/test/) && elem.split('=')[1].match(/on/)) { // TestMode = true; //} else if (elem.split('=')[0].match(/test/) && elem.split('=')[1].match(/off/)) { // TestMode = false; //} if (elem.split('=')[0].match(/cno/)) { checkNum = elem.split('=')[1]; } if (elem.split('=')[0].match(/gno/)) { groupNo = elem.split('=')[1]; } } ); } } //画面切り替え $.pageInitSwitch(mode); //mode="list"の場合、リストへ if (mode == "list") { ////var url = "./Pages/PopGroup/PopGroup.aspx/GetJsonGroupData"; //$.pageInitDisplay(); //検索結果エリア:非表示 //TODO: 検索条件を持ち回る } //mode="detail"の場合、詳細へ if (mode == "detail") { //test data //groupNo = "GROUP001"; //checkNum = "X19060100001"; //Title = "GroupTitle1"; //新規の場合のタイトル //注意:新規作成の場合、gno = '新規作成'->新規作成用のデータも積む if (groupNo == "新規作成") { //$.pageInitMainDetail(); } else { } var url = "./Pages/PopGroup/PopGroup.aspx/GetJsonGroupDetailData"; var data = JSON.stringify({ GroupNo: groupNo, CheckNum: checkNum }); var result = parent.$.getAjaxData(url, data); //エラーの場合 if (result.match(/エラー:/)) { alert(result); return false; } var retData = JSON.parse(result); var grpData1 = null; var grpData2 = null; if (retData != null) { grpData1 = retData["group_table1"] grpData2 = retData["group_table2"] $.pageInitDetail(grpData1, grpData2); $.pageDisplayDetail(groupNo, checkNum); } else { } } $("#Mode").val(mode); $("#CheckNum").val(checkNum); $("#GroupNo").val(groupNo); }); //───────────────────────────────────── //機能: グループ管理画面 初期化 //引数: //戻値: //補足: //───────────────────────────────────── $.pageInitMain = function () { } //───────────────────────────────────── //機能: グループ管理画面 取得データ編集 //引数: //戻値: //補足: //───────────────────────────────────── $.pageInit = function (grpData) { } //───────────────────────────────────── //機能: グループ管理画面 取得データ表示 //引数: //戻値: //補足: //───────────────────────────────────── $.pageDisplay = function () { } //*****************************リスト画面・詳細画面 切替表示***************** //───────────────────────────────────── //機能: グループ管理・リスト 初期表示 //引数: //戻値: //補足: //───────────────────────────────────── $.pageInitSwitch = function (mode) { if (mode == "list") { $("#group_detail_area").children().remove(); } if (mode == "detail") { $("#group_list_area").children().remove(); } } //*****************************リスト 初期*********************************** //───────────────────────────────────── //機能: グループ管理・リスト 初期表示 //引数: //戻値: //補足: //───────────────────────────────────── $.pageInitDisplay = function () { $("#group_result_table").children().remove(); } //*****************************詳細 見積追加*********************************** //20200317 ADD //───────────────────────────────────── //機能: グループ管理・詳細・見積追加 初期化 //引数: //戻値: //補足: //───────────────────────────────────── $.pageInitMainDetailNew = function () { //results[0]="T"->廃止 CheckNum = ""; //results[1]->results[0] SalesPersonName = ""; //results[2]->results[1] Title = ""; //results[3]->results[2] CustomerCode = ""; //results[4]->results[3] CustomerName = ""; //results[5]->results[4] } //20200317 ADD //───────────────────────────────────── //機能: グループ管理・詳細・見積追加 データ編集 //引数: //戻値: //補足: //───────────────────────────────────── $.pageInitDetailNew = function (grpData) { // 変数初期化 $.pageInitMainDetailNew(); if (Object.keys(grpData).length > 0) { CheckNum = $.trim(grpData[0]["CheckNum"]) SalesPersonName = $.trim(grpData[0]["SalesPersonName"]) Title = $.trim(grpData[0]["Title"]) CustomerCode = $.trim(grpData[0]["CustomerCode"]) CustomerName = $.trim(grpData[0]["CustomerName"]) } } //20200317 ADD //───────────────────────────────────── //機能: グループ管理・詳細・見積追加 データ表示 //引数: //戻値: //補足: //───────────────────────────────────── $.pageDisplayDetailNew = function () { // DOM操作 group_table = document.getElementById("group_table"); group_table_th = document.getElementById("group_table_th"); // 結合を増やす document.getElementById("group_table_th").rowSpan = group_table_th.rowSpan + 1; // 行を増やす rows = group_table.insertRow(-1); cell1 = rows.insertCell(-1); cell2 = rows.insertCell(-1); cell3 = rows.insertCell(-1); rows.setAttribute('id', 'LN_' + CheckNum); //innerHTMLはidに対して cell1.innerHTML = CheckNum + '<br /><span class="leader_flag no_disp" id="LF_' + CheckNum + '">L </span>' + SalesPersonName; cell2.innerHTML = Title + '<br />' + CustomerCode + ':' + CustomerName; cell3.setAttribute('id', 'DL_' + CheckNum); cell3.innerHTML = '<input type="button" class="btn3" id="BN_' + CheckNum + '" value="リーダー" onclick="estimateSystemGroupWindowDetailLeader(\'' + CheckNum + '\');" /> ' + '< input type = "button" class="btn3" value = "削 除" onclick="estimateSystemGroupWindowDetailDelete(\'' + CheckNum + '\');" /> '; // 結果の値に追加 if (document.getElementById("CheckNumList").value != "") { document.getElementById("CheckNumList").value = document.getElementById("CheckNumList").value + "," + CheckNum; } else { document.getElementById("CheckNumList").value = CheckNum; } // グループ名が空の場合は件名を自動挿入 if (document.getElementById("rGroupName").value == "") { document.getElementById("rGroupName").value = Title; } } //*****************************リスト 検索*********************************** //20200324 ADD //───────────────────────────────────── //機能: グループ管理・リスト・検索 初期化 //引数: //戻値: //補足: //───────────────────────────────────── $.pageInitMainSearch = function () { NowDispMax = MaxDispLine; GroupNo = {}; rGroupName = {}; SalesPersonName = {}; for (trCnt = 0; trCnt < NowDispMax; trCnt++) { GroupNo[trCnt] = ""; rGroupName[trCnt] = ""; SalesPersonName[trCnt] = ""; } } //20200324 ADD //───────────────────────────────────── //機能: グループ管理・リスト・検索 データ編集 //引数: //戻値: //補足: //───────────────────────────────────── $.pageInitSearch = function (grpData) { // 変数初期化 $.pageInitMainSearch(); //最大表示件数 if (grpData == null) { NowDispMax = 0; } else if (Object.keys(grpData).length < MaxDispLine) { NowDispMax = Object.keys(grpData).length; } else { NowDispMax = MaxDispLine; } //検索結果 if (NowDispMax > 0) { for (trCnt = 0; trCnt < NowDispMax; trCnt++) { GroupNo[trCnt] = $.trim(grpData[trCnt]["GroupNo"]); rGroupName[trCnt] = $.trim(grpData[trCnt]["rGroupName"]); SalesPersonName[trCnt] = $.trim(grpData[trCnt]["SalesPersonName"]); } } } //20200324 ADD //───────────────────────────────────── //機能: グループ管理・リスト・検索 データ表示 //引数: //戻値: //補足: //───────────────────────────────────── $.pageDisplaySearch = function () { $("#group_result_table").children().remove(); var table_html = ""; table_html += '<table class="group_result_table">'; table_html += ' <tr>'; table_html += ' <th style="width: 100px">グループ番号</th>'; table_html += ' <th>グループ名</th>'; table_html += ' <th style="width: 100px">案件リーダー</th>'; table_html += ' <th style="width: 100px">詳細</th>'; table_html += ' </tr>'; // グループ一覧を表示 if (NowDispMax > 0) { //<%--●データありの場合--%> //TODO:データをセットする for (trCnt = 1; trCnt <= NowDispMax; trCnt++) { table_html += ' <tr>'; table_html += ' <td>' + GroupNo[trCnt - 1] + '</td>'; table_html += ' <td>' + rGroupName[trCnt - 1] + '</td>'; table_html += ' <td>' + SalesPersonName[trCnt - 1] + '</td>'; table_html += ' <td><input type="button" class="btn1" value="詳 細" onclick="estimateSystemGroupWindowDetail(\' ' + GroupNo[trCnt - 1] + ' \');" /></td>'; table_html += ' </tr>'; } } else { //<%--●データなしの場合--%> table_html += ' <tr>'; table_html += ' <td colspan="4" class="td_nodata">グループが見つかりません。</td>'; table_html += ' </tr>'; } table_html += '</table>'; $("#group_result_table").append(table_html); } //*****************************詳細*********************************** //───────────────────────────────────── //機能: グループ管理・詳細 初期化 //引数: //戻値: //補足: //───────────────────────────────────── $.pageInitMainDetail = function () { NowDispMax = MaxDispLine; GroupNoArr = {}; rGroupNameArr = {}; LeaderNameArr = {}; rGroupCycleArr = {}; GroupNoArr[0] = ""; rGroupNameArr[0] = ""; LeaderNameArr[0] = ""; rGroupCycleArr[0] = ""; CheckNumArr = {}; SalesPersonNameArr = {}; LeaderFlagArr = {}; TitleArr = {}; CustomerCodeArr = {}; CustomerNameArr = {}; for (trCnt = 0; trCnt < NowDispMax; trCnt++) { CheckNumArr[trCnt] = ""; SalesPersonNameArr[trCnt] = ""; LeaderFlagArr[trCnt] = "0"; TitleArr[trCnt] = ""; CustomerCodeArr[trCnt] = ""; CustomerNameArr[trCnt] = ""; EditFlagArr[trCnt] = "0"; NewCheckNumFlagArr[trCnt] = "0"; } } //───────────────────────────────────── //機能: グループ管理・詳細 データ編集 //引数: //戻値: //補足: //───────────────────────────────────── $.pageInitDetail = function (grpData1, grpData2) { // 変数初期化 $.pageInitMainSearch(); //最大表示件数 if (grpData1 == null) { NowDispMax = 0; } else if (Object.keys(grpData1).length < MaxDispLine) { NowDispMax = Object.keys(grpData1).length; } else { NowDispMax = 0; } //検索結果 if (NowDispMax > 0) { GroupNoArr[0] = $.trim(grpData1[0]["GroupNo"]); rGroupNameArr[0] = $.trim(grpData1[0]["rGroupName"]); LeaderNameArr[0] = $.trim(grpData1[0]["LeaderName"]); rGroupCycleArr[0] = $.trim(grpData1[0]["rGroupCycle"]); } //最大表示件数 if (grpData2 == null) { NowDispMax = 0; } else if (Object.keys(grpData2).length < MaxDispLine) { NowDispMax = Object.keys(grpData2).length; } else { NowDispMax = MaxDispLine; } //検索結果 if (NowDispMax > 0) { for (trCnt = 0; trCnt < NowDispMax; trCnt++) { CheckNumArr[trCnt] = $.trim(grpData2[trCnt]["CheckNum"]); SalesPersonNameArr[trCnt] = $.trim(grpData2[trCnt]["SalesPersonName"]); LeaderFlagArr[trCnt] = $.trim(grpData2[trCnt]["LeaderFlag"]); TitleArr[trCnt] = $.trim(grpData2[trCnt]["Title"]); CustomerCodeArr[trCnt] = $.trim(grpData2[trCnt]["CustomerCode"]); CustomerNameArr[trCnt] = $.trim(grpData2[trCnt]["CustomerName"]); EditFlagArr[trCnt] = $.trim(grpData2[trCnt]["EditFlag"]); //新規作成 NewCheckNumFlagArr[trCnt] = $.trim(grpData2[trCnt]["NewCheckNumFlag"]); //紐づけの有無 } } } //───────────────────────────────────── //機能: グループ管理・詳細 データ表示 //引数: //戻値: //補足: //───────────────────────────────────── $.pageDisplayDetail = function (groupNo, checkNum) { $("#group_detail_area").children().remove(); var count = NowDispMax + 1; var table_html = ""; table_html += '<p class="new_group">'; table_html += ' <input type="button" value="一覧へ戻る" id="BtnBackToList" onclick="estimateSystemGroupWindowBack();" />'; table_html += '</p>'; table_html += '<p class="search_ttl">グループ情報</p>'; table_html += '<table class="group_table" id="group_table">'; table_html += ' <tr>'; table_html += ' <th style="width: 100px">グループ番号</th>'; table_html += ' <td colspan="3">'; table_html += ' <input type="text" class="box1" name="rGroupNo" id="rGroupNo" value="' + GroupNoArr[0] + '" maxlength="11" readonly />'; table_html += ' </td>'; table_html += ' </tr>'; table_html += ' <tr>'; table_html += ' <th>グループ名</th>'; table_html += ' <td colspan="3">'; if (EditFlagArr[0] == "0") { table_html += ' <input type="text" class="box3" name="rGroupName" id="rGroupName" value="' + rGroupNameArr[0] + '" maxlength="100" readonly />'; } else { table_html += ' <input type="text" class="box3" name="rGroupName" id="rGroupName" value="' + rGroupNameArr[0] + '" maxlength="100" />'; } table_html += ' </td>'; table_html += ' </tr>'; table_html += ' <tr>'; table_html += ' <th>案件リーダー</th>'; table_html += ' <td colspan="3">'; table_html += ' <input type="text" class="box1" name="rGroupLeader" id="rGroupLeader" value="' + LeaderNameArr[0] + '" maxlength="10" readonly />'; table_html += ' </td>'; table_html += ' </tr>'; table_html += ' <tr>'; table_html += ' <th>サイクル</th>'; table_html += ' <td colspan="3">'; if (EditFlagArr[0] == "0") { table_html += ' <input type="text" class="box4" name="rGroupCycle" id="rGroupCycle" value="' + rGroupCycleArr[0] + '" maxlength="2" readonly />'; } else { table_html += ' <input type="text" class="box4" name="rGroupCycle" id="rGroupCycle" value="' + rGroupCycleArr[0] + '" maxlength="2" />'; } table_html += ' </td>'; table_html += ' <tr>'; table_html += ' <th rowspan="' + count + '" id="group_table_th">所属見積<br>'; table_html += ' <input type="button" class="btn1" value="見積追加" onclick="estimateSystemGroupWindowDetailNew();" /></th>'; table_html += ' <th style="width: 110px">見積番号/営業</th>'; table_html += ' <th>見積件名/得意先CD・名</th>'; table_html += ' <th style="width: 120px"></th>'; table_html += ' </tr>'; var CheckNumListValue = ""; var LeaderFlagValue = ""; // グループ一覧を表示 if (NowDispMax > 0) { //<%--●データありの場合--%> for (trCnt = 1; trCnt <= NowDispMax; trCnt++) { //新規作成の場合 if (EditFlagArr[trCnt-1] == "1") { //見積番号がある場合 if (NewCheckNumFlagArr[trCnt - 1] == "1") { table_html += ' <tr class="tr_new">'; //table_html += ' <td><a href="../../Detail.aspx?cno=' + CheckNumArr[trCnt - 1] + '" target="_blank">' + CheckNumArr[trCnt - 1] + '</a><br>' + SalesPersonNameArr[trCnt - 1] + '</td>'; table_html += ' <td><a href="javascript: estimateSystemGroupWindowClose(\'' + CheckNumArr[trCnt - 1] + '\');">' + CheckNumArr[trCnt - 1] + '</a><br>' + SalesPersonNameArr[trCnt - 1] + '</td>'; table_html += ' <td>' + TitleArr[trCnt - 1] + '<br>' + CustomerCodeArr[trCnt - 1] + ':' + CustomerNameArr[trCnt - 1] + '</td>'; table_html += ' <td>'; table_html += ' <input type="button" class="btn3" id="new_add_btn" value="追 加" onclick="estimateSystemGroupWindowDetailAdd(\'' + CheckNumArr[trCnt - 1] + '\');" />'; table_html += ' </td>'; table_html += ' </tr>'; //見積番号がない場合 } else { table_html += ' <tr class="tr_new">'; table_html += ' <td>' + CheckNumArr[trCnt - 1] + '</td>'; table_html += ' <td>' + TitleArr[trCnt - 1] + '</td>'; // 不明データ table_html += ' <td>aaa</td>'; table_html += ' </tr>'; } //新規作成でない場合 } else { //リーダの場合 if (LeaderFlagArr[trCnt - 1] == "1") { table_html += ' <tr id="LN_' + CheckNumArr[trCnt - 1] + '" class="tr_leader">'; //table_html += ' <td><a href="../../Detail.aspx?cno=' + CheckNumArr[trCnt - 1] + '" target="_blank">' + CheckNumArr[trCnt - 1] + '</a><br>'; table_html += ' <td><a href="javascript: estimateSystemGroupWindowClose(\'' + CheckNumArr[trCnt - 1] + '\');">' + CheckNumArr[trCnt - 1] + '</a><br>'; table_html += ' <span class="leader_flag" id="LF_' + CheckNumArr[trCnt - 1] + '">L </span>' + SalesPersonNameArr[trCnt - 1] + '</td>'; table_html += ' <td>' + TitleArr[trCnt - 1] + '<br>' + CustomerCodeArr[trCnt - 1] + ':' + CustomerNameArr[trCnt - 1] + '</td>'; table_html += ' <td id="DL_' + CheckNumArr[trCnt - 1] + '">'; table_html += ' <input type="button" class="btn3" id="BN_' + CheckNumArr[trCnt - 1] + '" value="リーダー" onclick="estimateSystemGroupWindowDetailLeader(\'' + CheckNumArr[trCnt - 1] + '\');" disabled="disabled" />'; table_html += ' <input type="button" class="btn3" value="削 除" onclick="estimateSystemGroupWindowDetailDelete(\'' + CheckNumArr[trCnt - 1] + '\');" />'; table_html += ' </td>'; table_html += ' </tr>'; LeaderFlagValue = CheckNumArr[trCnt - 1]; } else { //リーダでない場合 table_html += ' <tr id="LN_' + CheckNumArr[trCnt - 1] + '">'; //table_html += ' <td><a href="../../Detail.aspx?cno=' + CheckNumArr[trCnt - 1] + '" target="_blank">' + CheckNumArr[trCnt - 1] + '</a><br>'; table_html += ' <td><a href="javascript: estimateSystemGroupWindowClose(\'' + CheckNumArr[trCnt - 1] + '\');">' + CheckNumArr[trCnt - 1] + '</a><br>'; table_html += ' <span class="leader_flag no_disp" id="LF_' + CheckNumArr[trCnt - 1] + '">L </span>' + SalesPersonNameArr[trCnt - 1] + '</td>'; table_html += ' <td>' + TitleArr[trCnt - 1] + '<br>' + CustomerCodeArr[trCnt - 1] + ':' + CustomerNameArr[trCnt - 1] + '</td>'; table_html += ' <td id="DL_' + CheckNumArr[trCnt - 1] + '">'; table_html += ' <input type="button" class="btn3" id="BN_' + CheckNumArr[trCnt - 1] + '" value="リーダー" onclick="estimateSystemGroupWindowDetailLeader(\'' + CheckNumArr[trCnt - 1] + '\');" />'; table_html += ' <input type="button" class="btn3" value="削 除" onclick="estimateSystemGroupWindowDetailDelete(\'' + CheckNumArr[trCnt - 1] + '\');" />'; table_html += ' </td>'; table_html += ' </tr>'; } if (CheckNumListValue != "") { CheckNumListValue = CheckNumListValue + "," ; } CheckNumListValue = CheckNumListValue + CheckNumArr[trCnt - 1]; } }//for table_html += '</table>'; table_html += '<p class="group_save">'; table_html += '<input type="button" class="btn2" value="保存する" onclick="estimateSystemGroupWindowDetailSave();" />'; table_html += '</p>'; table_html += '<p class="group_notice">※すべての操作は保存しないと反映されません。</p>'; table_html += '<input type="hidden" name="CheckNumList" id="CheckNumList" value="' + CheckNumListValue + '" />'; table_html += '<input type="hidden" name="LeaderCheckNum" id="LeaderCheckNum" value="' + LeaderFlagValue + '" />'; } else { //<%--●データなしの場合--%> //TODO:データをセットする } $("#group_detail_area").append(table_html); } }); // *********************************************** // イベント // *********************************************** // グループ管理・グループリスト 検索 //20200323 EDIT //function estimateSystemGroupWindowSubmit(mode) { // document.getElementById("SubmitMode").value = mode; // document.ESGroupWindow.submit(); //} function estimateSystemGroupWindowSubmit() { //var mode = "group_search"; //document.getElementById("SubmitMode").value = mode; //document.getElementById("Mode").value = "list"; //location.href = "./PopGroup.aspx?mode=" + mode; //SubmitMode = mode; //Mode = "list;" //var gno = $.trim($("#GroupNo").val()); //var cno = $.trim($("#CheckNum").val()); //document.ESGroupWindow.action = "./PopGroup.aspx?mode=" + mode; //document.ESGroupWindow.submit(); //グループ管理 一覧画面へ //event.preventDefault(); var sGroupNo = $.trim($("#sGroupNo").val()); var sGroupName = $.trim($("#sGroupName").val()); var sProductCode = $.trim($("#sProductCode").val()); var sSalesPerson = $.trim($("#sSalesPerson").val()); //alert("estimateSystemGroupWindowSubmit-$(#sGroupNo).val()=" + $("#sGroupNo").val()); //TODO:20200327 test:ok //parent.$.setCookie("sGroupNo", $.trim($("#sGroupNo").val())); //alert("getCookie(sGroupNo)=" + parent.$.getCookie("sGroupNo")); //***************************************************** //本番 var url = "./Pages/PopGroup/PopGroup.aspx/GetJsonGroupData"; //TODO:日本語はUrlEncode必要!!!h ttp://surferonwww.info/BlogEngine/post/2011/11/07/Encoding-of-URL-directly-written-in-address-bar-of-browser.aspx var data = JSON.stringify({ sGroupNo: sGroupNo, sGroupName: sGroupName, sProductCode: sProductCode, sSalesPerson: sSalesPerson }); //TODO:日本語はUrlEncode必要***************sample*************** //data = $.param(data); //jq //data = encodeURI(data); //js //data = decodeURIComponent($.param(data)); var result = parent.$.getAjaxData(url, data); //jQuery.Ajax //エラーの場合 if (result.match(/エラー:/)) { alert(result); return false; } var grpData = JSON.parse(result); //test //if (grpData == null) { // alert("該当データが見つかりませんでした。"); // return false; //} //if (grpData === "" || grpData === undefined) { // alert("test:grpData === 空 || grpData === undefined"); // return false; //} //if (grpData.length === undefined) { // alert("test:grpData.length === undefined"); // return false; //} //if (grpData.length == 0) { // alert("test:grpData.length == 0"); // return false; //} //if (Object.keys(grpData).length == 0) { // alert("test:Object.keys(grpData).length == 0"); // return false; //} if (grpData == null) { $.pageInitSearch(null); } else { $.pageInitSearch(grpData["group_result_table"]); } $.pageDisplaySearch(); //0件の場合もこのメソッドで画面表示する return false; } // グループ管理・グループ詳細 詳細・新規作成 20200317 EDIT function estimateSystemGroupWindowDetail(gno) { //document.getElementById("GroupNo").value = gno; //document.ESGroupWindow.submit(); //20200325 EDIT modeを追加 var mode = "detail"; //location.href = "./PopGroup.aspx?mode=" + mode + "&gno=" + gno; //新規作成の場合、gno='新規作成' //20200323 EDIT mode, cnoを追加 //TODO:詳細画面のグループ管理ボタン押下時、見積番号を持ち回る var cno = $.trim($("#CheckNum").val()); location.href = "./PopGroup.aspx?mode=" + mode + "&gno=" + gno + "&cno=" + cno; //新規作成の場合、gno='新規作成' //グループ管理 詳細画面へ } // function estimateSystemGroupWindowClose(cno) { parent.$.closeDialog(); parent.location.href = "../../Detail.aspx?cno=" + cno; } // グループ管理・グループ詳細 一覧へ戻る 20200318 ADD function estimateSystemGroupWindowBack() { //var mode = "group_back"; //session取得 //document.getElementById("SubmitMode").value = mode; //document.getElementById("Mode").value = "list"; //TODO:必要なパラメータをセットする //document.ESGroupWindow.action = "./PopGroup.aspx?mode=" + mode; //document.ESGroupWindow.submit(); //グループ管理 一覧画面へ //20200325 EDIT modeを追加 var mode = "list"; location.href = "./PopGroup.aspx?mode=" + mode + "&gno="; //20200323 EDIT cnoを追加 //TODO:詳細画面のグループ管理ボタン押下時、見積番号を持ち回る場合 20200325<-保留 //var cno = /document.getElementById("CheckNum").value; //location.href = "./PopGroup.aspx?mode=" + mode + "&gno=" + "&cno=" + cno; } // グループ管理・グループ詳細・追加ボタン function estimateSystemGroupWindowDetailAdd(CNo) { // 保存用に見積番号の受け渡し document.getElementById("NewAddChk").value = CNo; document.getElementById("new_add_btn").style.display = "none"; if (document.getElementById("CheckNumList").value != "") { document.getElementById("CheckNumList").value = document.getElementById("CheckNumList").value + "," + CNo; } else { document.getElementById("CheckNumList").value = CNo; } } // グループ管理・グループ詳細・保存ボタン function estimateSystemGroupWindowDetailSave() { //if (document.getElementById("CheckNumList").value == "") { // if (!confirm("紐付いた見積が無い為、削除されます。\nよろしいですか?")) { // return false; // } //} //if (document.getElementById("rGroupName").value == "") { // alert("グループ名を設定してください。"); // return false; //} //20200324 EDIT //document.getElementById("SubmitMode").value = "save"; //document.ESGroupWindow.submit(); var rGroupNo = $.trim($("#rGroupNo").val()); var rGroupName = $.trim($("#rGroupName").val()); var rGroupCycle = $.trim($("#rGroupCycle").val()); var LeaderCheckNum = $.trim($("#LeaderCheckNum").val()); var CheckNumList = $.trim($("#CheckNumList").val()); //***************************************************** //本番 var url = "./Pages/PopGroup/PopGroup.aspx/SaveJsonGroupData"; //TODO:日本語はUrlEncode必要!!!h ttp://surferonwww.info/BlogEngine/post/2011/11/07/Encoding-of-URL-directly-written-in-address-bar-of-browser.aspx var data = JSON.stringify({ GroupNo: rGroupNo, GroupName: rGroupName, GroupCycle: rGroupCycle, LeaderCheckNum: LeaderCheckNum, CheckNumList: CheckNumList }); var result = parent.$.getAjaxData(url, data); //エラーの場合 //Common.js ajaxがreturn ""設定の場合 if (result.match(/エラー:/)) { alert(result); return false; } var message = JSON.parse(result); //if (message == null) { // alert("該当データが見つかりませんでした。"); // return false; //} //if (message.length == 0) { // alert("該当データが見つかりませんでした。"); // return false; //} //if (Object.keys(message).length == 0) { // alert("該当データが見つかりませんでした。"); // return false; //} //結果表示 alert(message["aaa"][0]["message"]); //TODO:仮テーブル名 //Common.js ajaxがreturn null設定の場合 //if (result == "null") { // alert("該当データが見つかりませんでした。"); //} else { // alert("保存しました。"); //} return false; } // グループ管理・グループ詳細・リーダー選択 function estimateSystemGroupWindowDetailLeader(cno) { var now_cno = document.getElementById("LeaderCheckNum").value; if (document.getElementById("LF_" + now_cno)) { document.getElementById("LF_" + now_cno).style.display = "none"; document.getElementById("BN_" + now_cno).disabled = false; //$('button').prop('disabled', true); if (document.getElementById("LN_" + now_cno).className == "tr_leader") { document.getElementById("LN_" + now_cno).className = ""; } } document.getElementById("LF_" + cno).style.display = "inline"; document.getElementById("BN_" + cno).disabled = true; document.getElementById("LN_" + cno).className = "tr_leader"; document.getElementById("LeaderCheckNum").value = cno; } // グループ管理・グループ詳細・削除 function estimateSystemGroupWindowDetailDelete(cno) { document.getElementById("LN_" + cno).className = "tr_delete"; document.getElementById("DL_" + cno).innerHTML = "削除"; if (document.getElementById("LeaderCheckNum").value == cno) { document.getElementById("LeaderCheckNum").value = ""; document.getElementById("LF_" + cno).style.display = "none"; } var CList = document.getElementById("CheckNumList").value; if (CList.indexOf("," + cno) !== -1) { document.getElementById("CheckNumList").value = CList.replace("," + cno,""); } else if (CList.indexOf(cno + ",") !== -1) { document.getElementById("CheckNumList").value = CList.replace(cno + ",",""); } else if (CList.indexOf(cno) !== -1) { document.getElementById("CheckNumList").value = CList.replace(cno,""); } } // グループ管理・グループ詳細・見積追加 20200317 EDIT function estimateSystemGroupWindowDetailNew() { var cno = window.prompt("追加する見積番号を入力してください。", ""); if (cno != "" && cno != null) { var CList = document.getElementById("CheckNumList").value; //CNo + "," + CNo if (CList.indexOf(cno) !== -1) { alert("すでに追加されている見積番号です。"); return false; //ADD } else { // 見積番号の内容を取得する //参考:https://developer.mozilla.org/ja/docs/Learn/JavaScript/Objects/JSON //***************************************************** //test1 //var url = "./Pages/PopGroup/PopGroup.aspx/GetJsonTestData"; //var data = JSON.stringify({ test: 'TEST' }); //var result = $.getAjaxData(url, data); //var esData = JSON.parse(result); ////if (result.indexOf('エラー:') != -1) { //if (esData.match(/エラー:/)) { // alert(esData); // return false; //} //alert(esData["DT1"][0]["A"] + ':' + esData["DT1"][0]["B"] + ':' + esData["DT1"][0]["C"]); //alert(esData["DT2"][0]["A"]); //***************************************************** //本番 var url = "./Pages/PopGroup/PopGroup.aspx/GetJsonGroupDetailNew"; //TODO:日本語はUrlEncode必要!!!h ttp://surferonwww.info/BlogEngine/post/2011/11/07/Encoding-of-URL-directly-written-in-address-bar-of-browser.aspx var data = JSON.stringify({ cno: cno }); var result = parent.$.getAjaxData(url, data); //エラーの場合 if (result.match(/エラー:/)) { alert(result); return false; } //TODO: var grpData = JSON.parse(result); if (grpData == null) { alert("該当データが見つかりません。"); return false; } //if (grpData == null) { // $.pageInitDetailNew(null); //} else { $.pageInitDetailNew(grpData["xxx"]); //TODO:仮テーブル名 //} $.pageDisplayDetailNew(); return false; } } } //// グループ管理・グループ詳細・見積追加 20200317 EDIT //function estimateSystemGroupWindowDetailNew() { // cno = window.prompt("追加する見積番号を入力してください。", ""); // if (cno != "" && cno != null) { // CList = document.getElementById("CheckNumList").value; // if (CList.indexOf(cno) !== -1) { // alert("すでに追加されている見積番号です。"); // } else { // // 見積番号の内容を取得する // var url = "ES_GroupEstimate.asp?CNO=" + cno; // http.open("GET", url, false); // http.onreadystatechange = hhrAdminGroupWindowDetailNew; // Process_flg = true; // http.send(null); // } // } //} //// 結果代入用 ・・・ 見積追加 20200317 EDIT //function hhrAdminGroupWindowDetailNew() { // if (http.readyState == 4) { // if (http.status == 200) { // if (http.responseText.indexOf('invalid') == -1) { // results = http.responseText.split("@"); // if (results[0] == "T") { // // DOM操作 // group_table = document.getElementById("group_table"); // group_table_th = document.getElementById("group_table_th"); // // 結合を増やす // document.getElementById("group_table_th").rowSpan = group_table_th.rowSpan + 1; // // 行を増やす // rows = group_table.insertRow(-1); // cell1 = rows.insertCell(-1); // cell2 = rows.insertCell(-1); // cell3 = rows.insertCell(-1); // rows.setAttribute('id', 'LN_' + results[1]); // cell1.innerHTML = results[1] + '<br /><span class="leader_flag no_disp" id="LF_' + results[1] + '">L </span>' + results[2]; // cell2.innerHTML = results[3] + '<br />' + results[4] + ':' + results[5]; // cell3.setAttribute('id', 'DL_' + results[1]); // cell3.innerHTML = '<input type="button" class="btn3" id="BN_' + results[1] + '" value="リーダー" onclick="estimateSystemGroupWindowDetailLeader(\'' + results[1] + '\');" /> <input type="button" class="btn3" value="削 除" onclick="estimateSystemGroupWindowDetailDelete(\'' + results[1] + '\');" />'; // // 結果の値に追加 // if (document.getElementById("CheckNumList").value != "") { // document.getElementById("CheckNumList").value = document.getElementById("CheckNumList").value + "," + results[1]; // } else { // document.getElementById("CheckNumList").value = results[1]; // } // // グループ名が空の場合は件名を自動挿入 // if (document.getElementById("rGroupName").value == "") { // document.getElementById("rGroupName").value = results[3]; // } // } else { // alert("該当の見積が見つかりません。"); // } // Process_flg = false; // } // } // } //} //20200318 ADD -> EDIT:changed to estimateSystemGroupWindowBack // グループ管理・グループ詳細 一覧へ戻る //function estimateSystemGroupWindowDetailBack() { // location.href = "./PopGroup.aspx?mode=list"; //グループ管理 一覧画面へ戻る //} //sample************************************** //h ttps://www.sejuku.net/blog/42985 //$('form').submit(function (event) { // event.preventDefault(); //画面が必ず更新されるというブラウザの仕様をキャンセルするため // //post()の処理をここに記述する // $.post('https://httpbin.org/post', 'name=太郎') // .done(function (data) { // console.log(data.form); // }) //})
/** * CSS Relative colors * The CSS Relative Color syntax allows a color to be defined relative to another color using the `from` keyword and optionally `calc()` for any of the color values. * @see https://caniuse.com/css-relative-colors */ /** * @type {import('../features').Feature} */ export default { '': /((rgb)|(rgba)|(hsl)|(hsla)|(hwb))\(\s*from/, };
(function () { "use strict"; angular.module('public') .controller('SignUpController', SignUpController); SignUpController.$inject = ['MenuService', 'UserService']; function SignUpController(MenuService, UserService) { var $ctrl = this; // invoke IFFE to fire up controller actions to save data from the browser (function() { var usr = UserService.getUser(); if (usr) { $ctrl.user = usr; } else { $ctrl.user = { firstName: "", lastName: "", email: "", phone: "", dish: { shortName: "" } } } })(); $ctrl.submitted = false; $ctrl.submit = function() { $ctrl.submitted = true; // console.log("in sign-up.submit") UserService.saveUser($ctrl.user); // console.log("user info:", $ctrl.user.firstName, $ctrl.user.dish) }; $ctrl.checkMenuItem = function() { var promise = MenuService.getMenuItem($ctrl.user.dish.shortName); promise .then(function(result) { $ctrl.regForm.shortName.$setValidity('shortName', true); // console.log("in .then", $ctrl.regForm.shortName) }, function(reason) { $ctrl.regForm.shortName.$setValidity('shortName', false); }); }; } })();
const body=document.querySelector('section'); const div=document.createElement('div'); const el = document.createElement('div'); el.classList.add('visualizzaDOT'); div.classList.add('container'); body.appendChild(el); el.appendChild(div); document.querySelector('body').classList.add('no-scroll'); const dot1=document.createElement('div'); dot1.classList.add('dot'); dot1.setAttribute('id', 'dot1'); div.appendChild(dot1); const dot2=document.createElement('div'); dot2.classList.add('dot'); dot2.setAttribute('id', 'dot2'); div.appendChild(dot2); const dot3=document.createElement('div'); dot3.classList.add('dot'); dot3.setAttribute('id', 'dot3'); div.appendChild(dot3); setTimeout(removeLoad, 4000, el); const propic=document.getElementById('propic'); const foto=document.getElementById('printFoto'); propic.addEventListener('change', checkSize); foto.addEventListener('change', checkSize); function checkSize (event){ const file = event.currentTarget.files[0]; const form=event.currentTarget.parentNode; const submit=form.querySelector('.submit'); if(file.size>41943040){ window.alert('Le dimensioni del file non possono superare 49 Mb') console.log(submit); submit.disabled = true; } else submit.disabled= false; } function removeLoad(el){ el.remove(); document.querySelector('body').classList.remove('no-scroll'); } const div3=document.getElementById('form3'); const div2=document.getElementById('form2'); const div1=document.getElementById('form1'); const articles=document.querySelectorAll('article'); for(let article of articles){ const title=document.createElement('h5'); const div=article.querySelector('div'); title.textContent=article.dataset.type; fetch("managementArea/dati/"+article.dataset.type).then(onResponse).then(onJsonCaricamento); article.insertBefore(title, div); } function onResponse(response){ return response.json(); } function onJsonCaricamento(promise){ console.log(promise); if(promise.type==='fotografi'){ const article=document.querySelectorAll("[data-type='fotografi']")[0]; const table=document.createElement('table'); table.setAttribute('id', 'fotografi'); const titles=document.createElement('tr'); const t0=document.createElement('th'); titles.appendChild(t0); t0.style.width='50px'; const t1=document.createElement('th'); t1.textContent="Nome"; titles.appendChild(t1); const t2=document.createElement('th'); t2.textContent="Cognome"; titles.appendChild(t2); const t3=document.createElement('th'); t3.textContent="Città di nascita"; titles.appendChild(t3); const t4=document.createElement('th'); t4.textContent="Data di nascita"; titles.appendChild(t4); const t5=document.createElement('th'); t5.textContent="Codice Fiscale"; titles.appendChild(t5); const t6=document.createElement('th'); t6.textContent="Data inizio"; titles.appendChild(t6); const t9=document.createElement('th'); t9.textContent="Playlist"; titles.appendChild(t9); const t10=document.createElement('th'); t10.textContent="Profile Picture"; titles.appendChild(t10); table.appendChild(titles); article.insertBefore(table, div1); for(let fotografo of promise.items){ const row=document.createElement('tr'); row.dataset.row=fotografo.CF; row.dataset.nome=fotografo.nome; row.dataset.cognome=fotografo.cognome; const remove=document.createElement('td'); remove.style.width='50px'; const img=document.createElement('img'); img.src="immagini/delete.png"; remove.appendChild(img); img.dataset.ID=fotografo.CF; img.addEventListener('click', deleteFotografo); row.appendChild(remove); const nome=document.createElement('td'); nome.textContent=fotografo.nome; row.appendChild(nome); const cognome=document.createElement('td'); cognome.textContent=fotografo.cognome; row.appendChild(cognome); const citta=document.createElement('td'); citta.textContent=fotografo.citta; row.appendChild(citta); const data=document.createElement('td'); data.textContent=fotografo.data_nascita; row.appendChild(data); const CF=document.createElement('td'); CF.textContent=fotografo.CF; row.appendChild(CF); const dataIn=document.createElement('td'); dataIn.textContent=fotografo.data_inizio; row.appendChild(dataIn); const sp=document.createElement('td'); sp.textContent=fotografo.playlist; row.appendChild(sp); const propic=document.createElement('td'); const im=document.createElement('img'); im.src=fotografo.propic; propic.appendChild(im); im.classList.add('file'); im.style.opacity='1'; im.style.width='150px'; row.appendChild(propic); table.appendChild(row); console.log(row); } const add = document.createElement('img'); add.src='immagini/add.png'; article.insertBefore(add, div1); add.classList.add("add"); add.addEventListener('click', addFotografo); } if(promise.type==='foto'){ const article=document.querySelectorAll("[data-type='foto']")[0]; const table=document.createElement('table'); table.setAttribute('id', 'foto'); const titles=document.createElement('tr'); const t0=document.createElement('th'); titles.appendChild(t0); t0.style.width='50px'; const t1=document.createElement('th'); t1.textContent="Codice"; titles.appendChild(t1); const t2=document.createElement('th'); t2.textContent="Data scatto"; titles.appendChild(t2); const t3=document.createElement('th'); t3.textContent="descrizione"; titles.appendChild(t3); const t4=document.createElement('th'); t4.textContent="Fotografo"; titles.appendChild(t4); const t5=document.createElement('th'); t5.textContent="Genere"; titles.appendChild(t5); const t6=document.createElement('th'); t6.textContent="Titolo"; titles.appendChild(t6); const t9=document.createElement('th'); t9.textContent="Foto"; titles.appendChild(t9); table.appendChild(titles); article.insertBefore(table, div2); for(let fot of promise.items){ console.log(fot); const row=document.createElement('tr'); row.dataset.row=fot.ID; row.dataset.titolo=fot.titolo; const remove=document.createElement('td'); remove.style.width='50px'; const img=document.createElement('img'); img.src="immagini/delete.png"; remove.appendChild(img); img.dataset.ID=fot.ID; img.addEventListener('click', deleteFoto); row.appendChild(remove); const id=document.createElement('td'); id.textContent=fot.ID; row.appendChild(id); const data=document.createElement('td'); data.textContent=fot.data_scatto; row.appendChild(data); const desc=document.createElement('td'); desc.textContent=fot.descrizione; row.appendChild(desc); const fotografo=document.createElement('td'); fotografo.textContent=fot.fotografo; row.appendChild(fotografo); const genere=document.createElement('td'); genere.textContent=fot.genere; row.appendChild(genere); const titolo=document.createElement('td'); titolo.textContent=fot.titolo; row.appendChild(titolo); const foto=document.createElement('td'); const file=document.createElement('img'); file.src=fot.file; file.style.opacity='1'; file.style.width='150px'; foto.appendChild(file); file.classList.add('file'); row.appendChild(foto); table.appendChild(row); console.log(row); } const add = document.createElement('img'); add.src='immagini/add.png'; article.insertBefore(add, div2); add.classList.add("add"); add.addEventListener('click', addFoto); } if(promise.type==='stampe'){ const article=document.querySelectorAll("[data-type='stampe']")[0]; const table=document.createElement('table'); table.setAttribute('id', 'stampe'); const titles=document.createElement('tr'); const t0=document.createElement('th'); titles.appendChild(t0); t0.style.width='50px'; const t1=document.createElement('th'); t1.textContent="Codice"; titles.appendChild(t1); const t2=document.createElement('th'); t2.textContent="Altezza"; titles.appendChild(t2); const t3=document.createElement('th'); t3.textContent="Larghezza"; titles.appendChild(t3); const t4=document.createElement('th'); t4.textContent="Materiale"; titles.appendChild(t4); const t5=document.createElement('th'); t5.textContent="Prezzo"; titles.appendChild(t5); const t7=document.createElement('th'); t7.textContent="Likes"; titles.appendChild(t7); const t8=document.createElement('th'); t8.textContent="Ordini"; titles.appendChild(t8); const t6=document.createElement('th'); t6.textContent="Foto"; titles.appendChild(t6); table.appendChild(titles); article.insertBefore(table, div3); for(let i=0; i<promise.items.length; i++){ let stampa = promise.items[i]; const row=document.createElement('tr'); row.dataset.rowS=stampa.ID; row.dataset.fotoID=stampa.foto; const remove=document.createElement('td'); remove.style.width='50px'; const img=document.createElement('img'); img.src="immagini/delete.png"; remove.appendChild(img); img.dataset.IDS=stampa.ID; img.addEventListener('click', deleteStampa); row.appendChild(remove); const id=document.createElement('td'); id.textContent=stampa.ID; row.appendChild(id); const altezza=document.createElement('td'); altezza.textContent=stampa.altezza; row.appendChild(altezza); const larghezza=document.createElement('td'); larghezza.textContent=stampa.larghezza; row.appendChild(larghezza); const materiale=document.createElement('td'); materiale.textContent=stampa.materiale; row.appendChild(materiale); const prezzo=document.createElement('td'); prezzo.textContent=stampa.prezzo+'$'; row.appendChild(prezzo); const likes=document.createElement('td'); likes.textContent=promise.likes[i].liked; row.appendChild(likes); const saved=document.createElement('td'); saved.textContent=promise.ordered[i].ordered; row.appendChild(saved); const fotoID=document.createElement('td'); fotoID.textContent=stampa.foto; row.appendChild(fotoID); table.appendChild(row); console.log(row); } const add = document.createElement('img'); add.src='immagini/add.png'; article.insertBefore(add, div3); add.classList.add("add"); add.addEventListener('click', addStampa); } } function addStampa(event){ const button=event.currentTarget; button.removeEventListener('click', addStampa); div3.classList.remove('hidden'); const fotoID= document.getElementById('idFoto'); const results=document.querySelectorAll('[data-type="foto"] tr'); const rows=[]; for(let result of results){ rows.push(result); } rows.shift(); const op=fotoID.querySelectorAll('option'); for(let o of op){ o.remove(); } for(let rw of rows){ const opt=document.createElement('option'); opt.setAttribute('value', rw.dataset.row); const txt=document.createElement('p'); txt.textContent=rw.dataset.titolo+ ' (ID '+rw.dataset.row+')'; console.log(rw.dataset.titolo); opt.appendChild(txt); fotoID.appendChild(opt); } const invia= document.getElementById('button3'); invia.addEventListener('click', sendStampa); } function addFoto(event){ const button=event.currentTarget; button.removeEventListener('click', addFoto); div2.classList.remove('hidden'); const fotografo= document.getElementById('cfFotografo'); const results=document.querySelectorAll('[data-type="fotografi"] tr'); console.log(results) const rows=[]; for(let result of results){ rows.push(result); } rows.shift(); for(let rw of rows){ const opt=document.createElement('option'); opt.setAttribute('value', rw.dataset.row); const txt=document.createElement('p'); txt.textContent=rw.dataset.nome+' '+rw.dataset.cognome; opt.appendChild(txt); fotografo.appendChild(opt); } } function addFotografo(event){ const button=event.currentTarget; button.removeEventListener('click', addFotografo); div1.classList.remove('hidden'); } function sendStampa(event){ const button=event.currentTarget; const div=button.parentNode; const altezza=document.getElementsByName('altezza')[0]; const larghezza=document.getElementsByName('larghezza')[0]; const materiale=document.getElementsByName('materiale')[0]; const prezzo=document.getElementsByName('prezzo')[0]; const foto=document.getElementsByName('idFoto')[0]; if((altezza.value!=0)&&(larghezza.value!=0)&&(materiale.value!=0)&&(prezzo.value!=0)&&(foto.value!=0)){ const error=div.querySelector('#error-stampa'); if(error){ error.remove(); } div.classList.add('hidden'); const add=document.querySelectorAll(".add")[2]; add.addEventListener('click', addStampa); fetch("managementArea/addStampa/"+encodeURIComponent(String(altezza.value))+'/'+encodeURIComponent(String(larghezza.value))+'/'+encodeURIComponent(String(materiale.value))+'/'+encodeURIComponent(String(prezzo.value))+'/'+encodeURIComponent(String(foto.value))).then(onResponse).then(onJsonInsertStampa); } else{ const txt=document.getElementById('error-stampa'); if(txt) txt.remove(); const error=document.createElement('p'); error.classList.add('error'); error.setAttribute('id', 'error-stampa'); error.textContent='Compila correttamente tutti i campi.'; div.appendChild(error); } } function onJsonInsertStampa(stampa){ console.log(stampa); const table=document.getElementById('stampe'); const row=document.createElement('tr'); row.dataset.rowS=stampa.ID; row.dataset.fotoID=stampa.foto; const remove=document.createElement('td'); remove.style.width='50px'; const img=document.createElement('img'); img.src="immagini/delete.png"; remove.appendChild(img); img.dataset.IDS=stampa.ID; img.addEventListener('click', deleteStampa); row.appendChild(remove); const id=document.createElement('td'); id.textContent=stampa.ID; row.appendChild(id); const altezza=document.createElement('td'); altezza.textContent=stampa.altezza; row.appendChild(altezza); const larghezza=document.createElement('td'); larghezza.textContent=stampa.larghezza; row.appendChild(larghezza); const materiale=document.createElement('td'); materiale.textContent=stampa.materiale; row.appendChild(materiale); const prezzo=document.createElement('td'); prezzo.textContent=stampa.prezzo+'$'; row.appendChild(prezzo); const likes=document.createElement('td'); likes.textContent='0'; row.appendChild(likes); const ordered=document.createElement('td'); ordered.textContent='0'; row.appendChild(ordered); const fotoID=document.createElement('td'); fotoID.textContent=stampa.foto; row.appendChild(fotoID); table.appendChild(row); } function deleteFotografo(event){ fetch("managementArea/removeFotografo/"+event.currentTarget.dataset.ID).then(onResponse).then(onJsonRemoveFotografo); } function deleteFoto(event){ fetch("managementArea/removeFoto/"+event.currentTarget.dataset.ID).then(onResponse).then(onJsonRemoveFoto); } function onJsonRemoveFoto(promise){ const row=document.querySelector("[data-row='"+promise+"']"); row.remove(); const rows=document.querySelectorAll("[data-foto-i-d='"+promise+"']"); for(let r of rows) r.remove(); } function onJsonRemoveFotografo(promise){ const row=document.querySelector("[data-row='"+promise.cf+"']"); row.remove(); for(let foto of promise.foto){ const rowf=document.querySelectorAll("[data-row='"+foto.ID+"']"); for(let r of rowf) r.remove(); console.log(rowf); const rows=document.querySelectorAll("[data-foto-i-d='"+foto.ID+"']"); for(let rs of rows) rs.remove(); } } function deleteStampa(event){ fetch("managementArea/removeStampa/"+event.currentTarget.dataset.IDS).then(onResponse).then(onJsonRemoveStampa); } function onJsonRemoveStampa(promise){ console.log(promise); const row=document.querySelector("[data-row-s='"+promise+"']"); console.log(row); row.remove(); }
import React from 'react' import { Paper } from '@material-ui/core' import { makeStyles } from '@material-ui/core/styles' const useStyle = makeStyles((theme) => ({ card: { padding: theme.spacing(1, 1, 1, 2), margin: theme.spacing(1), }, })) export default function Card() { const classes = useStyle() return ( <div> <Paper>Making youtube video</Paper> </div> ) }
var WIDTH = 1216; var HEIGHT = 800; var heroSpeed = 400; var deadPartsKeys = [ 'deadParts0', 'deadParts1', 'deadParts2', 'deadParts3', 'deadParts4', 'deadParts5', 'deadParts6', 'deadParts7' ];
import{ useState, useEffect,useRef } from "react"; const useLocalStorage = ( key, standardDefault = '', { serialize = JSON.stringify, deserialize = JSON.parse } = {} ) => { const [state, setState] = useState(() => { const valueInLocalStorage = window.localStorage.getItem(key); if (valueInLocalStorage) { return deserialize(valueInLocalStorage); } return typeof standardDefault === "function" ? standardDefault() : standardDefault; }); const refKey = useRef(key) useEffect(() => { const prevKey = refKey.current if (prevKey !== key) { window.localStorage.removeItem(key); } refKey.current= key },[key]) useEffect(() => { window.localStorage.setItem(key, serialize(state)); }, [key, serialize, state]); return [state, setState]; }; export { useLocalStorage};
function round(value, decimals) { return Number(Math.round(value+'e'+decimals)+'e-'+decimals); } function toGrade(letter, isRetake) { if (letter == "A") { if (isRetake == "Y") { return 3.7; } else { return 4.0; } } else if (letter == "A-") { if (isRetake == "Y") { return 3.4; } else { return 3.7; } } else if (letter == "B+") { if (isRetake == "Y") { return 3; } else { return 3.4; } } else if (letter == "B") { if (isRetake == "Y") { return 2.7; } else { return 3; } } else if (letter == "B-") { if (isRetake == "Y") { return 2.4; } else { return 2.7; } } else if (letter == "C+") { if (isRetake == "Y") { return 2; } else { return 2.4; } } else if (letter == "C") { if (isRetake == "Y") { return 1.7; } else { return 2; } } else if (letter == "C-") { if (isRetake == "Y") { return 1.4; } else { return 1.7; } } else if (letter == "D+") { if (isRetake == "Y") { return 1; } else { return 1.4; } } else if (letter == "D") { if (isRetake == "Y") { return 0.7; } else { return 1; } } else if (letter == "D-") { if (isRetake == "Y") { return 0; } else { return .7; } } else { return 0; } } function appChance() { var tempLetter; var tempIsRetake; var IS201; var IS303; var ACC200; var FIN201; var MKTG201; var sumBusPrereq; var ovrGPA; var last30GPA; var appGPA; //data collecting. Will need to be switched with HTML drop downs, but keep the function to bring back a number to the letter grade //Please note I've only prepared for exact versions of inputs for testing purposes. Lower case grades, or spaces between the letter and //the plus or minus will result in a 0 for that section tempLetter = prompt("What is your IS 201 course grade?"); tempIsRetake = prompt("Was this a retake? (Y/N"); IS201 = toGrade(tempLetter, tempIsRetake); //test, delete next line after test alert(IS201); tempLetter = prompt("What is your IS 303 course grade?"); tempIsRetake = prompt("Was this a retake? (Y/N"); IS303 = toGrade(tempLetter, tempIsRetake); //test, delete next line after test alert(IS303); tempLetter = prompt("What is your ACC 200 course grade?"); tempIsRetake = prompt("Was this a retake? (Y/N"); ACC200 = toGrade(tempLetter, tempIsRetake); //test, delete next line after test alert(ACC200); tempLetter = prompt("What is your FIN 201 course grade?"); tempIsRetake = prompt("Was this a retake? (Y/N"); FIN201 = toGrade(tempLetter, tempIsRetake); //test, delete next line after test alert(FIN201); tempLetter = prompt("What is your MKTG 201 course grade?"); tempIsRetake = prompt("Was this a retake? (Y/N"); MKTG201 = toGrade(tempLetter, tempIsRetake); //test, delete next line after test alert(MKTG201); ovrGPA = parseInt(prompt("What is your overall GPA?")); //test, delete next line after test alert(ovrGPA); last30GPA = parseInt(prompt("What is your GPA for your last 30 credits?")); //test, delete next line after test alert(last30GPA); //Next we combine the scores of FIN 201, ACC 200, and MKTG 201 into 1 score sumBusPrereq = (ACC200 + FIN201 + MKTG201)/3; //This section we are calculating the application GPA finding the average of all of our scores. Because we have already combined ACC, FIN, and MKTG //we do not need to do anything specific for weighting, as each is 20%, so we do a simple average calculation appGPA = (IS201 + IS303 + sumBusPrereq + ovrGPA + last30GPA)/5; appGPA = round(appGPA, 2); //Now we simply return either green, yellow or red, as well as the calculated GPA // These should be switched out with the html equivalents alert(appGPA); if (appGPA >= 3.7) { alert("Green"); } else if (appGPA >= 3.4) { alert("Yellow"); } else { alert("Red"); } }
import React from 'react'; import axios from 'axios'; import Loading from './shared/Loading'; import Form from './shared/Form'; let todoUrl = 'https://api.vschool.io/marcus/todo/'; class TodoList extends React.Component { constructor(props) { super(props); this.state = { todos: [], loading: true } } componentDidMount(){ axios.get(todoUrl) .then((response)=>{ let {data} = response; this.setState({todos:data, loading: false}) }) .catch(err => { console.error(err); }) } render () { let {todos, loading } = this.state; return ( loading ? <Loading /> : <div> {/*todo links goes here*/} <Form /> </div> ) } } export default TodoList;
var proto = require('proto') var ks = require("keysight") var Gem = require('gem'); var Style = require("gem/Style") var Text = require("gem/Text") module.exports = proto(Gem, function(superclass) { this.name = 'TextEditor' this.defaultStyle = Style({ Text: { minWidth: 100, wordBreak: 'break-word' }, $emptyText: { $inherit: true, position: 'absolute', //top: 4, left: 4, pointerEvents:'none', color: 'rgb(190,190,190)' } }) // label - A label to put on the component (for styling) // options can contain: // characterFilter - A function that's passed a character from the 'keydown' event, and should return true if the character is allowable // emptyText - Text to be displayed when the field is undefined // initial - The initial value // proxyEvents - A list of events to proxy. Defaults to ['blur', 'focus'] this.build = function(/*[label,] options*/) { if(arguments[0] instanceof Object) { var options = arguments[0] } else if(arguments[0] !== undefined) { var label = arguments[0] var options = arguments[1] } if(options === undefined) options = {} if(options.emptyText === undefined) options.emptyText = '' var that = this if(label) this.label = label if(options.emptyText) { this.emptyText = Text('emptyText', options.emptyText) this.add(this.emptyText) } var text = this.textField = Text() text.attr("contenteditable", true) this.add(text) // there's a reason this is wrapped in a container.. but i can't remember why if(options.initial !== undefined) this.text = options.initial if(options.characterFilter !== undefined) { this.on('keypress', function(event) { if(!options.characterFilter(ks(event).char)) { event.preventDefault() } }) this.on('paste', function(event) { // keypress doesn't seem to get paste events var types = event.clipboardData.types var pastedText = event.clipboardData.getData(types[0]) for(var n in pastedText) { if(!options.characterFilter(pastedText[n])) { event.preventDefault() break; } } }) } if(options.proxyEvents === undefined) { options.proxyEvents = ['blur', 'focus'] } this.proxy(text, {only: options.proxyEvents}) text.on('input', function() { that.renderEmptyText() }) onceAfterCooldown(text, 'input', 200, function(event) { that.emit('change') // since contenteditable divs don't seem to emit change events }) } this.renderEmptyText = function() { if(this.emptyText) this.emptyText.visible = this.empty } Object.defineProperty(this, 'text', { get: function() { var innerText = this.textField.domNode.innerText // using innerText here because it preserves newlines // for some weird reason, two newlines are created in a contenteditable node when you press enter, and // so backspacing will only get rid of one and the result is that it looks empty but still has a single newline in it - ugh if(innerText[innerText.length-1] === '\n') innerText = innerText.slice(0,-1) return innerText }, set: function(value) { if(value === undefined || value === '') { this.textField.text = '' if(this.emptyText) this.emptyText.visible = true } else { this.textField.text = value if(this.emptyText) this.emptyText.visible = false } } }) Object.defineProperty(this, 'val', { get: function() { return this.text }, set: function(value) { this.text = value } }) Object.defineProperty(this, 'focus', { get: function() {return this.textField.focus}, set: function(value) {this.textField.focus = value} }) Object.defineProperty(this, 'selectionRange', { get: function() {return this.textField.selectionRange}, set: function(value) {this.textField.selectionRange = value} }) }) // only fires the callback after a cooldown time has passed // returns the event callback (so you can off it) function onceAfterCooldown(gem, event, cooldownTime, callback) { var timeout, cb; gem.on(event, cb=function() { var args = arguments if(timeout) clearTimeout(timeout) timeout = setTimeout(function() { // only run new search when you stop typing timeout = undefined callback.apply(gem, args) },cooldownTime) }) return cb }
var Schema = require('mongoose').Schema; var userSchema = new Schema({ local:{ username: String, pass: String, } });
require("dotenv").config(); var DEBUG = process.env.NODE_ENV === "development"; var express = require("express"); var app = express(); const db = require("./db"); const session = require("express-session"); const KnexSessionStore = require('connect-session-knex')(session); const store = new KnexSessionStore({ knex: db }); var expressSession = session({ secret: process.env.COOKIE_SECRET, cookie: { sameSite: true, // TODO: enable this once https is enabled, need hobby level heroku // secure: DEBUG ? false : true, maxAge: 24 * 60 * 60 * 1000, }, // TODO: take a second look at these. saveUninitialized: true, resave: true, store: store, }); app.use(expressSession); var server = require("http").Server(app); var socketio = require("socket.io"); var io = socketio(server); const SharedSession = require("express-socket.io-session"); io.use(SharedSession(expressSession, { autoSave:true })); const Lobby = require("./libs/lobby"); var lobby = new Lobby(io, db); lobby.restore().then(lobby.listen()); app.set("port", process.env.PORT); app.use(express.static("public")); // Staticly serve pages, using directory 'public' as root var timesyncServer = require("timesync/server"); app.use("/timesync", timesyncServer.requestHandler); // User connects to server app.get("/", function(req, res) { // Will serve static pages, no need to handle requests }); // If any page not handled already handled (ie. doesn't exists) app.get("*", function(req, res) { res.status(404).send("Error 404 - Page not found"); }); // Start http server server.listen(app.get("port"), function() { console.log("Node app started on port %s", app.get("port")); });
const getAll = (req, res, next) => { const db = req.app.get("db"); db .getAll(req.user.authid) .then(response => { res.status(200).json(response); }) .catch(err => { res.status(500); }); }; const getCurrUser = (req, res, next) => { const db = req.app.get("db"); if (req.user) { db .getCurrUser([req.user.authid]) .then(response => { res.status(200).json(response); }) .catch(err => { res.status(500).json({ err: 'NoUserFound' }); }); }else { return res.status(500).json({ err: 'NoUserFound' }) } }; const getTransportation = (req, res, next) => { const db = req.app.get("db"); if (req.user) { db .getTransportation([req.params.tripid]) .then(response => { res.status(200).json(response); }) .catch(err => { res.status(500); }); } }; const getActivities = (req, res, next) => { const db = req.app.get("db"); if (req.user) { db .getActivities([req.params.tripid]) .then(response => { res.status(200).json(response); }) .catch(err => { res.status(500); }); } }; const getUserTrips = (req, res, next) => { const db = req.app.get("db"); if (req.user) { db .getUserTrips([req.user.authid]) .then(response => { res.status(200).json(response); }) .catch(err => { res.status(500); }); } }; const getCurrTrip = (req, res, next) => { const db = req.app.get("db"); db .getCurrTrip([req.params.tripid]) .then(response => { res .status(200) .json(response) .redirect("/#/main"); }) .catch(err => { res.status(500); }); }; const getHousing = (req, res, next) => { const db = req.app.get("db"); db .getHousing([req.params.tripid]) .then(response => res.status(200).json(response)); }; const getTripGuest = (req, res, next) => { const db = req.app.get("db"); db .getTripGuest([req.params.tripid]) .then(response => { res.status(200).json(response); }) .catch(err => { res.status(500); }); }; const getRules = (req, res, next) => { const db = req.app.get("db"); db .getRules([req.params.tripid]) .then(response => res.status(200).json(response)); }; const getTransitRiders = (req, res, next) => { const db = req.app.get("db"); db .getTransitRiders([req.params.tripid]) .then(response => { res.status(200).json(response); }) .catch(err => { res.status(500); }); }; const getActivityUser = (req, res, next) => { const db = req.app.get("db"); db .getActivityUser([req.params.tripid]) .then(response => { res.status(200).json(response); }) .catch(err => { res.status(500); }); }; const createUser = (req, res, next) => { const db = req.app.get("db"); db .createUser() .then(response => { res.status(200).json(response); }) .catch(err => { res.status(500); }); }; const createTrip = (req, res, next) => { const db = req.app.get("db"); db .createTrip( req.body.authid, req.body.location, req.body.start, req.body.end ) .then(response => { db.addFirstGuest(response[0].admin, response[0].tripid); }) .then(response => res.json(response)) .catch(err => { res.status(500); }); }; const createTransportation = (req, res, next) => { const db = req.app.get("db"); const {tripid, type, departurelocation, departuretime, arrivallocation, arrivaltime, } = req.body; if(type == 'Plane'){ var photo = '../img/plane.png' } if(type == 'Car'){ var photo = '../img/car.png' } db .createTransportation( [tripid, req.user.authid, type, departurelocation, departuretime, arrivallocation, arrivaltime, photo] ).then(response => { db.addTransitRider(response[0].creatinguser, response[0].tripid,response[0].id); }) .then(response => res.json(response)) .catch(err => { res.status(500); }); }; const createActivity = (req, res, next) => { const db = req.app.get("db"); const { authid,tripid, name,location,price,link,description,time } = req.body; var photo = '../img/activities.png'; db .createActivity( [ authid,tripid, name,location,price,link,description,time, photo] ).then(response => { db.addActivityGuest(response[0].creatinguser, response[0].tripid,response[0].id); }) .then(response => res.json(response)) .catch(err => { res.status(500); }); }; const addTripGuest = (req, res, next) => { const db = req.app.get("db"); db.addTripGuest([req.body.authid, req.params.tripid]).then(response => { if (response.length === 0) { db .addFirstGuest([req.body.authid, req.params.tripid]) .then(response => { res.status(200).json(response); }) .catch(err => { res.status(500); }); } }); }; const addActivityGuest = (req, res, next) => { const db = req.app.get("db"); db.checkActivityGuest([req.body.authid, req.params.tripid,req.body.activityid]).then(response => { if (response.length === 0) { db .addActivityGuest([req.body.authid, req.params.tripid,req.body.activityid]) .then(response => { res.status(200).json(response); }) .catch(err => { res.status(500); }); } }); }; const addTransitRider = (req, res, next) => { const db = req.app.get("db"); db.checkTransitRider([req.body.authid, req.params.tripid,req.body.transportid]).then(response => { if (response.length === 0) { db .addTransitRider([req.body.authid, req.params.tripid,req.body.transportid]) .then(response => { res.status(200).json(response); }) .catch(err => { res.status(500); }); } }); } const createRule = (req, res, next) => { const db = req.app.get("db"); db.createRule([req.body.tripid, req.body.authid, req.body.rule]).then(response => { res.status(200).json(response); }); }; const createHousing = (req, res, next) => { const db = req.app.get("db"); const { tripid, authid, location, price, link, photourl, submittedby } = req.body; if (photourl == undefined) { var photo = "../img/housing_placeholder.png"; } if (photourl != undefined) { var photo = photourl; } db .createHousing(tripid, authid, location, price, link, photo, submittedby) .then(response => { res.status(200).json(response); }) .catch(err => { res.status(500); }); }; const updateHousing = (req, res, next) => { const db = req.app.get("db"); const { id, price, location, link, photourl } = req.body; db .updateHousingInfo(id, price, location, link, photourl) .then(response => { res.status(200).json(response); }) .catch(err => { res.status(500); }); }; const updateTrip = (req, res, next) => { const db = req.app.get("db"); const { tripid, location, start, end } = req.body; db .updateTripInfo([tripid, location, start, end]) .then(response => { res.status(200).json(response); }) .catch(err => { res.status(500); }); }; const deleteTrip = (req, res, next) => { const db = req.app.get("db"); console.log("delete", req.params.id); db .deleteTrip([req.params.id]) .then(response => { res.redirect('/#/main') }) .catch(err => { res.status(500); }); }; const deleteHousing = (req, res, next) => { const db = req.app.get("db"); db .deleteHousing([req.params.id]) .then(response => res.status(200).json(response)) .catch(err => res.status(500)); }; const removeTripUser = (req, res, next) => { const db = req.app.get("db"); console.log('deleting guest:',req.params.id); db .removeTripUser([req.params.id]) .then(response => res.status(200).json(response)) .catch(err => res.status(500)); }; const removeRule = (req, res, next) => { const db = req.app.get("db"); console.log('deleting rule:',req.params.id); db .removeRule([req.params.id]) .then(response => res.status(200).json(response)) .catch(err => res.status(500)); }; const upvote = (req, res, next) => { const db = req.app.get("db"); db .upVote([req.body.id, req.body.upvote]) .then(response => res.status(200).json(response)) .catch(err => res.status(500)); }; const downvote = (req, res, next) => { const db = req.app.get("db"); db .downVote([req.body.id, req.body.downvote]) .then(response => res.status(200).json(response)) .catch(err => res.status(500)); }; module.exports = { getAll, getActivities, getActivityUser, getCurrUser, getUserTrips, getCurrTrip, getHousing, getTransportation, getTransitRiders, getTripGuest, getRules, createActivity, createUser, createHousing, createTransportation, createTrip, createRule, deleteHousing, deleteTrip, updateHousing, updateTrip, removeTripUser, removeRule, addTripGuest, addActivityGuest, addTransitRider, upvote, downvote };
import React,{Component} from 'react'; import { Menu, Icon ,Modal,Form,Input, Button, Label } from 'semantic-ui-react'; import firebase from '../../firebase' import {connect} from 'react-redux'; import {setChannel,setPrivateChannel}from '../../actions'; class Channels extends Component { state={ channels:[], channel:null, modal:false, channelDetails:'', channelName:'', channelRefs: firebase.database().ref('channels'), messagesRef: firebase.database().ref('messages'), user: this.props.currentUser, firstLoad:true, notifications:[], activeChannel:'', typingRef:firebase.database().ref('typing') } componentDidMount(){ this.addListeners(); } componentWillUnmount(){ this.removeListener(); } removeListener=()=>{ this.state.channelRefs.off(); } addListeners=()=>{ let loadedChannels= []; this.state.channelRefs.on('child_added',snap=>{ loadedChannels.push(snap.val()); this.setState({ channels:loadedChannels },()=>this.setFirstChannel()) this.addNotificationListener(snap.key) }) } addNotificationListener= channelId=>{ this.state.messagesRef.child(channelId).on('value',snap=>{ if(this.state.channel){ this.handleNotifications(channelId,this.state.channel.id,this.state.notifications,snap); } }); } handleNotifications =(channelId,currentChannelId,notifications,snap)=>{ let lastTotal =0; let index = notifications.findIndex(notification=> notification.id === channelId); if(index !== -1){ if(channelId !== currentChannelId){ lastTotal = notifications[index].total; if(snap.numChildren()-lastTotal>0){ notifications[index].count = snap.numChildren()-lastTotal; } } notifications[index].lastKnownTotal=snap.numChildren(); }else{ notifications.push({ id:channelId, total:snap.numChildren(), lastKnownTotal:snap.numChildren(), count:0 }) } this.setState({notifications}) } setFirstChannel=()=>{ const firstChannel= this.state.channels[0]; if(this.state.firstLoad && this.state.channels.length>0){ this.props.setChannel(firstChannel); this.setActiveChannel(firstChannel); this.setState({channel:firstChannel}); } this.setState({firstLoad:false}) } addChannel=()=>{ const {channelRefs,channelName,channelDetails,user} =this.state; const key = channelRefs.push().key; const newChannel ={ id:key, name: channelName, details:channelDetails, createdBy:{ name: user.displayName, avatar: user.photoURL } } channelRefs.child(key).update(newChannel) .then(()=>{ this.setState({channelName:'',channelDetails:''}) this.closeModal(); }) .catch((err)=>{ console.log(err) }) } handleSubmit=(event)=>{ event.preventDefault(); if(this.isFormValid(this.state)){ this.addChannel(); console.log('channel Added') }else{ } } isFormValid=({channelName,channelDetails})=>channelName && channelDetails openModal=()=>{ this.setState({ modal:true }) } closeModal=()=>{ this.setState({ modal:false }) } handleChange= event=>{ this.setState({[event.target.name]:event.target.value}) } getNotificationCount=channel=>{ let count = 0; this.state.notifications.forEach(notification=>{ if(notification.id === channel.id){ count = notification.count } }); if(count>0) return count; } displayChannels=channels=>( channels.length>0 && channels.map(channel=>( <Menu.Item key={channel.id} onClick={()=>this.changeChannel(channel)} name= {channel.name} style={{opacity:0.7}} active={channel.id ===this.state.activeChannel} > {this.getNotificationCount(channel)&&( <Label color="red">{this.getNotificationCount(channel)}</Label> )} # {channel.name} </Menu.Item> )) ) changeChannel= channel=>{ this.setActiveChannel(channel); this.clearNotifications(); this.props.setChannel(channel); this.props.setPrivateChannel(false); this.setState({channel}); this.state.typingRef .child(this.state.channel.id) .child(this.state.user.uid) .remove() } clearNotifications=()=>{ let index = this.state.notifications.findIndex(notification =>notification.id===this.state.channel.id); if(index !== -1){ let updatedNotifications =[...this.state.notifications]; updatedNotifications[index].total = this.state.notifications[index].lastKnownTotal; updatedNotifications[index].count =0; this.setState({notifications:updatedNotifications}) } } setActiveChannel=(channel)=>{ this.setState({activeChannel:channel.id}) } render(){ const {channels,modal} = this.state; return( <React.Fragment> <Menu.Menu className="menu"> <Menu.Item style={{color:"white"}}> <span> <Icon inverted name="group" /> Groups </span>{" "} ({channels.length}) <Icon name="add" onClick={this.openModal}/> </Menu.Item> {this.displayChannels(channels)} </Menu.Menu> <Modal basic open={modal} onClose={this.closeModal}> <Modal.Header>Add a Group</Modal.Header> <Modal.Content> <Form onSubmit={this.handleSubmit}> <Form.Field> <Input fluid name="channelName" label="Name of Group" onChange={this.handleChange} /> </Form.Field> <Form.Field> <Input fluid label="About the Group" name="channelDetails" onChange={this.handleChange} /> </Form.Field> </Form> </Modal.Content> <Modal.Actions> <Button color="green" inverted onClick={this.handleSubmit}> <Icon name="checkmark" /> Add </Button> <Button color="red" inverted onClick={this.closeModal}> <Icon name="remove" /> Cancel </Button> </Modal.Actions> </Modal> </React.Fragment> ); } } export default connect(null,{setChannel,setPrivateChannel})(Channels)
// TODO: Implement these methods: https://fiveminutes.jira.com/browse/SEEXT-2978 export default { arePushNotificationsEnabled: console.log.bind(null, 'Push notifications are available on Android unless the user' + ' explicitly disabled them'), openSettings: console.log.bind(null, 'Open settings not implemented for Android'), };