text
stringlengths
7
3.69M
module.exports = { // Development configuration options ip: 'localhost', port: 8000, strategies: { github: { clientID: 'e1848f969501734e3eaa', clientSecret: '0fa4575cee3e6ca3ee13a76ea2a56729f693052b', callbackURL: `http://localhost:8000/auth/github/callback` } }, sessionSecret: 'testSessionSecret', bcryptSalt: 'testBcryptSalt', dburi: 'mongodb://developer:repoleved@ds131480.mlab.com:31480/githubactivity' };
import React from 'react' import Header from '../Header/Header' import '../../Styles/HomePage.css' import Category from '../Category/Category' const PageNotFound = () => { return( <div> <Header title="Page Not Found" /> <Category /> <h1>Page Not Found</h1> </div> ) } export default PageNotFound
/*A instrução for cria um loop que consiste em três expressões for ([inicialização]; [condição]; [expressão final])*/ const nomes = ['Sílvia', 'Hellen', 'Larissa']; for(let i = 0; i < nomes.length; i = i + 1 ) { console.log('[for]', nomes[i]); }
ScoreOption = { tooltip : { formatter : "{a} <br/>{b} : {c}%" }, toolbox : { show : false, feature : { mark : { show : true }, restore : { show : true }, saveAsImage : { show : true } } }, series : [{ name : '西瓜信用', min : 300, max : 900, type : 'gauge', detail : { formatter : '{value}分' }, data : [{ value : 675, name : '西瓜分' }] }] } dimOption = { title : { show : false, text : '西瓜信用', subtext : '纯属虚构' }, tooltip : { trigger : 'axis' }, legend : { show : false, orient : 'vertical', x : 'center', data : ['维度评分'] }, toolbox : { show : false }, polar : [{ radius : 125, indicator : [{ text : '身份特质', axisLabel : { show : true, formatter : null, textStyle : { color : 'auto', fontWeight : 'bold' } }, max : 240 }, { text : '消费偏好', axisLabel : { show : true, formatter : null, textStyle : { color : 'auto', fontWeight : 'bold' } }, max : 240 }, { text : '履约能力', axisLabel : { show : true, formatter : null, textStyle : { color : 'auto', fontWeight : 'bold' } }, max : 240 }, { text : '人脉关系', axisLabel : { show : true, formatter : null, textStyle : { color : 'auto', fontWeight : 'bold' } }, max : 240 }, { text : '不良记录', axisLabel : { show : true, formatter : null, textStyle : { color : 'auto', fontWeight : 'bold' } }, max : 240 }] }], calculable : true, series : [{ name : '维度评分', type : 'radar', data : [{ value : [176, 135, 240, 180, 150], name : '维度评分' }] }] }; $(function() { $("#owl-demo").owlCarousel({ navigation : true, // Show next and prev // buttons slideSpeed : 300, paginationSpeed : 400, singleItem : true }); })
import { ContextProvider } from "./hooks/context"; import Router from "./Router"; import { createGlobalStyle } from "styled-components"; const Global = createGlobalStyle` body{ margin: 0; padding: 0; font-family: 'Rubik', sans-serif;} `; function App() { return ( <> <Global /> <ContextProvider> <Router /> </ContextProvider> </> ); } export default App;
export default { user: { isAuthenticated: true, role: 'admin', }, event: { setupComplete: false } }
import React from 'react' import { View, Text, StyleSheet } from 'react-native' const numberOfLines = { ellipsizeMode: 'tail', numberOfLines: 1 } const ItemTile = props => { const { place } = props return( <View style={styles.container}> <View style={styles.information}> <Text {...numberOfLines } style={styles.placeName}>{place.name}</Text> <Text {...numberOfLines} style={styles.description}>{place.description}</Text> </View> <Text {...numberOfLines} style={styles.price}>R$ {place.price}</Text> </View> ) } const styles = StyleSheet.create({ container: { padding: 16, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', borderBottomWidth: 1, borderBottomColor: '#dedede' }, placeName: { fontSize: 20, fontWeight: 'bold' }, description: { fontSize: 16, }, price: { fontSize: 16, color: '#45b4f9' }, information: { flex:1, marginRight: 10 } }) export default ItemTile
import Project from "./project.js" class Employee{ constructor({id, name, role, department, projects}){ this.id = id; this.name = name; this.role = role; this.department = department; if(projects.length == 0){ this.projects = []; } else{ this.projects = projects; } } addProject(newProject){ this.projects.push(newProject); } } const dbsPayroll = new Project( {id:1001, name:'DBS payroll', client:'DBS' }); const intranetDeployment = new Project( {id:2001, name:'Intranet v2 deployment', client:'Internal'} ); const john = new Employee( {id:1, name:'John', role:'Web Developer', department:'IT', projects: [ dbsPayroll ]}); const jane = new Employee( {id:2, name:'Jane', role:'Project Manager', department:'IT', projects:[ dbsPayroll, intranetDeployment ]}); export {Employee as default}
setInterval(() => consol.log(Cyk!)100); console.log(ziomekZbetonu); -------------------------- heckIsbn = ()=>{ let isbn = Number(prompt('podaj 13 cyfrowy nr ISBN')); if(!isNaN(isbn) && isbn.toString().length ===13){ return isbn; } else { alert('Podałeś zbyt krótki numer, lub użyłeś innych znaków niż cyfry, spróbuj jeszcze raz') checkIsbn(); } }; fetch(`https://www.googleapis.com/books/v1/volumes?q=isbn:${checkIsbn()}`) .then((response)=>response.json()) .then((data)=>{ const book = data.items[0].volumeInfo; console.log(data); console.log(`Tytuł książki to: ${book.title}, Autorami są: ${book.authors}`)}) .catch((err)=>console.log('coś nie działa', err)); ---------------------------- const secondP = document.querySelector('.second-p'); secondP.classList.add ('crazy-stuff'); undefined secondP.classList DOMTokenList(3) ["second-p", "highlight", "crazy-stuff", value: "second-p highlight crazy-stuff"] secondP.classList.remove('crazy-stuff') -------------------------------------- localStorage.setItem('name', 'krzychu'); localStorage.getItem('name'); ---------------------------------------- //get last visit date const lastSavedVisitDate = localStorage.getItem('last visit'); if (lastSavedVisitDate === null) { console.log('You are first here!'); } else { console.log (`You were here last time on , ${lastSavedVisitDate}.`) } //set last visit date const date= new Date(); const dateString = date.toString(); localStorage.setItem('last visit', dateString); --------------------------------- const btn =document.querySelector('.btn-toggle-color'); const h1 = document.querySelector('h1'); let counter = Number(localStorage.getItem('counter')); h1.innerText = String(counter); btn.addEventListener('click' () =>{ h1.innerText = String(++counter); localStorage.setItem('counter', String(counter)); }); }); ----------------------------------- const btn =document.querySelector('.btn-toggle-color'); const h1 = document.querySelector('h1'); let counter = Number(localStorage.getItem('counter')); h1.innerText = String(counter); btn.addEventListener('click' ( =>{ h1.innerText = String(++counter); localStorage.setItem('counter', String(counter)); }); })) ------------------------------- { "name":["Jan","Kowalski"], "email" : "jan@Kowalski.pl", "settings" : { "sound" : "off", "fullScreen": true, "newsDisplayed" : 5 }, "Characters" :[{"Conen":{ "level":10, "items":["topor"], "hungry": true } },{ "Druzzt":{ "level":4, "items":["sejmitar","sejmitar"], "hungry": true } },{ "Garelt":{ "level":10, "items":["miecz","miecz"], "hungry": true } }] } --------------------- const GoodMood =document.querySelector('.GoodMoodFeeling'); const BadMood = document.querySelector('.BadMoodFeeling'); const goodMoodFeeling = localStorage.getItem('goodClicks'); const badMoodFeeling = localStorage.getItem('badClicks'); let counter = Number(localStorage.getItem('')); GoodMood.innerText = String(counter); GoodMood.addEventListener('goodClicks' () =>{ h1.innerText = (++counter); localStorage.setItem('counter', String(counter)); }); }; localStorage.setItem('goodClicks', JSON.stringify()) localStorage.setItem('badClicks', JSON.stringify()) } if ------------------------ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .GoodMood-btn { background-color: forestgreen; color: white; font-size: 28px; } .BadMood-btn { background-color: darkred; color: white; font-size: 28px; } </style> </head> <body> <h1>Your mood stats</h1> <p1>How are you feeling today sir?</p1> <button class="GoodMood-btn"> Feeling Good Mood</button> <button class="BadMood-btn">Feeling Bad Mood</button> <p class = "text"></p> <script src="app.js"></script> </body> </html> ------------------------ const btn2= document.querySelector('.GoodMood-btn'); const btn3 = document.querySelector('.BadMood-btn'); const wyniki = document.querySelector('.text'); let liczDobrych = Number(localStorage,getItem('dobrze')); let liczZlych = Number(localStorage.getItem('zle')); wyniki.innerText = `Czules sie dobrze: ${liczDobrych} i tyle razy przycisk zle:${liczZlych}` function counterGoodDays (){ if (liczDobrych === null) { wyniki.innerText = 'Jeszcze nie wiesz co to zycie' }else { wyniki.innerText = `Tyle razy kliknales dobrze ${++liczDobrych},a tyle razy kliknales ${liczZlych}` localStorage.setItem('dobrze', liczDobrych.toString()); } } function counterBadDays (){ if (liczZlych === null) { wyniki.innerText = 'Jeszcze nie wiesz co to zycie' }else { wyniki.innerText = `Tyle razy kliknales dobrze ${liczDobrych},a tyle razy kliknales ${++liczZlych}` localStorage.setItem('zle', liczZlych.toString()); } } btn2.addEventListener('click', counterGoodDays) btn3.addEventListener('click', counterBadDays) ----------------------------------------- const obj = { name: 'Jan', surname: 'Spolsky', age: 33, }; //const keys = Object.keys(obj); //console.log(keys); //const values = Object.values(obj); //console.log(values); const entries = Object.entries(obj); for(const [raper, plyta] of entries) { console.log(raper,plyta); } ---------------------------------------- const ar = ['Anna', 'Andrzej', 'Bartek', 'Jakub']; const names = ar.reduce((prev, curr) => { if (curr[0] === 'A') { return `${prev} ${curr}`; } else { return prev; } }, ''); console.log(names); ---------------------- const ar = ['Anna', 'Andrzej', 'Bartek', 'Jakub']; const namesLength = ar.reduce((prev, curr) =>{ return prev + curr.length; }, 0); console.log(namesLength); --------------------------------------------------- shopBasket.addToTotalValue(-10); console.log(shopBasket);
(function ($,X) { /** * 这个只针对地址的, 默认三级 */ X.prototype.controls.widget("ComboBoxSecond",function (controlType) { var BaseControl = X.prototype.controls.getControlClazz("BaseControl"); /** @class ComboBox 下拉框 @constructor 构造函数 @param elem {DomNode} Dom节点 @param option {Object} 配置信息 */ function ComboBoxSecond(elem,option){ BaseControl.call(this,elem,option); this.elem = elem; this.option = option; this.props() this.loadTemplate() this.init() } X.prototype.controls.extend(ComboBoxSecond,BaseControl); /** @method init 初始化下拉框 @param field {Object} 下拉数据源配置,数据从服务器获取 @param callback {function} 回调函数,初始化完成后调用 */ ComboBoxSecond.prototype.init = function() { var that = this; var ds =[]; var getDataSource = function (source,target,id,name) { $.each(source,function(index,item){ target.push({key:item[id],value:item[name]}); }); }; var addressData = this.option.dataSource; if(addressData){ getDataSource(addressData["pro"],ds,"ProID","ProName"); } this.province = X.prototype.controls.getControl("ComboBox", this.subComboBox.eq(0),{dataSource:ds,selectedChanged: function (item) { var key = item.key; var citys =[]; $.each(addressData.city, function(index,city){ if(city["ProID"] == key){ citys.push({key:city["CityID"],value:city["CityName"]}) } }); that.city.setDataSource(citys); that.district.setDataSource(); if(that.options.provinceSelectedChanged){ that.options.provinceSelectedChanged.call(that, {text:that.province.selectItem.value,key:that.province.selectItem.key}); } }}); this.city = X.prototype.controls.getControl("ComboBox", this.subComboBox.eq(1),{selectedChanged: function (item) { var key = item.key; var countrys =[]; $.each(addressData.dis, function(index,district){ if(district["CityID"] == key){ countrys.push({key:district["Id"],value:district["DisName"]}) } }); that.district.setDataSource(countrys); if(that.options.citySelectedChanged){ that.options.citySelectedChanged.call(that, {text:that.city.selectItem.value,key:that.city.selectItem.key}); } }}); this.district = X.prototype.controls.getControl("ComboBox", this.subComboBox.eq(2),{selectedChanged:function (item) { if(that.options.districtSelectedChanged){ that.options.districtSelectedChanged.call(that,{text:that.district.selectItem.value,key:that.district.selectItem.key}); } }}); var dvProvince,dvCity,dvDistrict if(this.option.defaultValue){ dvProvince = this.option.defaultValue.province; dvCity = this.option.defaultValue.city; dvDistrict = this.option.defaultValue.district; this.province.setValue(dvProvince); this.city.setValue(dvCity); this.district.setValue(dvDistrict); } }; /** @method props 获取属性 @param value {string} 获取属性 */ ComboBoxSecond.prototype.props = function(){ this.level = this.option.level || 3 this.name = this.elem.attr('data-property-name') || this.elem.attr('name') this.clazz = this.elem.attr('subClazz') }; /** @method loadTemplate 添加html @param value {string} 添加html */ ComboBoxSecond.prototype.loadTemplate = function(){ var html = '<div class="wrapper-dropdown selected '+ this.clazz +'" data-property-name="{{name}}"></div>' var i = 0, nHtml = '' while (i < this.level) { nHtml += html.replace('{{name}}', this.name + i++) } this.elem.html(nHtml) this.subComboBox = this.elem.children() }; /** @method getValue 获取下拉框的值 @param value {string} 获取下拉框选中值 */ ComboBoxSecond.prototype.getValue = function(){ return { province:this.province.val(), city: this.city.val(), district :this.district.val() } }; /** @method setValue 设置(获取)下拉框的值 @param value {string} 设置下拉框选中值 */ ComboBoxSecond.prototype.setValue = function(value){ var province = value["province"]; var city = value["city"]; var district = value["district"]; if(province){ this.province.setValue(province); } if(city){ this.city.setValue(city); } if(district){ this.district.setValue(district); } }; return ComboBoxSecond; }); })(jQuery,this.Xbn);
var {http, app} = require('./server'); var socketAPI = require('./server/socket'); var io = require('socket.io')(http); var homeRouter = require('./server/router'); socketAPI(io); http.listen(8080, function () { console.log("On 8080..."); });
'use strict'; /* lista e explicação dos Datatypes: https://codewithhugo.com/sequelize-data-types-a-practical-guide/ */ module.exports = (sequelize, DataTypes) => { let Lampada = sequelize.define('Lampada',{ id_lampada: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, local: { type: DataTypes.STRING, allowNull: false }, fk_condominio: { type: DataTypes.INTEGER, allowNull: false }, fk_status_lampada: { type: DataTypes.INTEGER, allowNull: false } }, { tableName: 'lampada', freezeTableName: true, underscored: true, timestamps: false, }); return Lampada; };
const svg = d3.select('#svg'); let drawing = false; function draw_point() { if (drawing === false) return; const coords = d3.mouse(this); svg.append('circle') .attr('cx', coords[0]) .attr('cy', coords[1]) .attr('r', 5) .style('fill', 'black') } svg.on('mousedown', () => { drawing = true; }) svg.on('mouseup', () => { drawing = false; }) svg.on('mousemove', draw_point);
//we inject this function to createStore in index.js import { combineReducers } from 'redux'; import flashMessages from './reducers/flashMessages.js' export default combineReducers({ flashMessages })
(function() { let body = document.querySelector('body'); document.getElementById("red").addEventListener("click", function (){ body.setAttribute("style","background-color: red") }); document.getElementById("green").addEventListener("click", function (){ body.setAttribute("style","background-color: green") }); document.getElementById("yellow").addEventListener("click", function (){ body.setAttribute("style","background-color: yellow") }); document.getElementById("blue").addEventListener("click", function (){ body.setAttribute("style","background-color: blue") }); })();
'use strict'; describe('ng-step', function () { var element, scope, controller, sampleData; beforeEach(module('demo')); beforeEach(module('planavsky.directive.ngStep')); beforeEach(module('ng-step/views/index.html')); beforeEach(module('mock-data/sample-data.json')); beforeEach(inject(function($rootScope, $compile, $injector, $httpBackend) { scope = $rootScope.$new(); scope.sampleData = sampleData = $injector.get('mockDataSampleData'); element = angular.element('<ng-step data-items="sampleData"></ng-step>'); $compile(element)(scope); scope.$digest(); controller = element.controller('ngStep'); })); it('test example 1', function () { expect(element.isolateScope().vm.activeId).toBe(0); // Arrange var num1 = 1; var num2 = 3; var expected = 4; // Act var result = num1 + num2; // Assert expect(result).toBe(expected); }); });
angular.module('cstudio-admin').controller('adminAccountController', ['$scope', '$http', 'toastr', function ($scope, $http, toastr) { $scope.accounts = []; $scope.accountTypes = {1: 'Admin', 2: 'User'}; $scope.manageAccounts = function () { materialadmin.AppCard.addCardLoader('.card'); io.socket.get('/account/?limit=2000', function response(data, JWR) { if (JWR.statusCode >= 400) { $scope.error = true; console.log('something bad happened', data); $scope.$apply(); return; } materialadmin.AppCard.removeCardLoader('.card'); $scope.accounts = data; $scope.$apply(); }); }; $scope.createAccount = function () { materialadmin.AppCard.addCardLoader('.card'); var _newAccount = { gender: $scope.newAccountGender, firstname: $scope.newAccountFirstName, lastname: $scope.newAccountLastName, username: $scope.newAccountUserName, email: $scope.newAccountEmail, type: $scope.newAccountType, password: $scope.newAccountPassword }; io.socket.post('/account', _newAccount, function whenServerResponds(data, JWR) { if (JWR.statusCode >= 400) { toastr.error('Please fill up required fields.', 'Error'); console.log(data); console.log(JWR.statusCode); materialadmin.AppCard.removeCardLoader('.card'); return; } $scope.newAccountGender = ''; $scope.newAccountFirstName = ''; $scope.newAccountLastName = ''; $scope.newAccountEmail = ''; $scope.newAccountUserName = ''; $scope.newAccountPassword = ''; $scope.newAccountType = ''; $scope.$apply(); toastr.success('Account successfully created!', 'Success'); materialadmin.AppCard.removeCardLoader('.card'); }); }; }]);
import React, { Component } from "react"; class CreateDvdButton extends Component { constructor(props) { super(props); } showFormView = () => { this.props.setHomeState({ view: "form" }); }; render() { return ( <div id="create-dvd-button"> <button onClick={this.showFormView}>Create Dvd</button> </div> ); } } export default CreateDvdButton;
import React, { useState, useEffect } from 'react' import personService from './services/persons' const Notification = ({message, isError}) => { const notificationStyle = { color: isError ? 'red' : 'green', background: 'lightgrey', fontSize: 20, borderStyle: 'solid', borderRadius: 5, padding: 10, marginBottom: 10 } return message !== null ? ( <div style={notificationStyle}>{message}</div> ) : null } const Filter = ({filterText, changeFilterText}) => ( <div> filter shown with <input value={filterText} onChange={changeFilterText} /> </div> ) const PersonForm = ({addPerson, newName, changeNewName, newNumber, changeNewNumber}) => ( <form onSubmit={addPerson}> <div>name: <input value={newName} onChange={changeNewName} /></div> <div>number: <input value={newNumber} onChange={changeNewNumber} /></div> <div> <button type="submit">add</button> </div> </form> ) const Persons = ({persons, deletePerson}) => persons.map(person => ( <div key={person.name}> {person.name} {person.number} <button onClick={() => deletePerson(person)}>delete</button> </div> ) ) const App = () => { const [persons, setPersons] = useState([]) const [ newName, setNewName ] = useState('') const [ newNumber, setNewNumber ] = useState('') const [ filterText, setFilterText ] = useState('') const [notification, setNotification] = useState({ message: null, error: false }) useEffect(() => { personService .getAll() .then(setPersons) }, []) const changeNewName = event => setNewName(event.target.value) const changeNewNumber = event => setNewNumber(event.target.value) const changeFilterText = event => setFilterText(event.target.value.toLowerCase()) const setNotificationMessage = message => setNotification({message, error: false}) const changeNumber = person => { const changedPerson = {...person, number: newNumber} personService.changePerson(changedPerson).then(savedPerson => { const replace = person => person.id === savedPerson.id setPersons(persons.map(person => replace(person) ? savedPerson : person)) setNewName('') setNewNumber('') setNotificationMessage(`Changed ${person.name}`) setTimeout(() => setNotificationMessage(null), 5000) }) .catch(error => { setNotification({message: `Information of ${person.name} has already been removed from server`, error: true}) setTimeout(() => setNotificationMessage(null), 5000) setPersons(persons.filter(p => p.id !== person.id)) }) } const addPerson = event => { event.preventDefault() const existingPerson = persons.find(person => person.name === newName) if(existingPerson) { if(window.confirm(`${newName} is already added to phonebook, replace the old number with a new one?`)){ changeNumber(existingPerson) } return } const newPerson = { name: newName, number: newNumber } personService .addPerson(newPerson) .then(addedPerson => { setPersons(persons.concat(addedPerson)) setNewName('') setNewNumber('') setNotificationMessage(`Added ${addedPerson.name}`) setTimeout(() => setNotificationMessage(null), 5000) }) .catch(error => { const message = error.response.data.error setNotification({message, error: true}) }) } const deletePerson = person => { if(window.confirm(`Delete ${person.name} ?`)){ personService.deletePerson(person) .then(() => { setPersons(persons.filter(p => p.id !== person.id)) setNotificationMessage(`Deleted ${person.name}`) setTimeout(() => setNotificationMessage(null), 5000) }) .catch(error => { setNotification({message: `Information of ${person.name} has already been removed from server`, error: true}) setTimeout(() => setNotificationMessage(null), 5000) setPersons(persons.filter(p => p.id !== person.id)) }) } } const visiblePersons = persons.filter(person => person.name.toLowerCase().indexOf(filterText) > -1) return ( <div> <h2>Phonebook!</h2> <Notification message={notification.message} isError={notification.error} /> <Filter filterText={filterText} changeFilterText={changeFilterText} /> <h2>add a new</h2> <PersonForm addPerson={addPerson} newName={newName} changeNewName={changeNewName} newNumber={newNumber} changeNewNumber={changeNewNumber} /> <h2>Numbers</h2> <Persons persons={visiblePersons} deletePerson={deletePerson} /> </div> ) } export default App
function solve(input) { const playerResults = {}; const powers = { J: 11, Q: 12, K: 13, A: 14 } const types = { S:4, H:3, D:2, C:1 } for (const line of input) { let [player, cardsArgs] = line.split(': '); let cards = cardsArgs.split(', '); let distinctCards = [...new Set(cards)] for (const card of distinctCards) { if (!playerResults.hasOwnProperty(player)) { playerResults[player] = []; } if (playerResults[player].includes(card)) { continue; } playerResults[player].push(card); } } for (const key in playerResults) { let cardSum = 0; for (const card of playerResults[key]) { let cardPower = 0; let typeOfCard = 0; if (card.match(/^\d/) && card.length != 3) { cardPower = Number(card[0]); typeOfCard = types[card[1]]; } else if (card.length === 3) { cardPower = 10; typeOfCard = types[card[2]] } else { cardPower = powers[card[0]]; typeOfCard = types[card[1]]; } cardSum += cardPower * typeOfCard; } playerResults[key] = cardSum; console.log(`${key}: ${playerResults[key]}`); } } solve(['Peter: 2C, 4H, 9H, AS, QS', 'Tomas: 3H, 10S, JC, KD, 5S, 10S', 'Andrea: QH, QC, QS, QD', 'Tomas: 6H, 7S, KC, KD, 5S, 10C', 'Andrea: QH, QC, JS, JD, JC', 'Peter: JD, JD, JD, JD, JD, JD']);
var KiiGatewayAgent = require('kii-gateway-agent'); KiiGatewayAgent.preinit();
var PRIMARY_ROADS = 3; var PRIMARY_THICKNESS = 6; var SECONDARY_THICKNESS = 3; var TERTIARY_THICKNESS = 1; var STEP_SIZE = 10; var TLtoBR = 1; var TtoB = 2; var TRtoBL = 3; var LtoR = 4; var c = document.getElementById('citygen'); var ctx = c.getContext('2d'); var windowWidth = c.scrollWidth; var windowHeight = c.scrollHeight + 110; c.setAttribute('width', windowWidth); c.setAttribute('height', windowHeight); var chunkWidth = windowWidth / 3; var chunkHeight = windowHeight / 3; console.log(windowWidth + " " + windowHeight); var primaryRoads = []; var secondaryRoads = []; var tertiaryRoads = []; function getLength(a, b){ return Math.sqrt(Math.pow(a.x - b.x, 2) - Math.pow(a.y - b.y, 2)) } function getMidpoint(a, b){ return new Coord((a.x + b.x)/2, (a.y + b.y)/2); } function getPointsAlongRoad(road, size) { var list = []; var rawSize = road.length / size; var size = Math.floor(rawSize); for(var i = 0; i < size; i++){ var sx, sy, ex, ey, ix, iy; sx = road.start.x; sy = road.start.y; ex = road.end.x; ey = road.end.y; ix = (sx - ex) / rawSize; iy = (sy - ey) / rawSize; list.push(new Coord(sx - ix * i, sy - iy * i)); } return list; } function Coord(x, y){ this.x = x; this.y = y; this.print = "(" + this.x + ", " + this.y + ")"; } function Road(s, e, dir) { this.start = s; this.end = e; this.length = getLength(this.start, this.end); this.middle = getMidpoint(this.start, this.end); this.print = this.start.print + " -- " + this.end.print; this.direction = dir; } function generatePrimaryRoads(){ for(var i = 0; i < PRIMARY_ROADS; i++){ //generate a random point in the quadrant 1,2,3,4 var quad = Math.ceil(Math.random() * 2) * 2 - 1; var start; var end; switch(quad){ //if 1, pick corresponding point in 9 case TLtoBR: console.log("tltobr") start = new Coord(Math.floor(Math.random() * chunkWidth / STEP_SIZE), Math.floor(Math.random() * chunkHeight)); end = new Coord(start.x + chunkWidth * 2, start.y + chunkHeight * 2); break; //if 2, pick point in 8 case TtoB: console.log("ttob") start = new Coord(Math.floor(Math.random() * chunkWidth + chunkWidth), Math.floor(Math.random() * chunkHeight)); end = new Coord(start.x, start.y + chunkHeight * 2); break; //if 3, pick point in 7 case TRtoBL: console.log("trtobl") start = new Coord(Math.floor(Math.random() * chunkWidth + chunkWidth * 2), Math.floor(Math.random() * chunkHeight)); end = new Coord(start.x - chunkWidth * 2, start.y + chunkHeight * 2); break; //if 4, pick point in 6 case LtoR: console.log("ltor") start = new Coord(Math.floor(Math.random() * chunkWidth), Math.floor(Math.random() * chunkHeight + chunkHeight)); end = new Coord(start.x + chunkWidth * 2 + chunkWidth, start.y); break; } primaryRoads.push(new Road(new Coord(start.x, start.y), new Coord(end.x, end.y), quad)) } console.log("Primary generated") } function generateChildRoads(parents, childList, step) { $.each(parents, function(count, road){ $.each(getPointsAlongRoad(road, step), function(num, start){ dir = (road.direction + 2) % 4; var end1, end2; var rand = Math.random(); switch(dir){ case TLtoBR: end1 = new Coord(start.x - chunkWidth * rand, start.y - chunkHeight * rand); end2 = new Coord(start.x + chunkWidth * rand, start.y + chunkHeight * rand); break; // case TtoB: // end1 = new Coord(start.x, start.y - chunkHeight * rand); // end2 = new Coord(start.x, start.y + chunkHeight * rand); // break; case TRtoBL: end1 = new Coord(start.x + chunkWidth * rand, start.y - chunkHeight * rand); end2 = new Coord(start.x - chunkWidth * rand, start.y + chunkHeight * rand); break; // case LtoR: // end1 = new Coord(start.x - chunkWidth * rand, start.y); // end2 = new Coord(start.x + chunkWidth * rand, start.y); // break; } childList.push(new Road(start, end1 ,dir)) childList.push(new Road(start, end2 ,dir)) }) }) console.log("Child set generated") } function drawPrimaryRoads() { var path=new Path2D(); ctx.strokeStyle = '#008DF9'; $.each(primaryRoads, function(count, road){ ctx.beginPath(); ctx.lineWidth = 5; path.moveTo(road.start.x, road.start.y); path.lineTo(road.end.x, road.end.y); ctx.stroke(path); }) } function drawChildRoads(roadList, thickness) { var path=new Path2D(); ctx.strokeStyle = '#FFFFFF'; $.each(roadList, function(count, road){ ctx.beginPath(); ctx.lineWidth = thickness; path.moveTo(road.start.x, road.start.y); path.lineTo(road.end.x, road.end.y); ctx.stroke(path); }) } generatePrimaryRoads(); generateChildRoads(primaryRoads, secondaryRoads, STEP_SIZE * 10); generateChildRoads(secondaryRoads, tertiaryRoads, STEP_SIZE * 2); drawChildRoads(secondaryRoads, SECONDARY_THICKNESS); drawChildRoads(tertiaryRoads, TERTIARY_THICKNESS); drawPrimaryRoads();
/* @flow */ import React, { Component } from "react"; import { View, Text, Dimensions } from "react-native"; import styled from "styled-components/native"; var { height } = Dimensions.get("window"); const Wrapper = styled.View` flex: 1; justify-content: center; align-items: center; height: ${height - height * 0.2} `; const Emoji = styled.Text` font-size: 50; `; const PlaceHolder = () => ( <Wrapper> <Emoji>🎧</Emoji> <Text>Busca tu canción favorita</Text> </Wrapper> ); export default PlaceHolder;
import React from "react"; import ReactDOM from "react-dom"; import { Button, Container, Divider, Grid, Header, Image, Menu, Segment } from "semantic-ui-react"; import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom"; import PrivateRoute from "shared/lib/PrivateRoute"; import AuthService from "services/api/auth.js"; import ListingCard from "components/ListingCard"; import ScrollToTop from "components/ScrollToTop"; import MainNavbar from "components/MainNavbar"; import Footer from "components/Footer"; import Home from "views/Home"; import ListingDetail from "views/ListingDetail"; import Login from "views/Login"; import Logout from "views/Logout"; import Profile from "views/Profile"; import AddListing from "views/AddListing"; import FourOhFour from "views/FourOhFour"; import Empty from "views/Empty"; ReactDOM.render( ( <Router> <ScrollToTop> <div> <MainNavbar isAuthenticated={AuthService.isAuthenticated()} profile={AuthService.getUserName()}> </MainNavbar> <Switch> <Route exact path="/" component={Home}/> <Route exact path="/login" component={Login}/> <Route exact path="/logout" component={Logout}/> <PrivateRoute exact path="/listings/add" component={AddListing}/> <PrivateRoute path="/listings/:id" component={ListingDetail}/> <PrivateRoute exact path="/profile" component={Profile}/> <Route exact path="/empty" component={Empty} /> <Route component={FourOhFour}/> </Switch> <Footer /> </div> </ScrollToTop> </Router> ), document.getElementById("app") );
var jobDispatcher = require("./jobDispatcher"); var postHandler = {}; var getHandler = {}; postHandler["/build"] = function(request, response) { var appname = request.postData.appname; var jobDescription = { jobname:"build", payload:{ appname:appname }, completeHandler:function(jobDescription){ console.log("job completed"); console.log(jobDescription.result.toString()); } }; jobDispatcher.dispatchJob(jobDescription); }; exports.postHandler = postHandler; exports.getHandler = getHandler;
const log = (toLog) => console.log(toLog) const space = () => log("---") const actPrmpt = () => { space() log("What will you do?") space() } const parse = (toParse) => JSON.parse(toParse) let act = {} let items = {} const bagInv = () => { if (Object.keys(items).length) { return `The bag currently holds a ${Object.keys(items) .toString() .replace(/,/g, " and a ")}.` } else { return "There is nothing in the bag right now." } } const game = { logActions: false, switchLog(action) { this.logActions = !this.logActions action() this.logActions = !this.logActions return "" }, start() { log("Welcome to Bag of Holding") space() log("type game.cmds() at any time to see available commands") space() if (bag.level) { log("You already have a game in progress.") space() return eval(`${[bag.level]}.start()`) } else { bag.clear() return log( "Would you like to play the game with illustrations? Please type illu(true) or illu(false)" ) } }, cmds() { let commands Object.keys(items).length ? (commands = ` Available Commands and Inventory: ${bagInv()} act. ${Object.keys(act).toString().replace(/,/g, "()\n ")}() game. cmds() : lists game controls end() : ends session and erases game `) : (commands = ` Available Commands: act. ${Object.keys(act).toString().replace(/,/g, "()\n ")}() game. cmds() : lists game controls end() : ends session and erases game `) if (game.logActions) { log(commands) } else { return commands } }, end() { bag.clear() return "Don't quite have what it takes, eh? Well, maybe come back and try again sometime." }, } game.start()
'use strict'; angular. module('supprimerEleve'). component('supprimerEleve', { templateUrl: 'supprimer-eleve/supprimer-eleve.template.html', controller: ['$rootScope','$routeParams', function SuprrimerEleveController($rootScope,$routeParams) { angular.forEach( $rootScope.eleves, function(eleve){ if( eleve.tel == $routeParams.idEleve){ var index= $rootScope.eleves.indexOf(eleve); //$rootScope.eleves.splice(index,1); } }); } ] }) ;
import React, { useState, useEffect, useContext } from 'react'; import { SetlistContext } from '../../contexts/SetlistContext' import NavBar from '../../components/NavBar' import './styles.css' export default function EditSetlist({ match, history }) { const { setlists } = useContext(SetlistContext) const [setlist, setSetlist] = useState({}) const [loading, setLoading] = useState({}) useEffect(() => { const _id = match.params.setlist_id const response = setlists.find(item => item._id === _id) if (response){ setSetlist(response) setLoading(false) } else { console.log(`Error, couldn't find setlist with the id ${_id}`) history.push('/setlists') } }, [setlists]) if(loading) return "Loading" return ( <> <NavBar title="EDIT SETLIST" goBack={history.goBack} /> <form> </form> </> ); }
var express = require('express') , rp = require('request-promise'); var app = express(); app.use(express.static(__dirname + '/public')); app.get('/', function (req, res) { console.log('get /'); res.sendFile(__dirname + "/public/info.html", function (err) { if (err) { console.log(err); } else { console.log('Sent: info.html'); } }); }); function getTicket(usr,pw) { return new Promise((resolve, reject) => { var options= {}; options.url='http://kortforsyningen.kms.dk/service'; options.qs= {}; options.qs.service= 'META'; options.qs.request= 'GetTicket'; options.qs.login= usr; options.qs.password= pw; //options.resolveWithFullResponse= true; var jsonrequest= rp(options).then((body) => { console.log('getticket: %s, %d', body, body.length); if (body.length === 32) { // returnerer en status 200 ved ukendt username/password?! resolve(body); } else { reject('Ukendt username/password'); } }) .catch((err) => { reject('fejl i request af kortforsyningen: ' + err); }); }); } app.get('/getticket', function (req, res, next) { getTicket(usr,pw).then((ticket) => { res.status(200).send(ticket); }) .catch((err) => { res.status(400).send('Ukendt username og password: ' + err); }); }); app.get('/advvis', function (req, res) { //console.log(req); res.sendFile(__dirname + "/public/advvis.html", function (err) { if (err) { console.log('fejl: ' + err); } else { console.log('Sent: advvis.html'); } }); }); app.get('/stat', function (req, res) { //console.log(req); res.sendFile(__dirname + "/public/stat.html", function (err) { if (err) { console.log('fejl: ' + err); } else { console.log('Sent: stat.html'); } }); }); app.get('/live', function (req, res) { //console.log(req); res.sendFile(__dirname + "/public/live.html", function (err) { if (err) { console.log('fejl: ' + err); } else { console.log('Sent: stat.html'); } }); }); app.get('/gis', function (req, res) { //console.log(req); res.sendFile(__dirname + "/public/gis.html", function (err) { if (err) { console.log('fejl: ' + err); } else { console.log('Sent: gis.html'); } }); }); app.get('/adr', function (req, res) { //console.log(req); res.sendFile(__dirname + "/public/adr.html", function (err) { if (err) { console.log('fejl: ' + err); } else { console.log('Sent: gis.html'); } }); }); app.get(/.+/, function (req, res) { //console.log(req); res.sendFile(__dirname + "/public/vis.html", function (err) { if (err) { console.log('fejl: ' + err); } else { console.log('Sent: index.html'); } }); }); if (!(process.argv[2] && process.argv[3])) { console.log("node app.js <username> <password>"); return; } var usr= process.argv[2] , pw= process.argv[3] , port= process.argv[4]; if (!port) port= 5000; getTicket(usr,pw).then(ticket => { var server = app.listen(port, function () { var host = server.address().address; console.log('URL http://%s:%s', host, port); }); }) .catch(err => { console.log("Ukendt username og password (%s)",err); })
const RPC = require('./rpc-server'); const server = (protobufReqSchema, protobufResSchema) => new RPC({ // 解码请求包 decodeRequest(buffer) { const seq = buffer.readUInt32BE(); return { seq: seq, result: protobufReqSchema.decode(buffer.slice(8)) } }, // 编码返回包 encodeResponse(data, seq) { const body = protobufResSchema.encode(data); const head = Buffer.alloc(8); head.writeUInt32BE(seq); head.writeUInt32BE(body.length, 4); return Buffer.concat([head, body]); }, // 判断请求包是不是接收完成 isCompleteRequest(buffer) { const bodyLength = buffer.readUInt32BE(4); return 8 + bodyLength }, }); module.exports = server;
import React, { Component } from 'react' import {fetchAPI} from '../../../utility' import moment from 'moment' import FontAwesome from 'react-fontawesome' import { Col, Row, Image, ButtonToolbar, DropdownButton,MenuItem } from 'react-bootstrap' import Answer from './Answer.js' import AnswerQuestion from './AnswerQuestion.js' class QuestionPage extends Component { constructor(props) { super(props); this.state={ question:{ answers: [] } } } componentDidMount(){ this.getQuestion() } async getQuestion() { try { fetchAPI("GET", "/api/qa/questions/?question_id=" + this.props.match.params.id).then(response => { console.log(response.question) if (response.success) { this.setState({ question: response.question }) } }) } catch (e) { console.error("Error:", e) } } render() { console.log(this.state.question) let answers = this.state.question.answers.map((answer) => { return ( <div key={answer.id}> <Answer answer={answer} /> </div> ) }) return ( <div className="question-box answer-page"> <Row> <Col md={12}> <span className="question-tag">{this.state.question.engineer}</span> </Col> </Row> <Row className="question-box-text"> <Col md={1}> <div className="square"> <div className="fontawesomearrow down"> <FontAwesome name='chevron-up' /> </div> <div className="points down"> {this.state.question.ups} </div> </div> <div className="square"> <div className="fontawesomearrow up"> <FontAwesome name='chevron-down' /> </div> <div className="points up"> {this.state.question.downs} </div> </div> </Col> <Col md={11} right> <h1>{this.state.question.title}</h1> <p>{this.state.question.text}</p> </Col> </Row> <Row> <Col md={12}> <AnswerQuestion id={this.props.match.params.id} /> </Col> </Row> {answers} </div> ) } } export default QuestionPage;
let msg = ["plus grand", "plus petit", "pas un nombre"] let essais = 0; let min = 20; let max = 80; let getRandom = (min, max) => { return Math.floor(Math.random() * (max - min) + min); } console.log(getRandom(min, max)) let jouer = () => { let tentative = +prompt("nombre entre 20 et 80"); console.log('​jouer -> tentative', tentative); if (tentative >= getRandom()){ console.log("pas ok") }else{ console.log('ok') } }
const { Op } = require("sequelize"); const db = require("../models"); const bcrypt = require('bcrypt'); const product = require("../models/product"); const Product = db.products; const Order = db.orders; const Category = db.categories; const Brand = db.brands; const SubCategory = db.sub_categories; exports.getStock = function (req, res) { Product.findAll({ attributes: ["id", "name", "stock"] }) .then(function (data) { res.send({ data: data }); }) .catch(err => { res.status(500).send({ message: err.message || "Some error occurred while retrieving Products." }); }); } exports.getIncome = function (req, res) { Order.findAll({ attributes: [[db.sequelize.fn('sum', db.sequelize.col('amount')), 'income']] }) .then(data => { res.send({ data: data }); }) .catch(err => { res.status(500).send({ message: err.message || "Some error occurred while retrieving Products." }); }); } exports.getBrands = function (req, res) { Brand.findAll( { attributes: ["id", "name"], include: [{ model: Product, as: 'products', where: { brand_id: 4 } }] } ) .then(function (data) { res.send({ data: data }); }) .catch(err => { res.status(500).send({ message: err.message || "Some error occurred while retrieving Products." }); }); }
const express = require('express'); const {check} = require('express-validator/check'); const router = express.Router(); const models = require('../db/models'); router.get('/name', [ check('name', 'Invalid Query').isLength({min: 2}), check('limit', 'Invalid limit').optional().isInt({lt: 999}).toInt() ], (req, res) => { const err = req.validationErrors(); if (err) { res.status(401).json(err); } else { const {name} = req.query; const op = models.Sequelize.Op; models.store.findAll({ limit: req.query.limit || 10, where: {name: {[op.like]: `%${name}%`}} }).then(row => res.status(200).json(row)); } }); router.get('/near', [ check('x', 'Invalid location').isFloat({gt: 124, lt: 132}).toFloat(), check('y', 'Invalid location').isFloat({gt: 33, lt: 43}).toFloat(), check('limit', 'Invalid limit').optional().isInt({lt: 999}).toInt() ], (req, res) => { const err = req.validationErrors(); if (err) { res.status(401).json(err); } else { const {x: lng, y: lat} = req.query; const op = models.Sequelize.Op; models.store.findAll({ limit: req.query.limit || 10, where: { [op.and]: { x: {[op.between]: [lng - 0.035, lng + 0.035]}, y: {[op.between]: [lat - 0.027, lat + 0.027]} } } }).then(row => res.status(200).json(row)); } }); module.exports = router;
const dns = require('dns') console.log(dns.getServers()) // const search = (arr = [1, 2, 3, 4, 5, 6, 7, 8, 9], target = 2) => { // } // // 二分查找有序数组 // const search = (arr = [1, 2, 3, 4, 5, 6, 7, 8, 9], target = 2) => { // const mid = Math.floor(arr.length / 2) // console.log(arr, mid, target) // if (mid === target) { // return true // } // if (mid > target) { // // console.log(arr.slice(0, mid), target) // search(arr.slice(0, mid), target) // } // if (mid < target) { // search(arr.slice(mid, arr.length), target) // } // } // let res = search() // console.log(res)
import React from 'react'; import { View, Text, TouchableOpacity, StyleSheet } from 'react-native'; import PropTypes from 'prop-types'; import { Icon } from '@ant-design/react-native'; import ClassicHeader from 'react-native-classic-header'; import ActionButton from 'react-native-action-button'; import Spinner from 'react-native-loading-spinner-overlay'; import BaseView from '@/components/common/baseView'; import CommonStyles from '@/commonStyles'; /** * 浮动视图 * * @export * @class FloatingView * @extends {BaseView} */ export default class FloatingView extends BaseView { static propTypes = { visible: PropTypes.bool, maximum: PropTypes.bool, title: PropTypes.string, }; static defaultProps = { visible: false, maximum: false, }; state = { visible: this.props.visible, maximum: this.props.maximum, }; constructor(props) { super(props); } render() { const { visible, maximum } = this.state; if (!visible) { return null; } else if (!maximum) { return this._renderMark(); } const children = this._render() || this.props.children; return ( <View style={styles.container}> <Spinner visible={this.state.showWaitingBox} textContent={this.waitingMessage} textStyle={styles.waitingMessageStyle} /> <ClassicHeader titleComponent={<Text style={CommonStyles.headerTitle}>{this.props.title}</Text>} leftComponent={ <TouchableOpacity style={{ left: 16, position: 'absolute' }} onPress={() => this.setState({ visible: false })}> <Icon name="close" size="md" /> </TouchableOpacity> } rightComponent={ <TouchableOpacity style={{ right: 16, position: 'absolute' }} onPress={() => this.setState({ maximum: false })}> <Icon name="down" size="md" /> </TouchableOpacity> } /> {children} </View> ); } /** * 渲染标志 * * @return {*} * @memberof FloatingView */ _renderMark() { return <ActionButton buttonColor="rgba(231,76,60,1)" onPress={() => this.setState({ maximum: true })} />; } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'white' }, waitingMessageStyle: { color: '#FFF', }, });
var paths = [ ["好身材", "/question/297715922/answer/520615441"], ["好身材2", "/question/328457531/answer/733560542"], ["好身材3", "/question/297715922/answer/710626693"], ["大长腿", "/question/285321190/answer/657375937"], ["女朋友", "/question/313825759"], ["现实美", "/question/29289467/answer/72898476"], ] let index = 5 var options = { hostname: 'www.zhihu.com', port: 443, path: paths[index][1], } module.exports = { options, staticPath: paths[index][0] }
$(function() { /* 实现三级选择器 */ var picker = new mui.PopPicker({ layer: 3 }); picker.setData(cityData); $("#selectedCity").on("tap", function() { picker.show(function(selectItems) { $("#selectedCity").val(selectItems[0].text + selectItems[1].text + selectItems[2].text) }) }) /* 添加收获地址 1.注册点击事件 2.获取数据 3.校验 4.调用接口 5.跳转到address.html页面 */ // $(".checkAdd-btn").on("click", function() { // var address = $("[name='address']").val().trim(); // var addressDetail = $("[name='addressDetail']").val().trim(); // var recipients = $("[name='recipients']").val().trim(); // var postcode = $("[name='postcode']").val().trim(); // // console.log(address); // // console.log(addressDetail); // // console.log(recipients); // // console.log(postcode); // if (!address) { // mui.toast("请输入地址") // return; // } // if (!addressDetail) { // mui.toast("请输入详细地址") // return; // } // if (!recipients) { // mui.toast("请输入收货人") // return; // } // if (!postcode) { // mui.toast("请输入邮政编码") // return; // } // $.ajax({ // url: '/address/addAddress', // type: 'post', // data: { // address: address, // addressDetail: addressDetail, // recipients: recipients, // postcode: postcode // }, // success(res) { //成功就跳转到addrss.html页面 // // console.log(address); // // console.log(res); // setInterval(function() { // location.href = "address.html"; // }, 2000); // } // }) // }) /** * 实现修改地址功能 * 由于添加收获地址和修改收货地址都是同一个页面,因此要做一定的区分 * 根据收获地址判断。此次操作是添加还是修改页面 * 1.获取地址栏中的id参数 * 2.有则是修改操作,无则是添加操作 * 3.修改地址操作 * 1.调用接口,查询保存的地址 * 2.根据传递过来的id值获取想要的值 * 3.将值添加到文本框中 * 4.调用接口,修改地址 * 4.添加地址 * 1.复制之前的代码即可 * * */ var id = Number(getParamsByUrl(location.href, 'id')); if (id) { //表示这次是编辑数据 $.ajax({ url: '/address/queryAddress', type: 'get', success(res) { console.log(res); res.forEach((item, i) => { if (item.id === id) { // console.log(item); $("[name='address']").val(item.address); $("[name='addressDetail']").val(item.addressDetail); $("[name='recipients']").val(item.recipients); $("[name='postcode']").val(item.postCode); $(".checkAdd-btn").on("click", function() { var address = $("[name='address']").val().trim(); var addressDetail = $("[name='addressDetail']").val().trim(); var recipients = $("[name='recipients']").val().trim(); var postcode = $("[name='postcode']").val().trim(); // console.log(address); // console.log(addressDetail); // console.log(recipients); // console.log(postcode); if (!address) { mui.toast("请输入地址") return; } if (!addressDetail) { mui.toast("请输入详细地址") return; } if (!recipients) { mui.toast("请输入收货人") return; } if (!postcode) { mui.toast("请输入邮政编码") return; } $.ajax({ url: '/address/updateAddress', type: 'post', data: { id: id.toString(), address: address, addressDetail: addressDetail, recipients: recipients, postcode: postcode }, success(res) { //成功就跳转到addrss.html页面 // console.log(address); // console.log(res); setInterval(function() { location.href = "address.html"; }, 2000); } }) }) } }) } }) } else { //表示是添加数据 $(".checkAdd-btn").on("click", function() { var address = $("[name='address']").val().trim(); var addressDetail = $("[name='addressDetail']").val().trim(); var recipients = $("[name='recipients']").val().trim(); var postcode = $("[name='postcode']").val().trim(); // console.log(address); // console.log(addressDetail); // console.log(recipients); // console.log(postcode); if (!address) { mui.toast("请输入地址") return; } if (!addressDetail) { mui.toast("请输入详细地址") return; } if (!recipients) { mui.toast("请输入收货人") return; } if (!postcode) { mui.toast("请输入邮政编码") return; } $.ajax({ url: '/address/addAddress', type: 'post', data: { address: address, addressDetail: addressDetail, recipients: recipients, postcode: postcode }, success(res) { //成功就跳转到addrss.html页面 // console.log(address); // console.log(res); setInterval(function() { location.href = "address.html"; }, 2000); } }) }) } })
// const bcrypt = require('bcrypt'); // const jwt = require('jsonwebtoken'); // // sirve para filtrar los datos que quiero y por ende elimina los que noq uiero del objeto // const _ = require('underscore'); // const User = require('./worker.model'); // exports.saveUser = (req, res) => { // const { // nombre, apellido, email, password, role, identificacion, phone, direccion, edad, img, // idFront, // idBack, // } = req.body; // const user = new User({ // nombre, // apellido, // email, // password: bcrypt.hashSync(password, 10), // role, // direccion, // phone, // identificacion, // edad, // img, // idFront, // idBack, // }); // user.save((err, userDB) => { // if (err) { // return res.status(400).json({ // ok: false, // err, // }); // } // return User.findOne({ email: userDB.email }, (error, workerDB) => { // if (error) { // return res.status(500).json({ // ok: false, // error, // }); // } // if (!workerDB || !bcrypt.compareSync(password, workerDB.password)) { // return res.status(400).json({ // ok: false, // error: { // message: 'Usuario o contraseña incorrectos', // }, // }); // } // const token = jwt.sign({ // user: workerDB, // }, process.env.SEED_TOKEN, { expiresIn: process.env.EXP_TOKEN }); // expira en 30 dias // return res.json({ // ok: true, // // workerDB, // token, // }); // }); // // userDB.password = null; // // return res.json({ // // ok: true, // // user: userDB, // // }); // }); // }; // exports.updateUser = (req, res) => { // const { id } = req.params; // const body = _.pick(req.body, ['edad', 'nombre', 'email', 'img', 'role', 'estado', 'apellido', 'direccion', 'phone', 'identificacion']); // User.findByIdAndUpdate(id, body, { new: true, runValidators: true }, (err, userDB) => { // if (err) { // return res.status(400).json({ // ok: false, // err, // }); // } // return res.json({ // ok: true, // user: userDB, // }); // }); // }; // exports.getUsers = (req, res) => { // const { sky } = req.query || 0; // const { lim } = req.query || 5; // User.find({ estado: true }, 'nombre email role estado google img') // .skip(Number(sky)) // .limit(Number(lim)) // .exec((err, users) => { // if (err) { // return res.status(400).json({ // ok: false, // err, // }); // } // return User.countDocuments({ estado: true }, (errCount, count) => { // if (errCount) { // return res.status(400).json({ // ok: false, // errCount, // }); // } // return res.json({ // ok: true, // users, // count, // }); // }); // }); // }; // exports.getId = (req, res) => { // const { id } = req.params; // User.find({ estado: true, _id: id }) // .exec((err, users) => { // if (err) { // return res.status(400).json({ // ok: false, // err, // }); // } // return res.json({ // ok: true, // users, // }); // }); // }; // exports.getInfo = (req, res) => { // const { _id } = req.user; // User.find({ _id }) // .exec((err, users) => { // if (err) { // return res.status(400).json({ // ok: false, // err, // }); // } // return res.json({ // ok: true, // users, // }); // }); // }; // exports.deleteUser = (req, res) => { // const { id } = req.params; // // User.findByIdAndUpdate(id, (err, userDB) => { // User.findByIdAndUpdate(id, { estado: false }, { new: true }, (err, userDB) => { // if (err) { // return res.status(400).json({ // ok: false, // err, // }); // } // if (!userDB) { // return res.status(400).json({ // ok: false, // err: { // message: 'Usuario no encontrado', // }, // }); // } // return res.json({ // ok: true, // delete: userDB, // }); // }); // }; const admin = require('firebase-admin'); const service = require('./worker.service'); exports.register = (req, res) => { const { email, password, phone, name, lastname, address, img, idFront, idBack, } = req.body; admin.auth().createUser({ email, password, emailVerified: true, }) .then((auth) => { const params = { email, phone, name, lastname, address, id: auth.uid, }; if (typeof img === 'string' && img !== null && img.length > 0) { params.img = img; } if (typeof idFront === 'string' && idFront !== null && idFront.length > 0) { params.idFront = idFront; } if (typeof idBack === 'string' && idBack !== null && idBack.length > 0) { params.idBack = idBack; } service.SavedDataBasePromise(params, 'workers', auth) .then(response => res.status(201).json(response)) .catch(error => res.status(400).json(error)); return 1; }).catch((error) => { // res.status(400).json(error); res.status(400).json(error); return 1; }); return 1; };
#!/usr/bin/env node console.log('iview-admin-jopen-cli脚手架工具'); const { program } = require('commander'); const download = require('download-git-repo') const ora = require('ora') const chalk = require('chalk') const logSymbols = require('log-symbols') program .version('0.1.0') //输出对应的版本号 program .command('create <project>') // .description('初始化项目模板') .action(function(project){ // 在下载前提示 const spinner = ora('正在下载模板当中...').start() // download的 // 第一个参数:仓库地址#分支 注意需要改成所需要的格式,不要直接复制粘贴 // 第二个参数: 项目名 const downLoadUrl = `https://github.com:winwingo/ivew-admin-cli#master` download(downLoadUrl,project,{clone:true},err=>{ if (err){ spinner.fail() return console.log(logSymbols.error,chalk.red('下载失败,失败原因:'+err)); }else{ spinner.succeed(); return console.log(logSymbols.success,chalk.yellow('下载成功')); } }) }); program .command('help') .description('查看所有可用的模板帮助') .action(function(){ console.log(`在这里可以书写相关的帮助信息`); }); program.parse(process.argv);
import { connect } from 'react-redux'; import {Navbar, Nav} from 'react-bootstrap'; import { useRouter } from 'next/router'; import Link from 'next/link'; import AuthenticatedLinks from './AuthenticatedLinks'; import UnauthenticatedLinks from './UnauthenticatedLinks'; function NavBar(props) { const router = useRouter(); let authLinks = props.user ? <AuthenticatedLinks name={props.user.Name}/> : <UnauthenticatedLinks/> return ( <div> <Navbar collapseOnSelect expand="lg" bg="dark" variant="dark" className="w-100 fixed-top d-flex"> <Link href="/"> <a className="navbar-brand"> Covid19 Vaccine Notifier </a> </Link> <Navbar.Toggle aria-controls="responsive-navbar-nav" /> <Navbar.Collapse id="responsive-navbar-nav" className="ml-auto"> <Nav className="ml-auto"> <Nav.Item> <Link href="/checkAvailability"> <a className={"nav-link " +(router.pathname == "/checkAvailability" ? "active" : "")}> Check Availability </a> </Link> </Nav.Item> {authLinks} </Nav> </Navbar.Collapse> </Navbar> <style jsx>{` `}</style> </div> ) } function mapStateToProps(state) { return { user: state.auth.user } } export default connect(mapStateToProps)(NavBar);
class ScriptBuilder { Opcode_NOP() { return 0; } // register Opcode_MOVE() { return 1; } Opcode_COPY() { return 2; } Opcode_PUSH() { return 3; } Opcode_POP() { return 4; } Opcode_SWAP() { return 5; } // flow Opcode_CALL() { return 6; } Opcode_EXTCALL() { return 7; } Opcode_JMP() { return 8; } Opcode_JMPIF() { return 9; } Opcode_JMPNOT() { return 10; } Opcode_RET() { return 11; } Opcode_THROW() { return 12; } // data Opcode_LOAD() { return 13; } Opcode_CAST() { return 14; } Opcode_CAT() { return 15; } Opcode_SUBSTR() { return 16; } Opcode_LEFT() { return 17; } Opcode_RIGHT() { return 18; } Opcode_SIZE() { return 19; } Opcode_COUNT() { return 20; } Opcode_NOT() { return 21; } // logical Opcode_AND() { return 22; } Opcode_OR() { return 23; } Opcode_XOR() { return 24; } Opcode_EQUAL() { return 25; } Opcode_LT() { return 26; } Opcode_GT() { return 27; } Opcode_LTE() { return 28; } Opcode_GTE() { return 29; } // numeric Opcode_INC() { return 30; } Opcode_DEC() { return 31; } Opcode_SIGN() { return 32; } Opcode_NEGATE() { return 33; } Opcode_ABS() { return 34; } Opcode_ADD() { return 35; } Opcode_SUB() { return 36; } Opcode_MUL() { return 37; } Opcode_DIV() { return 38; } Opcode_MOD() { return 39; } Opcode_SHL() { return 40; } Opcode_SHR() { return 41; } Opcode_MIN() { return 42; } Opcode_MAX() { return 43; } // context Opcode_THIS() { return 44; } Opcode_CTX() { return 45; } Opcode_SWITCH() { return 46; } // array Opcode_PUT() { return 47; } Opcode_GET() { return 48; } VMType_None() { return 0; } VMType_Struct() { return 1; } VMType_Bytes() { return 2; } VMType_Number() { return 3; } VMType_String() { return 4; } VMType_Timestamp() { return 5; } VMType_Bool() { return 6; } VMType_Enum() { return 7; } VMType_Object() { return 8; } constructor() { this.script = ""; this.clearOptimizations(); } // just quick dirty method to convert number to hex wih 2 digits, rewrite this later if there's a cleaner way raw(value) { let result = value.toString(16); if (result.length == 1) { result = '0' + result; } return result; } rawString(value) { var data = []; for (var i = 0; i < value.length; i++) { data.push(value.charCodeAt(i)); } return data; } // appends a single byte to the script stream appendByte(value) { this.script = this.script + this.raw(value); } appendBytes(values) { for (let i = 0; i < values.length; i++) { this.appendByte(values[i]); } } appendVarInt(value) { if (value < 0) throw "negative value invalid"; if (value < 0xFD) { this.appendByte(value); } else if (value <= 0xFFFF) { let B = (value & 0x0000ff00) >> 8; let A = (value & 0x000000ff); // TODO check if the endianess is correct, might have to reverse order of appends this.appendByte(0xFD); this.appendByte(A); this.appendByte(B); } else if (value <= 0xFFFFFFFF) { let C = (value & 0x00ff0000) >> 16; let B = (value & 0x0000ff00) >> 8; let A = (value & 0x000000ff); // TODO check if the endianess is correct, might have to reverse order of appends this.appendByte(0xFE); this.appendByte(A); this.appendByte(B); this.appendByte(C); } else { let D = (value & 0xff000000) >> 24; let C = (value & 0x00ff0000) >> 16; let B = (value & 0x0000ff00) >> 8; let A = (value & 0x000000ff); // TODO check if the endianess is correct, might have to reverse order of appends this.appendByte(0xFF); this.appendByte(A); this.appendByte(B); this.appendByte(C); this.appendByte(D); } } appendMethodArgs(args) { let temp_reg = 0; for (let i = args.length - 1; i >= 0; i--) { let arg = args[i]; // NOTE the C# version does call LoadIntoReg (which internally calls emitLoad). TODO Confirm if the logic is okay this.emitLoad(temp_reg, arg); this.emitPush(temp_reg); } } emitOpcode(opcode) { this.appendByte(opcode); return this; } emitPush(reg) { this.emitOpcode(this.Opcode_PUSH()); this.appendByte(reg); return this; } emitPop(reg) { this.emitOpcode(this.Opcode_POP()); this.appendByte(reg); return this; } emitLoad(reg, obj) { if (typeof obj === 'string') { let bytes = this.rawString(obj); this.emitLoadEx(reg, bytes, this.VMType_String()); } else if (obj instanceof Date) { // https://stackoverflow.com/questions/9756120/how-do-i-get-a-utc-timestamp-in-javascript let num = (obj.getTime()/* + obj.getTimezoneOffset()*60*1000*/) / 1000; let a = (num & 0xff000000) >> 24; let b = (num & 0x00ff0000) >> 16; let c = (num & 0x0000ff00) >> 8; let d = (num & 0x000000ff); let bytes = [d, c, b, a]; this.emitLoadEx(reg, bytes, this.VMType_Timestamp()); } else if (typeof obj === 'boolean') { let bytes = []; if (obj) { bytes.push(1); } else { bytes.push(0); } this.emitLoadEx(reg, bytes, this.VMType_Bool()); } else if (typeof obj === 'number') { let bytes = this.rawString(obj.toString()); this.emitLoadEx(reg, bytes, this.VMType_String()); } else if (typeof obj === 'object') { this.emitLoadEx(reg, obj, this.VMType_Bytes()); } else { throw "unsupported or uniplemented type"; } return this; } // bytes is byte array emitLoadEx(reg, bytes, vmtype) { if (!Array.isArray(bytes)) { throw "byte array expected"; } if (bytes.length > 0xFFFF) { throw "tried to load too much data"; } this.emitOpcode(this.Opcode_LOAD()); this.appendByte(reg); this.appendByte(vmtype); this.appendVarInt(bytes.length); this.appendBytes(bytes); return this; } emitMethod(method, args) { this.appendMethodArgs(args); let temp_reg = 2; // NOTE this optimization assumes that reg 2 contains a valid method name due to this method being called multiple times if (this.lastMethod != method) { this.lastMethod = method; this.lastContract = null; this.emitLoad(temp_reg, method); } return temp_reg; } callInterop(method, args) { let temp_reg = this.emitMethod(method, args); this.emitOpcode(this.Opcode_EXTCALL()); this.appendByte(temp_reg); return this; } callContract(contractName, method, args) { let temp_reg = this.emitMethod(method, args); this.emitPush(temp_reg); let src_reg = 0; let dest_reg = 1; // NOTE this optimization assumes that reg 1 contains a valid context for this contract due to this method being called multiple times if (this.lastContract != contractName) { this.lastContract = contractName; this.lastMethod = null; this.emitLoad(src_reg, contractName); this.emitOpcode(this.Opcode_CTX()); this.appendByte(src_reg); this.appendByte(dest_reg); } this.emitOpcode(this.Opcode_SWITCH()); this.appendByte(dest_reg); return this; } endScript() { this.emitOpcode(this.Opcode_RET()); return this.script; } clearOptimizations() { this.lastContract = ""; this.lastMethod = ""; } nullAddress() { return 'S1111111111111111111111111111111111'; } } class PhantasmaLink { constructor(dappID) { this.host = "localhost:7090"; this.dapp = dappID; this.onLogin = function (succ) { // do nothing }; } login(callback) { this.onLogin = callback; this.createSocket(); } signTx(script, payload, callback) { console.log(script) if (script.length >= 65536) { alertbox.show('Error: script too big!'); return; } if (payload == null) { payload = ""; } else if (typeof payload === 'string') { // NOTE: here we convert a string into raw bytes let sb = new ScriptBuilder(); let bytes = sb.rawString(payload); sb.appendBytes(bytes); // then we convert the bytes into hex, because thats what PhantasmaLink protocol expects payload = sb.script; } else { alertbox.show('Error: invalid payload'); return; } alertbox.show('Relaying transaction to wallet...'); console.log('Relaying transaction to wallet...') var that = this; if (script.script) { script = script.script } this.sendLinkRequest('signTx/mainnet/main/' + script + '/' + payload, function (result) { callback(result); if (result.success && !result.hash.error) { alertbox.show('Transaction successful, hash: ' + result.hash); console.log('Transaction successful, hash: ' + result.hash); } }); } createSocket() { let path = "ws://" + this.host + "/phantasma"; alertbox.show('Phantasma Link connecting...'); console.log('Phantasma Link connecting: ' + path) this.socket = window.PhantasmaLinkSocket ? new PhantasmaLinkSocket() : new WebSocket(path); this.requestCallback = null; this.token = null; this.account = null; this.requestID = 0; var that = this; this.socket.onopen = function (e) { alertbox.show('Connection established, authorizing dapp in wallet...'); console.log('Connection established, authorizing dapp in wallet...') that.sendLinkRequest('authorize/' + that.dapp, function (result) { if (result.success) { that.token = result.token; that.wallet = result.wallet; alertbox.show('Authorized, obtaining account info...'); console.log('Authorized, obtaining account info...'); that.sendLinkRequest('getAccount', function (result) { if (result.success) { that.account = result; alertbox.show('Ready, opening ' + that.dapp + ' dapp connected with ' + that.account.name + ' on ' + that.wallet + '...'); console.log('Ready, opening ' + that.dapp + ' dapp connected with ' + that.account.name + ' on ' + that.wallet + '...'); } else { alertbox.show('Error: could not obtain account info... Make sure you have an account currently open in ' + that.wallet + '...'); console.log('Error: could not obtain account info... Make sure you have an account currently open in ' + that.wallet + '...'); disconnectLink(true); } that.onLogin(result.success); }); } else { alertbox.show('Error: authorization failed...'); console.log('Error: authorization failed...') that.onLogin(false); disconnectLink(true); } }); }; this.socket.onmessage = function (event) { if (JSON.parse(event.data).message == 'Wallet is Closed') { alertbox.show('Error: could not obtain account info... Make sure you have an account currently open in ' + that.wallet + '...'); console.log('Error: could not obtain account info... Make sure you have an account currently open in ' + that.wallet + '...'); disconnectLink(true); } else if (JSON.parse(event.data).message == 'not logged in') { alertbox.show('Error: could not obtain account info... Make sure you have an account currently open in your wallet...'); console.log('Error: could not obtain account info... Make sure you have an account currently open in in your wallet...'); disconnectLink(true); } else if (JSON.parse(event.data).message == 'A previouus request is still pending' || JSON.parse(event.data).message == 'A previous request is still pending') { alertbox.show('Error: you have a pending action in your wallet...'); console.log('Error: you have a pending action in your wallet...'); } else if (JSON.parse(event.data).message == 'user rejected') { alertbox.show('Error: transaction cancelled by user in ' + that.wallet + '...'); console.log('Error: transaction cancelled by user in ' + that.wallet + '...') } else { if (JSON.parse(event.data).wallet) { console.log(JSON.parse(event.data).dapp + " dapp is now connected with " + JSON.parse(event.data).wallet + '...'); alertbox.show(JSON.parse(event.data).dapp + " dapp is now connected with " + JSON.parse(event.data).wallet + '...'); } else if (JSON.parse(event.data).name) { console.log("Account info obtained, connected with " + JSON.parse(event.data).name + '...'); alertbox.show("Account info obtained, connected with " + JSON.parse(event.data).name + '...'); } else if (JSON.parse(event.data).hash) { console.log("Transaction accepted on wallet..."); alertbox.show("Transaction accepted on wallet..."); } else { console.log("Got Phantasma Link answer: " + JSON.parse(event.data).message); alertbox.show("Got Phantasma Link answer: " + JSON.parse(event.data).message); } var obj = JSON.parse(event.data); var temp = that.requestCallback; if (temp == null) { alertbox.show('Error: something bad happened...'); console.log('Error: something bad happened...') return; } that.requestCallback = null; temp(obj); } }; this.socket.onclose = function (event) { //if (linkDisconnected == 0) { if (!event.wasClean) { alertbox.show('Error: connection terminated...'); console.log('Error: connection terminated...') //linkDisconnected = 1; disconnectLink(true); } //} }; this.socket.onerror = function (error) { if (error.message !== undefined) { alertbox.show('Error: ' + error.message); console.log('Error: ' + error.message) } }; } retry() { this.createSocket(); } get dappID() { return this.dapp; } sendLinkRequest(request, callback) { console.log("Sending Phantasma Link request: " + request); if (this.token != null) { request = request + '/' + this.dapp + '/' + this.token; } this.requestID++; request = this.requestID + ',' + request; this.requestCallback = callback; this.socket.send(request); } } var AlertBox = function (id, option) { this.show = function (msg) { if (msg === '' || typeof msg === 'undefined' || msg === null) { throw '"msg parameter is empty"'; } else { var alertArea = document.querySelector(id); var alertBox = document.createElement('DIV'); var alertContent = document.createElement('DIV'); var alertClose = document.createElement('A'); var alertClass = this; alertContent.classList.add('alert-content'); alertContent.innerText = msg; alertClose.classList.add('alert-close'); alertClose.setAttribute('href', '#'); alertBox.classList.add('alert-box'); alertBox.appendChild(alertContent); if (!option.hideCloseButton || typeof option.hideCloseButton === 'undefined') { alertBox.appendChild(alertClose); } alertArea.appendChild(alertBox); alertClose.addEventListener('click', function (event) { event.preventDefault(); alertClass.hide(alertBox); }); if (!option.persistent) { var alertTimeout = setTimeout(function () { alertClass.hide(alertBox); clearTimeout(alertTimeout); }, option.closeTime); } } }; this.hide = function (alertBox) { alertBox.classList.add('hide'); var disperseTimeout = setTimeout(function () { if (alertBox.parentNode) { alertBox.parentNode.removeChild(alertBox); } clearTimeout(disperseTimeout); }, 500); }; }; var alertNonPersistent = document.querySelector('#alertNonPersistent'); var alertPersistent = document.querySelector('#alertPersistent'); var alertShowMessage = document.querySelector('#alertShowMessage'); var alertHiddenClose = document.querySelector('#alertHiddenClose'); var alertMessageBox = document.querySelector('#alertMessageBox'); var alertbox = new AlertBox('#alert-area', { closeTime: 25000, persistent: false, hideCloseButton: false }); var alertboxPersistent = new AlertBox('#alert-area', { closeTime: 25000, persistent: true, hideCloseButton: false }); var alertNoClose = new AlertBox('#alert-area', { closeTime: 25000, persistent: false, hideCloseButton: true }); function disconnectLink(triggered) { if (triggered) { if (currentCallType == 'Auction') { $("#retry-link").html('<button data-bb-handler="confirm" type="button" class="btn btn-primary" onclick="confirmAuction(\'' + currentCall + '\')" id="retry-link"><i class="fa fa-check"></i> Retry</button>') } else if (currentCallType == 'Item') { $("#retry-link").html('<button data-bb-handler="confirm" type="button" class="btn btn-primary" onclick="confirmSale(\'' + currentCall + '\',\'' + currentCallCurrency + '\')" id="retry-link"><i class="fa fa-check"></i> Retry</button>') } $('#phantasmaError').modal('show'); } console.log('Phantasma Link disconnecting...') alertbox.show('Phantasma Link disconnecting...'); }
import React, { useState } from "react"; import axios from "axios"; import ListItem from "./ListItem"; import { infiniteScroll } from "../helpers/infiniteScroll"; export const RepoList = () => { const [list, setList] = useState([]); const [isLoading, setIsLoading] = useState(false); const [page, setPage] = useState(1) infiniteScroll(() => isLoading, () => { setIsLoading(true); axios .get("https://api.github.com/users/charlax/repos", { params: { page: page, per_page: 20 } }) .then(({ data }) => { setList([...list, ...data]); setPage(page + 1); setIsLoading(false); }); }); return list.length ? ( <ul className="repos-list" > {list.map(item => ( <li className="repos-list__item" key={item.id}> <ListItem list={item} /> </li> ))} </ul> ) : "Lądowanie"; };
// 1. (* Print the first non repeated character from a string *) // // - Split the string in to characters // - Loop through the string and check if the characters and the string's characters are duplicated more than once. Return the character. const firstNonRepeatedCharacter = function (string) { let chars = string.split(""); for (let i = 0; i < string.length; i++) { if ( chars.filter(function (j) { return j == string.charAt(i); }).length == 1 ) return string.charAt(i); } }; // console.log(firstNonRepeatedCharacter("aabbcddd")); // Output: c // console.log(firstNonRepeatedCharacter("abbcddd")); // Output: a // console.log(firstNonRepeatedCharacter("abcd")); // Output: a // 2. (* Find the missing numbers in a given integer array *) // // - Get min and max values using Math.min and .max by spreading the original array // - Check the arrays and minus the max value from the min value, then filter out any missing numbers and assign the items equal to the numbers that the arr doesn't include const arr = [1, 3, 5, 7, 9]; const [min, max] = [Math.min(...arr), Math.max(...arr)]; const missingNumber = Array.from(Array(max - min), (v, i) => i + min).filter( (i) => !arr.includes(i) ); // console.log(missingNumber); // Output: [ 2, 4, 6, 8 ] // 3. (* Check if two strings are a rotation of each other *) // - Using repeat to repeat the second string being passed as 'rotated' twice and checking if the first string passed as 'string' is included within this repetition function checkRotationStrings(string, rotated) { return string.length === rotated.length && rotated.repeat(2).includes(string); } // console.log(checkRotationStrings("apple", "elppa")); // Output: false // console.log(checkRotationStrings("apple", "leapp")); // Output: true // console.log(checkRotationStrings("hello", "lohel")); // Output: true // console.log(checkRotationStrings("hello", "ohell")); // Output: true // 4. (* Generate all permutations of a string - ES6 *) // - First check is the strings length // - Then if it's greater than 2, then return an array with the string permutations // - With the string being passed, use split("") then reduce() to pass acc, letter and i for concat to run stringPermutations on that string, slice it and map through each value and letter and create the permutations of that string const stringPermutations = (str) => { if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str]; return str .split("") .reduce( (acc, letter, i) => acc.concat( stringPermutations(str.slice(0, i) + str.slice(i + 1)).map( (val) => letter + val ) ), [] ); }; // console.log(stringPermutations("abc")); // console.log(stringPermutations("tree")); // console.log(stringPermutations("ab")); // console.log(stringPermutations("a")); // 5. (* Check if a string contains only digits using Regex and prototype *) / String.prototype.isNumber = function () { return /^\d+$/.test(this); }; // console.log("123123".isNumber()); // Output: true // console.log("ABC123".isNumber()); // Output: false // 6. (* Check if two strings are anagrams of each other *) // function isAnagram(stringA, stringB) { // Remove any non-alphabet character using regex and convert the strings to lowercase stringA = stringA.replace(/[^\w]/g, "").toLowerCase(); stringB = stringB.replace(/[^\w]/g, "").toLowerCase(); // Get the character map of both strings const charMapA = getCharMap(stringA); const charMapB = getCharMap(stringB); // Next loop through each character in the charMapA, and check if it exists in charMapB and has the same value asin charMapA. If it does not, return false for (let char in charMapA) { if (charMapA[char] !== charMapB[char]) { return false; } } return true; } function getCharMap(string) { // Define an empty object that will hold the key - value pairs. let charMap = {}; //Loop through each character in the string. if the character already exists in the map, increase the value, otherwise add it to the map with a value of 1 for (let char of string) { charMap[char] = charMap[char] + 1 || 1; } return charMap; } // console.log(isAnagram("dog", "god")); // Output: true // console.log(isAnagram("silent", "listen")); // Output: true // console.log(isAnagram("true", "tteur")); // Output: false // 7. (* Find the position of a word in a given sentence *) // function findWord(sentence) { let num = 0; let message = ""; const arr = sentence.split(" "); for (let i = 0; i < arr.length; i++) { if (arr[i] === "Ferrari") { num = i + 1; break; } } message = num !== 0 ? `I found Ferrari at ${num}` : "I cant find Ferrari"; return message; } // console.log(findWord("There's a Ferrari")); // Output: I found Ferrari at 3 // console.log(findWord("There's a Lamborghini")); // Output: I cant find Ferrari // console.log(findWord("There's a convertible Ferrari")); // Output: I found Ferrari at 4 // 8. (* Write a function that creates an array of random, non-repeating numbers ordered randomly within a range of two stated numbers *) // function randomIntArrGenerator() { let keys = {}; while (Object.keys(keys).length < 10) { let num = Math.floor(Math.random() * (20 - 0) + 0); keys[num] = true; } let randomIntArr = Object.keys(keys).map((num) => parseInt(num)); let shuffledArr = randomIntArr.sort(() => Math.random() - 0.5); return shuffledArr; } // console.log(randomIntArrGenerator()); // Output: [ 18, 9, 19, 1, 13, 15, 2, 10, 5, 17 ] // 9. (* Write a function that returns the sum of two or more given numbers *) // const sumOfNumbers = (...numbers) => numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); // console.log(sumOfNumbers(1, 2, 3)); // Output: 6
import initialSize from '../initialContent/initialSize'; import initialDetailsInput from '../initialContent/initailDetailsInput'; const initialPizzaCreatorState = { selectedToppings: [], selectedSize: { sizeStyle: initialSize.sizeStyle, price: initialSize.price, }, detailsInput: initialDetailsInput, onSubmitClicked: false, }; export default initialPizzaCreatorState;
import express from 'express'; import dotenv from 'dotenv'; import db from './database/db.js'; import router from './api/api.js'; import bodyParser from 'body-parser'; import cors from 'cors'; const app = express(); dotenv.config(); const username = process.env.DB_USERNAME; const password = process.env.DB_PASSWORD; app.use(bodyParser.json({extended: true})); app.use(bodyParser.urlencoded({ extended: true })) app.use(cors()); app.use('/api',router); const URL = `mongodb+srv://niklo:niklo@cluster0.okd5s.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`; db(URL); app.listen(5000,() => { console.log('server is up and running on port 5000'); })
class Stopwatch extends React.Component { constructor(props) { super(props); this.state = { laps: [], text: '00:00:00', running: false, miliseconds: 0, seconds: 0, minutes: 0 }; this.start = this.start.bind(this); this.stop = this.stop.bind(this); this.reset = this.reset.bind(this); this.lap = this.lap.bind(this); } start() { if (!this.state.running) { this.setState({ running: true }); this.watch = setInterval(() => this.step(), 10); } } stop() { this.setState({ running: false }); clearInterval(this.watch); } step() { if (!this.state.running) return; this.calculate(); this.print(); } reset() { this.setState({ minutes: 0, seconds: 0, miliseconds: 0, text: '00:00:00', laps: [] }); } print() { this.setState({ text: this.format() }); } format() { return `${pad0(this.state.minutes)}:${pad0(this.state.seconds)}:${pad0(this.state.miliseconds)}`; } calculate() { this.state.miliseconds += 1; if (this.state.miliseconds >= 100) { this.state.seconds += 1; this.state.miliseconds = 0; } if (this.state.seconds >= 60) { this.state.minutes += 1; this.state.seconds = 0; } } lap() { if (this.state.running) { this.setState({ laps: this.state.laps.concat(this.state.text) }); } } render() { return React.createElement( 'div', { className: 'main' }, React.createElement( 'div', { className: 'stopwatch' }, this.state.text ), React.createElement( 'nav', null, React.createElement( 'button', { className: 'start', onClick: this.start }, 'start' ), React.createElement( 'button', { className: 'start', onClick: this.stop }, 'stop' ), React.createElement( 'button', { onClick: this.reset }, 'reset' ), React.createElement( 'button', { onClick: this.lap }, 'lap' ) ), React.createElement( 'ul', { className: 'results' }, this.state.laps.map(lapTime => React.createElement( 'li', null, lapTime )) ) ); } } function pad0(value) { let result = value.toString(); if (result.length < 2) { result = '0' + result; } return result; } var app = React.createElement(Stopwatch); ReactDOM.render(app, document.getElementById('app'));
'use strict' require('./setup')() const assert = require('assert') const helpers = require('./helpers') const state = require('../sample_game/state') describe('state', function() { before(helpers.boot) describe('collections', function() { it('should allow a user to view a collection', function*() { const ws = yield helpers.createAuthedSocket() yield helpers.request(ws, '/state/collection', { collection: 'users' }, res => assert.deepEqual(res.data, [])) }) it('should return an error for a collection that does not exist', function*() { const ws = yield helpers.createAuthedSocket() yield helpers.request(ws, '/state/collection', { collection: 'doesntexist' }, helpers.assertError('state/collectionNotFound')) }) it('should include advertised info for collections', function*() { const ws = yield helpers.createAuthedSocket() yield helpers.request(ws, '/state/advertised', { collection: 'users' }, res => assert.deepEqual(res.data.advertised, state.collections.users.advertised)) }) }) describe('modification', function() { const grantCurrencyChanges = [ { name: 'grantCurrency', params: { currency: 100, }, }, ] function setCurrencyRequest(currency) { return [ { name: 'setCurrency', params: { currency, }, }, ] } function buyItemRequest(itemName) { return [ { name: 'buyItem', params: { itemName, }, }, ] } function* modify(ws, options, tests) { const params = { collection: options.collection || 'users', id: options.id || 'ruan', changes: options.changes, } yield helpers.request(ws, '/state/modify', params, tests) } it('should allow a user to modify an instance with the correct privileges', function*() { const ws = yield helpers.createServerSocket() yield modify(ws, { changes: grantCurrencyChanges }, res => assert.strictEqual(res.data.instance.currency, 100)) yield modify(ws, { changes: grantCurrencyChanges }, res => assert.strictEqual(res.data.instance.currency, 200)) }) it('should persist changes across connections', function*() { const ws = yield helpers.createAuthedSocket() yield helpers.request(ws, '/state/instance', { collection: 'users', id: 'ruan' }, res => assert.strictEqual(res.data.instance.currency, 200)) }) it('should return an error for an instance that does not exist', function*() { const ws = yield helpers.createAuthedSocket() yield helpers.request(ws, '/state/instance', { collection: 'users', id: 'doesntexist' }, helpers.assertError('state/instanceNotFound')) }) it('should reject a request to modify an instance which triggers a game-defined error', function*() { const ws = yield helpers.createAuthedSocket() yield modify(ws, { changes: buyItemRequest('doesntexist') }, helpers.assertError('state/changeFailed')) yield modify(ws, { changes: setCurrencyRequest(0) }, res => assert.strictEqual(res.data.instance.currency, 0)) yield modify(ws, { changes: buyItemRequest('cheapItem') }, helpers.assertError('state/changeFailed')) }) it('should reject a request to modify an instance without the correct privileges', function*() { const ws = yield helpers.createAuthedSocket() yield modify(ws, { changes: grantCurrencyChanges }, helpers.assertError('state/changeDenied')) }) it('should reject a request to modify an instance without the correct ID-based privilege', function*() { const ws = yield helpers.createAuthedSocket() yield modify(ws, { changes: buyItemRequest('cheapItem'), id: 'notme' }, helpers.assertError('state/changeDenied')) }) it('should reject a request to modify an instance with a malformed change list', function*() { const ws = yield helpers.createAuthedSocket() function* invalidRequest(changes) { yield modify(ws, { changes }, helpers.assertError('core/messageParsingFailed')) } yield invalidRequest(1) yield invalidRequest('') yield invalidRequest({}) yield invalidRequest([ 1 ]) yield invalidRequest([ { name: undefined } ]) }) describe('cross-instance modification', function() { it('should allow a cross-instance modification request', function*() { const senderID = 'sender' const recipientID = 'recipient' const ws = yield helpers.createAuthedSocket(senderID) yield modify(ws, { id: senderID, changes: setCurrencyRequest(1000) }) const params = { name: 'transferCurrency', targets: { sender: senderID, recipient: recipientID, }, params: { amount: 400, }, } yield helpers.request(ws, '/state/transaction', params, res => { helpers.assertOk(res) assert.strictEqual(res.data.sender.currency, 600) assert.strictEqual(res.data.recipient.currency, 400) }) }) }) }) })
angular.module('shop2App') .controller("zxx_bm", ["$scope", "$http", "$state", function($scope, $http, $state) { //点击图片翻转 $scope.shangxia = true; $scope.zxx_sq = function() { $scope.zxx_ul = !$scope.zxx_ul; if($scope.shangxia) { $scope.shangxia = false; } else { $scope.shangxia = true; } } //获取服务器传送数据 $http({ url: "http://47.88.16.225:412/zhiwei", method: 'get' }).then(function(reqs) { $scope.zhicheng = reqs.data }, function() {}) //向服务器传送数据 弹窗 $scope.zxx_tjbm_zw = ""; $scope.zxx_tjbm_zwms = ""; $scope.zxx_sr = true; $scope.zxx_tjbm = function() { if($scope.zxx_tjbm_zw == "" || $scope.zxx_tjbm_zwms == "") { $scope.zxx_sr = false; } else { $http({ url: "http://47.88.16.225:412/zhiwei", method: 'post', data: { zhiwei: $scope.zxx_tjbm_zw, miaoshu: $scope.zxx_tjbm_zwms } }).then(function(reqs) { $state.go("guanli") }, function() {}) } } $scope.zxx_xs = function() { $scope.zxx_sr = true } $http({ url: "http://47.88.16.225:412/zhiwei", method: 'get' }).then(function(reqs) { $scope.zhicheng = reqs.data }, function() {}) $scope.zx_remove = function($index) { $http({ url: "http://47.88.16.225:412/zhiwei/" + $scope.zhicheng[$index].id, method: 'delete' }).then(function(reqs) { $scope.zhicheng.splice($index, 1) }, function() {}) } }]) // 公告 .controller("zxx_gg", ["$scope", "$http", "$state", "$timeout", function($scope, $http, $state, $timeout) { $scope.shangxia = true; $scope.zxx_sq = function() { $scope.zxx_ul = !$scope.zxx_ul; if($scope.shangxia) { $scope.shangxia = false; } else { $scope.shangxia = true; } } $http({ url: "http://47.88.16.225:412/gonggao", method: 'get' }).then(function(reqs) { $scope.products = reqs.data }, function() {}) $scope.zxx_tjgg_ms = ""; $scope.zxx_tjgg_nc = ""; $scope.zxx_sr = true; $scope.zxx_tjgg = function() { if($scope.zxx_tjgg_ms == "" || $scope.zxx_tjgg_nc == "") { $scope.zxx_sr = false } else { $http({ url: "http://47.88.16.225:412/gonggao", method: 'post', data: { biao: $scope.zxx_tjgg_nc, xiangqing: $scope.zxx_tjgg_ms, shijian: (new Date()).getTime() } }).then(function(reqs) { $state.go("gonggao") }, function() {}) } } $scope.zxx_xs = function() { $scope.zxx_sr = true } $http({ url: "http://47.88.16.225:412/gonggao", method: 'get' }).then(function(reqs) { $scope.products = reqs.data }, function() {}) $scope.products = []; $scope.zx_remove = function($index) { $http({ url: "http://47.88.16.225:412/gonggao/" + $scope.products[$index].id, method: 'delete' }).then(function(reqs) { $scope.products.splice($index, 1) }, function() {}) } $scope.zxx_zhuzhi = ""; $scope.zxx_phone = ""; $scope.zxx_name = ""; $scope.zxx_nr = ""; $scope.zxx_rs = true $scope.zxx_fw = function() { if($scope.zxx_zhuzhi == "" || $scope.zxx_phone == "" || $scope.zxx_name == "" || $scope.zxx_nr == "") { alert('请输入内容') } else { $http({ url: "http://47.88.16.225:412/zhuhu", method: 'post', data: { dizhi: $scope.zxx_zhuzhi, dianhua: $scope.zxx_phone, xingming: $scope.zxx_name, neirong: $scope.zxx_nr, shijian: (new Date()).getTime(), zt: "2" } }).then(function(reqs) { $scope.zxx_zhuzhi = ""; $scope.zxx_phone = ""; $scope.zxx_name = ""; $scope.zxx_nr = ""; $('.dl').css({"opacity":"1","top":"1rem"}); $('.row').html('已提交,请耐心等待服务人员'); $('.zhezao').css({"display":"block"}); setTimeout(function () { $(".dl").css({"opacity":"0"}); $('.row').html(''); $('.zhezao').css({"display":"none"}); },2000); }, function() {}) } } }])
import React, {Component} from 'react'; import ReactDOM from "react-dom"; import "./index.css"; import { Route, NavLink, BrowserRouter as Router, Switch } from "react-router-dom"; import App from "./App"; import Users from "./Dashboard/users"; import Contact from "./Dashboard/contact"; //import Login from "./Dashboard/login"; const arr=['Home','Users', 'Contact'] class Routing extends Component { constructor(props) { super(props); this.state={ name: 'Santhosh Reddy' } } render(){ return ( <Router> <div className= "App"> <ul className="ul_top_hypers"> {arr.map(item => <li className="col-xs-4"> <NavLink exact activeClassName="active" to={"/"+ item}> {item} </NavLink> </li> )} </ul> <hr /> <Route exact path="/Home" component={App} /> <Route path="/users" render= {()=> (<Users info= {this.state.name} />)}></Route> <Route path="/contact" component={Contact} /> {/* <Route path="/Login" component={Login} /> */} </div> </Router> ); } } ReactDOM.render(<Routing/>, document.getElementById("root"));
import React from 'react' import Navbar from '../components/Navbar' import ContactContent from '../components/ContactContent' import Background from '../components/Background' class ContactPage extends React.Component{ render(){ return( <div id="ContactPage"> <Background/> <Navbar/> <ContactContent/> </div> ) } } export default ContactPage
import React from 'react'; import { Link } from 'react-router-dom'; import { createPostLinkFromImmutable } from 'helpers/links' import { action as toggleMenu } from 'redux-burger-menu' import store from 'store' class LinkDescription extends React.Component { _handleCloseMenu() { const isOpen = false store.dispatch(toggleMenu(isOpen)); } render() { const { LinksInDay } = this.props return ( <div className="linkDescription"> {LinksInDay.map(link => { return ( <div className="postLink" key={link}> <Link to={createPostLinkFromImmutable(link)} onClick={this._handleCloseMenu}> <h5 className="postTitle">{link.get('title')}</h5> </Link> </div> ) })} </div> ) } } export default LinkDescription
module.exports = { //1. 请求检验忽略路径 uncheckPaths:['/bus/v1.0/user/signIn','/bus/v1.0/user/signUp'], //1. 是否开启鉴权 ifNeedAuth:true, }
/** * Book list controller */ bookApp.controller('BookListCtrl', function ($scope, $sce, BookHttp) { //secure books api url var mybaseurl = $sce.trustAsResourceUrl("https://www.googleapis.com/books/v1/volumes"); //when the user click on the search button this function will be called $scope.doSearch = function () { BookHttp.get(mybaseurl, $scope.searchTerm).then(function success(response) { $scope.bookResults = response.data.items; $scope.orderProp = 'volumeInfo.title'; console.log(response.data.items); }, function error(response) { // called asynchronously if an error occurs }); } }); /** * Book details controller */ bookApp.controller('BookDetailsCtrl', function ($scope, $sce, BookHttpOneItem) { //$scope.$on('$routeChangeSuccess', function () { $scope.init = function() { var id = window.location.hash.substr(1); mybaseurl = $sce.trustAsResourceUrl("https://www.googleapis.com/books/v1/volumes/" + id); BookHttpOneItem.get(mybaseurl).then(function success(response) { $scope.bookOneItem = response.data; }, function error(response) { // called asynchronously if an error occurs }); }; }); /** * Cart controller */ bookApp.controller('cartCtrl', function ($scope) { /** * Add to cart * @param item */ $scope.setCart = function (item) { console.log(item); //we have something in cart var cart = JSON.parse(localStorage.getItem('cart')); if (!cart) { cart = []; } //if we already have an item var index = cart.findIndex(function (cartItem) { return cartItem.id === item.id; }); //update the quantity if (index !== -1) { cart[index].qty += 1; } else { cart.push({ id: item.id, name: item.volumeInfo.title, image: item.volumeInfo.imageLinks.smallThumbnail, price: item.saleInfo.listPrice.amount +' '+ item.saleInfo.listPrice.currencyCode, qty: 1 }); }; localStorage.setItem('cart', JSON.stringify(cart)); }; /** * remove all items from cart */ $scope.removeAllFromCart = function(){ localStorage.removeItem('cart'); $('.modal-body').fadeOut(500, function(){ $('#pop').modal('hide'); $(this).fadeIn(500); }); } $scope.$watch(function () { if(localStorage.cart != undefined) { return JSON.parse(localStorage.cart).length; } }, function (newVal, oldVal) { if (oldVal !== newVal && newVal === undefined) { console.log('It is undefined, probably localStorage is empty.'); } }); }); //modal and get cart items bookApp.controller('myModalCtrl', function ($scope) { $scope.modalHide = function(elem){ $(elem).modal('hide'); $('body').removeClass('modal-open'); $('.modal-backdrop').remove(); } $scope.showModal = function (elem) { $scope.cartItems = JSON.parse(localStorage.getItem('cart')); $(elem).modal("show"); } $scope.itemInCart = function(){ if(localStorage.cart){ var qty = 0; $.each(JSON.parse(localStorage.getItem('cart')), function (k, v) { qty += parseInt(v.qty); }); return qty; } else{ return 0; } } if(localStorage.cart){ $scope.$watch(function () { var qty = 0; $.each(JSON.parse(localStorage.getItem('cart')), function (k, v) { qty += parseInt(v.qty); }); return qty; },function(newVal,oldVal){ if(oldVal!==newVal && newVal === undefined){ console.log('It is undefined'); } }); } });
import 'babel-polyfill'; import jsonpointer from 'jsonpointer'; const BAD_OPEN_PATTERN = new RegExp('\\{{3,}'); const BAD_CLOSE_PATTERN = new RegExp('\\}{3,}'); const GROUP_PATTERN = new RegExp('{{([^{^}]*)}}'); const OPEN_PATTERN = new RegExp('{{'); const CLOSE_PATTERN = new RegExp('}}'); /** * Returns key, value, parent triplets for all nested string values. * * @param {Object|Array} obj The object to generate values for. * @returns {Generator} A generator object to iterate over. */ export function* stringValueGenerator(obj) { if (Array.isArray(obj)) { for (let index = 0; index < obj.length; index++) { const value = obj[index]; if (typeof value === 'string') { yield [index, value, obj]; } if (typeof value === 'object') { yield* stringValueGenerator(value); } } } else if (typeof obj === 'object') { const keys = Object.keys(obj); for (let index = 0; index < keys.length; index++) { const key = keys[index]; const value = obj[key]; if (typeof value === 'string') { yield [key, value, obj]; } if (typeof value === 'object') { yield* stringValueGenerator(value); } } } } /** * Search string for embedded json pointers and return information on them. * * @param {String} string A value from the document that may have refs. * @returns {Object[]} Each has the form {pointer: {String}, indices: {Array}}. */ export function getReferences(string) { if (BAD_OPEN_PATTERN.test(string)) { throw new Error(`Syntax Error in ${string}.`) } if (BAD_CLOSE_PATTERN.test(string)) { throw new Error(`Syntax Error in ${string}.`) } const references = []; let searchIndex = 0; while (true) { const subString = string.slice(searchIndex); const test = GROUP_PATTERN.test(subString); if (!test) { if (OPEN_PATTERN.test(subString) || CLOSE_PATTERN.test(subString)) { throw new Error(`Syntax Error in ${string}.`); } break; } const search = subString.search(GROUP_PATTERN); const match = subString.match(GROUP_PATTERN); const start = searchIndex + search; const end = searchIndex + search + match[0].length; searchIndex = end; references.push({pointer: match[1], indices: [start, end]}); } return references; } /** * Resolve a string value using the given document as context. * * @param {String} string The string to resolve pointers inside of. * @param {Object|Array} document A loaded json document. * @param {Number} maxRecursion Prevents cyclic references. Increase if needed. * @returns {String} The resolved string. */ export function resolveString(string, document, maxRecursion = 100) { let recursions = 0; while (true) { if (recursions > maxRecursion) { throw new Error('Max Recursion'); } recursions += 1; const references = getReferences(string); if (!references.length) { break; } let offset = 0; for (let i = 0; i < references.length; i++) { const {pointer, indices} = references[i]; const [start, stop] = indices; const value = jsonpointer.get(document, pointer); if (typeof value !== 'string') { throw new Error('Variables must be strings.'); } string = string.slice(0, offset + start) + value + string.slice(offset + stop); offset += value.length - (stop - start); } } return string; } /** * Set pointers to equal their resolved values inside a loaded json document. * * @param {Object|Array} document A loaded json document. * @param {Boolean} inplace If false, set values in a *copy* of the document. * @param {Number} maxRecursion Prevents cyclic references. Increase if needed. * @returns {Object|Array} A dereferenced document (may be a copy). */ export default function dereference(document, inplace = true, maxRecursion = 100) { if (!inplace) { document = JSON.parse(JSON.stringify(document)); } for (let item of stringValueGenerator(document)) { const [key, value, parent] = item; parent[key] = resolveString(value, document, maxRecursion); } return document; }
let sendGrid = require('./email'); let Cache = require('./cache'); let clap = async ({body, command, ack, client, context}) => { await ack(); console.log('command: clapping') //console.log(body) let text = command.text; let text_2 = text.split(" "); let output = "" text_2.forEach(word => { output += word + ":clap:"; }) //console.log(context) // let userInfo = await client.users.info({ // token: context.botToken, // user: command.user_id // }) let userInfo = await Cache.user.fetch(command.user_id); //console.log(userInfo) let displayName = userInfo.user.profile.display_name || userInfo.user.profile.real_name //console.log(displayName) // console.log('userinfo') // console.log(userInfo) await client.chat.postMessage({ token: context.botToken, channel: command.channel_id, text: output, username: displayName }) } let save = async ({body, command, ack, client, context}) => { console.log('command: save') await ack(); let msg = { to: 'brian.c3po@gmail.com', // Change to your recipient from: 'brian.c3po@gmail.com', // Change to your verified sender subject: 'Sending with SendGrid is Fun', text: 'and easy to do anywhere, even with Node.js', html: '<strong>and easy to do anywhere, even with Node.js</strong>', } // console.log(body) // let userInfo = await client.users.info({ // token: context.botToken, // user: command.user_id // }) let userInfo = await Cache.user.fetch(command.user_id); let email = userInfo.user.profile.email; let channelId = command.channel_id; let channelHistory = await client.conversations.history({ token: context.botToken, channel: channelId }) let text = ""; let html = ""; if(channelHistory.ok){ let messages = channelHistory.messages; await messages.forEach(async message => { //console.log(message) if(message.user){ let myUser = await Cache.user.fetch(message.user) //console.log(myUser) text += `\n ${myUser.user.name} - ${message.text}` html += `<div> ${myUser.user.name} - ${message.text} </div>` } }) } // console.log("html:") // console.log(html) msg.subject = `archive of ${channelId}` msg.to = email; msg.text = text; msg.html = html; sendGrid .send(msg) .then(() => { console.log('Email sent') }) .catch((error) => { console.error(error) }) } module.exports = { clap, save }
var mongoose = require('mongoose'); var Loc = mongoose.model('Dish'); var sendJSONresponse = function(res, status, content) { res.status(status); res.json(content); }; var theEarth = (function() { var earthRadius = 6371; // km, miles is 3959 var getDistanceFromRads = function(rads) { return parseFloat(rads * earthRadius); }; var getRadsFromDistance = function(distance) { return parseFloat(distance / earthRadius); }; return { getDistanceFromRads: getDistanceFromRads, getRadsFromDistance: getRadsFromDistance }; })(); /* GET list of dishes */ module.exports.dishesListByDistance = function(req, res) { var lng = parseFloat(req.query.lng); var lat = parseFloat(req.query.lat); var maxDistance = parseFloat(req.query.maxDistance); var point = { type: "Point", coordinates: [lng, lat] }; var geoOptions = { spherical: true, maxDistance: theEarth.getRadsFromDistance(maxDistance), num: 10 }; if ((!lng && lng!==0) || (!lat && lat!==0) || ! maxDistance) { console.log('dishesListByDistance missing params'); sendJSONresponse(res, 404, { "message": "lng, lat and maxDistance query parameters are all required" }); return; } Loc.geoNear(point, geoOptions, function(err, results, stats) { var dishes; console.log('Geo Results', results); console.log('Geo stats', stats); if (err) { console.log('geoNear error:', err); sendJSONresponse(res, 404, err); } else { dishes = buildDishList(req, res, results, stats); sendJSONresponse(res, 200, dishes); } }); }; var buildDishList = function(req, res, results, stats) { var dishes = []; results.forEach(function(doc) { dishes.push({ distance: theEarth.getDistanceFromRads(doc.dis), name: doc.obj.name, address: doc.obj.address, rating: doc.obj.rating, tags: doc.obj.tags, _id: doc.obj._id }); }); return dishes; }; /* GET a dish by the id */ module.exports.dishesReadOne = function(req, res) { console.log('Finding dish details', req.params); if (req.params && req.params.dishid) { Loc .findById(req.params.dishid) .exec(function(err, dish) { if (!dish) { sendJSONresponse(res, 404, { "message": "dishid not found" }); return; } else if (err) { console.log(err); sendJSONresponse(res, 404, err); return; } console.log(dish); sendJSONresponse(res, 200, dish); }); } else { console.log('No dishid specified'); sendJSONresponse(res, 404, { "message": "No dishid in request" }); } }; /* POST a new dish */ /* /api/dishes */ module.exports.dishesCreate = function(req, res) { console.log(req.body); Loc.create({ name: req.body.name, address: req.body.address, tags: req.body.tags.split(","), coords: [parseFloat(req.body.lng), parseFloat(req.body.lat)], openingTimes: [{ days: req.body.days1, opening: req.body.opening1, closing: req.body.closing1, closed: req.body.closed1, }, { days: req.body.days2, opening: req.body.opening2, closing: req.body.closing2, closed: req.body.closed2, }] }, function(err, dish) { if (err) { console.log(err); sendJSONresponse(res, 400, err); } else { console.log(dish); sendJSONresponse(res, 201, dish); } }); }; /* PUT /api/dishes/:dishid */ module.exports.dishesUpdateOne = function(req, res) { if (!req.params.dishid) { sendJSONresponse(res, 404, { "message": "Not found, dishid is required" }); return; } Loc .findById(req.params.dishid) .select('-comments -rating') .exec( function(err, dish) { if (!dish) { sendJSONresponse(res, 404, { "message": "dishid not found" }); return; } else if (err) { sendJSONresponse(res, 400, err); return; } dish.name = req.body.name; dish.zipcode = req.body.address; dish.tags = req.body.tags.split(","); dish.coords = [parseFloat(req.body.lng), parseFloat(req.body.lat)]; dish.openingTimes = [{ days: req.body.days1, opening: req.body.opening1, closing: req.body.closing1, closed: req.body.closed1, }, { days: req.body.days2, opening: req.body.opening2, closing: req.body.closing2, closed: req.body.closed2, }]; dish.save(function(err, dish) { if (err) { sendJSONresponse(res, 404, err); } else { sendJSONresponse(res, 200, dish); } }); } ); }; /* DELETE /api/dishes/:dishid */ module.exports.dishesDeleteOne = function(req, res) { var dishid = req.params.dishid; if (dishid) { Loc .findByIdAndRemove(dishid) .exec( function(err, dish) { if (err) { console.log(err); sendJSONresponse(res, 404, err); return; } console.log("Dish id " + dishid + " deleted"); sendJSONresponse(res, 204, null); } ); } else { sendJSONresponse(res, 404, { "message": "No dishid" }); } };
const _ = require('lodash') // thanks! https://gist.github.com/ralphcrisostomo/3141412 function removeDuplicates(original) { var compressed = []; // make a copy of the input array var copy = original.slice(0); // first loop goes over every element for (var i = 0; i < original.length; i++) { var myCount = -1; // loop over every element in the copy and see if it's the same for (var w = 0; w < copy.length; w++) { if (_.isEqual(original[i], copy[w])) { // increase amount of times duplicate is found myCount++; // sets item to undefined delete copy[w]; } } if (myCount > -1) { var a = new Object(); a.value = original[i]; a.count = myCount; compressed.push(a); } } return compressed; }; function getBest(results) { let nouns = [], adverbs = [], verbs = [], adjectives = [] for (var i of results) { nouns = nouns.concat(i.nouns) adverbs = adverbs.concat(i.adverbs) verbs = verbs.concat(i.verbs) adjectives = adjectives.concat(i.adjectives) } return { nouns: _.uniqBy(_.orderBy(nouns, 'tf', 'desc'), 'term').slice(0, 20), adverbs: _.uniqBy(_.orderBy(adverbs, 'tf', 'desc'), 'term').slice(0, 20), verbs: _.uniqBy(_.orderBy(verbs, 'tf', 'desc'), 'term').slice(0, 20), adjectives: _.uniqBy(_.orderBy(adjectives, 'tf', 'desc'), 'term').slice(0, 20), } } function mergeSimilarObjects(results, property) { let cleanResults = []; for (let week of results) { cleanResults = week[property].reduce((acc, cur) => { let val = _.find(acc, ['term', cur.term]) if (!val) // if not yet found acc.push(cur) else { // update value in master array let idx = _.findIndex(acc, { term: cur.term }) acc.splice(idx, 1, { term: cur.term, tf: cur.tf + val.tf }); } return acc }, cleanResults) } // w/ each week of tweets go through mentions and summate return arrayOfObjToArrayOfArray(_.orderBy(cleanResults, 'tf', 'desc')) } function arrayOfObjToArrayOfArray(objArray) { return objArray.map(Object.values) } exports.getBest = getBest exports.removeDuplicates = removeDuplicates exports.mergeSimilarObjects = mergeSimilarObjects exports.arrayOfObjToArrayOfArray = arrayOfObjToArrayOfArray
window.alert ("Hi there!"); //pop up window with "hi there" window.alert("Ready or not! Here I come!"); //pop up window statment "ready or not" var A= ' this is a string'; //defines variable "A" a string var A = A.fontcolor("red"); document.write(A) document.write(A); //announces "A" value window.alert ("The saying goes\"There are plenty of fish in the sea\" and we believe that to be true. If it "+ " was false, we would have been alone.") //used '\' to separate the quotations so the program doesnt think it is a function var B=" plenty" + "fish" //added two variables and created id document.write(B) var family= " Robinsons", Mom=" Sue", Dad = " Drew", Son = " Charlie"; document.write (Son); //assigned id to family element var family= family.fontcolor("green"); //assigned family element font color document.write(family); //processed funtion and returned results function My_First_Function() { //Defining a function and naming it var str="This text is green!"; //defied variable and gave it string value var result = str.fontcolor("green"); // used the fontcolor method on str var document.getElementById("Green_Text").innerHTML = result; //put the value result into HTML element with "green text" id }
import apisauce from "apisauce"; import { Config } from "@app/api"; const get = (baseURL = Config.baseUrl) => { const api = apisauce.create({ baseURL }); const user = (token) => api.get(`/getUser`, {}, { headers: { "Authorization": `Bearer ${token}` } }); const logout = (token) => api.get(`/logout`, {}, { headers: { "Authorization": `Bearer ${token}` } }); const campaign = (token) => api.get(`/campaign`, {}, { headers: { "Authorization": `Bearer ${token}` } }); const campaignCurrent = (token) => api.get(`/campaign/getCurrent`, {}, { headers: { "Authorization": `Bearer ${token}` } }); const campaignCategory = (token, category) => api.get(`/campaign/getCategory/${category}`, {}, { headers: { "Authorization": `Bearer ${token}` } }); const campaignDetail = (token, id) => api.get(`/campaign/getDetail/${id}`, {}, { headers: { "Authorization": `Bearer ${token}` } }); const history = (token) => api.get(`/donasi/getHistory`, {}, { headers: { "Authorization": `Bearer ${token}` } }); const detailHistory = (token, id) => api.get(`/donasi/getHistoryDetail/${id}`, {}, { headers: { "Authorization": `Bearer ${token}` } }); return { user, logout, campaign, campaignCurrent, campaignCategory, campaignDetail, history, detailHistory } } const post = (baseURL = Config.baseUrl) => { const api = apisauce.create({ baseURL }); const login = (email, password) => api.post(`/loginAsDonatur`, { email: email, password: password }); const register = (name, email, password) => api.post(`/register`, { name: name, email: email, password: password, role_id: 3 }); const changePassword = (token, oldPassword, password) => api.post(`/changePassword`, { oldPassword: oldPassword, password: password }, { headers: { "Authorization": `Bearer ${token}` } }); const updateProfile = (token, name, email, file) => api.post(`/updateProfile`, { name: name, email: email, file: file }, { headers: { "Authorization": `Bearer ${token}` } }); const donasi = (token, id, location, long, lat, anonim, items) => api.post(`/donasi`, { id: id, location: location, long: long, lat: lat, anonim: anonim, items: items }, { headers: { "Authorization": `Bearer ${token}` } }); return { login, register, changePassword, updateProfile, donasi } } const github = (baseURL = "https://raw.githubusercontent.com/setakarim/kitapunya-mobile/master") => { const api = apisauce.create({ baseURL }); const readme = () => api.get(`/readme.md`); return { readme } } export default { get, post, github }
import Model from './Model'; class BranchDefinition extends Model { url() { return `${window.config.apiRoot}/branch/lookup?host=${this.options.host}&organization=${this.options.org}&repository=${this.options.repo}&branch=${this.options.branch}`; } } export default BranchDefinition;
import VueRouter from 'vue-router'; import Vue from 'vue'; import App from './App'; import store from './store'; import AddressList from './components/AddressList'; import EditAddress from './components/EditAddress'; import NewAddress from './components/NewAddress'; import Vuelidate from "vuelidate"; Vue.use(VueRouter); Vue.use(Vuelidate); export const router = new VueRouter({ //use browser router mode rather than hashrouter mode: 'history', routes: [ { path: '/', name: 'home', component: AddressList }, { path: '/edit/:id', name: 'editAddress', component: EditAddress }, { path: '/new', name: 'newAddress', component: NewAddress } ] }); new Vue({ el: '#app', router, store, render: h => h(App) });
/* *各项目公用文件 * */ console.log('common.js ') //不可删除,空文件不能读取
import Container from "../container"; import Card from "../card"; export default function PostContent({htmlContent}){ return( <div className="relative"> <Container> <div className="w-full md:w-10/12"> <Card> <div className="p-8 unreset" dangerouslySetInnerHTML={{ __html: htmlContent }} /> </Card> </div> </Container> </div> ) }
class WorldDrawer { COLOURS = { land: '#c17e00', stone: '#4e4431', grass: '#00ac17', grazer: '#275fe2', predator: '#9014c1', } constructor(data) { this.data = data; this.pointHeight = 10; this.pointWidth = 10; this.canvas = document.getElementById('world'); } draw() { this.data.forEach((line, x) => { line.forEach((point, y) => { this.drawPoint(x, y, point); }); }); } drawPoint(x, y, point) { if(point.entities.length == 0) { this.drawRect(x, y, point.landscape, 1); } else { let entities = point.entities const importantEntites = point.entities.filter(e => e.type != 'grass'); if(importantEntites.length > 0) { entities = importantEntites; } let fullnest = entities.length; entities.forEach(entity => { this.drawRect(x, y, entity.type, 1.0 / fullnest); }) } } drawRect(x, y, colour, globalAlpha) { let color = this.COLOURS[colour]; let context = this.canvas.getContext('2d'); context.beginPath(); context.strokeStyle = color; context.fillStyle = color; context.globalAlpha = globalAlpha; context.rect(x * this.pointWidth, y * this.pointHeight, this.pointWidth, this.pointHeight); context.fill(); } } App.cable.subscriptions.create("WorldUpdaterChannel", { received: function(data) { const worldData = JSON.parse(data['world']); if(worldUuid && data['world_id'] == worldUuid) { const drawer = new WorldDrawer(worldData['ground']); drawer.draw(); } } });
// For Player 1: var randomNumber1 = Math.floor(Math.random() * 6) + 1; // Generates a random number between 1-6. var ImageSource1 = "images/dice" + randomNumber1 + ".png"; //images/dice1.png - images/dice6.png. document.querySelectorAll("img")[0].setAttribute("src", ImageSource1); // Changing the image acc to the number generated. // For Player 2: var randomNumber2 = Math.floor(Math.random() * 6) + 1; // Generates a number between 1-6. var ImageSource2 = "images/dice" + randomNumber2 + ".png"; //images/dice1.png - images/dice6.png. document.querySelectorAll("img")[1].setAttribute("src", ImageSource2); // Changing the image acc to the number generated. // Deciding who wins: if (randomNumber1 > randomNumber2) { document.querySelector("h1").innerHTML = "Player 1 Wins!"; } else if (randomNumber2 > randomNumber1) { document.querySelector("h1").innerHTML = "Player 2 Wins!"; } else { document.querySelector("h1").innerHTML = "It's a Draw. Refresh again!"; }
/* * @lc app=leetcode id=802 lang=javascript * * [802] Find Eventual Safe States */ // @lc code=start /** * @param {number[][]} graph * @return {number[]} */ var eventualSafeNodes = function (graph) { const N = graph.length; const colors = new Array(N).fill(0); function isSafe(i) { if (colors[i] !== 0) { return colors[i] === 2; } colors[i] = 1; for (const next of graph[i]) { if (!isSafe(next)) { return false; } } colors[i] = 2; return true; } const results = []; for (let i = 0; i < N; i++) { if (isSafe(i)) { results.push(i); } } return results; }; // @lc code=end eventualSafeNodes([[0], [2, 3, 4], [3, 4], [0, 4], []]);
import React, { Component } from 'react'; import styles from './Offering.module.css'; import Container from '../../Container/Container'; import OfferingCard from './OfferingCard/OfferingCard'; import video from './video.png'; import PlayButton from './PlayButton/PlayButton'; class Offering extends Component { render() { return ( <div className={styles.offeringWrapper}> <Container> <div className={styles.offering}> <div className={styles.textContent}> <div className={styles.title}> Grow up your business with maketica maketing landing page </div> <div className={styles.offeringCardWrapper}> <OfferingCard title="Increase your visitors" subtitle="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam." /> <div className={styles.offeringCardWrapperLastItem}> <OfferingCard title="Start social media campaign" subtitle="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam." /> </div> </div> </div> <div className={styles.mediaContent}> <img className={styles.video} src={video} alt="Video" /> <div className={styles.playWrapper}> <PlayButton /> </div> </div> </div> </Container> </div> ); } } export default Offering;
angular.module('app') .controller('FooterController', function() { const vm = this; var date = new Date(); vm.year = date.getFullYear(); });
import axios from "axios"; import React, { useState } from "react"; import { useHistory } from "react-router"; import { link } from "../../../Proxy/proxy"; import SendMail from "./SendMail"; import ShowFeedbacks from "./ShowFeedbacks"; function WaterList(props) { const { city, location, userId, feedback, waterDesc, waterPressure, wid, duration, } = props.info; const [edit, setEdit] = useState(true); const [area, setArea] = useState(location); const [city_a, setCity] = useState(city); const [duration_a, setDuration] = useState(duration); const [pressure, setPressure] = useState(waterPressure); const [desc, setDesc] = useState(waterDesc); const [message, setMessage] = useState(""); const [showFeedbacks, setShowFeedbacks] = useState(false); const [isDeleted, setIsDeleted] = useState(false); const [showEmailPanel, setShowEmailPanel] = useState(false); const [showMessage, setShowMessage] = useState(false); const history = useHistory(); const handleSubmit = (e) => { e.preventDefault(); setEdit(true); // console.log(water); const update = async () => { const url = `${link}admin/${wid}`; await axios .put( url, { waterPressure: pressure, waterDesc: desc, location: area, city: city_a, duration: duration_a, }, { headers: { Authorization: `Bearer ${localStorage.getItem("token")}`, }, } ) .then((res) => { setShowMessage(true); setMessage(res.data.message); }) .catch((err) => { localStorage.removeItem("token"); alert("Session Timed Out! Login Again."); history.push("/login"); }); }; update(); }; const deleteInfo = () => { const delInfo = async () => { const url = `${link}admin/${wid}`; await axios .delete(url, { headers: { Authorization: `Bearer ${localStorage.getItem("token")}`, }, }) .then((res) => { setIsDeleted(true); setMessage(res.data.message); }) .catch((err) => { localStorage.removeItem("token"); alert("Session Timed Out! Login Again."); history.push("/login"); }); }; delInfo(); }; return ( <div> {showMessage && ( <div className="alert alert-primary" role="alert"> {message} </div> )} <div className="container mt-2"> {!isDeleted ? ( <div> <div className="alert alert-success" role="alert"> <p className="mb-0">Added By</p> <h4 className="alert-heading"> {userId.firstName} {userId.lastName} </h4> <p className="mb-0">Mobile Number</p> <h4>{userId.mobileNumber}</h4> <p className="mb-0">Email</p> <h4>{userId.email}</h4> <hr></hr> {wid} </div> <form onSubmit={handleSubmit}> <div> <h3>City</h3> <input value={city_a} disabled={edit} onChange={(e) => setCity(e.target.value)} maxLength="30" type="text" required className="form-control" ></input> </div> <h3> Location <input value={area} disabled={edit} onChange={(e) => setArea(e.target.value)} maxLength="100" type="text" required className="form-control" ></input> </h3> <h3> Pressure <input value={pressure} disabled={edit} onChange={(e) => setPressure(e.target.value)} min="0" max="100" type="number" required className="form-control" ></input> </h3> <h3> Description <input value={desc} disabled={edit} onChange={(e) => setDesc(e.target.value)} maxLength="200" required className="form-control" ></input> </h3> <h3> Duration <input value={duration_a} disabled={edit} onChange={(e) => setDuration(e.target.value)} type="number" min="0" max="300" required className="form-control" ></input> </h3> <div className="row"> <button type="submit" className="btn btn-primary my-3"> Update </button> {edit && ( <button onClick={() => setEdit(false)} className="btn btn-primary my-3" > Edit </button> )} </div> <br /> </form> <div className="row"> <button onClick={() => setShowFeedbacks(!showFeedbacks)} className="btn btn-primary my-3" > View FeedBacks </button> {showFeedbacks && ( <div> {feedback.map((feed, index) => { return ( <div key={index}> <ShowFeedbacks feed={feed} /> </div> ); })} </div> )} {showFeedbacks && feedback.length === 0 ? ( <div className="alert alert-warning" role="alert"> <h2 className="alert-heading">No FeedBack!</h2> </div> ) : null} <button onClick={deleteInfo} className="btn btn-primary my-3"> Delete Info </button> </div> </div> ) : null} <button onClick={() => setShowEmailPanel(!showEmailPanel)} className="btn btn-primary my-3" > Send Mail </button> {showEmailPanel && <SendMail to={userId.email} />} <hr /> </div> </div> ); } export default WaterList;
// 1.getArraysEqualElementsCount, которая принимает два аргумента - массивы, и возвращает количество одинаковых элементов function getArraysEqualElementsCount(arr1, arr2) { let length1 = arr1.length; let result = 0; for (let i = 0; i < length1; i++) { if (arr1[i] === arr2[i]) { result++; } } console.log(result) } getArraysEqualElementsCount([5, 6, 7 ,8], [5, 6, 7, 8]); // 2.getArraysNotEqualElementsCount, которая принимает два аргумента - массивы, и возвращает количество элементов, //у которых нет пары function getArraysNotEqualElementsCount(arr1, arr2) { let length1 = arr1.length; let result = 0; for (let i = 0; i < length1; i++) { if (arr1[i] !== arr2[i]) { result++; } } console.log(result) } getArraysNotEqualElementsCount([5, 6, 7, 8], [5, 6, 7, 8]); // 3.getArraysEqualElementsCountHard, которая принимает два аргумента - массивы, и возвращает количество одинаковых элементов //но теперь элементы массива могут идти не подряд, а как попало, но функция должна работать правильно ( написать цикл в цикле) function getArraysEqualElementsCountHard(arr1, arr2) { let count = 0; for (let i = 0; i < arr1.length; i++) { for(let k = 0; k < arr2.length; k++) { if (arr1[i] === arr2[k]) { delete arr1[i]; delete arr2[k]; console.log(arr1, arr2) count++; break; } } } return count; } console.log(getArraysEqualElementsCountHard([1, 2, 3, 'e', 'e', 'd', 'e', 'e', 'd'], ['a', 'b', 'c', 'd', 'e'])); // 4.getArrayElementsInARowAmount, которая возвращает количество раз, когда встретились два одинаковых элемента подряд. function getArrayElementsInARowAmount(arr) { let count = 0; for (let i = 1; i < arr.length; i++) { if (arr[i] === arr[i - 1]) { count++; } } return count; } console.log(getArrayElementsInARowAmount([1, 2, 1, 2])) // 5.getArrayElementByType, которая принимает 2 параметра - массив и строку, строка указывает тип элементов, которые должны //остаться в массиве function getArrayElementByType(arr, str) { let newArr = []; for (let i = 0; i < arr.length; i++) { if (typeof(arr[i]) === str) { newArr.push(arr[i]); } } return newArr; } console.log(getArrayElementByType([1, 'asd', 2, true, false, true, 3], 'boolean')) console.log(getArrayElementByType([1, 'asd', 2, true, false, true, 3], 'string')) console.log(getArrayElementByType([1, 'asd', 2, true, false, true, 3], 'number'))
import React from 'react'; import {connect} from 'react-redux'; import {addToCart, updateCartItem, deleteCartItem} from '../redux/actions/cartActions'; import styled from "styled-components"; import Link from 'next/link' import { IconButton } from './buttons' import { Table, THead, TBody, TFoot, Tr, Td, NumberColumn, DescriptionColumn, ImageColumn } from './table' import Price from './price' import {DeleteIcon} from './icons' import styles from './cartTable.module.scss' import utilStyles from '../styles/utils.module.scss' const StyledPrice = styled(Price)` && { color: #999; } `; class CartTable extends React.Component { constructor(props) { super(props); } updateProductQuantity(data) { this.props.updateCartItem(data.product_id, Number(data.quantity)) } render() { const products = this.props.order ? this.props.order.products : this.props.products; const subtotal = this.props.order ? this.props.order.subtotal : this.props.subtotal; const shippingFee = this.props.order ? this.props.order.shipping_fee : this.props.shippingFee; return ( <Table> <THead> <Tr> <Td colSpan='6'> <h2 className={`${utilStyles.headingMd} ${utilStyles.colorPrimary700}`}>{ this.props.cart ? 'Shopping cart' : 'Your order' }</h2> </Td> </Tr> </THead> <TBody> {products.map(product => ( <Tr key={product.product_id}> { this.props.editable && <Td width="1%"> <IconButton type="button" onClick={() => this.props.deleteCartItem(product.product_id) }> <DeleteIcon /> </IconButton> </Td> } <ImageColumn width="10%"> <Link href="/products/[id]" as={`/products/${product.product_id}`}> <a className={styles.thumb}> <img className={styles.tumbImage} src={product.photo_url} alt={product.name} /> </a> </Link> </ImageColumn> <DescriptionColumn> <Link href="/products/[id]" as={`/products/${product.product_id}`}> <a> <h3 className={`${utilStyles.headingMd} ${utilStyles.colorPrimary500}`}>{product.name}</h3> </a> </Link> <p className={`${utilStyles.lightText} ${utilStyles.caption}`}>{product.description}</p> </DescriptionColumn> <NumberColumn> <StyledPrice price={product.price} /> </NumberColumn> <NumberColumn width="10%"> { this.props.editable ? <input type="number" defaultValue={product.quantity} className={styles.productQuantity} onKeyUp={(e) => this.updateProductQuantity({ product_id: product.product_id, quantity: e.target.value })} /> : <span className={utilStyles.body}>{product.quantity}</span> } </NumberColumn> <NumberColumn> <Price price={product.price} quantity={product.quantity} /> </NumberColumn> </Tr> ))} </TBody> <TFoot> <Tr> <NumberColumn colSpan={this.props.editable ? 5 : 4}> <p className={`${utilStyles.headingMd} ${utilStyles.colorPrimary700}`}>Cart total</p> </NumberColumn> <NumberColumn colSpan='1'> <Price price={subtotal} /> </NumberColumn> </Tr> { !this.props.editable && <React.Fragment> <Tr> <NumberColumn colSpan={4}> <p className={`${utilStyles.headingMd} ${utilStyles.colorPrimary700}`}>Shipping fee</p> </NumberColumn> <NumberColumn colSpan='1'> <Price price={shippingFee} /> </NumberColumn> </Tr> <Tr> <NumberColumn colSpan={4}> <p className={`${utilStyles.headingMd} ${utilStyles.colorPrimary700}`}>Total</p> </NumberColumn> <NumberColumn colSpan='1'> <Price price={ shippingFee + subtotal } /> </NumberColumn> </Tr> </React.Fragment> } </TFoot> </Table> ); } } const mapStateToProps = state => ({ subtotal: state.cart.items.reduce((total, item) => (total + item.price * item.quantity), 0) }); const mapDispatchToProps= (dispatch) => { return { addToCart: (id) => { dispatch(addToCart(id)) }, updateCartItem: (id, quantity) => { dispatch(updateCartItem(id, quantity)) }, deleteCartItem: (id) => { dispatch(deleteCartItem(id)) } } } export default connect(mapStateToProps, mapDispatchToProps)(CartTable);
const { Client, Intents, Collection } = require('discord.js'); const bot = new Client({ intents: [ Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_PRESENCES, Intents.FLAGS.GUILD_INTEGRATIONS, Intents.FLAGS.DIRECT_MESSAGES, Intents.FLAGS.DIRECT_MESSAGE_TYPING, Intents.FLAGS.GUILD_VOICE_STATES, Intents.FLAGS.GUILD_WEBHOOKS, Intents.FLAGS.DIRECT_MESSAGE_REACTIONS, Intents.FLAGS.GUILD_INVITES, Intents.FLAGS.GUILD_MEMBERS, Intents.FLAGS.GUILD_BANS, Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS ] }); const config = require("./config.json") const fs = require('fs') const Timeout = new Set(); bot.prefix = config.prefix_command === true ? config.prefix : "/"; bot.commands = new Collection(); bot.aliases = new Collection(); bot.categories = fs.readdirSync("./commands/"); require(`./handlers/commandHandle`)(bot); bot.on('ready', () => { require('./events/ready')(bot) bot.user.setPresence({ activities: [{ name: `${bot.prefix}help 來獲取幫助` }], status: 'online' }); }) bot.on('messageCreate', async message => { require('./events/messageCreate')(bot, message, Timeout, config) }) bot.on('interactionCreate', async interaction => { require("./events/interactionCreate")(bot, interaction, Timeout, config) }); bot.login(config.token)
var express = require('express'); //var mysql = require('mysql'); var passport = require('passport') , LocalStrategy = require('passport-local').Strategy; router = express.Router(); var bkfd2Password = require("pbkdf2-password"); var hasher = bkfd2Password(); var connection = require('../mydb/db')(); //세션 사용 준비 var session = require('express-session'); var MySQLStore = require('express-mysql-session')(session); router.use(session({ secret : '1234DSFs@adf1234!@#$asd', resave : false, saveUninitialized : true, store:new MySQLStore({ host:'localhost', port:3306, user:'root', password:'111111', database:'board01' }) })); router.get('/login', function(req, res, next){ res.render('users/login'); }); router.use(passport.initialize()); router.use(passport.session()); /// passport.serializeUser(function(user, done){ console.log('serializeUser', user); done(null, user.authId); }); passport.deserializeUser(function(id, done){ console.log('deserializeUser', id); var sql = 'SELECT * FROM users WHERE authId=?'; connection.query(sql, [id], function(err, results){ if(err){ console.log(err); done('There is no user.'); }else { done(null, results[0]); } }); }); // passport.use(new LocalStrategy( function(username, password, done){ var uname=username; var pwd=password; var sql ='SELECT * FROM users WHERE authId=?'; connection.query(sql, ['local:'+uname], function(err, results){ console.log(results); if(err){ return done('There is no users'); } var user = results[0]; if(user){ return hasher({ password:pwd, salt:user.salt}, function(err, pass, salt, hash){ //사용자가 맞다면 if(hash==user.password){ /// //session.req.username=username; //console.log(session.req.username); console.log('LocalStrategy', user); //user객체 done(null, user); //사용자가 아니라면 }else { done(null, false); } }); }else { return done('There is no users'); } }); } )); router.post('/login', passport.authenticate('local', { successRedirect:'/users/welcome', failureRedirect:'/users/login', failureFlash:false }) ); module.exports = router;
/** * @note * @param arr * @return {Array} */ export default distinct = (arr) => { return Object.values( arr.reduce((obj, next) => { let key = JSON.stringify(next); return (obj[key] = next), obj; }, {}) ) }
import React, { Component } from 'react'; import './App.css'; import Comitment from './components/comitment'; import HaveServices from './components/haveServices'; import MobilePlan from './components/mobilePlan'; import axios from 'axios'; class App extends Component { constructor(props) { super(props); this.state = { beIsipareigojimu: true, mobile1: {}, allPlans: [], }; } handleRadio = (val) => { console.log('radio was pressed'); console.log(val); // jei gaunu commit tai nustatau busena i atitinkama if (val === 'commit') { this.setState({ beIsipareigojimu: false }); } else { this.setState({ beIsipareigojimu: true }); } // arba priesingai }; async componentDidMount() { const { data: dataAxios } = await axios.get('data/plan1.json'); console.log(dataAxios); this.setState({ mobile1: dataAxios }); } render() { return ( <div className="App"> <div className="container"> <h1>Mobiliojo ryšio planai</h1> <p>Visos Lietuvoje turimo plano naudos galioja Baltijos ir Skandinavijos šalyse.</p> <div className="controls d-flex"> <Comitment handleRadio={this.handleRadio} noCommitment={this.state.beIsipareigojimu} /> <HaveServices /> </div> <main className="plan-cards"> <MobilePlan beIsipareigojimu={this.state.beIsipareigojimu} plan={this.state.mobile1} /> </main> </div> </div> ); } } export default App;
'use strict'; const chai = require('chai'); const assert = chai.assert; const Promise = require('bluebird'); const accounts = require('../../routes/accounts'); const seed = require('../../lib/seed').testSeed; const utils = require('../../lib/utils'); const constants = require('../../lib/constants/utils'); const ADMIN = constants.ADMIN; const STAFF = constants.STAFF; const COACH = constants.COACH; const VOLUNTEER = constants.VOLUNTEER; const A0_CONST = require('../../lib/constants/auth0'); const ADMIN_AUTH0_ID = A0_CONST.ADMIN_AUTH0_ID; const STAFF_AUTH0_ID = A0_CONST.STAFF_AUTH0_ID; const COACH_AUTH0_ID = A0_CONST.COACH_AUTH0_ID; const VOLUNTEER_AUTH0_ID = A0_CONST.VOLUNTEER_AUTH0_ID; const query = utils.query; const q = require('../../lib/constants/queries'); const auth0 = require('../../lib/auth0_utils'); const SC = require('../../lib/constants/seed'); const ACCTS = SC.TEST_ACCTS; const ACCT_1 = SC.ACCT_1; const ACCT_2 = SC.ACCT_2; const ACCT_3 = SC.ACCT_3; const ACCT_4 = SC.ACCT_4; const ACCT_5 = SC.ACCT_5; const ACCT_6 = SC.ACCT_6; const ACCT_7 = SC.ACCT_7; const ACCT_8 = SC.ACCT_8; const ACCT_9 = SC.ACCT_9; const testUtils = require('../../lib/test_utils'); const assertEqualAuth0DB = testUtils.assertEqualAuth0DBAcct; const assertEqualDB = testUtils.assertEqualDBAcct; const assertEqualError = testUtils.assertEqualError; const assertEqualPermissionsError = testUtils.assertEqualPermissionsError; const assertEqualMissingAuthError = testUtils.assertEqualMissingAuthError; const dummyAccount = { first_name: 'first', last_name: 'last', username: 'dummy_account', email: 'dummy@americascores.org', password: 'Password123', acct_type: ADMIN }; const UPDATED_FIRST = 'updatedFirst'; const UPDATED_LAST = 'updatedLast'; const UPDATED_EMAIL = 'updated@americascores.org'; const UPDATED_ACCT_TYPE = COACH; function getAllAccounts() { // Get contents of Accounts table in DB, used for asserts return query(q.SELECT_ACCT); } function verifyNoAccountChanges(done) { // get contents of accounts table getAllAccounts().then(function(data) { // confirm no updates were made assert.deepEqual(data, ACCTS); // TODO confirm all data on Auth0 unaffected done(); }); } function updateAccountTester(target, updates, auth0Id, done, error) { var updateAccount = Object.assign({}, target); Object.assign(updateAccount, updates); var promise = accounts.updateAccount({ params: { acct_id: target.acct_id }, body: updates, auth: { auth0_id: auth0Id } }); if (error !== undefined) { promise.catch(function(err) { assertEqualError(err, error.name, error.status, error.message); verifyNoAccountChanges(done); }); } else { promise.then(function(data) { assert.deepEqual(data, [updateAccount]); auth0.getAuth0User(data[0].auth0_id).then(function(auth0Acct) { assertEqualAuth0DB(auth0Acct, updateAccount); getAllAccounts().then(function(accounts) { var accts = ACCTS.slice(); accts[target.acct_id - 1] = updateAccount; assert.deepEqual(accounts, accts); done(); }); }); }); } } function createAccountTester(newAcctData, auth0_id, done) { var req = { body: newAcctData, auth: { auth0_id: auth0_id } }; accounts.createAccount(req).then(function() { query('SELECT acct_id, first_name, last_name, email, acct_type, auth0_id FROM Acct ' + 'WHERE first_name = ? AND last_name = ? AND email = ?', [newAcctData.first_name, newAcctData.last_name, newAcctData.email]).then(function(accts) { // confirm new user returned var newAcct = accts[0]; assertEqualDB(newAcctData, newAcct); // get contents of accounts table getAllAccounts().then(function(dbAccts) { // confirm account list matches what was found in db assert.deepEqual(dbAccts, ACCTS.concat([newAcct])); auth0.getAuth0User(newAcct.auth0_id).then(function(auth0Acct) { // confirm new account added to Auth0 assertEqualAuth0DB(auth0Acct, newAcct); done(); }); }); }); }); } function createAccountErrorTester(newAcctData, auth0_id, errName, errStatus, errMessage, done) { var req = { body: newAcctData, auth: { auth0_id: auth0_id } }; accounts.createAccount(req).catch(function(err) { assertEqualError(err, errName, errStatus, errMessage); verifyNoAccountChanges(done); }); } function createPermissionErrorTester(auth0_id, createType, reqType, done) { var acct = { first_name: 'first', last_name: 'last', email: '10@americascores.org', password: 'Password123', acct_type: createType }; createAccountErrorTester(acct, auth0_id, 'AccessDenied', 403, 'Access denied: this account (' + reqType + ') does not have permission ' + 'for this action', done); } function createMissingFieldErrorTester(field, auth0_id, done) { var acct = Object.assign({}, dummyAccount); delete acct[field]; createAccountErrorTester(acct, auth0_id, 'Missing Field', 400, 'Request must have the following component(s): ' + field + ' (body)', done); } function createEmptyFieldErrorTester(field, auth0_id, done) { var acct = Object.assign({}, dummyAccount); acct[field] = ''; createAccountErrorTester(acct, auth0_id, 'Empty Field', 400, 'Request must have the following non-empty component(s): ' + field + ' (body)', done); } function deletePermissionErrorTester(auth0_id, type, done) { accounts.deleteAccount({ params: { account_id: createdDBId }, auth: { auth0_id: auth0_id } }).catch(function(err) { assertEqualPermissionsError(err, type); getAllAccounts().then(function(accts) { // verify the account didn't get deleted assertEqualDB(accts[accts.length - 1], dummyAccount); done(); }); }); } function resetAccount(acct) { return auth0.updateAuth0User(acct.auth0_id, { email: acct.email, user_metadata: { first_name: acct.first_name, last_name: acct.last_name }, app_metadata: { acct_type: acct.acct_type } }).then(function(data) { return query(accounts.UPDATE_ACCT_ALL, [acct.first_name, acct.last_name, acct.email, acct.acct_type, acct.acct_id]); }); } describe('Accounts', function() { // get original states of the database tables before(function(done) { /* eslint-disable no-invalid-this */ this.timeout(20000); /* eslint-enable no-invalid-this */ seed().then(function() { done(); }); }); describe('getAccounts(req)', function() { it('it should get all accounts in DB when requested by an admin', function(done) { // Retrieve all students when req.query.acct_type is empty accounts.getAccounts({ query: {}, auth: { auth0_id: ADMIN_AUTH0_ID } }).then(function(data) { // Confirm entire DB retrieved assert.deepEqual(ACCTS, data); done(); }); }); // Verify access errors xit('it should return a 400 error when no auth0 id is passed with the request', function(done) { accounts.getAccounts({ query: {} }).catch(function(err) { assertEqualMissingAuthError(err); done(); }); }); xit('it should return a 403 error because staff cannot request accounts', function(done) { accounts.getAccounts({ query: {}, auth: { auth0_id: STAFF_AUTH0_ID } }).catch(function(err) { assertEqualPermissionsError(err, STAFF); done(); }); }); xit('it should return a 403 error because coaches cannot request accounts', function(done) { accounts.getAccounts({ params: { acct_id: 7 }, body: { first_name: 'Beezlebub' }, auth: { auth0_id: COACH_AUTH0_ID } }).catch(function(err) { assertEqualPermissionsError(err, COACH); done(); }); }); xit('it should return a 403 error because volunteers cannot request accounts', function(done) { accounts.getAccounts({ query: {}, auth: { auth0_id: VOLUNTEER_AUTH0_ID } }).catch(function(err) { assertEqualPermissionsError(err, VOLUNTEER); done(); }); }); // Acct Type queries it('it should get all accounts in DB where type=Volunteer', function(done) { accounts.getAccounts({ query: { acct_type: VOLUNTEER, }, auth: { auth0_id: ADMIN_AUTH0_ID } }).then(function(data) { // Check that all Volunteer accounts returned assert.deepEqual(data, [ACCT_3, ACCT_4]); done(); }); }); it('it should get all accounts in DB where type=Staff', function(done) { accounts.getAccounts({ query: { acct_type: STAFF, }, auth: { auth0_id: ADMIN_AUTH0_ID } }).then(function(data) { // Check that all Staff accounts returned assert.deepEqual(data, [ACCT_5, ACCT_6]); done(); }); }); it('it should get all accounts in DB where type=Admin', function(done) { accounts.getAccounts({ query: { acct_type: ADMIN, }, auth: { auth0_id: ADMIN_AUTH0_ID } }).then(function(data) { // Check that all Admin accounts returned assert.deepEqual(data, [ACCT_7, ACCT_8]); done(); }); }); it('it should get all accounts in DB where type=Coach', function(done) { accounts.getAccounts({ query: { acct_type: COACH }, auth: { auth0_id: ADMIN_AUTH0_ID } }).then(function(data) { // Check that all Staff accounts returned assert.deepEqual(data, [ACCT_1, ACCT_2, ACCT_9]); done(); }); }); it('it should get accounts pertaining to an auth0 id', function(done) { accounts.getAccounts({ query: { auth0_id: ACCT_1.auth0_id }, auth: { auth0_id: ADMIN_AUTH0_ID } }).then(function(data) { // Check that referenced account is returned assert.deepEqual(data, [ACCT_1]); done(); }); }); it('it should get accounts pertaining to an id', function(done) { accounts.getAccounts({ query: { account_id: ACCT_1.acct_id }, auth: { auth0_id: ADMIN_AUTH0_ID } }).then(function(data) { // Check that referenced account is returned assert.deepEqual(data, [ACCT_1]); done(); }); }); it('it should get accounts pertaining to a full name and email', function(done) { accounts.getAccounts({ query: { first_name: ACCT_1.first_name, last_name: ACCT_1.last_name, email: ACCT_1.email }, auth: { auth0_id: ADMIN_AUTH0_ID } }).then(function(data) { // Check that referenced account is returned assert.deepEqual(data, [ACCT_1]); done(); }); }); it('it should get all accounts for a specific program', function(done) { accounts.getAccounts({ query: { program_id: 1 }, auth: { auth0_id: ADMIN_AUTH0_ID } }).then(function(data) { assert.deepEqual([ACCT_7, ACCT_1, ACCT_6], data); done(); }); }); it('it should get 0 accounts when a program id that DNE is passed', function(done) { accounts.getAccounts({ query: { program_id: 999 }, auth: { auth0_id: ADMIN_AUTH0_ID } }).then(function(data) { assert.deepEqual([], data); done(); }); }); it('it should get all accounts for a specific site', function(done) { accounts.getAccounts({ query: { site_id: 1 }, auth: { auth0_id: ADMIN_AUTH0_ID } }).then(function(data) { assert.deepEqual([ACCT_7, ACCT_1, ACCT_6], data); done(); }); }); it('it should get 0 accounts when a site id that DNE is passed', function(done) { accounts.getAccounts({ query: { site_id: 999 }, auth: { auth0_id: ADMIN_AUTH0_ID } }).then(function(data) { assert.deepEqual([], data); done(); }); }); it('it should return a 501 error because of a malformed query', function(done) { accounts.getAccounts({ query: { first_name: ACCT_1.first_name, email: ACCT_1.email }, auth: { auth0_id: ADMIN_AUTH0_ID } }).catch(function(err) { assertEqualError(err, 'UnsupportedRequest', 501, 'The API does not support a request of this format. ' + ' See the documentation for a list of options.'); done(); }); }); }); describe('updateAccount(req)', function() { var affected_accounts = ACCTS.slice(); afterEach(function(done) { /* eslint-disable no-invalid-this */ this.timeout(20000); /* eslint-enable no-invalid-this */ Promise.each(affected_accounts, function(acct) { return resetAccount(acct); }).then(function() { affected_accounts = ACCTS.slice(); done(); }); }); it('it should update an account with all new fields', function(done) { var updates = { first_name: UPDATED_FIRST, last_name: UPDATED_LAST, email: UPDATED_EMAIL, acct_type: UPDATED_ACCT_TYPE }; affected_accounts = [ACCT_5]; updateAccountTester(ACCT_5, updates, ADMIN_AUTH0_ID, done); }); it('it should update an account with a new first name', function(done) { var updates = { first_name: UPDATED_FIRST }; affected_accounts = [ACCT_7]; updateAccountTester(ACCT_7, updates, ADMIN_AUTH0_ID, done); }); it('it should update an account with a new last name', function(done) { var updates = { last_name: UPDATED_LAST }; affected_accounts = [ACCT_7]; updateAccountTester(ACCT_7, updates, ADMIN_AUTH0_ID, done); }); it('it should update an account with a new email', function(done) { var updates = { email: UPDATED_EMAIL }; affected_accounts = [ACCT_7]; updateAccountTester(ACCT_7, updates, ADMIN_AUTH0_ID, done); }); it('it should update an account with a new auth level', function(done) { var updates = { acct_type: UPDATED_ACCT_TYPE }; affected_accounts = [ACCT_7]; updateAccountTester(ACCT_7, updates, ADMIN_AUTH0_ID, done); }); it('it should return a 501 error because body is missing', function(done) { accounts.updateAccount({ params: { acct_id: ACCT_1.acct_id }, auth: { auth0_id: ADMIN_AUTH0_ID } }).catch(function(err) { assertEqualError(err, 'UnsupportedRequest', 501, 'The API does not support a request of this format. ' + ' See the documentation for a list of options.'); auth0.getAuth0Id(ACCT_1.acct_id).then(function(auth0Id) { auth0.getAuth0User(auth0Id).then(function(auth0Acct) { // check that the auth0 account did not get updated assertEqualAuth0DB(auth0Acct, ACCT_1); verifyNoAccountChanges(done); }); }); }); }); it('it should 400 because there is an unrecognized update key in the body', function(done) { accounts.updateAccount({ params: { acct_id: ACCT_1.acct_id }, body: { unknown: 'foobar' }, auth: { auth0_id: ADMIN_AUTH0_ID } }).catch(function(err) { assertEqualError(err, 'UnsupportedRequest', 501, 'The API does not support a request of this format. ' + ' See the documentation for a list of options.'); auth0.getAuth0Id(ACCT_1.acct_id).then(function(auth0Id) { auth0.getAuth0User(auth0Id).then(function(auth0Acct) { // check that the auth0 account did not get updated assertEqualAuth0DB(auth0Acct, ACCT_1); verifyNoAccountChanges(done); }); }); }); }); it('should not update if request is missing params section', function(done) { accounts.updateAccount({ body: { first_name: UPDATED_FIRST }, auth: { auth0_id: ADMIN_AUTH0_ID } }).catch(function(err) { assertEqualError(err, 'UnsupportedRequest', 501, 'The API does not support a request of this format. ' + ' See the documentation for a list of options.'); verifyNoAccountChanges(done); }); }); it('should not update if request is missing acct_id in params', function(done) { accounts.updateAccount({ params: { something_stupid: 7 }, body: { first_name: UPDATED_FIRST }, auth: { auth0_id: ADMIN_AUTH0_ID } }).catch(function(err) { assertEqualError(err, 'UnsupportedRequest', 501, 'The API does not support a request of this format. ' + ' See the documentation for a list of options.'); verifyNoAccountChanges(done); }); }); it('it should return a 400 if given a non-positive integer account id', function(done) { accounts.updateAccount({ params: { acct_id: -1 }, body: { first_name: UPDATED_FIRST }, auth: { auth0_id: ADMIN_AUTH0_ID } }).catch(function(err) { assertEqualError(err, 'InvalidArgumentError', 400, 'Given acct_id is of invalid format (e.g. not an integer or negative)'); verifyNoAccountChanges(done); }); }); it('it should return a 404 if the account id DNE', function(done) { accounts.updateAccount({ params: { acct_id: 999 }, body: { first_name: UPDATED_FIRST }, auth: { auth0_id: ADMIN_AUTH0_ID } }).catch(function(err) { assertEqualError(err, 'ArgumentNotFoundError', 404, 'Invalid request: The given acct_id does not exist in the database'); verifyNoAccountChanges(done); }); }); it('it should 501 if no updates are provided in the body', function(done) { accounts.updateAccount({ params: { acct_id: ACCT_1.acct_id }, body: {}, auth: { auth0_id: ADMIN_AUTH0_ID } }).catch(function(err) { assertEqualError(err, 'UnsupportedRequest', 501, 'The API does not support a request of this format. ' + ' See the documentation for a list of options.'); verifyNoAccountChanges(done); }); }); // TODO: Auth0 API should be throwing an error because of duplicate email ... but it's not xit('it should 500 when it encounters an auth0 error and rollback the database updates', function(done) { accounts.updateAccount({ params: { acct_id: ACCT_1.acct_id }, body: { email: ACCT_1.email }, auth: { auth0_id: ADMIN_AUTH0_ID } }).catch(function(err) { assertEqualError(err, 'InternalServerError', 500, 'The server encountered an unexpected condition which prevented it from fulfilling the request'); verifyNoAccountChanges(done); }); }); xit('it should return a 403 error because staff cannot update other accounts', function(done) { accounts.updateAccount({ params: { acct_id: ACCT_7.acct_id }, body: { first_name: UPDATED_FIRST }, auth: { auth0_id: STAFF_AUTH0_ID } }).catch(function(err) { assertEqualPermissionsError(err, STAFF); auth0.getAuth0Id(ACCT_7.acct_id).then(function(auth0Id) { auth0.getAuth0User(auth0Id).then(function(auth0Acct) { // check that the auth0 account did not get updated assertEqualAuth0DB(auth0Acct, ACCT_7); verifyNoAccountChanges(done); }); }); }); }); xit('it should return a 403 error because coaches cannot update other accounts', function(done) { accounts.updateAccount({ params: { acct_id: ACCT_7.acct_id }, body: { first_name: UPDATED_FIRST }, auth: { auth0_id: COACH_AUTH0_ID } }).catch(function(err) { assertEqualPermissionsError(err, COACH); auth0.getAuth0Id(ACCT_7.acct_id).then(function(auth0Id) { auth0.getAuth0User(auth0Id).then(function(auth0Acct) { // check that the auth0 account did not get updated assertEqualAuth0DB(auth0Acct, ACCT_7); verifyNoAccountChanges(done); }); }); }); }); xit('it should return a 403 error because volunteers cannot update other accounts', function(done) { accounts.updateAccount({ params: { acct_id: ACCT_7.acct_id }, body: { first_name: UPDATED_FIRST }, auth: { auth0_id: VOLUNTEER_AUTH0_ID } }).catch(function(err) { assertEqualPermissionsError(err, VOLUNTEER); auth0.getAuth0Id(ACCT_7.acct_id).then(function(auth0Id) { auth0.getAuth0User(auth0Id).then(function(auth0Acct) { // check that the auth0 account did not get updated assertEqualAuth0DB(auth0Acct, ACCT_7); verifyNoAccountChanges(done); }); }); }); }); xit('it should return a 403 error because staff cannot update their own type', function(done) { accounts.updateAccount({ params: { acct_id: ACCT_5.acct_id }, body: { acct_type: ADMIN }, auth: { auth0_id: STAFF_AUTH0_ID } }).catch(function(err) { assertEqualPermissionsError(err, STAFF_AUTH0_ID); auth0.getAuth0Id(ACCT_5.acct_id).then(function(auth0Id) { auth0.getAuth0User(auth0Id).then(function(auth0Acct) { // check that the auth0 account did not get updated assertEqualAuth0DB(auth0Acct, ACCT_5); verifyNoAccountChanges(done); }); }); }); }); xit('it should return a 403 error because coaches cannot update their own type', function(done) { accounts.updateAccount({ params: { acct_id: ACCT_1.acct_id }, body: { acct_type: ADMIN }, auth: { auth0_id: COACH_AUTH0_ID } }).catch(function(err) { assertEqualPermissionsError(err, COACH); auth0.getAuth0Id(ACCT_1.acct_id).then(function(auth0Id) { auth0.getAuth0User(auth0Id).then(function(auth0Acct) { // check that the auth0 account did not get updated assertEqualAuth0DB(auth0Acct, ACCT_1); verifyNoAccountChanges(done); }); }); }); }); xit('it should return a 403 error because volunteers cannot update their own type', function(done) { accounts.updateAccount({ params: { acct_id: ACCT_3.acct_id }, body: { acct_type: ADMIN }, auth: { auth0_id: VOLUNTEER_AUTH0_ID } }).catch(function(err) { assertEqualPermissionsError(err, VOLUNTEER); auth0.getAuth0Id(ACCT_3.acct_id).then(function(auth0Id) { auth0.getAuth0User(auth0Id).then(function(auth0Acct) { // check that the auth0 account did not get updated assertEqualAuth0DB(auth0Acct, ACCT_3); verifyNoAccountChanges(done); }); }); }); }); it('it should allow volunteers to update their own email and name', function(done) { var updates = { first_name: UPDATED_FIRST, last_name: UPDATED_LAST, email: UPDATED_EMAIL }; affected_accounts = [ACCT_3]; updateAccountTester(ACCT_3, updates, VOLUNTEER_AUTH0_ID, done); }); it('it should allow coaches to update their own email and name', function(done) { var updates = { first_name: UPDATED_FIRST, last_name: UPDATED_LAST, email: UPDATED_EMAIL }; affected_accounts = [ACCT_1]; updateAccountTester(ACCT_1, updates, COACH_AUTH0_ID, done); }); it('it should allow staff to update their own email and name', function(done) { var updates = { first_name: UPDATED_FIRST, last_name: UPDATED_LAST, email: UPDATED_EMAIL }; affected_accounts = [ACCT_5]; updateAccountTester(ACCT_5, updates, COACH_AUTH0_ID, done); }); }); describe('createAccount(req)', function() { afterEach(function(done) { /* eslint-disable no-invalid-this */ this.timeout(10000); /* eslint-enable no-invalid-this */ query('SELECT acct_id, auth0_id FROM Acct WHERE email = ?', [dummyAccount.email]).then(function(ids) { if (ids.length == 1) { setTimeout(function() { auth0.deleteAuth0User(ids[0].auth0_id).then(function() { query(accounts.DELETE_ACCT, [ids[0].acct_id]).then(function() { done(); }); }); }, 3000); } else { done(); } }); }); it('it should add an Admin account when requested by an existing admin', function(done) { var acct = Object.assign({}, dummyAccount); createAccountTester(acct, ADMIN_AUTH0_ID, done); }); it('it should add a Staff account when requested by an existing admin', function(done) { var acct = Object.assign({}, dummyAccount); acct.acct_type = STAFF; createAccountTester(acct, ADMIN_AUTH0_ID, done); }); it('it should add a volunteer account when requested by an existing admin', function(done) { var acct = Object.assign({}, dummyAccount); acct.acct_type = VOLUNTEER; createAccountTester(acct, ADMIN_AUTH0_ID, done); }); it('it should add a coach account when requested by an existing admin', function(done) { var acct = Object.assign({}, dummyAccount); acct.acct_type = COACH; createAccountTester(acct, ADMIN_AUTH0_ID, done); }); xit('it should return a 403 error because staff cannot create admin accounts', function(done) { var acct = Object.assign({}, dummyAccount); createPermissionErrorTester(acct, STAFF_AUTH0_ID, done); }); xit('it should return a 403 error because Volunteers cannot create admin accounts', function(done) { var acct = Object.assign({}, dummyAccount); createPermissionErrorTester(acct, VOLUNTEER_AUTH0_ID, done); }); xit('it should return a 403 error because Coaches cannot create staff accounts', function(done) { var acct = Object.assign({}, dummyAccount); acct.acct_type = STAFF; createPermissionErrorTester(acct, COACH_AUTH0_ID, done); }); xit('it should return a 403 error because coaches cannot create admin accounts', function(done) { var acct = Object.assign({}, dummyAccount); createPermissionErrorTester(acct, COACH_AUTH0_ID, done); }); xit('it should return a 403 error because volunteers cannot create staff accounts', function(done) { var acct = Object.assign({}, dummyAccount); acct.acct_type = STAFF; createPermissionErrorTester(acct, VOLUNTEER_AUTH0_ID, done); }); it('it should return a 400 error because a first_name is missing', function(done) { createMissingFieldErrorTester('first_name', ADMIN_AUTH0_ID, done); }); it('it should return a 400 error because a last_name is missing', function(done) { createMissingFieldErrorTester('last_name', ADMIN_AUTH0_ID, done); }); it('it should return a 400 error because email is missing', function(done) { createMissingFieldErrorTester('email', ADMIN_AUTH0_ID, done); }); it('it should return a 400 error because acct_type is missing', function(done) { createMissingFieldErrorTester('acct_type', ADMIN_AUTH0_ID, done); }); it('it should return a 400 error because password is missing', function(done) { createMissingFieldErrorTester('password', ADMIN_AUTH0_ID, done); }); it('it should return a 400 error because first_name is empty', function(done) { createEmptyFieldErrorTester('first_name', ADMIN_AUTH0_ID, done); }); it('it should return a 400 error because last_name is empty', function(done) { createEmptyFieldErrorTester('last_name', ADMIN_AUTH0_ID, done); }); it('it should return a 400 error because acct_type is empty', function(done) { createEmptyFieldErrorTester('acct_type', ADMIN_AUTH0_ID, done); }); it('it should return a 400 error because acct_type is invalid', function(done) { var acct = Object.assign({}, dummyAccount); acct.acct_type = 'Invalid'; createAccountErrorTester(acct, ADMIN_AUTH0_ID, 'Bad Request', 400, 'Account type must be one of: Admin, Coach, Staff, Volunteer', done); }); it('it should return a 400 error because the password does not meet requirements', function(done) { var acct = Object.assign({}, dummyAccount); acct.password = 'weak'; createAccountErrorTester(acct, ADMIN_AUTH0_ID, 'Bad Request', 400, 'Password is too weak', done); }); }); describe('deleteAccount(req)', function() { var createdDBId; var createdAuth0Id; // add a dummy account to auth0 and the db function createDummyAccount() { // first add to auth0 return auth0.createAuth0User(dummyAccount.first_name, dummyAccount.last_name, dummyAccount.username, dummyAccount.email, dummyAccount.acct_type, dummyAccount.password).then(function(auth0Id) { createdAuth0Id = auth0Id; // then add to our db return query(accounts.CREATE_ACCT, [dummyAccount.first_name, dummyAccount.last_name, dummyAccount.email, dummyAccount.acct_type, auth0Id]).then(function() { return query(accounts.ACCOUNT_BY_AUTH, [createdAuth0Id]).then(function(accts) { createdDBId = accts[0].acct_id; return Promise.resolve(); }); }); }); } afterEach(function(done) { auth0.getAuth0UserByEmail(dummyAccount.email).then(function(user) { // clear existing user so we don't get a duplicate email error on future creation auth0.deleteAuth0User(user.user_id).then(function() { query('DELETE FROM Acct WHERE auth0_id=?', [user.user_id]).then(function() { done(); }); }); }).catch(function(err) { // no user to delete, teardown is complete done(); }); }); xit('it should 403 when a coach tries to delete an account', function(done) { createDummyAccount().then(function() { deletePermissionErrorTester(COACH_AUTH0_ID, done); }); }); xit('it should 403 when a staff member tries to delete an account', function(done) { createDummyAccount().then(function() { deletePermissionErrorTester(STAFF_AUTH0_ID, done); }); }); xit('it should 403 when a volunteer tries to delete an account', function(done) { createDummyAccount().then(function() { deletePermissionErrorTester(VOLUNTEER_AUTH0_ID, done); }); }); it('it should delete an account if an admin requests the action', function(done) { createDummyAccount().then(function() { accounts.deleteAccount({ params: { account_id: createdDBId }, auth: { auth0_id: ADMIN_AUTH0_ID } }).then(function() { auth0.getAuth0User(createdAuth0Id).catch(function(err) { assertEqualError(err, 'ArgumentNotFoundError', 404, 'Invalid request: The given auth0_id' + ' does not exist in the database' ); verifyNoAccountChanges(done); }); }); }); }); it('it should return a 400 error if no id is passed', function(done) { accounts.deleteAccount({ params: {}, auth: { auth0_id: ADMIN_AUTH0_ID } }).catch(function(err) { assertEqualError(err, 'Missing Field', 400, 'Request must have the following component(s): account_id (params)'); verifyNoAccountChanges(done); }); }); it('it should 404 when passed the acct id is not recognized', function(done) { accounts.deleteAccount({ params: { account_id: 999 }, auth: { auth0_id: ADMIN_AUTH0_ID } }).catch(function(err) { assertEqualError(err, 'Not Found', 404, 'No account with id 999 exists in the database.'); verifyNoAccountChanges(done); }); }); }); });
(function () { var global = typeof window !== 'undefined' ? window : this || Function('return this')(); var nx = global.nx || require('@jswork/next'); var fetch = require('node-fetch'); var isValidUrl = require('@jswork/is-valid-url').default; var fs = require('fs'); var util = require('util'); var fromFile = util.promisify(fs.readFile); var NxFsOpen = nx.declare('nx.FsOpen', { statics: { fromFile, fromUrl: function (inUrl) { return fetch(inUrl).then((r) => r.buffer()); }, from: function (inTarget) { if (Buffer.isBuffer(inTarget)) return Promise.resolve(inTarget); var valid = isValidUrl(inTarget); var api = valid ? 'fromUrl' : 'fromFile'; return this[api](inTarget); } } }); if (typeof module !== 'undefined' && module.exports) { module.exports = NxFsOpen; } })();
const authenticateReducer = (state, action) => { switch (action.type) { case 'AUTHENTICATE_ADMINISTRATOR': return action.payload case 'SET_VALIDATION': return action.payload default: return typeof (state) === 'undefined' ? {} : state } } export default authenticateReducer
import React, { Component } from "react"; import ScrollableAnchor from "react-scrollable-anchor"; import { configureAnchors } from "react-scrollable-anchor"; import history from '../../history'; import "materialize-css/dist/css/materialize.min.css"; import "./main.css"; import about from "./assets/about-img.jpg"; import team1 from "./assets/team-1.jpg"; import team2 from "./assets/team-2.jpg"; import team3 from "./assets/team-3.jpg"; import team4 from "./assets/team-4.jpg"; // import team4 from "./assets/team-4.jpg"; import {connect} from 'react-redux'; class Main extends Component { state = {}; componentWillMount = () => { configureAnchors({ offset: -60, scrollDuration: 1000 }); }; render() { if(this.props.login.signup && this.props.login.category !== 'employee'){ history.push('/client'); } else if(this.props.login.signup && this.props.login.category === 'employee'){ history.push('/employee'); } return ( <div> <ScrollableAnchor id={"top"}> <div className='background'> <div className='headings'> <h2>Welcome to Helping Squad</h2> <h5>We Provide Emergency Services Needs Partner Like You</h5> <a onClick={()=>{history.push('/signup')}} className='waves-effect waves-light btn'> Sign up </a> <a onClick={()=>{history.push('/login')}} className='waves-effect waves-light btn'> Login </a> </div> </div> </ScrollableAnchor> <nav className='navv'> <div className='nav-wrapper container'> <a href='#top' className='brand-logo'> HSquad </a> <ul id='nav-mobile' className='right hide-on-small-only'> <li> <a href='#top'>Home</a> </li> <li> <a href='#about'>About Us</a> </li> <li> <a href='#services'>Services</a> </li> <li> <a href='#contact'>Contact Us</a> </li> </ul> </div> </nav> <ScrollableAnchor id={"about"}> <section className='about'> <div className='container'> <h4 style={{ fontWeight: "700" }}>About Us</h4> <div className='divider' /> <p> Emergency services is one of the best service that solve that problem a person is facing on daliy life .Our goal is to Solve Every problem,We are targeting ,MoterCycle,Doctor,Plumber,Electrical Service. </p> <div className='row'> <div className='col s12 m6'> <img style={{ maxWidth: "100%" }} src={about} alt='about' /> </div> <div className='col s12 m6 aboutc'> <h4>We provide great services and your Needs</h4> <p> We are providing great Services and Needs .In daliy life A lot of motorcycle puncture on the road.Man have no idea What he should our app providing them services. </p> <p> Road Accident A lot of person can death our app will communicate to nearest Doctor,So humanity Spreading is also involving in this app.{" "} </p> <p> In Daily Base in our Home if our light off ,We conffuse so Our app is finishing your problem you can communicate nearest Electrical problem. </p> </div> </div> </div> </section> </ScrollableAnchor> <ScrollableAnchor id={"services"}> <section className='services'> <div className='container'> <h4 style={{ fontWeight: "700" }}>Our Services</h4> <div className='divider' /> <p style={{ textAlign: "center" }}> We are providing great Services and Needs .In daliy life A lot of motorcycle puncture on the road. </p> <div className='row' style={{textAlign: 'left'}}> <div className='col s12 m4'> <h5> <i className='fa fa-user-md' /> Doctor </h5> <p> Road Accident A lot of person can death our app will communicate to nearest Doctor,So humanity Spreading is also involving in this app. </p> </div> <div className='col s12 m4'> <h5> <i className='fa fa-motorcycle' /> Motercycle Mechanic </h5> <p> Motercycle Mechanic will Work Professtionaly any Where When you Want. </p> </div> <div className='col s12 m4'> <h5> <i className='fa fa-bolt' /> Electrical Mechanic </h5> <p> Electricians install, maintain, repair, test and commission electrical and electronic equipment Get ourSelf </p> </div> </div> <div className='row'> <div className='col s12 m4'> <h5> <i className='fa fa-desktop' /> IT Master </h5> <p> iT Master solve all your problem witch you face using Any type of Technalog in your Home ,accourding to your time. </p> </div> <div className='col s12 m4'> <h5> <i className='fa fa-wrench' /> Plumber </h5> <p> Every Person Face many Problem when any thing distory at you Home ,Track plumber help on it self. </p> </div> <div className='col s12 m4'> <h5> <i className='fa fa-history' /> Future Services </h5> <p> in Future we Also can involve other services that can help human </p> </div> </div> </div> </section> </ScrollableAnchor> <section className='team'> <div className='container'> <h4 style={{ fontWeight: "700" }}>Our Team</h4> <div className='divider' /> <p style={{ textAlign: "center" }}> Our Team is one of the best Team witch include Mern Stack and full Stack developer </p> <div className='row'> <div className='col s12 m3'> <div> <img className='pic' src={team1} alt='Team 1' /> </div> <h5>Hammad</h5> <span>Full Stack Developer</span> <i className='fab fa-twitter' /> <i className='fab fa-facebook-f' /> <i className='fab fa-google-plus-g' /> <i className='fab fa-linkedin-in' /> </div> <div className='col s12 m3'> <div> <img className='pic' src={team2} alt='Team 2' /> </div> <h5>Usama</h5> <span>Full Stack Developer</span> <i className='fab fa-twitter' /> <i className='fab fa-facebook-f' /> <i className='fab fa-google-plus-g' /> <i className='fab fa-linkedin-in' /> </div> <div className='col s12 m3'> <div> <img className='pic' src={team3} alt='Team 3' /> </div> <h5>Moeez</h5> <span>Full Stack Developer</span> <i className='fab fa-twitter' /> <i className='fab fa-facebook-f' /> <i className='fab fa-google-plus-g' /> <i className='fab fa-linkedin-in' /> </div> <div className='col s12 m3'> <div> <img className='pic' src={team4} alt='Team 3' /> </div> <h5>Talha</h5> <span>Full Stack Developer</span> <i className='fab fa-twitter' /> <i className='fab fa-facebook-f' /> <i className='fab fa-google-plus-g' /> <i className='fab fa-linkedin-in' /> </div> </div> </div> </section> <ScrollableAnchor id={"contact"}> <section className='contact'> <div className='container'> <h4 style={{ fontWeight: "700" }}>Contact Us</h4> <div className='divider' /> <p style={{ textAlign: "center" }}> Any problem using our app contect with us. </p> <div className='row'> <div className='col s12 m6'> <p className='info'> <i className='fas fa-map-marker-alt' /> Emergency Service Faislabad </p> <p className='info'> <i className='fas fa-envelope' /> emergencyservice@gamil.com </p> <p className='info'> <i className='fas fa-phone' /> +1 5589 55488 55s </p> </div> <div className='col s12 m6'> <div className='row' style={{ marginTop: "30px" }}> <div className='input-field col s12'> <input type='text' name='username' id='username' placeholder='Your Name' className='browser-default' /> </div> <div className='input-field col s12'> <input type='email' name='email' id='email' placeholder='Your Email' className='browser-default' /> </div> <div className='input-field col s12'> <input type='text' name='subject' id='subject' placeholder='Subject' className='browser-default' /> </div> <div className='input-field col s12'> <textarea name='message' id='message' placeholder='Message' /> </div> <a className='waves-effect waves-light btn'>Send Message</a> </div> </div> </div> </div> </section> </ScrollableAnchor> <footer className='footer'> <div className='container'> <p> &copy; Copyright <strong>Emergency Service.</strong> All Rights Reserved </p> Designed by Helping Squad </div> </footer> </div> ); } } function recieveData(store) { return { login:store.LoginReducer }; } const newMain = connect(recieveData)(Main); export default newMain;
import { findIndex } from 'lodash' const isWeirdTime = (timeToReceive) => { if (!timeToReceive) return 0 if (timeToReceive <= 48) return 1 if (timeToReceive <= 51) return 2 if (timeToReceive <= 60) return 3 return 4 } const tipsetKeyFormatter = (block) => { return `${block.parentstateroot}-${block.height}` } // todo: need to update this to minimize length of edges or some simplified version that will accurately show side chains forming // maybe will be easier to calculate if tipsets aren't randomly ordered but ordered so that like tipsets are at similar x positions const calcX = (block, blocksAtTipset, tipsetsAtHeight, empty) => { const numTipsets = tipsetsAtHeight[block.height].length const centerTipset = Math.floor(numTipsets / 2) const tipsetKeyDefault = tipsetKeyFormatter(block) const tipsetKey = empty ? `${block.block}-e` : tipsetKeyDefault const positionOfCurrentTipset = findIndex(tipsetsAtHeight[block.height], { tipset: tipsetKey }) // add some padding around the tipset area // need to update this calc here to account for ones in the middle const tipsetMidPoint = (positionOfCurrentTipset - centerTipset) / numTipsets // from range -1 to 1 const tipsetArea = (1 / numTipsets) * 0.7 const tipsetStartingPoint = tipsetMidPoint - tipsetArea / 2 const numBlocksInTipset = blocksAtTipset[tipsetKey].length const positionOfCurrentBlock = blocksAtTipset[tipsetKey].indexOf(block.block) + 1 const xPos = tipsetStartingPoint + tipsetArea * (1 / (numBlocksInTipset + 1)) * positionOfCurrentBlock return xPos } const createBlock = (block, blockParentInfo, tipsets, miners, blockXPos, start, range) => { const blockId = block.block const timeToReceive = parseInt(block.syncedtimestamp) - parseInt(block.timestamp) const tipsetKey = tipsetKeyFormatter(block) return { id: blockId, key: blockId, height: block.height, group: tipsets[tipsetKey], label: block.miner, miner: block.miner, minerColor: miners[block.miner], parentWeight: block.parentweight, timeToReceive: `${timeToReceive}s`, weirdTime: isWeirdTime(timeToReceive), blockCid: blockId, minerPower: blockParentInfo[blockId] && blockParentInfo[blockId].power, weight: block.weight, tipset: tipsets[tipsetKey], x: blockXPos[block.block], y: (block.height - start) / range, timestamp: block.timestamp, messages: block.messages, } } const createEdge = (block, isBlockOrphan, timeToReceive, blockIndices) => { const blockId = block.block return { from: blockIndices[blockId], to: blockIndices[block.parent], key: `${blockId}-${block.parent}-e`, time: timeToReceive, edgeWeirdTime: isWeirdTime(timeToReceive), isOrphan: isBlockOrphan, } } const createEmptyEdges = (block, isBlockOrphan, blockIndices) => { const blockId = block.block const edgesToBeAdded = [] if (blockIndices[block.parent]) { edgesToBeAdded.push({ from: blockIndices[`${blockId}-e`], to: blockIndices[block.parent], key: `${blockId}-${block.parent}-eb`, isOrphan: 0, }) } edgesToBeAdded.push({ from: blockIndices[blockId], to: blockIndices[`${blockId}-e`], key: `${blockId}-${block.parent}-ep`, isOrphan: isBlockOrphan, }) return edgesToBeAdded } export const blocksToChain = (blocksArr, bhRangeEnd, bhRangeStart) => { // format chain as expected by elgrapho const range = bhRangeEnd - bhRangeStart || 1 const start = bhRangeStart || 0 const blockXPos = {} const chain = { nodes: [], edges: [], } // used to store info for data transformations necessary to parse query data to right format const blocks = {} const blockParentInfo = {} const blockIndices = {} const tipsets = {} const miners = {} const minerCount = {} const blocksAtTipset = {} const tipsetsAtHeight = {} const blockInfo = {} const blockParents = {} blocksArr.forEach((block, index) => { const isDirectParent = Number(block.parentheight) === Number(block.height) - 1 if (isDirectParent) { blockParents[block.block] ? blockParents[block.block].push(block.parent) : (blockParents[block.block] = [block.parent]) } else { blockParents[`${block.block}-e`] ? blockParents[`${block.block}-e`].push(block.parent) : (blockParents[`${block.block}-e`] = [block.parent]) blockParents[block.block] ? blockParents[block.block].push(`${block.block}-e`) : (blockParents[block.block] = [`${block.block}-e`]) } // blocksArr has duplicate blocks to establish the block - parent relationship, but we only need to do this for each unique block if (!blockInfo[block.block]) { minerCount[block.miner] = minerCount[block.miner] ? minerCount[block.miner] + 1 : 1 blockParentInfo[block.parent] = { power: block.parentpower, parentstateroot: block.parentstateroot } const tipsetKey = tipsetKeyFormatter(block) // make groups for tipsets and miners to be used in select tool if (!tipsets[tipsetKey]) { tipsets[tipsetKey] = index } if (!miners[block.miner]) { miners[block.miner] = index } // save what blocks are in each tipset so can calc x for each specific block after placing tipsets if (!blocksAtTipset[tipsetKey]) { blocksAtTipset[tipsetKey] = [block.block] } else { blocksAtTipset[tipsetKey].push(block.block) } // organize tipsets for each height so can place them along x axis if (!tipsetsAtHeight[block.height]) { tipsetsAtHeight[block.height] = [{ tipset: tipsetKey, parentweight: block.parentweight, numBlocks: 1 }] } else if (findIndex(tipsetsAtHeight[block.height], { tipset: tipsetKey }) === -1) { tipsetsAtHeight[block.height].push({ tipset: tipsetKey, parentweight: block.parentweight, numBlocks: 1 }) } else { const tipsetIndex = findIndex(tipsetsAtHeight[block.height], { tipset: tipsetKey }) tipsetsAtHeight[block.height][tipsetIndex].numBlocks += 1 } // empty blocks will be added to indicate nodes that have a parent from a previous epoch(skipped an epoch in chain) // need to add that here to use in our calculation of where to place tipsets on x axis if (!isDirectParent && block.height > parseInt(bhRangeStart) + 1) { const emptyNode = { tipset: `${block.block}-e`, parentweight: 0, numBlocks: 0, empty: true } tipsetsAtHeight[block.height - 1] ? tipsetsAtHeight[block.height - 1].push(emptyNode) : (tipsetsAtHeight[block.height - 1] = [emptyNode]) blocksAtTipset[`${block.block}-e`] ? blocksAtTipset[`${block.block}-e`].push(`${block.block}-e`) : (blocksAtTipset[`${block.block}-e`] = [`${block.block}-e`]) blockInfo[`${block.block}-e`] = { block: block.block, height: block.height - 1 } } } blockInfo[block.block] = block }) // find semi-optimal ordering for tipsets at same y axis position so can place them along x axis appropriately // we care about -- 1. heaviest tipset should be in center for easier visualization 2. minimize edge crossings // put heaviest tipset in middle const orderHeaviestTipset = (tipsets = []) => { let heaviestTipset = tipsets[0] const middlePosition = Math.floor(tipsets.length / 2) if (tipsets.length > 1) { let heaviestTipsetsIndex = 0 tipsets.forEach((tipset, index) => { if (tipset.parentweight > heaviestTipset.parentweight) { heaviestTipset = tipset heaviestTipsetsIndex = index } }) const currentMiddle = tipsets[middlePosition] tipsets[middlePosition] = heaviestTipset tipsets[heaviestTipsetsIndex] = currentMiddle } return { heaviestTipset } } // calcXPositions of nodes at height const calcXPosOfNodesAtHeight = (height) => { const tipsetsCurrentHeight = tipsetsAtHeight[height] || [] for (let t of tipsetsCurrentHeight) { if (blocksAtTipset[t.tipset]) { const { empty } = t for (let blockCID of blocksAtTipset[t.tipset]) { const block = blockInfo[blockCID] blockXPos[blockCID] = calcX(block, blocksAtTipset, tipsetsAtHeight, empty) } } } } const orderTipsetsAtHeightByPrevVertexMedian = (height) => { const tipsetsCurrentHeight = tipsetsAtHeight[height] || [] // put heaviest in middle and then put surrounding tipsets around it const { heaviestTipset } = orderHeaviestTipset(tipsetsCurrentHeight) // for each block in tipset, find the x value of the parents and then find the median const tipsetMedianXPos = {} const tipsetsToLeft = [] const tipsetsToRight = [] for (let tipset of tipsetsCurrentHeight) { const parentXPos = [] // blocks in same tipset have same parents so only need to check parents of one block for (let blockParent of blockParents[blocksAtTipset[tipset.tipset][0]]) { if (blockXPos[blockParent] || blockXPos[blockParent] === 0) { parentXPos.push(blockXPos[blockParent]) } } // get left median of xpos const sortedParentXPos = parentXPos.sort((a, b) => a - b) let median const midPosition = (sortedParentXPos.length - 1) / 2 if (midPosition === parseInt(midPosition)) { median = sortedParentXPos[midPosition] } else { median = (sortedParentXPos[Math.floor(midPosition)] + sortedParentXPos[Math.ceil(midPosition)]) / 2 } tipsetMedianXPos[tipset.tipset] = median } const medianOfHeaviestTipset = tipsetMedianXPos[heaviestTipset.tipset] for (let tipset of tipsetsCurrentHeight) { if (tipset.tipset !== heaviestTipset.tipset) { if (tipsetMedianXPos[tipset.tipset] < medianOfHeaviestTipset) { tipsetsToLeft.push({ ...tipset, median: tipsetMedianXPos[tipset.tipset] }) } else { tipsetsToRight.push({ ...tipset, median: tipsetMedianXPos[tipset.tipset] }) } } } tipsetsToLeft.sort((a, b) => { return a.median < b.median ? -1 : 1 }) tipsetsToRight.sort((a, b) => { return a.median < b.median ? -1 : 1 }) // force them to be equal so that heaviest always in middle while (tipsetsToLeft.length < tipsetsToRight.length) { tipsetsToLeft.unshift('faketipset') } while (tipsetsToRight.length < tipsetsToLeft.length) { tipsetsToRight.push('faketipset') } tipsetsAtHeight[height] = [...tipsetsToLeft, ...[heaviestTipset], ...tipsetsToRight] calcXPosOfNodesAtHeight(height) } // get x positions for first height orderHeaviestTipset(tipsetsAtHeight[bhRangeStart]) calcXPosOfNodesAtHeight(bhRangeStart) for (let height in tipsetsAtHeight) { orderTipsetsAtHeightByPrevVertexMedian(height) } blocksArr.forEach((block, index) => { const blockId = block.block // @todo: check if should be comparing parent timestamp or parent synced timestamp const timeToReceive = parseInt(block.syncedtimestamp) - parseInt(block.timestamp) // block.block may appear multiple times because there are many parent child relationships // we want to only add the node once but add all the edges to represent the different parent/child relationships if (!blocks[blockId]) { const chainLength = chain.nodes.push( createBlock(block, blockParentInfo, tipsets, miners, blockXPos, start, range), ) blockIndices[blockId] = chainLength - 1 } const isDirectParent = Number(block.parentheight) === Number(block.height) - 1 const isOrphan = (block) => { return blockParentInfo[block.block] && bhRangeEnd !== block.height ? 0 : 1 } const createEmptyBlock = (block, blockXPos) => { const blockId = block.block return { id: blockId, key: blockId, height: block.height, parentweight: 0, group: null, label: 'skipped', miner: null, minerColor: null, x: blockXPos[block.block], y: (block.height - start) / range, timestamp: block.timestamp, messages: block.messages, } } if (isDirectParent && blockIndices[blockId] && blockIndices[block.parent]) { const newEdge = createEdge(block, isOrphan(block), timeToReceive, blockIndices) chain.edges.push(newEdge) } else if (!blocks[blockId] && block.height > parseInt(bhRangeStart) + 1) { const emptyBlock = { ...block, block: `${block.block}-e`, height: block.height - 1 } const newEmptyBlock = createEmptyBlock(emptyBlock, blockXPos) const chainLength = chain.nodes.push(newEmptyBlock) blockIndices[`${blockId}-e`] = chainLength - 1 const newEmptyEdges = createEmptyEdges(block, isOrphan(block), blockIndices) chain.edges.push(...newEmptyEdges) } blocks[blockId] = index }) // push fake nodes so that chain renders in only half the available width for easier zooomoing chain.nodes.push({ y: 0, x: -1 }, { y: 0, x: 1 }) chain.miners = minerCount return chain }
import axios from 'axios'; import * as actions from './actionTypes'; export const fetchConnections = pageNo => { return dispatch => { axios.get(`https://randomuser.me/api/?page=${pageNo}&results=20&seed=abc`) .then(response => { dispatch(listConnections(response.data.results, pageNo)); }) .catch(error => { console.log(error); }) } } export const listConnections = (list, pageNo) => { return { type: actions.LIST_CONNECTIONS, payload: { list: list, pageNo: pageNo } } }
import React from 'react'; import PropTypes from 'prop-types'; import Container from './Container'; import Spinner from '../spinner/Spinner'; const Loading = ({ height, radius }) => ( <Container alignItems="center" justifyContent="center" height={height}> <Spinner radius={radius} /> </Container> ); Loading.propTypes = { height: PropTypes.number.isRequired, radius: PropTypes.number, }; Loading.defaultProps = { radius: 30, }; export default Loading;
import React from "react"; // reactstrap components import {Component} from 'react'; function iframe () { return ( <div> <iframe src="https://sktm9.csb.app/"/> </div> ) } export default class HackMap extends Component { render() { return( <div> <iframe src="https://sktm9.csb.app/" width="420" height="345" /> </div> ) } }
var EditAddress = function() { return { myVariable: null, init: function() { alert("EditAddress_[[widgetId]].init"); // // attach an event to an HTML element // var self = this; // jQuery(".EditAddress .myElementClass").click(function() { // self.myMethod(); // // do something // ... // }); }, myMethod: function() { alert("EditAddress.myMethod()"); } // no comma after last method }; }(); //jQuery(EditAddress_[[widgetId]].init()); // Run after page loads
var lightboxBlockerElements = document.querySelectorAll('[id*="smwoverlay"],[id*="wow-modal-overlay"],[id*="om-lightbox"],[id*="dgd_scrollbox"],[class*="snp-pop-"],[id*="ppsPopupShell"],[id*="ppsPopupBgOverlay"],.yithpopup_overlay,yithpopup_wrapper,#mkt-popup,#pdv4overlay,#pdv4wrap,#pty_pkg'); if (typeof lightboxBlockerElements == 'object') { lightboxBlockerElements.forEach(function(lightboxToBlock) { lightboxToBlock.style.display = 'none'; lightboxToBlock.setAttribute('id', 'lb-blocker'); }); }
import React from "react"; const VistaWeb = ({ poema }) => { const lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."; return ( <div style={{ display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center", }} > <h1 style={{ color: "#3388af", fontSize: "42px" }}> {poema ? poema.title : "..."} </h1> <p>Por {poema ? poema.poet.name : "..."}</p> <img src="https://picsum.photos/600/400" alt="random image" style={{ maxWidth: "600px", maxHeight: "400" }} /> <p style={{ color: "gray", fontStyle: "italic", fontSize: "10px", }} > {lorem} </p> <br /> <p style={{ maxWidth: "50ch" }}>{poema ? poema.content : null}</p> </div> ); }; export default VistaWeb;
import { arr, num } from 'types'; export default function pop(size) { return function innerPop(data) { return arr(data).slice(0, data.length - num(size)); } };
/** # Testnets https://github.com/CryptoLions/EOS-Jungle-Testnet Jungle chainId: `038f4b0fc8ff18a4f0842a8f0564611f6e96e8535901dd45e43ac8691a1c4dca` # Mainnets Find a trusted blockproducer (https://bloks.io/producers for example). EOS chainId: `aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906` Look for the published `bp.json` with an `api_endpoint` under the BPs domain (https://choosen_block_producer/bp.json for example). */ //chainId = 'aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906' //httpEndpoint = 'https://mainnet.libertyblock.io:7777' chainId = 'cf057bbfb72640471fd910bcb67639c22df9f92470936cddc1ade0e2f2e7dc4f'; httpEndpoint = 'http://localhost:8888'; eosConfig = { //chainId: chainId, httpEndpoint: httpEndpoint, verbose: true, //TODO: remove, get from other place: //keyProvider: "5K7mtrinTFrVTduSxizUc5hjXJEtTjVTsqSHeBHes1Viep86FP5" }; eos = Eos(eosConfig); const sampleParameters = { httpEndpoint, chainId: chainId.substring(0, 10) + '..' } console.log(`>> eos = Eos(${JSON.stringify(sampleParameters)})`); eosConfig.verbose = true; const doctorAccount = { "name": "doctor", "privateKey": "5KLqT1UFxVnKRWkjvhFur4sECrPhciuUqsYRihc1p9rxhXQMZBg", "publicKey": "EOS78RuuHNgtmDv9jwAzhxZ9LmC6F295snyQ9eUDQ5YtVHJ1udE6p" }; const personAccount = { "name": "patient", "privateKey": "5KNm1BgaopP9n5NqJDo9rbr49zJFWJTMJheLoLM5b7gjdhqAwCx", "publicKey": "EOS8LoJJUU3dhiFyJ5HmsMiAuNLGc6HMkxF4Etx6pxLRG7FU89x6X" }; const pharmacistAccount = { "name": "pharmacist", "privateKey": "5KaqYiQzKsXXXxVvrG8Q3ECZdQAj2hNcvCgGEubRvvq7CU3LySK", "publicKey": "EOS5btzHW33f9zbhkwjJTYsoyRzXUNstx1Da9X2nTzk8BQztxoP3H" }; const registrarAccount = { "name": "registrar", "privateKey": "5KZASPEgUpSfmp1nDPSZErVp4fYTrG6vXGgWSz4MgjhN35yPAJh", "publicKey": "EOS7nWanA2itjE9tcmzQBMHhyfXDYGnSiqyZ4h2k3zC2yDowNuETu" }; async function bcRegisterPerson(name) { let actionName = "update"; let actionData = { //TODO: remove, get from other place: _user: personAccount.name, _note: name, }; // eosjs function call: connect to the blockchain //const eos = Eos({ keyProvider: privateKey }); const result = await eos.transaction({ actions: [{ account: "registrar", name: actionName, authorization: [{ actor: personAccount.name, permission: 'active', }], data: actionData, }]}, { keyProvider : personAccount.privateKey } ); console.log(result); alert("Person Saved"); } async function savePrescriptionBchain(prescription) { let actionName = "update"; let actionData = { //TODO: remove, get from other place: _user: doctorAccount.name, _note: prescription, }; // eosjs function call: connect to the blockchain //const eos = Eos({ keyProvider: privateKey }); const result = await eos.transaction({ actions: [{ account: "notechainacc", name: actionName, authorization: [{ actor: doctorAccount.name, permission: 'active', }], data: actionData, }]}, { keyProvider : doctorAccount.privateKey } ); console.log(result); alert("Prescription Saved"); } function getPatientDataFromEos() { var rows = null; var jsonObj = eos.getTableRows({ "json": true, "code": "registrar", // contract who owns the table "scope": "registrar", // scope of the table "table": "smedical", // name of the table as specified by the contract abi "limit": 100, }); jsonObj .then(res => { console.log(res.rows); let html = ''; res.rows.forEach(res => html += `<tr><td>${res.fullname}</td><td>${res.dob}</td><td>${res.medical_history}</td></tr>`); document.getElementById("patient-view-table").innerHTML = html; }) .catch(e => console.log(e)); //jsonObj.then(result => $('body').append(result.rows)); //jsonObj.then(result => alert(JSON.stringify(result.rows))); } function bcLoadApprovals() { var jsonObj = eos.getTableRows({ "json": true, "code": "registrar", // contract who owns the table "scope": "registrar", // scope of the table "table": "smedical", // name of the table as specified by the contract abi "limit": 100, }); jsonObj .then(res => { console.log("Updates: " + res.rows[0].pending_updates); console.log("Prescriptions: " + res.rows[0].prescriptions); document.getElementById("pending_text").value = res.rows[0].pending_updates; document.getElementById("prescription_text").value = res.rows[0].prescriptions; document.getElementById("hello").innerHTML = "Hello, " + res.rows[0].forename; }) .catch(e => console.log(e)); } async function bcAcceptAction() { console.log("ACCEPT************"); let actionName = "acceptupd"; let actionData = { _patient: personAccount.name, }; // eosjs function call: connect to the blockchain //const eos = Eos({ keyProvider: privateKey }); const result = await eos.transaction({ actions: [{ account: "registrar", name: actionName, authorization: [{ actor: personAccount.name, permission: 'active', }], data: actionData, }]}, { keyProvider : personAccount.privateKey } ); console.log(result); bcLoadApprovals(); } async function bcRejectAction() { console.log("REJECT************"); let actionName = "rejectupd"; let actionData = { _patient: personAccount.name, }; // eosjs function call: connect to the blockchain //const eos = Eos({ keyProvider: privateKey }); const result = await eos.transaction({ actions: [{ account: "registrar", name: actionName, authorization: [{ actor: personAccount.name, permission: 'active', }], data: actionData, }]}, { keyProvider : personAccount.privateKey } ); console.log(result); bcLoadApprovals(); } async function bcDispensedAction() { console.log("Dispensed************"); let actionName = "dispensed"; let actionData = { _pharmacist: pharmacistAccount.name, _patient: personAccount.name, }; // eosjs function call: connect to the blockchain //const eos = Eos({ keyProvider: privateKey }); const result = await eos.transaction({ actions: [{ account: "registrar", name: actionName, authorization: [{ actor: personAccount.name, permission: 'active', }], data: actionData, }]}, { keyProvider : personAccount.privateKey } ); console.log("dispensed"); } function bcLoadPatientData() { console.log("LoadPatientData************"); var jsonObj = eos.getTableRows({ "json": true, "code": "registrar", // contract who owns the table "scope": "registrar", // scope of the table "table": "smedical", // name of the table as specified by the contract abi "limit": 100, }); jsonObj .then(res => { document.getElementById("medical_history").value = res.rows[0].medical_history; document.getElementById("pending_update").value = res.rows[0].pending_updates; document.getElementById("prescriptions").value = res.rows[0].prescriptions; document.getElementById("fullname").value = res.rows[0].forename + " " + res.rows[0].surname; }) .catch(e => console.log(e)); } async function bcPushUpdate() { console.log("PushUpdate************"); let actionName = "pushupdate"; let updateData = document.getElementById("pending_update").value; console.log(updateData) let actionData = { _doctor: doctorAccount.name, _patient: personAccount.name, _update: updateData, }; // eosjs function call: connect to the blockchain //const eos = Eos({ keyProvider: privateKey }); const result = await eos.transaction({ actions: [{ account: "registrar", name: actionName, authorization: [{ actor: personAccount.name, permission: 'active', }], data: actionData, }]}, { keyProvider : personAccount.privateKey } ); console.log(result); }
/* Event Details Overlay - Full screen overlay - Slides in from bottom of the screen - Displays all known event details */ import styles from './styles/events.module.css' const Overlay = ({ details = Object }) => { // If no rep exists, create an empty array for it. if(!Object.keys(details).includes('repertoire')){ details.repertoire = [] } return ( <div className={styles.overlayWrapper} id="eventOverlay" > <div className={styles.overlayCloseButton} onClick={()=>{document.getElementById('eventOverlay').style.top = '150%'}} > <div /> <div /> </div> <div className={styles.overlayInfo}> <span className={styles.overlayItalic}>{new Date(details.performanceDate * 1000).toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'long', year: 'numeric' })}</span> <span className={styles.overlayItalic}>{details.location}</span> <h1> {details.institution} <span /> </h1> <ul> { details.repertoire.length ? details.repertoire.map((item, i) => ( <li key={i}><strong>{item.composer}</strong> - {item.work}</li> )) : '' } </ul> { details.soloist ? <span className={styles.overlayItalic}> {details.soloist} </span> : '' } { details.status ? <div className={styles.overlayStatus}> {details.status} </div> : '' } </div> </div> ) } export default Overlay
'use strict'; module.exports = function(bunyan){ function ConsoleLoggerStream() {} ConsoleLoggerStream.prototype.write = function (rec) { // eslint-disable-next-line console.log('[%s] %s: %s', rec.time.toISOString(), bunyan.nameFromLevel[rec.level], rec.msg, rec); }; return new ConsoleLoggerStream(); };
export const getPurchases = async () => { let response = await fetch("/api/history"); let history = await response.json(); return history.map(purchase => ({ ...purchase, date: new Date(purchase.date) })); }; export const postPurchase = async purchase => { await fetch("/api/history", { method: "POST", cache: "no-cache", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...purchase, date: purchase.date.toISOString() }) }); }; export const updatePurchases = async setPurchases => { let purchases = await getPurchases(); setPurchases(purchases); };
$(document).delegate('a[data-toggle="slide"]', 'click', function(event) { event.preventDefault(); var $this = $(this); $this.toggleClass('active'); $this.closest('.message-wrapper').toggleClass('comments-open'); $($this.data('target')).slideToggle(); }); // Extending a javascript class if (typeof Object.create !== 'function') { Object.create = function (o) { function F() {} F.prototype = o; return new F(); }; }
const Compra = [12,32,32,53]; const totalCompra = Compra.map( function(Compra){ return (Compra*1.21); }); console.log("funcional - "+totalCompra);
import React,{Component} from 'react'; import { Dimensions, ListView, ScrollView, Image, View, StyleSheet, Text, Platform, TouchableOpacity, RefreshControl, Animated, Easing } from 'react-native'; import { connect } from 'react-redux'; var {height, width} = Dimensions.get('window'); import Icon from 'react-native-vector-icons/FontAwesome'; import Ionicons from 'react-native-vector-icons/Ionicons'; var Popover = require('react-native-popover'); import CreateGroup from './CreateGroup'; import GroupDetail from './GroupDetail'; import AllGroup from './AllGroup'; import { fetchMyGroupList,disableMyGroupOnFresh,enableMyGroupOnFresh,fetchGroupMemberList } from '../../action/ActivityActions'; import { getAccessToken, } from '../../action/UserActions'; class MyGroup extends Component{ goBack(){ const { navigator } = this.props; if(navigator) { navigator.pop(); } } _onRefresh() { this.setState({ isRefreshing: true, fadeAnim: new Animated.Value(0) }); setTimeout(function () { this.setState({ isRefreshing: false, }); Animated.timing( // Uses easing functions this.state.fadeAnim, // The value to drive { toValue: 1, duration: 600, easing: Easing.bounce }, // Configuration ).start(); }.bind(this), 500); this.props.dispatch(enableMyGroupOnFresh()); } showPopover(ref){ this.refs[ref].measure((ox, oy, width, height, px, py) => { this.setState({ menuVisible: true, buttonRect: {x: px+5, y: py+10, width: 200, height: height} }); }); } closePopover(){ this.setState({menuVisible: false}); } setMyGroupList(){ this.props.dispatch(enableMyGroupOnFresh()); } navigate2CreateGroup(){ const { navigator } = this.props; if(navigator) { navigator.push({ name: 'create_group', component: CreateGroup, params: { setMyGroupList:this.setMyGroupList.bind(this), } }) } } navigate2AllGroup(){ const { navigator } = this.props; if(navigator) { navigator.push({ name: 'all_group', component: AllGroup, params: { setMyGroupList:this.setMyGroupList.bind(this), } }) } } navigate2GroupDetail(group){ this.props.dispatch(fetchGroupMemberList(group)) .then((json)=> { if (json.re == 1) { var memberList = json.data; const { navigator } = this.props; if(navigator) { navigator.push({ name:'group_detail', component: GroupDetail, params: { setMyGroupList:this.setMyGroupList.bind(this), groupInfo:group, memberList:memberList, flag:'我的组详情' } }) } }else{ if(json.re==-100){ this.props.dispatch(getAccessToken(false)); } } }) } renderRow(rowData,sectionId,rowId){ var row=( <TouchableOpacity style={{flex:1,flexDirection:'row',backgroundColor:'#fff',marginBottom:5,padding:10}} onPress={()=>{ this.navigate2GroupDetail(rowData); }}> <View style={{flex:1,}}> <Image resizeMode="stretch" style={{height:40,width:40,borderRadius:20}} source={require('../../../img/portrait.jpg')}/> </View> <View style={{flex:3,justifyContent:'center',alignItems: 'center',flexDirection:'row'}}> <Text style={{color:'#343434'}}>{rowData.groupName}</Text> <Text style={{color:'#343434'}}></Text> { rowData.groupManager==this.props.personInfo.personId? <Icon name={'user'} style={{marginLeft:10}} size={18} color="pink"/>:null } </View> <View style={{flex:1,justifyContent:'center',alignItems: 'center',}}> </View> <TouchableOpacity style={{flex:1,justifyContent:'center',alignItems: 'center',margin:10,borderWidth:1,borderColor:'#66CDAA',borderRadius:5}} onPress={()=>{ this.navigate2GroupDetail(rowData); }}> <Text style={{color:'#66CDAA',fontSize:12,}}>详情</Text> </TouchableOpacity> </TouchableOpacity> ); return row; } fetchData(){ this.state.doingFetch=true; this.state.isRefreshing=true; this.props.dispatch(fetchMyGroupList()).then((json)=> { if(json.re==1){ this.props.dispatch(disableMyGroupOnFresh()); this.setState({doingFetch:false,isRefreshing:false}) }else{ if(json.re==-100){ this.props.dispatch(getAccessToken(false)); }else{ this.props.dispatch(disableMyGroupOnFresh()); this.setState({doingFetch:false,isRefreshing:false}) } } }).catch((e)=>{ this.props.dispatch(disableMyGroupOnFresh()); this.setState({doingFetch:false,isRefreshing:false}); alert(e) }); } constructor(props) { super(props); this.state={ doingFetch: false, isRefreshing: false, fadeAnim: new Animated.Value(1), } } render() { var displayArea = {x:5, y:10, width:width-20, height: height - 10}; var groupListView=null; var {myGroupList,myGroupOnFresh}=this.props; if(myGroupOnFresh==true) { if(this.state.doingFetch==false) this.fetchData(); }else { var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); if (myGroupList !== undefined && myGroupList !== null && myGroupList.length > 0) { groupListView = ( <ListView automaticallyAdjustContentInsets={false} dataSource={ds.cloneWithRows(myGroupList)} renderRow={this.renderRow.bind(this)} /> ); } } return ( <View style={{flex:1, backgroundColor:'#eee',}}> <View style={{height:55,width:width,paddingTop:20,flexDirection:'row',justifyContent:'center', backgroundColor:'#66CDAA',borderBottomWidth:1,borderColor:'#66CDAA'}}> <TouchableOpacity style={{flex:1,justifyContent:'center',alignItems: 'center',}} onPress={()=>{this.goBack();}}> <Icon name={'angle-left'} size={30} color="#fff"/> </TouchableOpacity> <View style={{flex:3,justifyContent:'center',alignItems: 'center',}}> <Text style={{color:'#fff',fontSize:18}}>我的群</Text> </View> <TouchableOpacity style={{flex:1,justifyContent:'center',alignItems: 'center',}} onPress={this.showPopover.bind(this, 'menu')} ref="menu"> <Ionicons name='md-add' size={26} color="#fff"/> </TouchableOpacity> </View> <Animated.View style={{opacity: this.state.fadeAnim,height:height-150,borderTopWidth:1,borderColor:'#eee'}}> <ScrollView refreshControl={ <RefreshControl refreshing={this.state.isRefreshing} onRefresh={this._onRefresh.bind(this)} tintColor="#9c0c13" title="刷新..." titleColor="#9c0c13" colors={['#ff0000', '#00ff00', '#0000ff']} progressBackgroundColor="#ffff00" /> } > { groupListView==null? <View style={{justifyContent:'center',alignItems: 'center',marginTop:20}}> <Text style={{color:'#343434'}}>尚未加入任何群组</Text> </View> :null } {groupListView} </ScrollView> </Animated.View> {/*popover part*/} <Popover isVisible={this.state.menuVisible} fromRect={this.state.buttonRect} displayArea={displayArea} onClose={()=>{this.closePopover() }} style={{backgroundColor:'transparent'}} placement="bottom" > <TouchableOpacity style={[styles.popoverContent,{borderBottomWidth:1,borderBottomColor:'#ddd',flexDirection:'row',justifyContent:'flex-start'}]} onPress={()=>{ this.closePopover(); setTimeout(()=>{ this.navigate2AllGroup(); },300); }}> <Ionicons name='md-person-add' size={20} color="#343434"/> <Text style={[styles.popoverText]}>添加群</Text> </TouchableOpacity> <TouchableOpacity style={[styles.popoverContent,{borderBottomWidth:1,borderBottomColor:'#ddd',flexDirection:'row'}]} onPress={()=>{ this.closePopover(); setTimeout(()=>{ this.navigate2CreateGroup(); },300); }}> <Ionicons name='md-add' size={20} color="#343434"/> <Text style={[styles.popoverText]}>创建新群</Text> </TouchableOpacity> </Popover> </View> ); } } var styles = StyleSheet.create({ popoverContent: { width: 90, height: 30, justifyContent: 'center', alignItems: 'center', }, popoverText:{ color:'#444', marginLeft:14, fontWeight:'bold' }, }); module.exports = connect(state=>({ accessToken:state.user.accessToken, personInfo:state.user.personInfo, myGroupList:state.activity.myGroupList, myGroupOnFresh:state.activity.myGroupOnFresh }) )(MyGroup);
var kitty = {};
import classes from './Articles.module.css'; function Articles() { return ( <div className={classes.Articles}> Articles </div> ) } export default Articles;
var path = require('path'); var gulp = require('gulp'); var globule = require('globule'); var watchify = require('watchify'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); gulp.task('browserify', function() { var Bundler = global.isWatching ? watchify : browserify; var bundle = function() { globule.find(path.join(__dirname, '../web/js/**/index.js')).forEach(function(fp) { var entryName = path.basename(path.dirname(fp)); Bundler({ entries: [fp], debug: true }).bundle() .pipe(source(entryName + '.js')) .pipe(gulp.dest('./build/js/')); }); } if (global.isWatching) { // Rebundle with watchify on changes. bundler.on('update', bundle); } return bundle(); });
import React, {useEffect, useState, Fragment} from 'react'; import {useSelector, useDispatch} from 'react-redux'; import Pulse from '../loading/Pulse'; import {clearMessage} from '../../actions/messageActions'; import {addBudget, deleteBudget} from '../../actions/budgetActions'; import Alert from '../alert/Alert'; const Report = ({year, month, category, budget_number, user_id, budget}) => { const dispatch = useDispatch(); const message = useSelector(state => state.message); const budgeData = budget.budget; const loading = budget.loading; //Set message const [isReport, setReport] = useState( { message: null, status: null } ) useEffect(() => { //Add expense if(message.id === 'ADD_BUDGET_FAIL' || message.id === 'ADD_BUDGET_SUCCESS'){ setReport(prevState => { return { ...prevState, message : message.msg.msg, status: message.status } }) } else { setReport(prevState => { return { ...prevState, message : null, status: null } }) } },[message]) const onSubmit = (e) => { e.preventDefault(); //Clear Messages dispatch(clearMessage()); const newBudget = { year_number : parseInt(year), month_name : month, category_name : category === '' ? 'none' : category, budget_number : budget_number === '' ? -1.00 : parseFloat(budget_number).toFixed(2), user_id : user_id } //Add new budget dispatch(addBudget(newBudget)); } const contentLoading = ( <Pulse loadAmount={budgeData.length > 1 ? parseInt(budgeData.length / 2) : 1}/> ) const reportTitle = `${month} ${year} Budget`; let contentLoaded = ''; if(budgeData.length > 0){ contentLoaded = ( <Fragment> <tbody> {budgeData.map(({_id, category_name, budget_number}) => ( <tr key={_id} className="hover:bg-gray-100"> <td className="text-left py-2 px-4 border-b border-gray-500">{category_name}</td> <td className="text-left py-2 px-4 border-b border-gray-500">${parseFloat(budget_number).toFixed(2)}</td> <td className="text-left py-2 px-4 border-b border-gray-500"> <button className="text-gray-200 font-bold py-1 px-3 rounded text-xs bg-red-500 hover:bg-red-700 outline-none focus:outline-none" onClick={() => dispatch(deleteBudget(_id))}>Delete</button> </td> </tr> ))} </tbody> </Fragment> ) } else { contentLoaded = ( <Fragment> <tbody> <tr className="hover:bg-gray-100"> <td colSpan="4" className="text-center py-2 px-4 border-b border-gray-500">NO RECORDS FOUND</td> </tr> </tbody> </Fragment> ) } let returnMessage = ''; if(isReport.message){ returnMessage = ( <Fragment> <div className="w-full mb-4 md:mb-0"> <Alert message={isReport.message} status={isReport.status}/> </div> </Fragment> ) } else { returnMessage = null } const displayReport = ( <Fragment> <div className="flex justify-center mb-2"> <div className="w-full"> <button className="float-right bg-teal-400 text-white hover:bg-teal-600 font-bold uppercase text-sm px-6 py-4 rounded shadow hover:shadow-lg outline-none focus:outline-none mr-1 mb-1" type="button" style={{ transition: "all .15s ease" }} onClick={onSubmit}> Update </button> </div> </div> {returnMessage} <div className="mx-auto"> <h1 className="font-bold text-2xl text-center">{reportTitle}</h1> <div className="bg-white shadow-md rounded my-4"> <table className="w-full border-collapse"> <thead> <tr> <th className="text-left py-3 px-5 bg-blue-500 font-bold uppercase text-sm text-white border-blue-800">Store / Description</th> <th className="text-left py-3 px-5 bg-blue-500 font-bold uppercase text-sm text-white border-blue-800">Budget ($)</th> <th className="text-left py-3 px-5 bg-blue-500 font-bold uppercase text-sm text-white border-blue-800">&nbsp;</th> </tr> </thead> {contentLoaded} </table> </div> </div> </Fragment> ) return ( <div> {loading === true ? contentLoading : displayReport} </div> ) } export default Report;
import Home from './components/home/Home.vue'; import Login from './components/login/Login.vue'; import Pagamento from './components/pagamento/Pagamento.vue' export const routes = [ /* rotas aqui */ { path: '/', component: Login }, { path: '/Home',component: Home }, { path: '/Transferencias', component: Pagamento}, ];