text
stringlengths
7
3.69M
"use strict"; var Router = require("react-router"); var Route = Router.Route; var DefaultRoute = Router.DefaultRoute; var NotFoundRoute = Router.NotFoundRoute; var App = require("./app"); var Home = require("./home/homePage"); var Project = require("./project/projectPage"); var NotFound = require("./notFound"); var routes = ( <Route path="/" handler={App}> <DefaultRoute name="index" handler={Home} /> <Route name="project" path="/projects/:url" handler={Project} /> <NotFoundRoute name="404" handler={NotFound} /> </Route> ); module.exports = routes;
import { storiesOf } from '@storybook/vue'; import { withKnobs, text } from '@storybook/addon-knobs'; import Tile from './Tile'; import Container from './../atoms/Container'; import Column from './../molecules/Column'; import Columns from './../molecules/Columns'; storiesOf('Design System|Molecules/Tile', module) .addDecorator(withKnobs) .add('default', () => { return { components: { Tile }, template: `<div :style="this.style"><Tile image="/img/cacao-bg.jpg" heading="kakaopulver" cta="jetzt entdecken" /></div>`, data: () => ({ style: { width: '505px' } }), }; }) .add('long text', () => { return { components: { Tile }, template: `<div :style="this.style"><Tile image="/img/cacao-bg.jpg" heading="kakaopulver kakaopulver kakaopulver kakaopulver kakaopulver kakaopulver kakaopulver kakaopulver " cta="jetzt entdecken" /></div>`, data: () => ({ style: { width: '505px' } }), }; }) .add('highlight', () => { return { components: { Tile }, template: `<div :style="this.style"><Tile highlight image="/img/cacao-bg.jpg" heading="kakaopulver" cta="jetzt entdecken" /></div>`, data: () => ({ style: { width: '505px' } }), }; }) .add('highlight different color', () => { return { components: { Tile }, template: `<div :style="this.style"><Tile highlight highlightColor="#333333" image="/img/cacao-bg.jpg" heading="kakaopulver" cta="jetzt entdecken" /></div>`, data: () => ({ style: { width: '505px' } }), }; }) .add('highlight knobs', () => { return { components: { Tile }, props: { highlightColor: { default: text("Highlight Color", "#1561ac") } }, template: `<div :style="this.style"><Tile highlight :highlightColor="highlightColor" image="/img/cacao-bg.jpg" heading="kakaopulver" cta="jetzt entdecken" /></div>`, data: () => ({ style: { width: '505px' } }), }; }) .add('no image', () => { return { components: { Tile }, template: `<div :style="this.style"><Tile heading="kakaopulver" cta="jetzt entdecken" /></div>`, data: () => ({ style: { width: '505px' } }), }; }) .add('no image heading and cta', () => { return { components: { Tile }, template: `<div :style="this.style"><Tile /></div>`, data: () => ({ style: { width: '505px' } }), }; }) .add('no max-width', () => { return { components: { Tile }, template: `<div :style="this.style"><Tile image="/img/cacao-bg.jpg" heading="kakaopulver" cta="jetzt entdecken" /></div>`, data: () => ({ style: { } }), }; }, { notes: 'Use different viewports' }) .add('high', () => { return { components: { Tile }, template: `<div :style="this.style"><Tile high image="/img/cacao-bg.jpg" heading="kakaopulver" cta="jetzt entdecken" /></div>`, data: () => ({ style: { width: '505px' } }), }; }) .add('wide', () => { return { components: { Tile }, template: `<div :style="this.style"><Tile wide image="/img/cacao-bg.jpg" heading="kakaopulver" cta="jetzt entdecken" /></div>`, data: () => ({ style: { } }), }; });
module.exports = function(d2) { /** * * @param {Point} pc - arc center * @param {number} w - horizontal radius * @param {number} w - vertical radius * @param {number} startAngle - start angle in degrees from 0 to 360 * @param {number} endAngle - end angle in degrees from -360 to 360 */ d2.Arcellipse = class Arcellipse extends d2.Ellipse { constructor(pc,w,h) { super(pc,w,h); this.startAngle = 20; this.rotation=0; this.endAngle = 190; } clone(){ let copy=new d2.Arcellipse(this.pc.clone(),this.w,this.h); copy.startAngle = this.startAngle; copy.endAngle = this.endAngle; copy.rotation=this.rotation; return copy; } get center(){ return this.pc; } get start() { let angles=this._convert(this.startAngle,this.endAngle); let x=this.pc.x+(this.w*Math.cos(d2.utils.radians(angles[0]))); let y=this.pc.y+(this.h*Math.sin(d2.utils.radians(angles[0]))); let p=new d2.Point(x,y); p.rotate(this.rotation,this.pc); return p; } get sweep(){ return Math.abs(this.endAngle); } get middle() { let angle = this.endAngle>0 ? this.startAngle + this.sweep/2 : this.startAngle - this.sweep/2; let x=this.pc.x+(this.w*Math.cos(-1*d2.utils.radians(angle))); let y=this.pc.y+(this.h*Math.sin(-1*d2.utils.radians(angle))); let p=new d2.Point(x,y); p.rotate(this.rotation,this.pc); return p; } get end() { let angles=this._convert(this.startAngle,this.endAngle); let x=this.pc.x+(this.w*Math.cos(d2.utils.radians(angles[1]))); let y=this.pc.y+(this.h*Math.sin(d2.utils.radians(angles[1]))); let p=new d2.Point(x,y); p.rotate(this.rotation,this.pc); return p; } get vertices(){ this.vert[0].set(this.pc.x-this.w,this.pc.y); this.vert[1].set(this.pc.x,this.pc.y-this.h); this.vert[2].set(this.pc.x+this.w,this.pc.y); this.vert[3].set(this.pc.x,this.pc.y+this.h); let s=this.start; let e=this.end; this.vert[4].set(s.x,s.y); this.vert[5].set(e.x,e.y); return this.vert; } contains( x, y) { var c=super.contains(x, y); if(!c) { return c; } let l=new d2.Line(this.start,this.end); let result=l.isLeftOrTop(this.middle); //are they on the same line side? return (l.isLeftOrTop(new d2.Point(x,y))==result); } isPointOn(pt,diviation){ //same as ellipse let alpha=-1*d2.utils.radians(this.rotation); let cos = Math.cos(alpha), sin = Math.sin(alpha); let dx = (pt.x - this.pc.x), dy = (pt.y - this.pc.y); let tdx = cos * dx + sin * dy, tdy = sin * dx - cos * dy; let pos= (tdx * tdx) / (this.w * this.w) + (tdy * tdy) / (this.h * this.h); let v=new d2.Vector(this.pc,pt); let norm=v.normalize(); //1.in if(pos<1){ let xx=pt.x +diviation*norm.x; let yy=pt.y +diviation*norm.y; //check if new point is out if(super.contains(xx,yy)){ return false; } }else{ //2.out let xx=pt.x - diviation*norm.x; let yy=pt.y - diviation*norm.y; //check if new point is in if(!this.contains(xx,yy)){ return false; } } //narrow down to start and end point/angle let start=new d2.Vector(this.pc,this.start).slope; let end=new d2.Vector(this.pc,this.end).slope; let clickedAngle =new d2.Vector(this.pc,pt).slope; if(this.endAngle>0){ if(start>end){ return (start>=clickedAngle)&&(clickedAngle>=end); }else{ return !((start<=clickedAngle)&&(clickedAngle<=end)); } }else{ if(start>end){ return !((start>=clickedAngle)&&(clickedAngle>=end)); }else{ return (start<=clickedAngle)&&(clickedAngle<=end); } } } _convert(start,extend){ let s = 360 - start; let e=0; if(extend>0){ e = 360 - (start+extend); }else{ if(start>Math.abs(extend)){ e = s+Math.abs(extend); }else{ e = Math.abs(extend+start); } } return [s,e]; } mirror(line){ this.pc.mirror(line); this.endAngle=-1*this.endAngle; if(line.isVertical){ if(this.startAngle>=0&&this.startAngle<=180){ this.startAngle=180-this.startAngle; }else{ this.startAngle=180+(360-this.startAngle); } }else{ this.startAngle=360-this.startAngle; } } paint(g2){ g2.beginPath(); //d2.utils.drawCrosshair(g2,5,[this.start,this.end]); let alpha=this.convert(this.rotation); let angles=this._convert(this.startAngle,this.endAngle); g2.beginPath(); g2.ellipse(this.pc.x,this.pc.y,this.w, this.h,alpha,d2.utils.radians(angles[0]), d2.utils.radians(angles[1]),this.endAngle>0); if(g2._fill!=undefined&&g2._fill){ g2.fill(); }else{ g2.stroke(); } } } }
// @flow import { createStore, combineReducers, compose, applyMiddleware } from 'redux' import logger from 'redux-logger' import reducer from '../../domain/redux/client/reducers' const reducers = combineReducers({ domain: reducer, }) const middlewareList = [ logger, ] const store = createStore( reducers, compose(applyMiddleware(...middlewareList)) ) export default store
import styled from 'styled-components'; const ScreenLabel = styled.h1` color: #ffffff; `; export default ScreenLabel;
import React, {useState} from 'react'; import Skeleton from '@material-ui/lab/Skeleton'; import Auxi from '../hoc/auxi'; import { makeStyles } from '@material-ui/core/styles'; import PropTypes from 'prop-types'; const useStyles = makeStyles((theme) => ({ modalImage: { width: '100%', height: 'auto', marginBottom: 10 }, media: { width: '100%', height: 140, } })); const ImageComp = (props) => { const classes = useStyles(); let [imageLoaded, setImageLoaded] = useState(false); let imageSrc = (!props.src || props.src === "N/A") ? "/noimage.gif" : props.src; return ( <Auxi> <Skeleton style={imageLoaded ? {display: 'none'} : {}} animation="wave" variant="rect" className={classes.media} /> <img className={classes.modalImage} style={!imageLoaded ? {display: 'none'} : {}} onLoad={() => setImageLoaded(true)} alt={props.alt ? props.alt : ""} height="140" src={imageSrc} /> </Auxi> ); } ImageComp.propTypes = { src: PropTypes.string, alt: PropTypes.string } export default ImageComp;
import React from 'react'; import Todoitem from './todo-item/todoitem'; class Todocontainer extends React.Component { constructor(props){ super(props); } render(){ const todosList = this.props.todos.map(c => <Todoitem todo={c}></Todoitem>); return ( <ul> {todosList} </ul> ); } } export default Todocontainer;
const express = require('express'); const router = express.Router(); const orderController = require('../controllers/order'); router.post('/add', orderController.postOrder); router.get('/detail', orderController.getDetail); module.exports = router;
var express = require("express"); var app = express(); var bodyParser = require("body-parser"); var router = express.Router() router.use(bodyParser.urlencoded({ extended: true })); router.use(bodyParser.json()); var logic = require("./logic"); var model = require("./model"); router.get("/clear", function (req, res) { model.set(0); res.render("index.ejs", { initialValue: 1, result: 0, currency: "" }) // establed an obj to be viewed on the index, AND that data(key) on the index.ejs page's to be set w properties in db(above) }); router.get("/convert", function (req, res) { res.render("index.ejs", { initialValue: 1, result: 0, currency: "" }) }); router.post("/convert", function (req, res) { model.set(req.body.number); var number = model.get(); var direction = req.body.direction ? true : false; var result = logic.convert(number, direction); var currency = direction ? "$" : "€"; res.render("index.ejs", { initialValue: number, result: result, currency: currency }); }); router.get("/", function (req, res) { res.render("index.ejs", { initialValue: 1, result: 0, currency: "" }); }); // establed an obj to be viewed on the index, AND that data(key) on the index.ejs page's to be set w properties in db(above) router.use("", function (req, res) { res.status(404).send("404: Page not found"); }); module.exports = router; // where do I keep router?
// FINCAD // React Assignment - Janurary 28, 2017 // Chedwick Montoril // License MIT // Internal dependencies. import PHOTOS from './constants'; export function getAlbum(albumId) { return { type: PHOTOS.GET_ALBUM, albumId }; } export function getAlbums() { return { type: PHOTOS.GET_ALBUMS }; } export function getPhoto(photoId) { return { type: PHOTOS.GET_PHOTO, photoId }; } export function consumeAlbum(album) { return { type: PHOTOS.CONSUME_ALBUM, album }; } export function consumeAlbums(albums, users) { return { type: PHOTOS.CONSUME_ALBUMS, albums, users }; } export function consumePhoto(photo) { return { type: PHOTOS.CONSUME_PHOTO, photo }; }
import React, {useReducer} from 'react'; import logo from './logo.svg'; import './App.css'; import {ContextApp, initialState, reducer} from "./reducers/reducer.js"; import Form from "./components/Form/Form"; import UrlList from "./components/UrlList/UrlLIst"; const StoreContext = React.createContext(initialState); const App = () => { const [state, dispatch] = useReducer(reducer, initialState); return ( <ContextApp.Provider value={{dispatch, state}}> <div className={'wrapper'}> <UrlList /> <Form /> </div> </ContextApp.Provider> ) }; export default App;
import * as Sentry from 'sentry-expo' var { hashRiskPoint } = require('./risk') // Can add multiple servers export const SALT_SERVERS = [ __DEV__ ? 'http://localhost:3000/dev/get-salt' : 'https://13ua7sp8li.execute-api.eu-central-1.amazonaws.com/production/get-salt' ] /** * Gets salts for risk points. * @param {string} serverUrl The url to get salts from * @param {string} dtos[0].preSaltHash A seed string for our new salt * @param {number} dtos[0].timestamp The timestamp of what point in time this * data point represents. If it isn't recent, the server will error. */ export const getSalts = async function(serverUrl, dtos){ var response = await fetch(serverUrl, { method: 'post', body: JSON.stringify({ seeds: dtos.map(dto => ({ seed: dto.preSaltHash, timestamp: dto.timestamp, })) }), }) var result = await response.json() if (response.status != 200){ Sentry.captureMessage(JSON.stringify(result)) throw new Error('Unable to get salts.') } return result['hashes'] }
//require Employee from the proper path const { TestScheduler } = require("jest"); const Employee = require("../lib/Employee"); //create a test that will check for: //if employee is an object test("Employee is an object", function() { const e = new Employee(); expect(typeof(e)).toBe("object"); }) //if you can set the name test("Can set employee name", function () { const name = "Rose"; const e = new Employee(name); expect(e.name).toBe(name); }); //can set the ID test("Can set employee id", function() { const testId = 80; const e = new Employee("Rose", testId); expect(e.id).toBe(testId); }) //can set emp email test("Can set employee email", () => { const testEmail = "hi@hi.com"; const e = new Employee("Rose", 30, testEmail); expect(e.email).toBe(testEmail); }); //can get name with proper function test("getName function returns name", () => { const testName = "Rose"; const e = new Employee(testName); expect(e.getName()).toBe(testName); }); //can get id with proper function test("getId function returns id", () => { const testId = 6; const e = new Employee("Rose", testId); expect(e.getId()).toBe(testId); }); //can get email with proper function test("getEmail function returns email", () => { const testEmail = "Hi@hi.com"; const e = new Employee("Rose", 8, testEmail); expect(e.getEmail()).toBe(testEmail); }); //can return the proper role test("getRole function returns employee", () => { const testRole = "Employee"; const e = new Employee ("Rose", 5, "hi@hi2.com"); expect(e.getRole()).toBe(testRole); });
import React, { Component } from 'react'; import './App.css'; import store from "./store" import AllBooks from "./components/AllBooks/AllBooks" import BookForm from "./components/BookForm/BookForm" class App extends Component { constructor() { super(); this.state = { showAddBookButton: false, showEditBookButton: false } } _showAddBookButton = (bool) => { if (this.state.showForm === false) { this.setState({ showForm: true }) } else { this.setState({ showForm: false }) } }; render() { return ( <div className="App"> <div className='title'> <h1>My Library</h1> </div> <div className='add-btn-container'> <button className='add-btn' onClick={this._showAddBookButton}>Add</button> {this.state.showForm && (<BookForm store={store} />)} <AllBooks /> </div> </div> ); } } export default App;
export default class UniqueExtension { constructor(naja) { naja.addEventListener('interaction', this.checkUniqueness.bind(this)); naja.addEventListener('before', this.abortPreviousRequest.bind(this)); naja.addEventListener('complete', this.clearRequest.bind(this)); } xhr = null; checkUniqueness({element, options}) { options.unique = element.getAttribute('data-naja-unique') !== 'off'; } abortPreviousRequest({xhr, options}) { if (!!this.xhr && options.unique !== false) { this.xhr.abort(); } this.xhr = xhr; } clearRequest() { this.xhr = null; } }
const mongoose = require('mongoose'); const Schema = mongoose.Schema; // Create Schema const PortfolioSchema = new Schema ({ user:{ type: Schema.Types.ObjectId, ref:'companies' }, handle:{ type: String, required:true, max:40 }, phone: { type:String, required:true }, website: { type:String, required:true }, address: { city: { type:String, //required:true }, country: { type:String, //required:true }, }, description:{ type:String, required:true }, social:{ youtube :{ type:String }, twitter :{ type:String }, facebook :{ type:String }, linkedin :{ type:String }, instagram :{ type:String }, date:{ type:Date, default:Date.now } }, }); module.exports = Portfolio = mongoose.model('portfolios',PortfolioSchema);
var fireData = new Firebase("https://inncubator-booking.firebaseio.com"); $(document).ready(function() { $("#add").click(function() { var property = $("#houseName").val(); var guestName = $("#guestName").val(); var guestLastName = $("#guestLastName").val(); var guestID = guestName + "-" + guestLastName; guestID = guestID.toLowerCase(); var startDate = $("#start").val(); var endDate = $("#end").val(); var paymentStatus = $("#paymentStatus").val(); var email = $("#email").val(); fireData.once("value", function(snapshot) { var totalNumberOfGuests = snapshot.numChildren(); var arrayOfGuestsToCompareAgainst = []; fireData.on("child_added", function(snapshot) { guestLoopedThrough = snapshot.val(); guestLoopedThroughName = guestLoopedThrough.title; console.log(guestLoopedThroughName); arrayOfGuestsToCompareAgainst.push(guestLoopedThroughName.toLowerCase()); if (arrayOfGuestsToCompareAgainst.length == totalNumberOfGuests) { console.log(arrayOfGuestsToCompareAgainst); if (arrayOfGuestsToCompareAgainst.indexOf(guestID) > 0) { alert("THIS GUEST IS ALREADY IN THE SYSTEM"); fireData.on("child_added", function(snapshot) { var guestInfoOfFinalLoop = snapshot.val(); if (guestInfoOfFinalLoop.title == guestID) { var duplicateGuestInfo = "<!DOCTYPE html><head></head><body><h1>" + guestInfoOfFinalLoop.title + "</h1><h3>" + guestInfoOfFinalLoop.location + "</h3><h3>" + guestInfoOfFinalLoop.start + "</h3><h3>" + guestInfoOfFinalLoop.end + "</h3><h3>" + guestInfoOfFinalLoop.status + "</h3></body>"; var displayPage = window.open(); displayPage.document.write(duplicateGuestInfo); }; }); } else {; fireData.push({ start: startDate, end: endDate, title: guestID, status: paymentStatus, email: email, location: property, }); alert("You are about to add " + guestID + " " + "to " + property + " starting on: " + startDate + " and ending on: " + endDate) window.location.reload(); }; }; }); }); }); });
const mkdirp = require ('mkdirp'); const rimraf = require('rimraf'); const Store = require('../lib/models/index'); describe('Store', () => { let store = null; beforeEach(done => { rimraf('./testData/store', err => { done(err); }); }); beforeEach(done => { mkdirp('./testData/store', err => { done(err); }); }); beforeEach(() => { store = new Store('./testData/store'); }); it('creates an object in my store', done => { store.create({ name: 'ryan' }, (err, createdPerson) => { expect(err).toBeFalsy(); expect(createdPerson).toEqual({ name: 'ryan', _id: expect.any(String) }); done(); }); }); it('finds an object by id', done => { store.create({ name: 'sophie' }, (err, createdPerson) => { store.findById(createdPerson._id, (err, foundPerson) => { expect(err).toBeFalsy(); expect(foundPerson).toEqual({ name: 'sophie', _id: createdPerson._id }); done(); }); }); }); it('find all objects tracked by the store', done => { store.create({ name: 'ryan' }, (err, person1) => { store.create({ name: 'mariah' }, (err, person2) => { store.create({ name: 'kevin' }, (err, person3) => { store.create({ name: 'marty' }, (err, person4) => { store.create({ name: 'shannon' }, (err, person5) => { store.find((err, listOfPeople) => { expect(err).toBeFalsy(); expect(listOfPeople).toHaveLength(5); expect(listOfPeople).toContainEqual(person1); expect(listOfPeople).toContainEqual(person2); expect(listOfPeople).toContainEqual(person3); expect(listOfPeople).toContainEqual(person4); expect(listOfPeople).toContainEqual(person5); done(); }); }); }); }); }); }); }); it('deletes an object with an id', done => { store.create({ person: 'I am going to delete' }, (err, createdPerson) => { store.findByIdAndDelete(createdPerson._id, (err, result) => { expect(err).toBeFalsy(); expect(result).toEqual({ deleted:1 }); store.findById(createdPerson._id, (err, foundPerson) => { expect(err).toBeTruthy(); expect(foundPerson).toBeFalsy(); done(); }); }); }); }); it('updates an existing object', done => { store.create({ name: 'meghan' }, (err, typoCreated) => { store.findByIdAndUpdate(typoCreated._id, { name: 'megan' }, (err, updatedWithoutTypo) => { expect(err).toBeFalsy(); expect(updatedWithoutTypo).toEqual({ name: 'megan', _id: typoCreated._id }); store.findById(typoCreated._id, (err, foundPerson) => { expect(foundPerson).toEqual(updatedWithoutTypo); done(); }); }); }); }); });
import React from 'react'; import ReactDOM from 'react-dom'; import TodoList from './components/ToDoList' import './index.css'; function App() { return ( <div className="ToDoList"> <TodoList/> </div> ); } ReactDOM.render(<App />, document.getElementById('root'));
import Dashboard from "views/Dashboard/Dashboard.jsx"; import About from "../views/About/About"; import Logout from "../layouts/Logout/Logout"; import CreateAdvert from "../views/CreateAdvert/CreateAdvert"; import ManageAdverts from "../views/ManageAdverts/ManageAdverts"; import Reports from "../views/Reports/Reports"; import CreditMarket from "../views/CreditMarket/CreditMarket"; var dashRoutes = [ { path: "/dashboard", name: "Dashboard", icon: "fa fa-tachometer-alt", component: Dashboard }, { path: "/credit", name: "Credit Market", icon: "fas fa-fill-drip", component: CreditMarket }, { path: "/create", name: "Create Advert", icon: "fas fa-plus-square", component: CreateAdvert }, { path: "/manage", name: "Manage Adverts", icon: "fas fa-dice-d20", component: ManageAdverts }, { dynamic: true, path: "/reports/:advert_id", component: Reports }, { path: "/reports", name: "Reports", icon: "fas fa-chart-pie", component: Reports }, { path: "/about", name: "About", icon: "fas fa-bell", component: About }, { path: "/logout", name: "Logout", icon: "fas fa-sign-out-alt", component: Logout }, { redirect: true, path: "/", pathTo: "/dashboard", name: "Dashboard" } ]; export default dashRoutes;
if (localStorage.getItem('_feature._enabled') !== null && JSON.parse(localStorage.getItem('_feature._enabled')) === true) { chrome.runtime.sendMessage({ event: 'usesFeatureToggle' }); }
let dia = 'sexta'; let resultado = dia == 'domingo' ? 'Vou a praia' : 'Fico em casa'; switch (dia) { case 'segunda': console.log('Vou tomar café'); break; case 'quarta': console.log('Vou no cinema'); break; default: console.log('Eu não vou fazer nada!'); }
/* Import */ var chai = require('chai'); var assert = chai.assert; /* Shorten var names */ var Network = neataptic.Network; var Methods = neataptic.Methods; var Config = neataptic.Config; /* Turn off warnings */ Config.warnings = false; /******************************************************************************************* Tests the effectiveness of evolution *******************************************************************************************/ describe('Neat', function () { it('AND', function () { this.timeout(40000); // Train the AND gate var trainingSet = [{ input: [0, 0], output: [0] }, { input: [0, 1], output: [0] }, { input: [1, 0], output: [0] }, { input: [1, 1], output: [1] }]; var network = new Network(2, 1); network.evolve(trainingSet, { mutation: Methods.Mutation.FFW, equal: true, elitism: 10, mutationRate: 0.5, error: 0.03 }); // Get average and check if it's enough var test = network.test(trainingSet); assert.isBelow(test.error, 0.03); }); it('XOR', function () { this.timeout(40000); // Train the XOR gate var trainingSet = [{ input: [0, 0], output: [0] }, { input: [0, 1], output: [1] }, { input: [1, 0], output: [1] }, { input: [1, 1], output: [0] }]; var network = new Network(2, 1); network.evolve(trainingSet, { mutation: Methods.Mutation.FFW, equal: true, elitism: 10, mutationRate: 0.5, error: 0.03 }); // Get average and check if it's enough var test = network.test(trainingSet); assert.isBelow(test.error, 0.03); }); it('XNOR', function () { this.timeout(60000); // Train the XNOR gate var trainingSet = [{ input: [0, 0], output: [1] }, { input: [0, 1], output: [0] }, { input: [1, 0], output: [0] }, { input: [1, 1], output: [1] }]; var network = new Network(2, 1); network.evolve(trainingSet, { mutation: Methods.Mutation.FFW, equal: true, elitism: 10, mutationRate: 0.5, error: 0.03 }); // Get average and check if it's enough var test = network.test(trainingSet); assert.isBelow(test.error, 0.03); }); });
var files________4____8js__8js_8js = [ [ "files____4__8js_8js", "files________4____8js__8js_8js.html#adb147a86c4e5837337240286370df47d", null ] ];
import { fromJS } from 'immutable'; import { setUser, setRepositories, setError } from '../src/actions/actions.js'; import reducer from '../src/reducer/reducer.js'; describe('Reducer', () => { let state; beforeEach(() => { state = reducer(undefined, setUser('testuser')) }); it('should set the user name and wait for repositories', () => { state.should.eql(fromJS({ user: 'testuser', waitForRepos: true, repositories: [], error: null })); }); it('should set the repositories', () => { let testRepos = ['repo1', 'repo2', 'repo3']; reducer(state, setRepositories(testRepos)).should.eql(fromJS({ user: 'testuser', waitForRepos: false, repositories: ['repo1', 'repo2', 'repo3'], error: null })); }); it('should set errors and clear repos', () => { let state = fromJS({ user: 'testuser', waitForRepos: true, repositories: ['some', 'old', 'repos'], error: null }) reducer(state, setError('Some Error')).should.eql(fromJS({ user: 'testuser', waitForRepos: false, repositories: [], error: 'Some Error' })); }); });
app.service('getIngredients', ['$http', function($http){ var getIngredients = {}; this.getSome = function(){ return $http.get('../../json/ingredients.json'); } }]) app.service('food2forkAjaxCall', ['$http', function($http){ var food2forkAjaxCall = {}; this.getData = function(userIngredients){ userIngredients= userIngredients.join(',') console.log(userIngredients); return $http.get('/api/' + userIngredients) // return $http.get('../../json/food2forkdatasample.json'); } }])
const log = console.log; const searchForm = document.querySelector( "#query-form" ); searchForm.addEventListener( "submit", e => { e.preventDefault(); let searchTerm = document.querySelector( "#search" ).value; fetch( `/weather?address=${ searchTerm }` ) .then( (res) => { return res.json(); }) .then( (data) => { document.querySelector( ".search-results" ).style.display = "block"; document.querySelector( ".address" ).innerHTML = `You searched for: <span style="color: #cb2728; text-decoration: underline;">${ data[0].address }</span>`; document.querySelector( ".location" ).innerHTML = data[0].location; document.querySelector( ".forecast" ).innerHTML = data[0].forecast; }) .catch( (err) => { log( err ); }); });
import { getHourTextWithMinutes, getFormatedDate } from '../utilities' import { hours, hourHeight } from '../constants' import React from 'react'; import './day.css'; function EventHTML(props) { const divStyle = { height: (props.event.endTime - props.event.startTime) * hourHeight + 'px', top: (props.event.startTime) * hourHeight + 'px', } return <div className="active" style={divStyle}> <div> {props.event.summary}</div> <div> {props.event.startTime ? getHourTextWithMinutes(props.event.startTime) + '-' : ''} {props.event.endTime ? getHourTextWithMinutes(props.event.endTime) : ''}</div> </div>; } function Day(props) { const events = props.event.map((e, index) => { return <EventHTML key={index} event={e} /> }) const hoursMapped = hours.map((hour) => { let divStyle = { height: (hourHeight - 1) + 'px' } return ( <div className="hour" style={divStyle} key={hour.value}> <div className="half-hour-break" ></div> </div> ); }); return ( <div className="day" > <div className="day-name">{props.day} </div> <div className={"hour-container " + (props.day === getFormatedDate(new Date()) ? 'is-today' : '')}> {events} {hoursMapped} </div> </div > ); } export { Day }
import express from 'express'; import todo from './todo'; import done from './done'; let api = express.Router(); api.use('/todo', todo); api.use('/done', done); export default api;
/* * C.UI.Popup //TODO description */ 'use strict'; /** * Creates a popup * * @class Popup * @namespace C * @constructor * @param {C.Feature} feature Feature linked to the popup * @param {Object} options Data * @param {String} options.content Popup content. * @param {Boolean} [options.auto] Open popup when added. * @example * var popup = C.Popup(your_feature, { * content: '<span>content</span>' * }); */ C.UI.Popup = C.Utils.Inherit(function (base, feature, options, initialized) { options = options || {}; base(); this.feature = feature; this._initialized = false; this._content = options.content; this._opened = false; this._initializedCallback = initialized; this._metadata = options.metadata || {}; this.dom = document.createElement('div'); this.dom.className = 'popup-container'; this._wrapper = document.createElement('div'); this._wrapper.className = 'popup-wrapper'; this._selector = $(this._wrapper); var tip = document.createElement('div'); tip.className = 'popup-tip-container'; tip.innerHTML = '<div class="popup-tip"></div>'; var close = document.createElement('a'); close.innerHTML = 'x'; close.className = 'popup-close'; close.href = '#'; var self = this; close.addEventListener('click', function () { self.close(); }); this.dom.appendChild(this._wrapper); this.dom.appendChild(tip); this.dom.appendChild(close); if (options.auto) { this.open(); } }, EventEmitter, 'C.UI.Popup'); /* * Constructor */ C.UI.Popup_ctr = function (args) { return C.UI.Popup.apply(this, args); }; C.UI.Popup_ctr.prototype = C.UI.Popup.prototype; C.UI.Popup_new_ctr = function () { var obj = new C.UI.Popup_ctr(arguments); obj._context = this; return obj }; C.UI.Popup.prototype.$ = function (selector) { return this._selector.find(selector); }; /** * Open the popup * * @method open * @public * @param {Event} event Event from click event on feature. */ C.UI.Popup.prototype.open = function (event) { this._opened = true; if (!this._initialized) { this._initialized = true; var self = this; this._context._module.ui.renderTemplate(this._content, function (err, output) { if (err) { return; } self._wrapper.innerHTML = output; C.UI.PopupManager.register(self, event); if (self._initializedCallback) { self._initializedCallback(self); } }); } else { C.UI.PopupManager.register(this, event); } }; /** * Set a metadata * * @method set * @public * @param {Object} key Key link to value. * @param {Object} value Value to store. * @return {Object} Added value. */ C.UI.Popup.prototype.set = function (key, value) { this._metadata[key] = value; return value; }; /** * Get a metadata * * @method get * @public * @param {Object} key Key link to value. * @return {Object} Key value or null if not found. */ C.UI.Popup.prototype.get = function (key) { if (key in this._metadata) { return this._metadata[key]; } return null; }; /** * Close the popup * * @method close * @public */ C.UI.Popup.prototype.close = function () { this._opened = false; C.UI.PopupManager.unregister(this); this.emit('close', this); }; C.UI.Popup.prototype.toggle = function (event) { if (this._opened) { this.close(); } else { this.open(event); } };
module.exports = (sequelize, DataTypes) => { const requests = sequelize.define('requests', { tipo: DataTypes.STRING, comentario: DataTypes.TEXT, }, {}); requests.associate = (models) => { // associations can be defined here. This method receives a models parameter. requests.locals = requests.belongsTo(models.locals, { foreignKey: { allowNull: false } }); }; return requests; };
"use strict"; /** * Created by srayker on 12/10/2015. */ define(['jquery', 'pcs/charts/visualization/viewModel/util/visualizationUtil'], function($, utils){ var self = this; //Object for maintaining all service path information var paths = { 'applicationNameList' : 'ootbqueries/APPLICATION_NAME_LIST', 'datasources' : 'businessquery-metadata/datasources', 'columnsListByApp' : 'businessquery-metadata/datasources/{dataSource}/columns?applicationName={appName}', 'processList' : 'ootbqueries/PROCESS_LABEL_LIST', 'aggregateOperations' : 'businessquery-metadata/aggregateoperations', 'comparisonOperators': 'businessquery-metadata/comparisonoperators', 'businessQuery' : 'businessquery', 'businessQueries' : 'businessquery-metadata/businessqueries', 'businessQueryById' : 'businessquery-metadata/businessqueries/{businessQueryId}' }; var authInfo = ""; var baseRestURL = ""; // Handle errors during a ajax call function ajaxErrorHandler(jqXHR){ var defaultErrMsg = oj.Translations.getTranslatedString('vis.error_msg.data_fetch_error'); if(jqXHR.status === 400 || jqXHR.status === 500){ var respJSON = $.parseJSON(jqXHR.responseText); var respMsg = respJSON && respJSON.detail ? respJSON.detail : defaultErrMsg; utils.errorHandler('', respMsg); } else if (jqXHR.status !== 403 && jqXHR.status !== 404 && jqXHR.status !== 204){ utils.errorHandler('', defaultErrMsg); } } // wrapper function for HTTP GET var doGet = function(url){ utils.drilldown(); return doAjax(url, 'GET'); }; // wrapper function for HTTP POST var doPost = function(url, payload){ utils.drilldown(); return doAjax(url, 'POST', payload); }; // wrapper function for HTTP PUT var doPut = function(url, payload){ utils.drilldown(); return doAjax(url, 'PUT', payload); }; // wrapper function for HTTP DELETE var doDelete = function(url, payload){ utils.drilldown(); return doAjax(url, 'DELETE', payload); }; //AJAX utility function var doAjax = function(url, method, payload){ var promise = $.ajax ({ type: method, url: url, data: payload, beforeSend: function (xhr) { if(authInfo) { xhr.setRequestHeader('Authorization', authInfo); } }, xhrFields: { withCredentials: true }, contentType: 'application/json', dataType: 'json', error: function(jqXHR){ ajaxErrorHandler(jqXHR); } }); return promise; }; var replacePlaceHolders = function(str, paramsObj){ return str.replace(/{\w+}/g, function(placeHolder) { return paramsObj[placeHolder]; } ); }; //List of services var services = { setAuthInfo : function(data){ authInfo = data; }, setBaseRestURL : function(data){ baseRestURL = data }, getAppNameList : function(){ var serverPath = baseRestURL + paths.applicationNameList; return doGet(serverPath); }, getDataSourceList : function(){ var serverPath = baseRestURL + paths.datasources; return doGet(serverPath); }, getColumnListByApp : function(params){ var serverPath = baseRestURL + paths.columnsListByApp; serverPath = replacePlaceHolders(serverPath, params); return doGet(serverPath); }, getProcessList : function(){ var serverPath = baseRestURL + paths.processList; return doGet(serverPath); }, getAggregateOperations : function(){ var serverPath = baseRestURL + paths.aggregateOperations; return doGet(serverPath); }, getComparisonOperators : function(){ var serverPath = baseRestURL + paths.comparisonOperators; return doGet(serverPath); }, getChartData : function(payload){ var serverPath = baseRestURL + paths.businessQuery; return doPost(serverPath, payload); }, getSavedQueries : function(){ var serverPath = baseRestURL + paths.businessQueries; return doGet(serverPath); }, saveQuery : function(payload){ var serverPath = baseRestURL + paths.businessQueries; return doPost(serverPath, payload); }, updateQuery : function(payload, params){ var serverPath = baseRestURL + paths.businessQueryById; serverPath = replacePlaceHolders(serverPath, params); return doPut(serverPath, payload); }, deleteQuery : function(params){ var serverPath = baseRestURL + paths.businessQueryById; serverPath = replacePlaceHolders(serverPath, params); return doDelete(serverPath); }, getQuery : function(params){ var serverPath = baseRestURL + paths.businessQueryById; serverPath = replacePlaceHolders(serverPath, params); return doGet(serverPath); } }; return services; } );
const btn = document.getElementById('btn'); const btn1 = document.getElementById('btn1'); const recipe_wrap = document.getElementById('recipe_wrap'); let wrap = document.getElementById('recipe_wrap'); let recipeContent = document.getElementById('recipe_content'); btn1.addEventListener('click', loadDatos); function loadDatos(){ const ourRequest = new XMLHttpRequest(); ourRequest.open('GET', 'js/recipes.json', true); ourRequest.send(); ourRequest.onreadystatechange = function() { if(this.readyState === 4 && this.status === 200) { // console.log(this.responseText); let dados = JSON.parse(this.responseText); // console.log(dados); let newDados = dados.slice(0,10); wrap.innerHTML = ''; for(let item of newDados) { // console.log(item.Name); wrap.innerHTML += ` <div id="recipe_content"> <div class="content_text"> <h2 class="Name">${item.Name}</h2> <h3 class="url"><a href="${item.url}">${item.url}</a></h3> <h3 class="Description">Description: <br> ${item.Description}</p></h3> <h3 class="Author">Author: ${item.Author}</h3> </div> <div class="content_img"> <img src="img/foto.jpg" alt=""> </div> </div> <div class="recipe_method"> <div class="ingredients-wrap"> <h3>Ingredients:</h3> <ul class="ingredients"> <li>${item.Ingredients}<li> </ul> </div> <div class="method-wrap"> <h3>Method:</h3> <ul class="method"> <li>${item.Method}</li> </ul> </div> </div> ` } } }; };
var name = prompt ('Enter your name', 'Petro'), myEvent = prompt ('Enter the event you have to visit', 'meeting'), place = prompt ('Enter the place you need to be', 'Milan'), time = prompt ('Enter the time', 'today at 17:00'), output; if (name && myEvent && place && time) { output = name + ' has a ' + myEvent + ' ' + time + ' in ' + place; //result in console console.log(output); document.querySelector('.main-text').innerHTML = 'Great, thank you!'; } else { document.querySelector('.main-text').innerHTML = 'Please, refresh the page and fill in all of the fields.'; }
let gameProgress = [] function play(id){ let playerSpan = document.getElementById("player") let clickedId = document.getElementById(id) if(playerSpan.innerText === "X"){ playerSpan.innerText = "O" clickedId.innerText = "X" gameProgress.push("X") console.log(gameProgress) }else{ playerSpan.innerText = "X" clickedId.innerText = "O" gameProgress.push("O") gameProgress[id] = "0" console.log(gameProgress) } let topLeft = gameProgress[0] let topMiddle = gameProgress[1] let topRight = gameProgress[2] let middleLeft = gameProgress[3] let center = gameProgress[4] let middleRight = gameProgress[5] let bottomLeft =gameProgress[6] let bottomMiddle = gameProgress[7] let bottomRight = gameProgress[8] console.log(gameProgress) if(topRight !== undefined && topRight === topMiddle && topRight === topLeft){ alert(`Congrats ${topRight} is the winner!`) } if(middleRight !== undefined && middleRight === center && middleRight === middleLeft){alert(`Congrats ${topRight} is the winner!`) } if(bottomRight !== undefined && bottomRight === bottomMiddle && bottomRight === bottomLeft){alert(`Congrats ${topRight} is the winner!`) } if(topRight !== undefined && topRight === middleRight && topRight === bottomLeft){alert(`Congrats ${topRight} is the winner!`) } if(topMiddle !== undefined && topMiddle === center && topMiddle === bottomMiddle){alert(`Congrats ${topRight} is the winner!`) } if(topLeft !== undefined && topLeft === middleLeft && topLeft === bottomLeft){alert(`Congrats ${topRight} is the winner!`) } if(topRight !== undefined && topRight === center && topRight === bottomLeft){alert(`Congrats ${topRight} is the winner!`) } if(topLeft !== undefined && topLeft === center && topLeft === topRight){alert(`Congrats ${topRight} is the winner!`) } console.log("Worked") }//console.log(gameProgress[0]) // console.log(gameProgress[1]) console.log(topLeft)
// const A = () => { // console.log(1) // } // // const B = () => { // console.log(2) // } // // const b: B = new A() // // const c: string = '1' // // const d: Array<string | number> = ['1', 4, 5] // // function reverse(array): Array<number> { // let ret = [] // let i = array.length // while (i--) { ret.push(array[i]) } // return ret // } // // class Box<T> { // _value: T; // // constructor(value: T) { // this._value = value // } // // get(): T { // return this._value // } // } // // type People = { // name: string, // age: number, // height: number, // // lovers:Array[string], // height: Number // }
export class HealthBarAnimsManager extends Phaser.GameObjects.Graphics { constructor(scene, x, y, width, value) { super(scene, { x, y }); scene.add.existing(this); this.width = width; this.value = value; this.instant = value; this.max = value; this.draw(); } decrease(amount) { this.value = Phaser.Math.MinSub(this.value, amount, 0); return this.value === 0; } draw() { let percentage = this.instant * this.width / this.max; this.lineStyle(2, 0x00ff00); this.beginPath(); this.moveTo(0, 0); this.lineTo(percentage, 0); this.closePath(); this.strokePath(); this.lineStyle(1, 0xff0000); this.beginPath(); this.moveTo(percentage, 0); this.lineTo(this.width, 0); this.closePath(); this.strokePath(); } preUpdate(time, delta) { if (this.instant === this.value) return; this.instant = Phaser.Math.MinSub(this.instant, delta * 0.05, this.value); this.clear(); if (this.instant > 0) this.draw(); } get progress() { return (this.max - this.instant) / this.max; } }
var querystring = require('querystring'); var query = 'name=cyh&age=20&sex=man&name=aaa'; console.log(querystring.parse(query)); //querystring.parse(qs, sep, eq, options); sep:分隔符 eq:指定分析时使用的赋值运算符,默认为=
import {Page} from 'ionic/ionic'; @Page({ templateUrl: 'build/pages/info/info.html' }) export class InfoPage { constructor() { } }
const Poll = require('../Model/Pollmodel') const chalk = require('chalk') module.exports={ PollgetController(req,res,next){ res.render('create.ejs') }, async PollpostController (req,res,next){ let {title,description,options}=req.body console.log(req.body) options = options.map(opt=>{ return{ name:opt, vote:0 } }) if(title=='') { console.log('what do you want') } let poll = new Poll({ title, description, options }) try{ await poll.save() res.redirect('/allpolls') }catch(err){ console.log(err) } }, async AllgetPoll(req,res,next){ try{ let Polls = await Poll.find() res.render('polls.ejs',{Polls}) }catch(err){ console.log(err) } }, async ViewgetPoll(req,res,next){ const {id} = req.params try{ let Polls = await Poll.findById(id) let options = [...Polls.options] let result=[] /*options.forEach(option=>{ let parcentage = (option.vote*100)/Polls.totalVote result.push({ ...option._doc, parcentage:parcentage ? parcentage : 0 }) })*/ for ( i = 0; i<options.length;i++) { let option = options[i].vote let parcentage = (option*100)/Polls.totalVote result.push({ ...options._doc, parcentage:parcentage ? parcentage : 0 }) } console.log(chalk.blue.bgRed.bold(Polls)) console.log(Poll.options) res.render('ViewPolls.ejs',{Polls,result}) }catch(err){ console.log(err) } }, async ViewpostPoll(req,res,next){ let {id} = req.params let optionId = req.body.option console.log(req.ips) try{ let Polls = await Poll.findById(id) let options = [...Polls.options] let index = options.findIndex(o=>o.id === optionId) options[index].vote = options[index].vote + 1 let totalVote = Polls.totalVote + 1 await Poll.findOneAndUpdate( {_id:Polls._id}, {$set:{options,totalVote}} ) //res.cookie('name', 'tobi', { signed: true }) res.cookie('name', 'Cook', {httpOnly: true }) res.redirect('/allpolls/' +id) }catch(err){ console.log(err) } } }
var StakeTreeWithTokenization = artifacts.require("./StakeTreeWithTokenization.sol"); const ERROR_INVALID_OPCODE = 'VM Exception while processing transaction: invalid opcode'; contract('StakeTreeWithTokenization', function(accounts) { let instance; const account_a = accounts[0]; // Beneficiary const account_b = accounts[1]; const account_c = accounts[2]; const account_d = accounts[3]; const account_e = accounts[4]; const account_f = accounts[5]; const nowUnix = new Date().getTime()/1000; const nowParsed = parseInt(nowUnix.toFixed(0), 10); let deployed = false; const config = { beneficiaryAddress: account_a, withdrawalPeriod: 0, startTime: nowParsed, sunsetWithdrawalPeriod: 5184000, // 2 months minimumFundingAmount: 1 }; beforeEach(async () => { if(!deployed) { instance = await StakeTreeWithTokenization.new( config.beneficiaryAddress, config.withdrawalPeriod, config.startTime, config.sunsetWithdrawalPeriod, config.minimumFundingAmount, {from: account_a}); deployed = true; } }); describe('Init & unit tests of pure functions', async () => { it("should have set beneficiary address during deploy", async () => { const beneficiary = await instance.getBeneficiary.call(); assert.equal(beneficiary, account_a, "Beneficiary address has been set"); }); it("should have initial next withdrawal period in correct timeframe", async () => { const withdrawalPeriod = await instance.withdrawalPeriod.call(); const nextWithdrawal = await instance.nextWithdrawal.call(); const lastWithdrawal = await instance.lastWithdrawal.call(); const timingIsCorrect = lastWithdrawal['c'][0] + withdrawalPeriod['c'][0] == nextWithdrawal['c'][0]; assert.equal(timingIsCorrect, true, "Contract withdrawal timing is correctly setup"); }); }); describe('Simple integration test: New funder, account_c, arrives, withdrawal happens and then refund', async () => { it("[account c] should add funds to the contract", async () => { await web3.eth.sendTransaction({gas: 150000, from: account_c, to: instance.address, value: 100}); const balance = await instance.getContractBalance.call(); assert.equal(balance, 100, "Contract has 100 wei balance"); }); it("should get total funders as 1", async () => { const totalFunders = await instance.getCurrentTotalFunders.call(); assert.equal(totalFunders, 1, "There are 0 total funders"); }); it("[account c] should have arrived at withdrawal 0", async () => { const withdrawalCounter = await instance.getWithdrawalEntryForFunder.call(account_c); assert.equal(withdrawalCounter, 0, "Arrived at withdrawal 0"); }); it("should withdraw to beneficiary", async () => { await instance.withdraw({from: account_a}); const balanceAfter = await instance.getContractBalance.call(); assert.equal(balanceAfter, 90, "Beneficiary has withdrawn 10%"); }); it("[account c] should refund by funder", async () => { await instance.refund({from: account_c}); const balance = await instance.getContractBalance.call(); assert.equal(balance, 0, "Account B has been refunded 90. Wallet balance is now 0"); }); }); describe('Complex integration test 1: one funder -> two withdrawals -> funder tops up -> three withdrawals -> funder refunds', async () => { it("[account d] should add funds to the contract", async () => { await web3.eth.sendTransaction({gas: 150000, from: account_d, to: instance.address, value: 10000}); const balance = await instance.getContractBalance.call(); assert.equal(balance, 10000, "Contract has 100 wei balance"); }); it("[account d] should have arrived at withdrawal 1", async () => { const withdrawalCounter = await instance.getWithdrawalEntryForFunder.call(account_d); assert.equal(withdrawalCounter, 1, "Arrived at withdrawal 1"); }); // x2 it("should withdraw to beneficiary", async () => { await instance.withdraw(); const balanceAfter = await instance.getContractBalance.call(); assert.equal(balanceAfter, 9000, "Beneficiary has withdrawn 10%"); }); it("[account d] should have correct withdrawal amount", async () => { const totalRefund = await instance.getRefundAmountForFunder.call(account_d); assert.equal(totalRefund, 9000, "Account D has 9000 left to withdraw"); }); it("should withdraw to beneficiary", async () => { await instance.withdraw(); const balanceAfter = await instance.getContractBalance.call(); assert.equal(balanceAfter, 8100, "Beneficiary has withdrawn 10%"); }); it("[account d] should have correct withdrawal amount", async () => { const totalRefund = await instance.getRefundAmountForFunder.call(account_d); assert.equal(totalRefund, 8100, "Account D has 81000 left to withdraw"); }); // Topup it("[account d] should add funds to the contract", async () => { await web3.eth.sendTransaction({gas: 150000, from: account_d, to: instance.address, value: 11900}); const balance = await instance.getContractBalance.call(); assert.equal(balance, 20000, "Contract has 20000 wei balance"); }); it("[account d] should have correct withdrawal amount", async () => { const totalRefund = await instance.getRefundAmountForFunder.call(account_d); assert.equal(totalRefund, 20000, "Account D has 20000 left to withdraw"); }); it("[account d] should have a contribution allocated after topping up after a withdrawal", async () => { const contribution = await instance.getFunderContribution.call(account_d); assert.equal(contribution, 1900, "Account D should have been allocated 1900 as a contribution"); }); // x3 it("should withdraw to beneficiary", async () => { await instance.withdraw(); const balanceAfter = await instance.getContractBalance.call(); assert.equal(balanceAfter, 18000, "Beneficiary has withdrawn 10%"); }); it("[account d] should have correct withdrawal amount", async () => { const totalRefund = await instance.getRefundAmountForFunder.call(account_d); assert.equal(totalRefund, 18000, "Account D has 9000 left to withdraw"); }); it("should withdraw to beneficiary", async () => { await instance.withdraw(); const balanceAfter = await instance.getContractBalance.call(); assert.equal(balanceAfter, 16200, "Beneficiary has withdrawn 10%"); }); it("[account d] should have correct withdrawal amount", async () => { const totalRefund = await instance.getRefundAmountForFunder.call(account_d); assert.equal(totalRefund, 16200, "Account D has 81000 left to withdraw"); }); it("should withdraw to beneficiary", async () => { await instance.withdraw(); const balanceAfter = await instance.getContractBalance.call(); assert.equal(balanceAfter, 14580, "Beneficiary has withdrawn 10%"); }); it("[account d] should have correct withdrawal amount", async () => { const totalRefund = await instance.getRefundAmountForFunder.call(account_d); assert.equal(totalRefund, 14580, "Account D has 9000 left to withdraw"); }); it("[account d] should refund their funds", async () => { await instance.refund({from: account_d}); const balance = await instance.getContractBalance.call(); assert.equal(balance, 0, "Account D has been refunded 14580. Wallet balance is now 0"); }); }); describe('Complex integration test 2: three funders arrive -> one tops up -> withdrawal -> refund one -> one tops up -> 2nd withdrawal -> refund two', async () => { // Three funders arrive it("[account d] should add funds to the contract", async () => { await web3.eth.sendTransaction({gas: 150000, from: account_d, to: instance.address, value: 100}); const balance = await instance.getContractBalance.call(); assert.equal(balance, 100, "Contract has 100 wei balance"); }); it("[account e] should add funds to the contract", async () => { await web3.eth.sendTransaction({gas: 150000, from: account_e, to: instance.address, value: 200}); const balance = await instance.getContractBalance.call(); assert.equal(balance, 300, "Contract has 300 wei balance"); }); it("[account f] should add funds to the contract", async () => { await web3.eth.sendTransaction({gas: 150000, from: account_f, to: instance.address, value: 300}); const balance = await instance.getContractBalance.call(); assert.equal(balance, 600, "Contract has 600 wei balance"); }); it("should get total funders as 3", async () => { const totalFunders = await instance.getCurrentTotalFunders.call(); assert.equal(totalFunders, 3, "There are 3 total funders"); }); // One tops up it("[account e] should add funds to the contract", async () => { await web3.eth.sendTransaction({gas: 150000, from: account_e, to: instance.address, value: 800}); const balance = await instance.getContractBalance.call(); assert.equal(balance, 1400, "Contract has 1100 wei balance"); }); // E 200 -> 1000 it("[account e] should have funds correct balance", async () => { const balance = await instance.getFunderBalance.call(account_e); assert.equal(balance, 1000, "Account E has 1000 wei balance"); }); it("should still get total funders as 3", async () => { const totalFunders = await instance.getCurrentTotalFunders.call(); assert.equal(totalFunders, 3, "There are 3 total funders"); }); // Withdraw it("should withdraw to beneficiary", async () => { await instance.withdraw(); const balanceAfter = await instance.getContractBalance.call(); assert.equal(balanceAfter, 1260, "Beneficiary has withdrawn 10%"); }); // D 100 -> 90 it("[account d] should have correct withdrawal amount", async () => { const totalRefund = await instance.getRefundAmountForFunder.call(account_d); assert.equal(totalRefund, 90, "Account D has 90 left to withdraw"); }); // E 1000 -> 900 it("[account e] should have correct withdrawal amount", async () => { const totalRefund = await instance.getRefundAmountForFunder.call(account_e); assert.equal(totalRefund, 900, "Account E has 900 left to withdraw"); }); // F 300 -> 270 it("[account f] should have correct withdrawal amount", async () => { const totalRefund = await instance.getRefundAmountForFunder.call(account_f); assert.equal(totalRefund, 270, "Account F has 270 left to withdraw"); }); // Refund Account D // D 90 -> 0 it("[account d] should refund their funds", async () => { await instance.refund({from: account_d}); const balance = await instance.getContractBalance.call(); assert.equal(balance, 1170, "Account D has been refunded 90. Wallet balance is now 1170"); }); it("[account d] should fail refunding their funds again", async () => { try { await instance.refund({from: account_d}); assert.equal(true, false); } catch (err) { assert.equal(err.message, ERROR_INVALID_OPCODE); } }); // Account F tops up // F 270 -> 600 it("[account f] should add funds to the contract again", async () => { await web3.eth.sendTransaction({gas: 150000, from: account_f, to: instance.address, value: 330}); const balance = await instance.getContractBalance.call(); assert.equal(balance, 1500, "Contract has 1500 wei balance"); }); it("[account f] should get balance", async () => { const balance = await instance.getFunderBalance.call(account_f); assert.equal(balance, 600, "Account F has 600 wei balance"); }); // Withdraw it("should withdraw to beneficiary", async () => { await instance.withdraw(); const balanceAfter = await instance.getContractBalance.call(); assert.equal(balanceAfter, 1350, "Beneficiary has withdrawn 10%"); }); // E 900 -> 810 it("[account e] should have correct withdrawal amount", async () => { const totalRefund = await instance.getRefundAmountForFunder.call(account_e); assert.equal(totalRefund, 810, "Account E has 567 left to withdraw"); }); // F 600 -> 540 it("[account f] should have correct withdrawal amount", async () => { const totalRefund = await instance.getRefundAmountForFunder.call(account_f); assert.equal(totalRefund, 540, "Account F has 540 left to withdraw"); }); it("should show get withdrawal counter", async () => { const counter = await instance.getWithdrawalCounter.call(); assert.equal(counter, 8, "Counter is 8"); }); // Refund last two accounts // 1350 -> 540 it("[account e] should refund their funds", async () => { await instance.refund({from: account_e}); const balance = await instance.getContractBalance.call(); assert.equal(balance, 540, "Account E has been refunded 810. Wallet balance is now 540"); }); // 540 -> 0 it("[account f] should refund their funds", async () => { const totalRefund = await instance.getRefundAmountForFunder.call(account_f); await instance.refund({from: account_f}); const balance = await instance.getContractBalance.call(); assert.equal(balance, 0, "Account F has been refunded 540. Wallet balance is now 0"); }); }); });
import React from "react"; import './Home.css'; export default function Home() { return ( <div className='home'> <div className='text'> <span className="l">H</span><span className="l">e</span><span className="l">l</span> <span className="l">l</span><span className="l">o</span>, <span className="l">I'm </span> <span className="juan">Juan Abrate</span>. <br/> I'm a full-stack web developer. </div> <div className="button"> <span className="button-text"> My Skills </span> </div> </div> ) }
import { createStore, applyMiddleware, compose, combineReducers } from 'redux' import { composeWithDevTools } from 'redux-devtools-extension/logOnlyInProduction' import { connectRoutes } from 'redux-first-router' import ReduxThunk from 'redux-thunk' import { combineForms } from 'react-redux-form' import routesMap from './routesMap' import options from './options' import * as reducers from './reducers' import * as actionCreators from './actions' import * as forms from './forms' import api from './middlewares/api' // exported reference to the redux store export let store = null export default (history, preLoadedState) => { const { reducer, middleware, enhancer, thunk } = connectRoutes( history, routesMap, options ) const rootReducer = combineReducers({ ...reducers, location: reducer, forms: combineForms({ ...forms }, 'forms') }) const middlewares = applyMiddleware(middleware, ReduxThunk, api) const enhancers = composeEnhancers(enhancer, middlewares) store = createStore(rootReducer, preLoadedState, enhancers) if (module.hot && process.env.NODE_ENV === 'development') { module.hot.accept('./reducers/index', () => { const reducers = require('./reducers/index') const rootReducer = combineReducers({ ...reducers, location: reducer }) store.replaceReducer(rootReducer) }) } return { store, thunk } } const composeEnhancers = (...args) => typeof window !== 'undefined' ? composeWithDevTools({ actionCreators })(...args) : compose(...args)
var navtree________________8js________8js____8js__8js_8js = [ [ "navtree________8js____8js__8js_8js", "navtree________________8js________8js____8js__8js_8js.html#a75a50f9bb042737b0800274cbb702a74", null ] ];
import axios from "axios"; import { store, updateToken, updatePlayers } from "../stores/MainStore"; const positions = [ "Attaquant", "Milieu", "Défenseur", "Gardien", ]; const playStyle = [ "Offensif", "Polyvalent", "Défensif" ] class MainRequest { login() { let qs = require("querystring"); let config = { headers: { "Content-Type": "application/x-www-form-urlencoded", }, }; let form = { userName: store.login, grant_type: "password", client_id: "jPs3vVbg4uYnxGoyunSiNf1nIqUJmSFnpqJSVgWrJleu6Ak7Ga", client_secret: "ePOVDMfAvU8zcyfaxLMtqYSmND3n6vmmKx9ZlVnNGjGkzucMCt", password: store.password, }; axios .post("https://web-api.onlinesoccermanager.com/api/token", qs.stringify(form), config) .then((response) => { //console.log("res", response); updateToken("Bearer " + response.data.access_token); this.getPlayers(); }) .catch((err) => console.log("err", err)); } getPlayers() { let config = { headers: { Authorization: store.token, }, }; let promises = []; for (let i = 0; i < 20; i++) promises.push(axios.get("https://web-api.onlinesoccermanager.com/api/v1/leagues/39476588/teams/" + (i + 1) + "/players")); Promise.all(promises) .then((responses) => { let players = []; console.log("responses", responses); responses.forEach((arr, i) => { //console.log("arr " + i + " :", arr); players = players.concat(arr.data); }); console.log("all players", players); players.forEach(p => { p.nation = p.nationality.name; p.position = positions[p.position - 1]; p.style = playStyle[p.style - 1]; }) updatePlayers(players); //updateToken("Bearer " + response.data.access_token); }) .catch((err) => console.log("err", err)); } } export default new MainRequest();
// 1 // // Разработать шифратор-дешифратор: // два текстовых поля, две кнопки Зашифровать и Расшифровать. // При нажатии на первую текст из первого текстового поля шифруется и попадает во второе. // При нажатии на вторую - из второго дешифруется и попадает в первое. // Алгоритм шифрования\дешифрования подобрать по своему усмотрению. const cryptArr = ['_', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; const decryptArr = ['_', 'а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ'] for (let i = 0; i < cryptArr.length; i++) { console.log(`${cryptArr[i]} = ${decryptArr[i]}`) } const cryptField = document.getElementById('crypt-field'); const decryptField = document.getElementById('decrypt-field'); const cryptButton = document.getElementById('crypt-button'); const decryptButton = document.getElementById('decrypt-button'); const pCryptedText = document.getElementById('crypted-text'); const pDecryptedText = document.getElementById('decrypted-text'); cryptButton.addEventListener('click', function() { const textCrypt = String(cryptField.value); let text = ''; pDecryptedText.innerText = text; for (let i = 0; i < textCrypt.length; i++) { for (let j = 0; j < cryptArr.length; j++) { if (textCrypt[i] == cryptArr[j]) { text = decryptArr[j]; pDecryptedText.innerText += `${text}` } } } }) decryptButton.addEventListener('click', function() { const textDecrypt = String(decryptField.value); let text = ''; pCryptedText.innerText = text; for (let i = 0; i < textDecrypt.length; i++) { for (let j = 0; j < decryptArr.length; j++) { if (textDecrypt[i] == decryptArr[j]) { text = cryptArr[j]; pCryptedText.innerText += `${text}` } } } })
// 1. Open Firebug, enable & select the Console panel. // 2. Enter anything (like '1+2') into the console several times, enough to // overflow the console space. // 3. The Console panel scroll position must be at the bottom. function runTest() { // Step 1. FBTest.openNewTab(basePath + "console/2694/issue2694.html", function(win) { FBTest.openFirebug(function() { FBTest.enableConsolePanel(function() { executeSetOfCommands(40, function() { FBTest.ok(isScrolledToBottom(), "The Console panel must be scrolled to the bottom."); FBTest.testDone(); }); }); }); }); } // ************************************************************************************************ function executeSetOfCommands(counter, callback) { if (counter > 0) { FBTest.executeCommand("1+" + counter); setTimeout(function() { executeSetOfCommands(--counter, callback); }, 50); } else { callback(); } } function isScrolledToBottom() { var panel = FBTest.getPanel("console"); return FW.FBL.isScrolledToBottom(panel.panelNode); }
const mongoose = require('mongoose'); // The actual database of users const _ = require('lodash'); var Schema = mongoose.Schema; const UserSchema = new Schema({ name:String, provider: String, uid:String, photoUrl:String, }) UserSchema.methods.toJSON = function () { var user = this; var userObject = user.toObject(); return _.pick(userObject, ['uid', 'name','photoUrl','provider']); }; var User = mongoose.model('User', UserSchema); module.exports = User;
const express = require('express'); const router = express.Router(); const path = require('path'); const URL = require('../models/url'); router.get('/:id', (req,res) => { res.sendFile(path.resolve(__dirname + '/../public/verify.html')); }); router.post('/verify', (req,res) => { let body = req.body; URL.find({shortURL: body.endpoint}) .then((urlFound)=>{ if(urlFound.length > 0) { if(urlFound[0].privateOrPublic === body.passcode) res.status(200).json({ message: urlFound[0].longURL}) else res.status(400).json({ error: `Password does not match` }) } else{ res.status(400).json({ error: `URL does not exist` }) } }) .catch(()=>{ res.status(400).json({ error: 'Wrong' }) }); }); router.get('*', (req,res) => { res.sendFile(path.resolve(__dirname + '/../public/404.html')); }) module.exports = router;
// An empty array. let apiLegos = []; // An exported function that returns the export const useLegos = () => { return [...apiLegos] } export const loadLegos = () => { return fetch("../data/lego-colors.json") .then(response => response.json()) .then((legoArray) => { apiLegos = legoArray.LegoColorss; return legoArray.LegoColorss; }) };
const sql = require('./db.js'); // constructor const OrderDetails = function (orderDetails) { this.orderID = orderDetails.orderID; this.productID = orderDetails.productID; this.userID = orderDetails.userID; }; OrderDetails.create = (newOrderDetails, result) => { sql.query( 'CALL insertOrderDetails(?, ?, ?)', [ newOrderDetails.orderID, newOrderDetails.productID, newOrderDetails.userID, ], (err, res) => { if (err) { console.log('error: ', err); result(err, null); return; } console.log('created order: ', { ...newOrderDetails }); result(null, { ...newOrderDetails }); } ); }; OrderDetails.getAll = (result) => { sql.query('SELECT * FROM orderDetails', (err, res) => { if (err) { console.log('error: ', err); result(null, err); return; } console.log('orders: ', res); result(null, res); }); }; OrderDetails.findByOrderID = (userID, result) => { sql.query( `SELECT * FROM orderDetails WHERE userID = '${userID}'`, (err, res) => { if (err) { console.log('error: ', err); result(err, null); return; } if (res.length) { console.log('found order: ', res); result(null, res); return; } // not found Customer with the id result({ kind: 'not_found' }, null); } ); }; module.exports = OrderDetails;
import React, { Component } from 'react'; import { Text, View, TextInput, FlatList, TouchableHighlight, Dimensions, TouchableOpacity } from 'react-native'; import { List, ListItem } from 'react-native-elements'; import { MapView } from 'expo'; import { connect } from 'react-redux'; import Qs from 'qs'; import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete'; class AddLocation extends Component { constructor(props) { super(props); this.state = { textInput: '', predictions: [], location: { name: '', secondary: '' }, mapViewLat: 40.76727216, mapViewLong: -73.99392888, markerLat: null, markerLng: null }; this.onChangeText = this.onChangeText.bind(this); this.GooglePlacesAutocomplete = this.GooglePlacesAutocomplete.bind(this); this.renderPredictions = this.renderPredictions.bind(this); this.renderRow = this.renderRow.bind(this); this.setPredictions = this.setPredictions.bind(this); this.choosePlace = this.choosePlace.bind(this); this.reverseGeocode = this.reverseGeocode.bind(this); this.setMap = this.setMap.bind(this); this.renderMapMarker = this.renderMapMarker.bind(this); } setPredictions(results) { this.setState({ predictions: results }); } onChangeText(text) { this.setState({ textInput: text }); if (text.length < 2) { return; } this.GooglePlacesAutocomplete(text); } reverseGeocode(placeId) { const setMap = this.setMap; const httpReq = new XMLHttpRequest(); httpReq.onreadystatechange = function() { if (httpReq.readyState !== 4) { return; } if (this.readyState === 4 && this.status === 200) { // Typical action to be performed when the document is ready: const responseJSON = JSON.parse(httpReq.responseText); if (typeof responseJSON.result !== 'undefined'){ const result = responseJSON.result; setMap(result); } else { console.log(responseJSON.error_message); } } }; httpReq.open('GET', 'https://maps.googleapis.com/maps/api/place/details/json?' + Qs.stringify({ placeid: placeId, key: 'AIzaSyDN6MBMMQBCJoXgbYSqxvVJ1M0wR9c3KsM', fields: 'geometry' })); httpReq.send(); } GooglePlacesAutocomplete(text) { const request = new XMLHttpRequest(); const setPredictions = this.setPredictions; request.onreadystatechange = function() { if (request.readyState !== 4) { return; } if (this.readyState === 4 && this.status === 200) { // Typical action to be performed when the document is ready: const responseJSON = JSON.parse(request.responseText); if (typeof responseJSON.predictions !== 'undefined'){ const results = responseJSON.predictions; setPredictions(results); } else { console.log(responseJSON.error_message); } } }; request.open('GET', 'https://maps.googleapis.com/maps/api/place/autocomplete/json?' + Qs.stringify({ key: 'AIzaSyDN6MBMMQBCJoXgbYSqxvVJ1M0wR9c3KsM', input: text, libraries: "places" })); request.send(); } renderRow(item){ return( <TouchableOpacity style={styles.row} onPress={() => this.choosePlace(item)}> <Text style={styles.textStyle}> {item.description} </Text> </TouchableOpacity> ); } // keyExtractor = (item, index) => item.id; renderPredictions() { return( <List containerStyle={styles.listStyle}> <FlatList data={this.state.predictions} renderItem={({ item }) => this.renderRow(item)} {...this.props} keyExtractor={(item, index) => index.toString()} /> </List> ); } async choosePlace(place) { this.setState({ location: { name: place.structured_formatting.main_text, secondary: place.structured_formatting.secondary_text }, predictions: [], textInput: place.description }); await this.reverseGeocode(place.place_id); } setMap(result){ const lat = result.geometry.location.lat; const lng = result.geometry.location.lng; const name = this.state.location.name; const secondary = this.state.location.secondary; this.setState({ mapViewLat: lat, mapViewLong: lng, markerLat: lat, markerLng: lng }); this.props.onSelectLocation({ name: name, secondary: secondary, address: result.geometry }); } renderMapMarker() { if ( this.state.markerLat === null ) { return ; } return( <MapView.Marker coordinate={{ latitude: this.state.markerLat, longitude: this.state.markerLng}} title={this.state.location.name} description={this.state.location.secondary} /> ); } render() { return( <View style={{flex: 1, flexDirection: 'column'}}> <TextInput onChangeText={this.onChangeText} style={styles.textInput} placeholder="Search Location..." placeholderTextColor="#C0C0C0" value={this.state.textInput} /> {this.renderPredictions()} <MapView style={{height: 250}} provider="google" region={{ latitude: this.state.mapViewLat, longitude: this.state.mapViewLong, latitudeDelta: 0.0622, longitudeDelta: 0.0221 }}> {this.renderMapMarker()} </MapView> </View> ); } } const styles = { textInput: { paddingRight: 15, paddingLeft: 15, height: 40, width: 300, color: '#4c5267', fontSize: 20 }, textStyle: { height: 24, margin: 10, paddingBottom: 10, fontSize: 15, color: '#808080' }, row: { height: 33, borderBottomWidth: 0.5, borderBottomColor: '#DCDCDC' }, listStyle: { flex: 1, position: 'absolute', zIndex: 1, top: 10 } }; export default AddLocation;
describe('standard.filter.prevent', () => { test.todo('Executa o preventDefault antes de chamar o metodo alvo') })
import React from 'react'; import {createBottomTabNavigator} from '@react-navigation/bottom-tabs'; import HomeScreen from '../screens/Home'; import Explorenavigator from './Explorenavigator' import Fontisto from 'react-native-vector-icons/Fontisto'; import FontAwesome from 'react-native-vector-icons/FontAwesome'; import FontAwesome5 from 'react-native-vector-icons/FontAwesome5'; import Feather from 'react-native-vector-icons/Feather'; import EvilIcons from 'react-native-vector-icons/EvilIcons'; import { color } from 'react-native-reanimated'; const Tab = createBottomTabNavigator(); const HomeTabNavigator = (props) => { return ( <Tab.Navigator tabBarOptions={{ activeTintColor:'#f15454', }}> <Tab.Screen name={'Explore'} component={Explorenavigator} options={{ tabBarLabel: 'Explore', tabBarIcon: ({color}) => ( <Fontisto name={"search"} size={25} color={color}/> ) }} /> <Tab.Screen name={'Home'} component={HomeScreen} options={{ tabBarLabel: 'Home', tabBarIcon: ({color}) => ( <FontAwesome name={"heart-o"} size={25} color={color}/> ) }} /> <Tab.Screen name={'Map'} component={HomeScreen} options={{ tabBarLabel: 'Map', tabBarIcon: ({color}) => ( <FontAwesome5 name={"safari"} size={25} color={color}/> ) }} /> <Tab.Screen name={'Messages'} component={HomeScreen} options={{ tabBarLabel: 'Messages', tabBarIcon: ({color}) => ( <Feather name={"message-square"} size={25} color={color} /> ) }} /> <Tab.Screen name={'Profile'} component={HomeScreen} options={{ tabBarLabel: 'Profile', tabBarIcon: ({color}) => ( <EvilIcons name={"user"} size={30} color={color} /> ) }} /> </Tab.Navigator> ); }; export default HomeTabNavigator;
const config = require("../config.js"); const lib = require("./shared.js"); const api = require("./Api.js"); const fs = require("fs"); const { promisify } = require("util"); class Project { constructor(name) { this.name = name; this.dependsOn = [config.ENDPOINT_HANDLER_LOGICAL_NAME]; this.apis = []; } async init() { this.apis = await this.getApiResources(); } get nameUppercase() { return lib.capitalize(this.name); } logName(type) { type = type.replace("AWS::", ""); type = type.replace("::", "-"); type = lib.camelcased(type); return lib.camelcased(this.nameUppercase) + type; } getDomainName() { return config.CUSTOM_DOMAIN_PREFIX + this.name + "." + config.MAIN_DOMAIN; } getRestApisLambdaPermissions() { let resources = {}; this.apis.forEach((api) => { resources = { ...resources, ...api.getLambdaPermission(config.ENDPOINT_HANDLER_LOGICAL_NAME), }; }); return resources; } apiGatewayDomain() { return { [this.logName(lib.AWS.APIGATEWAY.DOMAIN_NAME)]: { Type: lib.AWS.APIGATEWAY.DOMAIN_NAME, DependsOn: this.dependsOn, Properties: { CertificateArn: config.WILDCARD_CERTIFICATE, DomainName: domainName(this.name), }, }, }; } route53RecordSetGroup() { return { [this.logName(lib.AWS.ROUTE53.RECORD_SET_GROUP)]: { Type: lib.AWS.ROUTE53.RECORD_SET_GROUP, DependsOn: [this.logName(lib.AWS.APIGATEWAY.DOMAIN_NAME)], Properties: { Comment: "Creating recordset for " + this.nameUppercase + " project", HostedZoneName: config.MAIN_DOMAIN + ".", RecordSets: [ { Name: domainName(this.name), Type: "A", AliasTarget: { DNSName: { "Fn::GetAtt": [ this.logName(lib.AWS.APIGATEWAY.DOMAIN_NAME), "DistributionDomainName", ], }, EvaluateTargetHealth: false, HostedZoneId: { "Fn::GetAtt": [ this.logName(lib.AWS.APIGATEWAY.DOMAIN_NAME), "DistributionHostedZoneId", ], }, }, }, { Name: domainName(this.name), Type: "AAAA", AliasTarget: { DNSName: { "Fn::GetAtt": [ this.logName(lib.AWS.APIGATEWAY.DOMAIN_NAME), "DistributionDomainName", ], }, EvaluateTargetHealth: false, HostedZoneId: { "Fn::GetAtt": [ this.logName(lib.AWS.APIGATEWAY.DOMAIN_NAME), "DistributionHostedZoneId", ], }, }, }, ], }, }, }; } async getApiResources() { const readdir = promisify(require("fs").readdir); const projectDir = "./" + config.PROJECTS_DIR + "/" + this.name; const apisDir = projectDir + "/" + config.APIS_DIR; const files = await readdir(apisDir); let apis = []; if (!fs.existsSync(projectDir) || !fs.existsSync(apisDir)) { return apis; } files.forEach((file) => { const currFile = apisDir + "/" + file; const oapiSpecFile = currFile + "/" + config.OPENAPI_SPEC_FILE; if (fs.lstatSync(currFile).isDirectory() && fs.existsSync(oapiSpecFile)) { apis.push( new api(file, this.name, [ this.logName(lib.AWS.APIGATEWAY.DOMAIN_NAME), ]) ); } }); return apis; } getResources() { let resources = { ...this.apiGatewayDomain(), ...this.getRestApisLambdaPermissions(), ...this.route53RecordSetGroup(), }; this.apis.forEach((api) => { resources = { ...resources, ...api.getResources() }; }); return resources; } } /** * Get Domain Name * @param projectName Project Name */ const domainName = (project) => { return config.CUSTOM_DOMAIN_PREFIX + project + "." + config.MAIN_DOMAIN; }; module.exports.create = Project; module.exports.domainName = domainName;
import Case from 'case' import Request from 'request' import ProgressBar from 'progress' import Bytes from 'bytes' import Fs from 'fs-extra' import Promise from 'bluebird' import { saveFile } from './file' import getStoredCourses from './getStoredCourses' const download = (url, filePath) => new Promise((resolve, reject) => { let bar let transfered = 0 const req = Request(url) req .on('data', chunk => { const length = req.response.headers['content-length'] const total = parseInt(length, 10) const size = Bytes(total) transfered += +chunk.length const downloaded = Bytes(transfered) const barString = '[:bar] :percent ' + 'total: ' + size + ' ' + 'downloaded: :downloaded' bar = bar || new ProgressBar(barString, { complete: '*', incomplete: ' ', width: 20, total, }) bar.tick(chunk.length, { downloaded }) }) .on('error', reject) .on('end', resolve) .pipe(Fs.createWriteStream(filePath)) }) export default async course => { // make sure folder with the name of course's title exists const folderName = Case.kebab(course.title) const basePath = process.cwd() + '/' + folderName + '/' await Fs.ensureDirSync(basePath) // download each videos in the course if it is not already downloaded const { videos } = course const total = videos.length if (total <= 0) { console.log('No videos to download in this course.') return } await Promise.each(videos, async (video, index) => { const fileName = (index + 1) + '-' + Case.kebab(video.title) const filePath = basePath + fileName + '.mp4' console.log() console.log(`Downloading '${video.title} (${index + 1} of ${total})'`) if (video.downloaded) { console.log(' Already Downloaded') return } await download(video.url, filePath) const storedCourses = await getStoredCourses() storedCourses[course.title].videos[index].downloaded = true await saveFile(storedCourses) }) }
/** * The module managing the entry point of the APP * @module Main */ import React from 'react' import ReactDOM from 'react-dom' import '@styles/index.scss' import App from '@src/App' const container = document.getElementById('root') /** Now, we create a root * */ const root = ReactDOM.createRoot(container, { hydrate: true }) /** * @function render * Render the Home component inside the element root of the index page */ root.render( <React.StrictMode> <App /> </React.StrictMode> )
import express from 'express'; import authRoutes from './auth.route'; import stopsRoutes from './stops.route'; import questionsRoutes from './questions.route'; import categoriesRoutes from './categories.route'; import historiesRoutes from './histories.route'; const router = express.Router(); // eslint-disable-line new-cap /** GET /health-check - Check service health */ router.get(['/', '/zen'], (req, res) => res.send('Yello')); // mount auth routes at /auth router.use('/auth', authRoutes); // mount stops routes at /stops router.use('/stops', stopsRoutes); // mount question routes at /questions router.use('/questions', questionsRoutes); // mount question routes at /categories router.use('/categories', categoriesRoutes); // mount history routes at /histories router.use('/histories', historiesRoutes); export default router;
import { FooClass } from './FooClass' export function main() { // fix inconsistent implementations console.log(parseInt("10")); // pollyfill prototypes console.log([1, 2, 3].find((i) => i % 2 === 0)); //ES 6 class & modules const fooInst = new FooClass(); console.log(fooInst.propertyBar); }
import React, {PropTypes} from 'react'; import {getObject} from '../../common/common'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import SuperTab from '../../components/SuperTab'; import s from './TabPage.less'; /** * 功能:创建一个包含TAB标签的页面组件 * 参数: * getComponent:原型func(activeKey),该函数应该依据activeKey返回一个组件(表达当前选卡的内容) * 返回值:React组件 */ const createTabPage = (getComponent) => { class TabPage extends React.Component { static propTypes = { activeKey: PropTypes.string.isRequired, tabs: PropTypes.array.isRequired, onTabChange: PropTypes.func, onTabClose: PropTypes.func }; tabContent = (activeKey) => { const Component = getComponent(activeKey); return Component && <Component close={this.props.onTabClose.bind(null, activeKey)} />; }; render() { return ( <div className={s.root}> <SuperTab {...getObject(this.props, SuperTab.PROPS)} /> {this.tabContent(this.props.activeKey)} </div> ); } } return withStyles(s)(TabPage); }; const createCommonTabPage = (OrderPageContainer, EditPageContainer) => { const getComponent = (activeKey) => { if (activeKey === 'index') { return OrderPageContainer } else { return EditPageContainer; } }; return createTabPage(getComponent); }; export default createTabPage; export {createCommonTabPage};
var net = require('net'); /** * Control socket, * * echo PING | nc -U /tmp/portawiki.sock # log an Alive * echo EXIT | nc -U /tmp/portawiki.sock # process exits normally * */ var statusSocket = net.createServer(function (c) { try{ var string = ''; c.on('data', function(buffer) { string += buffer.toString('utf-8'); }); c.on('end', function() { if (string.indexOf("PING") == 0) { console.log("Alive"); } else if (string.indexOf("EXIT") == 0) { console.log("Going down"); process.exit(0); } }); } catch(err) { console.log(err); } }); statusSocket.listen("/tmp/portawiki.sock");
// There are N children standing in a line. Each child is assigned a rating value. // // You are giving candies to these children subjected to the following requirements: // // Each child must have at least one candy. // Children with a higher rating get more candies than their neighbors. // What is the minimum candies you must give? // ratings: [5, 6, 2, 2, 4, 8, 9, 5, 4, 0, 5, 1] // candies: [1, 2, 1, 1, 2, 3, 4, 3, 2, 1, 2, 1] // 23 candies function minCandy(array) { // start with an array of 1's let pieces = Array.from({length: array.length}, () => 1); // two loops // check if neighbor is greater tha, if we are in a hill // if we are in a 'hill' then each subquential item is hill + 1 let hill; for (let i = 1; i < array.length; i++) { if (array[i-1] < array[i]) { hill = pieces[i-1]; pieces[i] = hill + 1; } } console.log(pieces); for (let j = array.length-1; j > 0; j--) { if (array[j-1] > array[j] && pieces[j-1] <= pieces[j]) { hill = pieces[j]; pieces[j-1] = hill + 1; } } console.log(pieces) return pieces.reduce((a,b) => a + b); } // let ratings = [2,1]; let ratings = [4,2,3,4,1] // [2,1,2,3,1] // let ratings = [ 5, 6, 2, 2, 4, 8, 9, 5, 4, 0, 5, 1 ]; // first pass [ 1, 2, 1, 1, 2, 3, 4, 1, 1, 1, 2, 1 ] // let candies = [1, 2, 1, 1, 2, 3, 4, 3, 2, 1, 2, 1]; // [ 1, 2, 1, 1, 2, 3, 4, 3, 2, 1, 2, 1 ] console.log(minCandy(ratings));
let app = new Vue({ el: '#app', data: { term1data: {}, term2data: {}, loading: false, term1: 'strewn', term2: 'balloon', comments: {}, poemLine1: '', poemLine2: '', }, created() { this.poetrydb(); }, computed: { }, watch: { term1(value, oldvalue) { if (oldvalue === '') { this.term1 = value; } }, term2(value, oldvalue) { if (oldvalue === '') { this.term2= value; } }, }, methods: { async poetrydb() { this.loading = true; if (this.term1 != '' && this.term2 != '') { try { const response1 = await axios.get('http://poetrydb.org/lines/' + this.term1) .catch(error => { this.term1 = ""; }); this.term1data = response1.data; } catch (error) { console.log(error); } try { const response2 = await axios.get('http://poetrydb.org/lines/' + this.term2) .catch(error => { this.term2 = ""; }); this.term2data = response2.data; } catch (error) { console.log(error); } } this.loading = false; }, generatePoem() { this.poetrydb(); this.poemLine1 = ''; this.poemLine2 = ''; var found1 = false; for (var i = 0; i < this.term1data.length; i++) { var poem = this.term1data[i]; for (var k = 0; k < poem.lines.length; k++) { var line = poem.lines[k]; var n = line.split(" "); var lastword = n[n.length - 1]; lastword = lastword.substring(0, lastword.length - 1); if (lastword === this.term1) { var cleanLine = line.substring(0, line.length - 1); this.poemLine1 += cleanLine + '\n'; found1 = true; break; } } if (found1 === true) { break; } } if (found1 === false) { this.poemLine1 = "Word 1 is invalid or not found"; } var found2 = false; for (var i = 0; i < this.term2data.length; i++) { var found2 = false; var poem = this.term2data[i]; for (var k = 0; k < poem.lines.length; k++) { var line = poem.lines[k]; var n = line.split(" "); var lastword = n[n.length - 1]; lastword = lastword.substring(0, lastword.length - 1); if (lastword === this.term2) { var cleanLine = line.substring(0, line.length - 1); this.poemLine2 += cleanLine + '\n'; found2 = true; break; } } if (found2 === true) { break; } } if (found2 === false) { this.poemLine2 += "Word 2 is invalid or not found"; } }, } });
import React from "react"; const ErrorMessage = () => ( <div className="alert alert-danger" role="alert"> <h4 className="alert-heading">Something went wrong!</h4> </div> ); export default ErrorMessage;
../../landing/js/codemirror.js
/** * 碰撞检测: * 大鱼吃果实 * 大鱼喂小鱼 */ function momFruitCollision() { if(data.gameOver){ return; } for(let i = 0; i < fruit.num; i++){ if(fruit.alive[i]){ //得到果实和大鱼的直线距离 let l = calLength2(fruit.x[i], fruit.y[i], mom.x, mom.y); if(l < 900){ //果实被eated fruit.dead(i); //果实+1 data.fruitNum++; //大鱼吃到果实,身体渐渐变色,当达到最大值,不再变 mom.bigBodyCount++; if (mom.bigBodyCount > mom.bigBodyLen -1){ mom.bigBodyCount = mom.bigBodyLen - 1; } //吃到蓝色果实 if (fruit.type[i] == 'blue'){ data.double = 2; } //出现圈圈 wave.born(fruit.x[i], fruit.y[i]); } } } } function momBabyCollision () { if(data.fruitNum <= 0 || data.gameOver){ return; } let l = calLength2(mom.x, mom.y, baby.x, baby.y); if(l < 900){ //baby recover baby.babyBodyCount = 0; //mom mom.bigBodyCount = 0;//当大于碰到小鱼,归零 //score update data.addScore(); //圈圈出现 halo.born(baby.x, baby.y); } }
import React from "react"; import Nav from "./game/Nav"; import RankingPage from "./game/RankingPage"; import GameOver from "./game/GameOver"; import * as get from "./game/modules/GetRanks"; class App extends React.Component { constructor(props) { super(props); this.state = { number: 0, formular: null, randomNumber: 99, operator: { 1: "+", 2: "-", }, isRight: 0, isWrong: 0, isRankingOpen: false, result: "", fetching: false, rank: [], }; this.fetchRanks = this.fetchRanks.bind(this); } componentDidMount() { this.fetchRanks(); } setNumber() { this.setState({ number: Math.floor(Math.random() * 70) + 30 }); } createRandomFormular() { this.setState({ formular: `${Math.floor(Math.random() * this.state.randomNumber) + 1} ${this.state.operator[Math.floor(Math.random() * 2) + 1]} ${Math.floor(Math.random() * this.state.randomNumber) + 1} ${this.state.operator[Math.floor(Math.random() * 2) + 1]} ${Math.floor(Math.random() * this.state.randomNumber) + 1}`, }); } gotoGameOver() { this.setState({ isWrong: this.state.isWrong + 3 }); } checkAnswer() { if (eval(this.state.formular) === this.state.number) { this.setState((prevState) => ({ isRight: prevState.isRight + 1, result: "o", })); } else { this.setState((prevState) => ({ isWrong: prevState.isWrong + 1, result: "x", })); } } checkAnswerBelowNumber() { if (eval(this.state.formular) < this.state.number) { this.setState((prevState) => ({ isRight: prevState.isRight + 1, result: "o", })); } else { this.setState((prevState) => ({ isWrong: prevState.isWrong + 1, result: "x", })); } } checkAnswerAmongNumber() { if (eval(this.state.formular) > this.state.number) { this.setState((prevState) => ({ isRight: prevState.isRight + 1, result: "o", })); } else { this.setState((prevState) => ({ isWrong: prevState.isWrong + 1, result: "x", })); } } handleRankingButtonClick() { this.setState((prevState) => ({ isRankingOpen: !prevState.isRankingOpen, })); } handelStart() { this.setState({ isStart: true }); } clearNumber() { this.setState({ number: 0, isWrong: 0, isRight: 0, formular: null, result: "", isStart: false, }); } fetchRanks = async () => { this.setState({ fetching: true, }); const ranks = await get.getRanks(); console.log(ranks.data); this.setState({ rank: this.state.rank.concat(ranks.data), fetching: false, }); }; updateRanks = async () => { const ranks = await get.getRanks(); console.log(ranks.data); this.setState({ rank: this.state.rank.concat(ranks.data), }); }; render() { return ( <div> <GameOver score={this.state.isRight} defeat={this.state.isWrong} clear={this.clearNumber.bind(this)} update={this.updateRanks.bind(this)} /> {this.state.isWrong < 3 ? ( <div> <Nav set={this.setNumber.bind(this)} number={this.state.number} create={this.createRandomFormular.bind(this)} formular={this.state.formular} correct={this.checkAnswer.bind(this)} below={this.checkAnswerBelowNumber.bind(this)} among={this.checkAnswerAmongNumber.bind(this)} open={this.handleRankingButtonClick.bind(this)} isOpen={this.state.isRankingOpen} wrong={this.state.isWrong} right={this.state.isRight} over={this.gotoGameOver.bind(this)} result={this.state.result} /> <RankingPage isOpen={this.state.isRankingOpen} open={this.handleRankingButtonClick.bind(this)} rank={this.state.rank} /> </div> ) : null} </div> ); } } export default App;
$(function(){ var includes = $('[data-include]'); jQuery.each(includes, function(){ var file = $(this).data('include') + '.html'; $(this).load(file, function (params) { links = $(document).find('.nav-item a'); links.each(function () { const ruta = $(this).attr('href'); const actual = document.location.pathname; if (document.location.pathname == '/index.html') { $(this).attr('href', 'pages/' + $(this).attr('href')); }else{ $(this).attr('href', '../' + $(this).attr('href')); } }); }); if ("usuario" in localStorage) { var USER = JSON.parse(localStorage.usuario); $('.nombre_usuario').html(USER.nombres) } else { window.location.href='../../index.html' } }); });
import express from 'express' import passport from 'passport' import User from '../models/User' import ServiceProvider from '../services/ServiceProvider' import UserService from '../services/User' const router = express.Router() let Provider = new ServiceProvider(User) /** * GET /users */ router.get('/', passport.authenticate('jwt', { session: false }), async function (req, res) { const response = await Provider.all('-password -jwt') res.status(response.status).json(response) } ) /** * GET /users/:id * @param {string} id A valid mongoose ObjectId */ router.get('/:id', passport.authenticate('jwt', { session: false }), async function (req, res) { const id = req.params.id const response = await Provider.get(id, '-password -jwt') res.status(response.status).json(response) } ) /** * POST /users/ * @param {string} email User's email * @param {string} password User's password */ router.post('/', passport.authenticate('jwt', { session: false }), async function (req, res) { const { email, password } = req.body const response = await Provider.create({ email, password }, 'email') res.status(response.status).json(response) } ) /** * PUT /users/:id * @param {string} id A valid mongoose ObjectId * @param {string} password New password */ router.put('/:id', passport.authenticate('jwt', { session: false }), async function (req, res) { const id = req.params.id const params = { password: req.body.password } const response = await Provider.update(id, params) res.status(response.status).json(response) } ) /** * DELETE /users/:id * @param {string} id A valid mongoose ObjectId */ router.delete('/:id', passport.authenticate('jwt', { session: false }), async function (req, res) { const id = req.params.id const response = await Provider.delete(id) res.status(response.status).json(response) } ) /** * POST /users/auth * @param {string} email User's email * @param {string} password User's password */ router.post('/auth', async function (req, res) { const { email, password } = req.body const response = await UserService.authenticate(email, password) res.status(response.status).json(response) }) export default router
$(function () { changeAppNameSize(); $('#txtEmail').focus(); $('#btnDangNhap').click(function (e) { var email = $('#txtEmail').val().trim(); var pass = $('#txtPassword').val(); if (pass === '') { e.preventDefault(); $('.k-empty-password').show(); setTimeout(function () { $('.k-empty-password').hide(); }, 5000); $('#txtPassword').focus(); } if (email === '') { e.preventDefault(); $('.k-empty-username').show(); setTimeout(function () { $('.k-empty-username').hide(); }, 5000); $('#txtEmail').focus(); } }); $('#txtPassword,#txtEmail').focus(function () { $(this).select(); }); $('#ddlChuongTrinh').kendoDropDownList({ change: function () { $('#hfChuongTrinh').val(this.value()); }, dataSource: { data: [ { text: 'Quản lý hợp đồng mua sắm', value: 'HD' }, { text: 'Quản lý vật tư web', value: 'VT' } ] }, dataTextField: 'text', dataValueField: 'value' }); $('#ddlChuongTrinh').data('kendoDropDownList').value($('#hfChuongTrinh').val()); function changeAppNameSize() { $('.AppName').css('font-size', $(document).width() / 42); if ($('.AppName').height() > 80) $('.AppName').css('line-height', '40px'); else $('.AppName').css('line-height', '80px'); } });
'use strict'; import bankCtrl from './bankController'; import bankConfig from './routes'; export default angular .module('ae.bank', []) .controller('bankCtrl', bankCtrl) .config(bankConfig);
import React from 'react' import styled from 'styled-components' import Color from 'color' const StyledContainer = styled.div` background-color: ${({ theme }) => theme.pageContentSelectionColor}; * ::selection { background: ${({ theme }) => theme.pageContentSelectionColor}; } * ::-mox-selection { background: ${({ theme }) => new Color(theme.pageContentSelectionColor).darken(0.5).hex()}; } p { color: ${({ theme }) => theme.pageContentFontColor} } ` function WebsiteLayout({ children }) { return <StyledContainer>{children}</StyledContainer> } export default WebsiteLayout
$(function() { var arr = []; var arr1 = []; var goodImg = []; var goodLogo = []; var goodTitle = []; var goodb = []; var goodi = []; var goodzk = []; var goodsKey=[]; var goodskeyLength=[]; var goodsXsImg=[]; var goodsXsimglength=[]; var str = '<div class="priceScreen">' + '<input type="text" id="start-price"/> <b> - </b> <input type="text" id="end-price"/>' + '<input type="button" value="确认"/>' + '</div>' var r = window.location.search.substr(1).split("=")[1]; $.getJSON("js/" + r + ".json", function(data) { for(var key in data["list"]) { arr.push(data["list"][key].length) for(var i = 0; i < data["list"][key].length; i++) { arr1.push(data["list"][key][i]); } } for(var i = 0; i < arr.length; i++) { for(var j = 0; j < arr[i]; j++) { $(".screenContent").eq(i).append("<a href='javascript:;'><i></i><em></em></a>"); } } for(var i = 0; i < arr1.length; i++) { $(".screenContent").find("i").eq(i).text(arr1[i]) } $(".screenContent").eq(2).append(str); for(var i = 0; i < $(".screenContent").eq(0).find("a").length; i++) { $(".screenContent").eq(0).find("a").eq(i).attr("href", "list.html?name=goods" + (i + 1)); $(".screenContent").eq(0).find("a").eq(parseInt(r.split("goods")[1]) - 1).css({ border: "1px solid #f8584f", // padding: "0 3px", marginTop: "0", color: "#f8584f" }) $(".screenContent").eq(0).find("a").eq(parseInt(r.split("goods")[1]) - 1).find("em").css("opacity", 1); } //这个是分类的样式显示 }) // if(r=="goods1"){ $.getJSON("js/" + r + ".json", function(data) { //遍历goodsa for(var key1 in data[r]) { goodsKey.push(key1); goodskeyLength.push(data[r][key1]["img"].length) goodsXsImg.push(data[r][key1]["img"]) for(var i = 0; i < data[r][key1]["img"].length; i++) { goodImg.push(data[r][key1]["img"][i]); //装图片容器 } for(var i = 0; i < data[r][key1]["atitle"].length; i++) { goodLogo.push(data[r][key1]["atitle"][i][0]); goodTitle.push(data[r][key1]["atitle"][i][1]); goodb.push(data[r][key1]["atitle"][i][2]); goodi.push(data[r][key1]["atitle"][i][3]); goodzk.push(data[r][key1]["atitle"][i][4]); goodsXsimglength.push(data[r][key1]["atitle"][i][5]) } $(".screen").find("em").click(function() { $(this).closest("a").css({ border: "1px solid #fff", // padding: 0, marginTop: 0, color: "#000 " }) $(this).css("opacity", 0) }) $(".screen").find("i").click(function() { $(this).closest("a").css({ border: "1px solid #f8584f", // padding: "0 3px", marginTop: "0", color: "#f8584f" }) $(this).next("em").css("opacity", 1); }); //筛选点击结束 function logo() { $(".screen").eq(1).find("i").click(function() { var self = this; for(var i = 0; i < $(".goodlist_name").find("a").length; i++) { // console.log($(".goodlist_name").find("a").eq(i).text()) // console.log($(self).find("i").text()) if($(".goodlist_name").find("a").eq(i).text() != $(self).text()) { $(".goodlist_name").find("a").eq(i).closest("li").hide(); } } }); //a标签点击消失 $(".mainSearch").find("a").attr("href", "javascript:;"); //a标签去跳转 $(".screen").eq(1).find("em").click(function() { var selfem = this; for(var i = 0; i < $(".goodlist_name").find("a").length; i++) { $(".goodlist_name").find("a").eq(i).closest("li").show(); } }) } //这个方法是用来判断品牌的 logo() // console.log($(".mainSearch").find(".screen").eq(1).find("i").text().splice("-")) $(".mainSearch").find(".screen").eq(1).find("i").click(function() { var pirce = this; var pirceText = $(this).text().split("-"); for(var i = 0; i < $(".goodtpirce").find("b").length; i++) { var listPirce = $(".goodtpirce").find("b").eq(i).text().split("¥"); if((parseInt(listPirce[1]) > parseInt(pirceText[0]) && parseInt(listPirce[1]) < parseInt(pirceText[1])) == false) { $(".goodtpirce").find("b").eq(i).closest("li").hide(); } } }) $(".mainSearch").find(".screen").eq(1).find("em").click(function() { var selfem = this; for(var i = 0; i < $(".goodtpirce").find("b").length; i++) { $(".goodtpirce").find("b").eq(i).closest("li").show(); // console.log($(".goodtpirce").find("b").eq(i).closest("li")) } }) // $(".screenContent")..eq(1).find("a").attr("onclick","lihan();return false;") //价格点击筛选 $(".priceScreen").find("input").eq(2).click(function() { var selfpice = this; var startprice = $("#start-price").val(); var endprice = $("#end-price").val(); // console.log(endprice) for(var i = 0; i < $(".goodtpirce").find("b").length; i++) { var listPirce = $(".goodtpirce").find("b").eq(i).text().split("¥"); if((parseInt(listPirce[1]) > parseInt(startprice) || parseInt(listPirce[1]) < parseInt(endprice)) == false && (startprice != "" || endprice != "")) { $(".goodtpirce").find("b").eq(i).closest("li").hide(); } } }) $(".screen").eq(3).find("a").eq(1).attr("href","list.html?name=goods2") $(".screen").eq(3).find("a").eq(0).attr("href","list.html?name=goods1") } for(var i = 0; i < goodImg.length; i++) { //遍历加图片 $(".listGoods-ul").append($(".listGoods-ul").find("li").eq(0).clone()); $(".listGoods-lg").find("img").eq(i).attr("src", "img/subgoods/" + goodImg[i] + ".jpg"); $(".listGoods-lg").find("img").eq(i).data("dataImg",goodImg[i]); $(".listImgXs-box").find("img").eq(i).attr("src","img/subgoods/" + goodImg[i] + ".jpg"); } $(".listGoods-ul").find("li").last().remove(); //最后一个删除 $(".listGoods-ul").find("li").hide() //给他加logo //cookie //str1= goodsTitle标题 + "," + goodsPirce 价格+ "," + imgKey 图片key + "," + imgLength 隐藏属性 +","+oldPirce老价格+ ","+goodsLogo logo+";"; var arr11=[]; for(var i=0;i<goodsXsimglength.length;i++){ if(goodsXsimglength[i]!=undefined){ arr11.push(goodsXsimglength[i]); } } for(var j=0;j<arr11.length;j++){ $(".listGoods-ul").find("li").find(".listGoods-lg").find("img").eq(j).data("length",arr11[j]) } // console.log(arr11) // console.log($(".listGoods-ul").find("li").find(".listGoods-lg").find("img").eq(0).data("length")) // $(".listGoods-ul").find("li").find(".listGoods-lg").find("img").eq(0).data("length",3) // $(".listGoods-ul").find("li").find(".listGoods-lg").find("img").eq(1).data("length",1) // $(".listGoods-ul").find("li").find(".listGoods-lg").find("img").eq(2).data("length",2); $(".listGoods-ul").find("li").find(".listGoods-lg").attr("target","_blank") $(".listGoods-ul").find("li").each(function(index,ele){ $.cookie("goods",""); var str3="" var imgLength=""; $(this).click(function(){ console.log($(this).find("img").attr("src")) var goodsImg = $(this).find("img").attr("src"); var goodsTitle=$(this).closest("li").find(".goodtitle").find("a").text(); var goodsPirce=$(this).closest("li").find(".goodtpirce").find("b").text(); var imgKey=$(this).closest("li").find(".listGoods-lg").find("img").attr("src").split(".jpg")[0].split("/")[2]; if(window.location.href.slice(-1)==1){ imgLength=$(this).closest("li").find(".listGoods-lg").find("img").data("length"); }else{ imlength=undefined; } var oldPirce=$(this).closest("li").find(".goodtpirce").find("i").text(); var goodsLogo=$(this).closest("li").find(".goodlist_name").find("a").text() // console.log($(this).closest("li").find(".listGoods-lg").find("img").data("length")); str1= goodsTitle + "," + goodsPirce + "," + imgKey + "," + imgLength +","+oldPirce+ ","+goodsLogo+";"; str3=goodsImg + "," + goodsTitle + "," + goodsPirce + ";"; // $.cookie("his", str3 + $.cookie("his")); $.cookie("goods",str1); $(".listGoods-ul").find("li").find(".listGoods-lg").attr("href","goods.html?"+"goodsTitle="+goodsTitle+"&goodsPirce="+goodsPirce+"&imgKey="+imgKey+"&imgLength="+imgLength+"&oldPirce="+oldPirce+"&goodsLogo="+goodsLogo); // console.log(str3) }) }) // console.log($.cookie("his")) for(var i = 0; i < goodLogo.length; i++) { $(".goodlist_name").find("a").eq(i).text(goodLogo[i]); //logo标题后期可能要过来加上链接的 } for(var i = 0; i < goodTitle.length; i++) { $(".goodtitle").find("a").eq(i).text(goodTitle[i]); } for(var i = 0; i < goodb.length; i++) { $(".goodtpirce").find("b").eq(i).text(goodb[i]); } for(var i = 0; i < goodi.length; i++) { $(".goodtpirce").find("i").eq(i).text(goodi[i]); } for(var i = 0; i < goodzk.length; i++) { $(".goodlist_discount").eq(i).text(goodzk[i] + "折"); } //遍历查看data属性 $.getJSON("js/" + r + ".json", function(data) { // console.log(data[r]) for(var i=0;i<$(".listGoods-lg").find("img").length;i++){ // console.log($(".listGoods-lg").find("img").eq(i).data("dataImg").split("-")[0].substr(-1)); for(var j=0;j<goodsKey.length;j++){ if($(".listGoods-lg").find("img").eq(i).data("dataImg").split("-")[0].substr(-1)==j+1){ $(".listGoods-lg").find("img").eq(i).attr("title",goodsKey[j]); } } for(var k=0;k<goodskeyLength.length;k++){ if($(".listGoods-lg").find("img").eq(i).data("dataImg").split("-")[0].substr(-1)==k+1){ for(var g=0;g<goodskeyLength[k];g++){ $(".listImgXs-box").eq(i).append("<a href='javascript:;'><img/></a>"); } } } for(h=0;h<goodsXsImg.length;h++){ if($(".listGoods-lg").find("img").eq(i).data("dataImg").split("-")[0].substr(-1)==h+1){ // $(".listImgXs-box").eq(i).find("img").eq(h).not(":first").attr("src","img/subgoods/"+goodsXsImg[h]+".jpg"); for(var n=0;n<goodsXsImg[h].length;n++){ // console.log(goodsXsImg[h].length) $(".listImgXs-box").eq(i).find("img").eq(n)[0].src="img/subgoods/"+goodsXsImg[h][n]+".jpg" // $(".listImgXs-box").eq(i).find("img").not(":first").attr("src","img/subgoods/"+goodsXsImg[h][n]+".jpg");想· // console.log(goodsXsImg[h]) } } } } if(r=="goods1"){ console.log($(".listImgXs-box").eq(0).find("a").eq(1).find("img").eq(0)) $(".listImgXs-box").eq(0).find("a").eq(0).find("img").eq(0).attr("src","img/goodsxq/goods1-1l.jpg"); $(".listImgXs-box").eq(0).find("a").eq(1).find("img").eq(0).attr("src","img/goodsxq/goods1-2l.jpg"); $(".listImgXs-box").eq(0).find("a").eq(2).find("img").eq(0).attr("src","img/goodsxq/goods1-3l.jpg"); $(".listImgXs-box").eq(0).find("a").eq(3).find("img").eq(0).attr("src","img/goodsxq/goods1-4l.jpg"); $(".listImgXs-box").eq(0).find("a").eq(4).find("img").eq(0).attr("src","img/goodsxq/goods1-5l.jpg"); $(".listImgXs-box").eq(1).find("a").eq(0).find("img").eq(0).attr("src","img/goodsxq/goods2-1l.jpg"); $(".listImgXs-box").eq(1).find("a").eq(1).find("img").eq(0).attr("src","img/goodsxq/goods2-2l.jpg"); $(".listImgXs-box").eq(1).find("a").eq(2).find("img").eq(0).attr("src","img/goodsxq/goods2-3l.jpg"); $(".listImgXs-box").eq(1).find("a").eq(3).find("img").eq(0).attr("src","img/goodsxq/goods2-4l.jpg"); $(".listImgXs-box").eq(1).find("a").eq(4).find("img").eq(0).attr("src","img/goodsxq/goods2-5l.jpg"); } var lgim="" $(".listImgXs-box").find("img").hover(function(){ lgimg=$(this).closest("li").find('.listGoods-lg').find("img").attr("src") $(this).closest("li").find('.listGoods-lg').find("img").attr("src",$(this).attr("src")); },function(){ $(this).closest("li").find('.listGoods-lg').find("img")[0].src=lgimg; })//小图切换大图 $(".listImgXs-box").each(function(index,ele){ var listselft=this; $(this).css("width",$(this).find("a").length*35); $(this).parent(".listGoods-scroll").next(".listToggle-r").click(function(){ $(listselft).animate({"left":"-150px"},1000); }) $(this).parent(".listGoods-scroll").prev(".listToggle-l").click(function(){ $(listselft).animate({"left":"0px"},1000); }) //console.log($(this).find("a").length) }) }) $(".pagination").css("width", (Math.ceil(goodLogo.length / 20)) * 30 + 173); var listIndex = 0; for(var i = 0; i < Math.ceil(goodLogo.length / 20); i++) { // $(".pagination").append("<a href='javascript:;'></a>") $(".pagination").find("a").eq(0).before("<a href='javascript:;' class='listIndex'></a>"); $(".filterRight-l").find("b").eq(0).text(($(".currentPage").index() + 2) + "/" + parseInt($(".pagination").find(".listIndex").length)) $(".filterRight-l").find("b").eq(1).text($(".pagination").find(".listIndex").length) } function listPage() { for(var i = 0; i < $(".listGoods-ul").find("li").length; i++) { if(i >=listIndex * 20 && i <(listIndex + 1) * 20) { $(".listGoods-ul").find("li").eq(i).show() } else { $(".listGoods-ul").find("li").eq(i).hide() } } } $(".pagination").find(".listIndex").each(function(index, ele) { $(ele).text(index + 1) $(ele).eq(index).addClass("currentPage"); $(ele).click(function() { $(this).addClass("currentPage").siblings().removeClass("currentPage"); listIndex = $(this).index() listPage(); $(".filterRight-l").find("b").eq(0).text($(".currentPage").index() + 1 + "/" + parseInt($(".pagination").find(".listIndex").length)) }) }); //切换下一页 function IndexAdd() { if(listIndex < $(".pagination").find(".listIndex").length - 1) { listIndex++; } listPage() $(".filterRight-l").find("b").eq(0).text($(".currentPage").index() + 2 + "/" + parseInt($(".pagination").find(".listIndex").length)) if($(".currentPage").index() + 1 < $(".pagination").find(".listIndex").length) { $(".currentPage").removeClass("currentPage").next().addClass("currentPage"); } if($(".currentPage").index() + 1 == $(".pagination").find(".listIndex").length) { return false; } } $(".filterRight-l").click(function() { if(listIndex < $(".pagination").find(".listIndex").length - 1) { listIndex++; } listPage() if($(".currentPage").index() + 1 < $(".pagination").find(".listIndex").length) { $(".filterRight-l").find("b").eq(0).text($(".currentPage").index() + 2 + "/" + parseInt($(".pagination").find(".listIndex").length)) $(".currentPage").removeClass("currentPage").next().addClass("currentPage"); } if($(".currentPage").index() + 3 == $(".pagination").find(".listIndex").length) { return false; } }) $(".nextList").click(function() { IndexAdd() }) //点击下一页 listPage() $(".lastList").click(function() { $(".currentPage").removeClass("currentPage"); $(".pagination").find(".listIndex").last().addClass("currentPage"); listIndex = 5; listPage() }) //最后一页 //显示隐藏li }) // } //点击变色 //筛选品牌 })
#!/usr/bin/env node /** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ /** * Generates a draft release notes markdown file for a release. This script * takes a start version of the union package, and optionally an end version. * It then finds the matching versions for all the dependency packages, and * finds all commit messages between those versions. * * The release notes are grouped by repository, and then bucketed by a set of * tags which committers can use to organize commits into sections. See * DEVELOPMENT.md for more details on the available tags. * * This script will ask for your github token which is used to make requests * to the github API for usernames for commits as this is not stored in git * logs. You can generate a token for your account here; * https://github.com/settings/tokens * * Usage: * # Release notes for all commits after tfjs union version 0.9.0. * yarn release-notes --startVersion 0.9.0 --out ./draft_notes.md * * # Release notes for all commits after version 0.9.0 up to and including * # version 0.10.0. * yarn release-notes --startVersion 0.9.0 --endVersion 0.10.3 \ * --out ./draft_notes.md */ import * as commander from 'commander'; import * as mkdirp from 'mkdirp'; import * as readline from 'readline'; import * as fs from 'fs'; import * as util from './util'; import {$, Commit, Repo, RepoCommits} from './util'; // tslint:disable-next-line:no-require-imports const octokit = require('@octokit/rest')(); const TMP_DIR = '/tmp/tfjs-release-notes'; commander.option('--startVersion <string>', 'Which version of union to use') .option('--endVersion <string>', 'Which version of union to use') .option('--out <string>', 'Where to write the draft markdown') .parse(process.argv); if (commander.startVersion == null) { console.log('Please provide a start version with --startVersion.'); process.exit(1); } if (commander.out == null) { console.log('Please provide a file to write the draft to with --out'); process.exit(1); } const UNION_DEPENDENCIES: Repo[] = [ {name: 'Core', identifier: 'tfjs-core'}, {name: 'Data', identifier: 'tfjs-data'}, {name: 'Layers', identifier: 'tfjs-layers'}, {name: 'Converter', identifier: 'tfjs-converter'} ]; const startVersion = 'v' + commander.startVersion; const endVersion = commander.endVersion != null ? 'v' + commander.endVersion : 'HEAD'; mkdirp(TMP_DIR, (err) => { if (err) { console.log('Error creating temp dir', TMP_DIR); process.exit(1); } }); // Remove anything that exists already in the tmp dir. $(`rm -f -r ${TMP_DIR}/*`); // Get all the commits of the union package between the versions. const unionCommits = $(`git log --pretty=format:"%H" ${startVersion}..${endVersion}`); const commitLines = unionCommits.trim().split('\n'); // Read the union package.json from the earliest commit so we can find the // dependencies. const earliestCommit = commitLines[commitLines.length - 1]; const earliestUnionPackageJson = JSON.parse($(`git show ${earliestCommit}:package.json`)); const latestCommit = commitLines[0]; const latestUnionPackageJson = JSON.parse($(`git show ${latestCommit}:package.json`)); const repoCommits: RepoCommits[] = []; // Clone all of the dependencies into the tmp directory. UNION_DEPENDENCIES.forEach(repo => { // Find the version of the dependency from the package.json from the // earliest union tag. const npm = '@tensorflow/' + repo.identifier; const repoStartVersion = earliestUnionPackageJson.dependencies[npm]; const repoEndVersion = latestUnionPackageJson.dependencies[npm]; console.log( `${repo.name}: ${repoStartVersion}` + ` =====> ${repoEndVersion}`); const dir = `${TMP_DIR}/${repo.name}`; // Clone the repo and find the commit from the tagged start version. console.log(`Cloning ${repo.identifier}...`); $(`mkdir ${dir}`); $(`git clone https://github.com/tensorflow/${repo.identifier} ${dir}`); const startCommit = $(repoStartVersion != null ? `git -C ${dir} rev-list -n 1 v${repoStartVersion}` : // Get the first commit if there are no tags yet. `git rev-list --max-parents=0 HEAD`); console.log('Querying commits...'); // Get subjects, bodies, emails, etc from commit metadata. const commitFieldQueries = ['%s', '%b', '%aE', '%H']; const commitFields = commitFieldQueries.map(query => { // Use a unique delimiter so we can split the log. const uniqueDelimiter = '--^^&&'; const versionQuery = repoStartVersion != null ? `v${repoStartVersion}..v${repoEndVersion}` : `#${startCommit}..v${repoEndVersion}`; return $(`git -C ${dir} log --pretty=format:"${query}${uniqueDelimiter}" ` + `${versionQuery}`) .trim() .split(uniqueDelimiter) .slice(0, -1) .map(str => str.trim()); }); const commits: Commit[] = []; for (let i = 0; i < commitFields[0].length; i++) { commits.push({ subject: commitFields[0][i], body: commitFields[1][i], authorEmail: commitFields[2][i], sha: commitFields[3][i] }); } repoCommits.push({ repo, startVersion: repoStartVersion, endVersion: repoEndVersion, startCommit, commits }); }); // Ask for github token. const rl = readline.createInterface({input: process.stdin, output: process.stdout}); rl.question( 'Enter GitHub token (https://github.com/settings/tokens): ', token => writeReleaseNotesDraft(token)); export async function writeReleaseNotesDraft(token: string) { octokit.authenticate({type: 'token', token}); const notes = await util.getReleaseNotesDraft(octokit, repoCommits); fs.writeFileSync(commander.out, notes); console.log('Done writing notes to', commander.out); // So the script doesn't just hang. process.exit(0); }
import Review from './Review.container' export { Review }
import { connect } from "react-redux"; import FilterLink from "../components/FilterLink"; import { setPurchasedFilter } from "../actions"; import { filterGrocery } from "../actions"; // Compare the current filter in state to the filter // link container's own prop of filter to see if it // is the active one const mapStateToProps = (state, ownProps) => { return { active: state.groceryFilters === ownProps.filter }; }; const mapDispatchToProps = (dispatch, ownProps) => { return { onClick: e => { // Don't reload the page e.preventDefault(); // Pass in the filter for that link to set it in the store dispatch(setPurchasedFilter(ownProps.filter)); dispatch(filterGrocery(ownProps.filter)); } }; }; const FilterLinkContainer = connect(mapStateToProps, mapDispatchToProps)( FilterLink ); export default FilterLinkContainer;
//binding for showing tooltip only when the element text has ellipsis (function( factory ) { "use strict"; if ( typeof define === 'function' && define.amd ) { // AMD define( ['jquery', 'knockout', 'mario'], function ( $, ko, mario ) { return factory( $, ko, mario); } ); } else if ( typeof exports === 'object' ) { // CommonJS module.exports = function () { var jq = $; if(!jq) { jq = require('jquery'); } var ko = require('knockout'), mario = require('mario'); return factory( jq, ko, mario ); }; } else { // Browser if(!ko || !mario || !jQuery) { throw new Error('Dependencies not found. [jQuery, ko, mario] required as global variables if not using AMD'); } factory( jQuery, ko, mario); } } (function ($, ko, mario) { ko.bindingHandlers.ellipsisTooltip = { init: function (element, valueAccessor, allBindingsAccessor) { var text = allBindingsAccessor().text, value = valueAccessor(), $element = $(element); if (value && isEllipsisPresent(element)) { $element.attr('title', $element.text()); } else { $element.removeAttr('title'); } //Make sure ellipsisTooltip is applied after text binding is updated in case its an observable if (ko.isObservable(text)) { text.subscribe(function (newValue) { $element.ellipsisTooltip(); $element.trigger('ellipsisTooltip:updated'); }); } }, update: function (element, valueAccessor) { var value = valueAccessor(), $element = $(element); if (value && isEllipsisPresent(element)) { $element.attr('title', $element.text()); } else { $element.removeAttr('title'); } } }; function isEllipsisPresent(element) { if (mario.chrome || mario.safari) { return (element.offsetWidth < element.scrollWidth); } // In IE and FF in some cases element.offsetWidth and element.scrollWidth are same even though there is ellipsis. // So we make a clone div with same text and width = 'auto' and compare its width var $element = $(element), isEllipsisPresent = false, clone = document.createElement('div'), $clone = $(clone).text($element.text()); clone.style.cssText = getComputedStyleCssText(element); $clone .css({ position: 'absolute', top: '0px', left: '0px', visibility: 'hidden', width: 'auto'}) .appendTo('body'); if ($clone.width() > $element.width()) { isEllipsisPresent = true; } $clone.remove(); return isEllipsisPresent; } function getComputedStyleCssText(element) { var style = window.getComputedStyle(element), cssText; if (style.cssText !== '') { return style.cssText; } cssText = ''; for (var i = 0; i < style.length; i++) { cssText += style[i] + ': ' + style.getPropertyValue(style[i]) + '; '; } return cssText; } }));
import React, { useState, useContext } from 'react'; import { NavLink, useHistory } from 'react-router-dom'; import { makeStyles } from '@material-ui/core/styles'; import Modal from '../../shared/components/UIElements/Modal'; import ErrorModal from '../../shared/components/UIElements/ErrorModal'; import { AuthContext } from '../../shared/context/auth-context'; import { useHttpClient } from '../../shared/hooks/http-hook'; import { red } from '@material-ui/core/colors'; import { Card, Button, CardHeader, CardMedia, CardContent, CardActions, Typography, } from '@material-ui/core'; import './ProductItem.css'; const useStyles = makeStyles((theme) => ({ root: { width: 350, }, media: { height: 420, paddingTop: '56.25%', }, avatar: { backgroundColor: red[500], }, button: { margin: theme.spacing(1), }, })); const SaberItem = (props) => { const classes = useStyles(); const history = useHistory(); const { error, sendRequest, clearError } = useHttpClient(); const auth = useContext(AuthContext); const [showConfirmModal, setShowConfirmModal] = useState(false); const showDeleteWarningHandler = () => { setShowConfirmModal(true); }; const cancelDeleteHandler = () => { setShowConfirmModal(false); }; const confirmDeleteHandler = async () => { setShowConfirmModal(false); try { await sendRequest( process.env.REACT_APP_BACKEND_URL + `/saber/${props.id}`, 'DELETE', null, { Authorization: 'Bearer ' + auth.token, } ); props.onDelete(props.id); } catch (err) {} }; const orderItem = async () => { console.log('order yap', props.price); try { await sendRequest( `${process.env.REACT_APP_BACKEND_URL}/order/saber/${props.saberId}`, 'POST', null, { Authorization: 'Bearer ' + auth.token, } ); history.push(`/saber/order`); } catch (err) {} }; console.log('price', props.price); return ( <React.Fragment> <ErrorModal error={error} onClear={clearError} /> <Modal show={showConfirmModal} onCancel={cancelDeleteHandler} header='Are you sure?' footerClass='place-item__modal-actions' footer={ <React.Fragment> <Button variant='contained' color='primary' onClick={cancelDeleteHandler} > CANCEL </Button> <Button variant='contained' color='secondary' className={classes.button} onClick={confirmDeleteHandler} > DELETE </Button> </React.Fragment> } > <p> Do you want to proceed and delete this saber? Please note that it can't be undone thereafter. </p> </Modal> <li className='place-item'> <Card className={`${classes.root} place-item-container-place`}> <CardMedia className={classes.media} image={`${process.env.REACT_APP_ASSET_URL}/${props.image}`} title='Paella dish' > <div className='item-info-part-place'> <CardHeader className={classes.root} title={props.name} /> <CardContent> <Typography variant='body2' color='textSecondary' component='p'> Crystal Name: {props.crystal.name} </Typography> <Typography variant='body2' color='textSecondary' component='p'> Crystal Color: {props.crystal.color} </Typography> {auth.isAdmin && ( <Typography variant='body2' color='textSecondary' component='p' > Available : {props.available} </Typography> )} {!auth.isAdmin && ( <Typography variant='body2' gutterBottom> {props.price === 0 ? props.degree : `Price : $$ ${props.price}` } </Typography> )} </CardContent> <CardActions> {auth.isAdmin && ( <Button variant='contained' color='primary' component={NavLink} to={{ pathname: `/sabers/${props.saberId}`, }} > EDIT </Button> )} {auth.isAdmin && ( <Button variant='contained' color='secondary' onClick={showDeleteWarningHandler} className={classes.button} > DELETE </Button> )} {!auth.isAdmin && ( <Button variant='contained' color='secondary' onClick={orderItem} className={classes.button} > Order </Button> )} </CardActions> </div> </CardMedia> </Card> </li> </React.Fragment> ); }; export default SaberItem;
/** * 意见控制层 */ Ext.define('eapp.controller.Shop', { extend:'Ext.app.Controller', config: { refs: { mainview:'mainview', shoppageview:'shoppageview', addshopview:'addshopview', shoplistview:'shoplistview', sqshopname:{selector: 'shoppageview formpanel fieldset labelEx[name=sqshopname]'}, fbfwshopname:{selector: 'shoppageview formpanel fieldset labelEx[name=fbfwshopname]'}, ckfwshopname:{selector: 'shoppageview formpanel fieldset labelEx[name=ckfwshopname]'}, shopsubmitname:{selector: 'addshopview formpanel button[name=shopsubmitname]'}, }, control: { sqshopname: { tap:'OnSqshopnameTap', }, fbfwshopname: { tap:'OnFbfwshopnameTap' }, ckfwshopname: { tap:'OnCkfwshopnameTap', }, shopsubmitname: { tap:'OnShopsubmitnameTap' } } }, /** * 申请商户 */ OnShopsubmitnameTap:function() { var me = this; var addshopview = me.getAddshopview(); if(addshopview == null || addshopview == 'undefined') { addshopview = Ext.create('eapp.view.hexiejiayuan.AddShop'); } //商户名称 var shopname = Ext.ComponentQuery.query('#shopnameid', addshopview)[0].getValue(); // 服务类别 var shopfw = Ext.ComponentQuery.query('#shopfwid', addshopview)[0].getValue(); // 电话 var tel = Ext.ComponentQuery.query('#shoptelid', addshopview)[0].getValue(); // 地址 var shopfwdz = Ext.ComponentQuery.query('#shopfwdzid', addshopview)[0].getValue(); // 服务内容 var shopfwcontent = Ext.ComponentQuery.query('#shopfwcontentid', addshopview)[0].getValue(); if(shopname == null || shopname == 'undefined' || shopname.length <= 0) { eapp.view.Dialogs.showAlert('智慧潘家园','商户名称不能为空!~'); return; } if(shopfw == null || shopfw == 'undefined' || shopfw.length <= 0) { eapp.view.Dialogs.showAlert('智慧潘家园','服务类别不能为空!~'); return; } if(tel == null || tel == 'undefined' || tel.length <= 0) { eapp.view.Dialogs.showAlert('智慧潘家园','电话不能为空!~'); return; } if(shopfwdz == null || shopfwdz == 'undefined' || shopfwdz.length <= 0) { eapp.view.Dialogs.showAlert('智慧潘家园','商户地址不能为空!~'); return; } if(shopfwcontent == null || shopfwcontent == 'undefined' || shopfwcontent.length <= 0) { eapp.view.Dialogs.showAlert('智慧潘家园','服务内容不能为空!~'); return; } var user = eapp.util.GlobalData.getCurrentUser(); var userid = user.get('userid'); Ext.Viewport.setMasked({ xtype: 'loadmask', message: '请稍候...'}); var shopService = Ext.create('eapp.business.ShopService'); shopService.addshop(userid,shopname,tel,shopfw,shopfwdz,shopfwcontent, { success:function(josnData) { if(jsonData == "OK") { eapp.view.Dialogs.showAlert('智慧潘家园','申请提交成功!~'); var backButton = me.getMainview().getNavigationBar().getBackButton(); backButton.fireEvent('tap', backButton, null, null); }else { eapp.view.Dialogs.showAlert('智慧潘家园','申请提交失败!~'); } console.log(jsonData); Ext.Viewport.setMasked(false); }, failure: function(message) { console.log(message); Ext.Viewport.setMasked(false); } }); }, /** * 跳转到申请商户页面 */ OnSqshopnameTap:function() { var me = this; var addshopview = me.getAddshopview(); if(addshopview == null || addshopview == 'undefined') { addshopview = Ext.create('eapp.view.hexiejiayuan.AddShop'); } me.getMainview().push(addshopview); var len = eapp.app.pageStack.length; if(eapp.app.pageStack[len-1] != 'addshopview') { eapp.app.pageStack.push('addshopview'); } }, /** * 显示服务列表 */ OnFbfwshopnameTap:function() { var me = this; var shoplistview = me.getShoplistview(); if(shoplistview == null || shoplistview == 'undefined') { shoplistview = Ext.create('eapp.view.hexiejiayuan.ShopList'); } var user = eapp.util.GlobalData.getCurrentUser(); var userid = user.get('userid'); var shopService = Ext.create('eapp.business.ShopService'); Ext.Viewport.setMasked({ xtype: 'loadmask', message: '请稍候...'}); shopService.findshoplist(userid, { success:function(jsonData) { shoplistview.init(jsonData); console.log(jsonData); Ext.Viewport.setMasked(false); }, failure: function(message) { console.log(message); Ext.Viewport.setMasked(false); } }); me.getMainview().push(shoplistview); var len = eapp.app.pageStack.length; if(eapp.app.pageStack[len-1] != 'shoplistview') { eapp.app.pageStack.push('shoplistview'); } }, /** * 查看服务 */ OnCkfwshopnameTap:function() { alert('查看服务'); } });
module.exports = { apiKey: "FIREBASE_API_KEY", authDomain: "xxxxxx.firebaseapp.com", databaseURL: "https://xxxxxxx.firebaseio.com", projectId: "xxxxxxx", storageBucket: "xxxxxxx.appspot.com", messagingSenderId: "xxxxxxxx" };
require("dotenv").config(); // Get ARGS if (process.argv.length < 3) { console.log("\nRequires one argument: RGMID\n"); process.exit(1); } let nextScreen = null; try { nextScreen = parseInt(process.argv[2]); } catch (e) { console.error("Could not parse number"); process.exit(1); } const firebase = require("firebase"); const app = firebase.initializeApp(JSON.parse(process.env.FIREBASE_CONFIG)); app.database().ref("/chain/").set({ node: { nextScreen, }, }); setTimeout(() => { process.exit(0); }, 500);
import React from "react"; import { Box, Flex, Heading, Text, Select, Skeleton, useMediaQuery, } from "@chakra-ui/react"; import Sidebar from "./Sidebar"; import { getDash, updateDash } from "../data/api"; import { useHistory } from "react-router-dom"; import { formattedTaskDate, MILLISECONDS_IN_HOUR, msTimestamp, msToFormattedTime, } from "../helpers/date"; import applicationColors from "../style/colors"; import { convertWorkToHours, sum, totalIncome, greeting, } from "../helpers/helper"; import { BarChart, PieChart } from "./charts/DashChart"; import { dashReducer } from "../data/reducers"; import CurrencyContext from "../contexts/currencyContext"; import { HamburgerBox, HamburgerLine } from "./styled/HamburgerElements"; const Dashboard = () => { // ----- STATE ----- let history = useHistory(); const initialState = { loading: false, error: null, user: null, tasks: null, workPeriods: null, nextProject: null, active: null, period: "week", }; const [dashState, dispatch] = React.useReducer(dashReducer, initialState); const { user, tasks, loading, workPeriods, period, error, nextProject, active, } = dashState; const { currency } = React.useContext(CurrencyContext); const [sidebarOpen, setSidebarOpen] = React.useState(false); // MEDIA QUERIES const [breakpoint500] = useMediaQuery("(max-width: 500px)"); const [breakpoint900] = useMediaQuery("(max-width: 900px)"); const [breakpoint1000] = useMediaQuery("(max-width: 1000px)"); const [breakpoint1500] = useMediaQuery("(max-width: 1500px)"); // ----- RENDER ----- React.useEffect(() => { dispatch({ type: "request" }); getDash() .then((data) => { // Load over at least 1 secs - smoother transition setTimeout(() => { dispatch({ type: "success", tasks: data.tasks, user: data.user, work_periods: data.work_periods, nextProject: data.next_project, active: [data.active_clients, data.active_projects], }); }, 1000); }) .catch((e) => { // Redirect unauthorised if (e?.response?.status === 401) history.push("/401"); dispatch({ type: "failure", data: e.message }); }); }, [history]); // Set title React.useEffect(() => { window.document.title = `ClockOn | ${ user?.name ? `${user?.name} - ` : "" } Dashboard`; }, [user]); // ---- FETCH NEW WORK PERIODS ----- React.useEffect(() => { dispatch({ type: "request" }); updateDash(period) .then((data) => { if (data.work_periods) { setTimeout(() => { dispatch({ type: "updateWorkPeriods", data: data.work_periods }); }, 1000); } }) .catch((e) => { // Redirect unauthorised if (e?.response?.status === 401) history.push("/401"); }); }, [period]); return ( <Flex h="100%"> {/* Hamburger */} <Box display={breakpoint1000 && !sidebarOpen ? "block" : "none"} position="fixed" left="10px" top="10px" id="hamburger" cursor="pointer" borderRadius="50%" boxShadow="3px 3px 10px 3px rgba(0, 0,0, .2)" zIndex="1000" onClick={() => setSidebarOpen(true)} > <HamburgerBox> <HamburgerLine /> <HamburgerLine /> <HamburgerLine /> </HamburgerBox> </Box> {/* Sidebar */} <Box w="200px" bgGradient="linear(to-b, #30415D, #031424)" h="100%" p="15px" opacity={breakpoint1000 && !sidebarOpen ? 0 : 1} transition=".3s" display={breakpoint1000 && !sidebarOpen ? "none" : "block"} position="fixed" id="sidebar" zIndex="1000" > <Sidebar setSidebarOpen={setSidebarOpen} /> </Box> <Box flex="1" ml={breakpoint1000 ? "0" : "200px"}> <Flex direction="column" align="center" paddingTop="50px" bg={breakpoint1000 ? applicationColors.NAVY : "white"} minHeight="100vh" w="100%" > {(loading || error) && ( <Flex direction="column" h="50vh" align="center" justify="center"> {/* LOADING */} {loading && ( <> <Heading mb="40px" size="2xl" color={breakpoint1000 ? "white" : "gray.700"} fontWeight="400" > Loading Dashboard </Heading> <Flex w="100px" justify="space-between"> <Skeleton startColor={applicationColors.LIGHT_BLUE} endColor={applicationColors.NAVY} h="30px" w="30px" borderRadius="50%" /> <Skeleton startColor={applicationColors.LIGHT_BLUE} endColor={applicationColors.NAVY} h="30px" w="30px" borderRadius="50%" /> <Skeleton startColor={applicationColors.LIGHT_BLUE} endColor={applicationColors.NAVY} h="30px" w="30px" borderRadius="50%" /> </Flex> </> )} {/* ERROR */} {error && ( <Heading size="2xl" color={applicationColors.ERROR_COLOR} fontWeight="400" > An error occurred whilst loading </Heading> )} </Flex> )} {/* REGULAR APPEARANCE */} {!loading && !error && ( <Box> {/* GREETING */} <Heading as="h2" size="2xl" mb={breakpoint1500 ? "30px" : "0"} style={{ fontWeight: 300 }} color={breakpoint1000 ? "white" : "#031424"} textAlign="center" > {greeting()},{" "} <strong style={{ color: applicationColors.DARK_LIGHT_BLUE }}> {user?.name}! </strong> </Heading> {/* ROW */} <Flex marginBottom="25px" direction={breakpoint1500 ? "column-reverse" : "row"} p="20px" width="100%" > <Flex direction="column" justify="center" align="center" mr={breakpoint1000 ? "0" : "40px"} > {/* BAR GRAPH */} <Box display={breakpoint500 ? "none" : "block"}> <Heading alignSelf="center" as="h3" size="lg" color={breakpoint1000 ? "white" : "gray.700"} mb="10px" > Hours Worked Per Project </Heading> <BarChart workPeriods={workPeriods} period={period} /> </Box> {/* TASKS */} <Flex direction="column" padding={breakpoint1000 ? "0" : "20px"} width={breakpoint900 ? "90vw" : "750px"} marginTop="50px" > <Heading as="h3" mb="20px" color={ breakpoint1000 ? applicationColors.DARK_LIGHT_BLUE : "gray.700" } size="lg" > Upcoming Tasks </Heading> {(!tasks || tasks.length === 0) && ( <Text>No tasks to display</Text> )} {tasks?.map((task) => { return ( <Flex key={task.id} align="center" p="3px" w="90%" fontWeight={ msTimestamp(Date.now()) > msTimestamp(task.due_date) ? "bold" : "400" } color={ msTimestamp(Date.now()) > msTimestamp(task.due_date) ? applicationColors.ERROR_COLOR : breakpoint1000 ? "white" : "gray.600" } fontSize={breakpoint1000 ? "sm" : "med"} > <Text width="100px"> {formattedTaskDate(task.due_date)} </Text> <Box bg={task.project_color} mr="5px" ml="10px" style={{ width: "10px", height: "10px", borderRadius: "50%", }} ></Box> <Text w="100px" mr="20px" whiteSpace="nowrap" overflow="hidden" textOverflow="ellipsis" > {task.project} </Text> <Text whiteSpace={breakpoint1000 ? "wrap" : "nowrap"} overflow="hidden" textOverflow="ellipsis" flex="1" > {task.title} </Text> </Flex> ); })} </Flex> </Flex> {/* WRAPPER */} <Flex direction="column" width={breakpoint1000 ? "95%" : "90%"} alignSelf="center" align={breakpoint1500 ? "center" : "start"} mb={breakpoint1500 ? "75px" : "0"} > <Flex direction="row" justify="space-around"> {/* TOTALS */} <Flex direction="column" align="center"> <Select alignSelf="flex-end" w={breakpoint1500 ? "100%" : "200px"} mb={breakpoint1000 ? "20px" : "10px"} color={breakpoint1000 ? "white" : "gray.700"} textTransform="uppercase" value={period} fontSize={breakpoint1000 ? "md" : "lg"} onChange={(e) => dispatch({ type: "setPeriod", data: e.target.value, }) } > <option style={ breakpoint1000 ? { background: applicationColors.NAVY } : {} } value="week" > Last week </option> <option style={ breakpoint1000 ? { background: applicationColors.NAVY } : {} } value="month" > Last six weeks </option> </Select> <Heading as="h3" size="lg" color={breakpoint1000 ? "white" : "gray.700"} mb="10px" > Currently Active Projects </Heading> <Flex direction="row" align="center" mt={breakpoint1000 ? "30px" : "0"} > <Box> {workPeriods && workPeriods.length !== 0 && ( <PieChart workPeriods={workPeriods} /> )} {(!workPeriods || workPeriods.length === 0) && ( <Text fontSize="3xl" color={breakpoint1000 ? "white" : "gray.400"} mb="20px" > No work to display </Text> )} </Box> <Box> <Heading as="h3" size="md" color={ breakpoint1000 ? applicationColors.DARK_LIGHT_BLUE : "gray.700" } > Total Hours </Heading> <Text fontSize={breakpoint1000 ? "2xl" : "3xl"} color={breakpoint1000 ? "white" : "gray.400"} mb="20px" > {workPeriods && workPeriods.length !== 0 ? msToFormattedTime( sum(convertWorkToHours(workPeriods)) * MILLISECONDS_IN_HOUR ) : "No work to display"} </Text> <Heading as="h3" size="md" color={ breakpoint1000 ? applicationColors.DARK_LIGHT_BLUE : "gray.700" } > Estimated Total Income </Heading> <Text fontSize={breakpoint1000 ? "2xl" : "3xl"} color={breakpoint1000 ? "white" : "gray.400"} mb="20px" > {workPeriods && workPeriods.length !== 0 ? `${currency[currency.length - 1]}${totalIncome( workPeriods ).toFixed(2)}` : "No work to display"} </Text> </Box> </Flex> {/* NEXT PROJECT */} <Box borderRadius="5px" marginTop="20px" width="450px" height="120px" bgGradient="linear(to-r, #30415D, #031424)" boxShadow="2px 2px 8px 2px rgba(0,0,0,.2)" color="white" border={breakpoint1000 ? "3px solid white" : null} fontWeight="bold" > <Flex justify="space-between"> <Text p="15px 20px" casing="uppercase"> NEXT DUE: </Text> <Text p="15px 20px"> {formattedTaskDate(nextProject?.due_date)} </Text> </Flex> <Text p="0 30px" casing="uppercase" fontSize="2xl"> {nextProject?.name} </Text> </Box> {/* ACTIVE */} <Flex direction="row" justify="center" align="center"> <Flex justify="center" align="center" borderRadius="5px" marginTop="20px" marginRight="50px" width="200px" height="200px" boxShadow="2px 2px 8px 2px rgba(0,0,0,.2)" border={ breakpoint1000 ? "3px solid white" : `3px solid ${applicationColors.NAVY}` } bgGradient={`linear(to-r, ${applicationColors.SOFT_LIGHT_BLUE}, ${applicationColors.DARK_LIGHT_BLUE})`} > <Text casing="uppercase" fontSize="3xl" textAlign="center" color="gray.800" fontWeight="bold" > {active && active[0] ? active[0] : 0} Active Client {active && active[0] === 1 ? "" : "s"} </Text> </Flex> <Flex justify="center" align="center" borderRadius="5px" marginTop="20px" width="200px" height="200px" boxShadow="2px 2px 8px 2px rgba(0,0,0,.2)" border={ breakpoint1000 ? "3px solid white" : `3px solid ${applicationColors.NAVY}` } bgGradient={`linear(to-r, ${applicationColors.SOFT_LIGHT_BLUE}, ${applicationColors.DARK_LIGHT_BLUE})`} > <Text casing="uppercase" fontSize="3xl" textAlign="center" color="gray.800" fontWeight="bold" > {active && active[1] ? active[1] : 0} Active Project {active && active[1] === 1 ? "" : "s"} </Text> </Flex> </Flex> </Flex> </Flex> </Flex> </Flex> </Box> )} </Flex> </Box> </Flex> ); }; export default Dashboard;
import React, { Component } from 'react'; import moment from 'moment'; import classname from 'classname'; import styles from './index.css'; export default class ServiceStats extends Component { render() { const { service } = this.props; const taskDefinition = service.TaskDefinition.split('task-definition/')[1]; const classes = classname({ [styles.ServiceStats]: true, [styles['ServiceStats--left-aligned']]: this.props.left }); return ( <div className={classes}> <table> <tbody> <tr> <th>task def</th> <td>{taskDefinition}</td> </tr> </tbody> </table> </div> ); } };
var GoogleMapsAPI = require('googlemaps'); var publicConfig = { key: 'AIzaSyDjE5MTfUt5RYaEdA_I_PVvaQJlkro5e80', stagger_time: 1000, // for elevationPath encode_polylines: false, secure: true, // use https proxy: 'http://127.0.0.1:9999' // optional, set a proxy for HTTP requests }; var gmAPI = new GoogleMapsAPI(publicConfig); module.exports.gmAPI = gmAPI;
// include packages to our project var express = require('express'); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var cors = require('cors'); var Place = require('./models/place'); var PlaceController = require('./controllers/placeController'); //connecting to DB mongoose.connect('mongodb://localhost:27017/nodetest'); // create the app itself var app = express(); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); app.use(cors()); var port = 3000; var router = express.Router(); router.route('/places') .post(PlaceController.postPlaces) .get(PlaceController.getPlaces); router.route('/places/:place_id') .get(PlaceController.getPlace) .put(PlaceController.putPlace) .delete(PlaceController.deletePlace); router.route('/places/:place_id/rate') .post(PlaceController.ratePlace); app.use('/api', router); app.listen(port); console.log('App initialised');
export const colors = { main: '#1D4F95', second: '#bdf1f6', secondDark: '#8fbaf3', dark: '#0245a3', green: '#27B647', greenLight: '#E9FFF4', blueDark: '#00337A', blue: '#66A0ED', blueLight: '#E0EBFB', grey: '#5A697D', greyLight: '#DCE3EC', };
import React, { useState } from 'react'; import UploadDocs from '../../common/UploadDocs'; import LightningKid from '../../../assets/images/hero_images/hero4.png'; import { Header } from '../../common'; import ChildFooter from '../../common/ChildFooter'; import { Row, Col } from 'antd'; import { connect } from 'react-redux'; import Thrashbar from './Thrashbar'; const YourMissionComp = ({ ...props }) => { const [rwd, setsRwd] = useState({ read: false, write: false, draw: false, mode: 'single', }); const fxd = () => { if (props.child.gamemode.write) { props.child.gamemode.write = true; props.child.gamemode.draw = false; props.child.gamemode.read = true; setsRwd({ write: props.child.gamemode.write, draw: props.child.gamemode.draw, read: props.child.gamemode.read, }); } if (props.child.gamemode.draw) { props.child.gamemode.write = false; props.child.gamemode.draw = true; props.child.gamemode.read = true; setsRwd({ write: props.child.gamemode.write, draw: props.child.gamemode.draw, read: props.child.gamemode.read, }); } }; return ( <> <Header displayMenu={true} /> <div> <Thrashbar props={props} sread={e => { props.sread(e); }} /> </div> { // End Your Mission BUtton Bar //Begin Read orange or Write yellow Background colors fxd() } <div className={rwd.write === true ? 'rectangle130-yellow' : 'rectangle130'} > <Row className="btmRow"> <img src={LightningKid} alt="A child dressed as a superhero called lightning kid" /> <Col> <h1 className="dont4get">DONT FORGET!</h1> <p className="dont4get-p"> When you are finished drawing, snap a photo and upload your masterpiece. </p> <div className="kids-story-upload kids-story-upload-font"> {rwd.write ? 'Upload your writing' : 'Upload your drawing'} <UploadDocs {...props} /> </div> <div onClick={() => { props.pdw(); }} > <p className="id-rather-choose-another-choice-font"> {rwd.write ? "I'd rather draw" : "I'd rather write"} </p> </div> </Col> </Row> </div> <ChildFooter /> </> ); }; export default connect( state => ({ child: state.child, }), {} )(YourMissionComp);
sap.ui.jsview("com.slb.eam.mob.view.WOMaster", { /** Specifies the Controller belonging to this View. * In the case that it is not implemented, or that "null" is returned, this View does not have a Controller. * @memberOf view.WOListMaster */ getControllerName : function() { return "com.slb.eam.mob.view.WOMaster"; }, /** Is initially called once after the Controller has been instantiated. It is the place where the UI is constructed. * Since the Controller is given to this method, its event handlers can be attached right away. * @memberOf view.WOListMaster */ createContent : function(oController) { var page = new sap.m.Page("masterpage",{showHeader: true,showFooter: true, showNavButton: true, alignItems:"center", title: "Work List" }); page.setCustomHeader(new sap.m.Bar({contentLeft: new sap.m.Button({icon:"sap-icon://home",press:oController.goHome}),contentMiddle: new sap.m.Text({text:"Work List"}) ,contentRight:new sap.m.Button({icon:"sap-icon://filter"}) })); page.setFooter(new sap.m.Bar({})); page.setSubHeader(new sap.m.Bar({contentMiddle: new sap.m.SearchField({showRefreshButton: true})})); var woList = new sap.m.List({ id:"masterlist", select:oController.onListItemPress }); woList.attachEvent("drawmaster", function(oEvent) { var masterModel = oCore.getModel("mastermodel"); var masterdata=masterModel.getData(); jQuery.each(masterdata, function(i,val) { var objectTemplate = new sap.m.ObjectListItem({press: oController.onListItemPress}); objectTemplate.setTitle(val.WOId); objectTemplate.setNumber(val.Plant); objectTemplate.setType(sap.m.ListType.Active); var attr = new sap.m.ObjectAttribute(); attr.setText(val.WOText); objectTemplate.addAttribute(attr); attr = new sap.m.ObjectAttribute(); attr.setText("Rig ID: "+val.RigId); objectTemplate.addAttribute(attr); attr = new sap.m.ObjectAttribute(); attr.setText("Job ID: "+val.JobId); objectTemplate.addAttribute(attr); attr = new sap.m.ObjectAttribute(); attr.setText("Start Date: "+val.StartDate); objectTemplate.addAttribute(attr); woList.addItem(objectTemplate); }); }); page.addContent(woList); return page; } });
/* * grunt-fail-fast-task-runner * * * Copyright (c) 2015 Greg Alexander * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Node Modules var path = require('path'), util = require('util'), // 3rd party modules _ = require('lodash'), async = require('async'), chalk = require('chalk'); grunt.registerMultiTask('fail_fast_task_runner', 'A Grunt task to run tasks on multiple Grunt projects that will fail fast', function () { var options = this.options({ concurrency: 1, includeSelf: false }), args = this.args.length < 1 ? false : this.args, errors = 0, // We get this from grunt. Let async process know its done done = this.async(), // Get process.argv options without grunt.cli.tasks to pass to child processes cliArgs = _.without.apply(null, [[].slice.call(process.argv, 2)].concat(grunt.cli.tasks)), ownGruntFile = grunt.option('gruntfile') || grunt.file.expand({filter: 'isFile'}, '{G,g}runtfile.{js,coffee}')[0], lastFileWritten; var writeToLog = function(isError, buf, gruntfile, dir) { if (gruntfile !== lastFileWritten) { grunt.log.writeln(''); grunt.log.writeln(''); grunt.log.writeln(chalk.bold.cyan(util.format('Running gruntfile in /%s:', dir))); } grunt.log[(isError) ? 'error' : 'write'](buf); lastFileWritten = gruntfile; }; ownGruntFile = path.resolve(process.cwd(), ownGruntFile || ''); // queue for concurrently ran tasks var queue = async.queue(function(taskToRun, next) { var skipNext = false; grunt.log.ok(chalk.bold.magenta(util.format('Running grunt task [%s] on %s', taskToRun.tasks, taskToRun.gruntfile))); if (cliArgs) { // Create new cliArgs array matching criteria cliArgs = cliArgs.filter(function(currentValue) { if (skipNext) { return (skipNext = false); } var out = /^--gruntfile(=?)/.exec(currentValue); if (out) { if (out[1] !== '=') { skipNext = true; } return false; } return true; }); } var child = grunt.util.spawn({ // Use grunt to run the tasks grunt: true, // Run from dirname of gruntfile opts: {cwd: path.dirname(taskToRun.gruntfile)}, // Run task to be run and any cli options args: taskToRun.tasks.concat(cliArgs || [], '--gruntfile=' + taskToRun.gruntfile) }, function(err) { if (err) { errors++; } next(err); }); child.stdout.on('data', function(buf) { writeToLog(false, buf, taskToRun.gruntfile, taskToRun.dir); }); child.stderr.on('data', function(buf) { writeToLog(true, buf, taskToRun.gruntfile, taskToRun.dir); }); }, options.concurrency); // When the queue is all done queue.drain = function() { done((errors === 0)); }; // All files specified using any Grunt-supported file formats and options, globbing patterns or dynamic mappings this.files.forEach(function(files) { // Return a unique array of all file or directory paths that match the given globbing pattern(s) var gruntfiles = grunt.file.expand({filter: 'isFile'}, files.src), splitPath; if (gruntfiles.length === 0) { grunt.log.warn(chalk.bold.red(util.format('No Gruntfiles matched the file patterns: %s"', files.orig.src.join(', ')))); } gruntfiles.forEach(function(gruntfile) { gruntfile = path.resolve(process.cwd(), gruntfile); // To get directory splitPath = gruntfile.split('/'); // Skip it's own gruntfile. Prevents infinite loops. if (!options.includeSelf && gruntfile === ownGruntFile) { return; } queue.push({ gruntfile: gruntfile, tasks: args || files.tasks || ['default'], dir: splitPath.length > 1 ? splitPath[splitPath.length - 2] : process.cwd() }, function(err) { if (err) { queue.kill(); done((errors === 0)); } }); }); }); // Make sure that at least one file is queued if (queue.idle()) { // If the queue is idle, assume nothing was queued and call done() immediately after sending warning grunt.warn(chalk.bold.red('No Gruntfiles matched any of the provided file patterns')); done(); } }); };
import React from "react"; import { useHistory } from "react-router-dom"; import arrowLeft from "../../../../../public/images/left_arrow.svg"; import "./backbutton.scss"; export const Buttonback = () => { let history = useHistory(); return ( <> <a className="backbuttonWrapper" onClick={() => history.goBack()}> <img src={arrowLeft} alt="Go previous" /> <span>Return</span> </a> </> ); };
/** * Created by ttnd on 4/2/16. */ var fs = require('fs'); var rs = fs.readFile(process.argv[2],function (error,data){ console.log(data.toString().split("\n").length-1); });
var tnt_theme_track_sequence_track = function() { var theme = function(board, div) { board(div); board.right (1000); var seq_info = (function (seq) { var k = []; for (var i=0; i<seq.length; i++) { k.push ({ pos : i+1, nt : seq[i] }); } return k; })(seq); // Block Track1 var sequence_track = tnt.track() .height(30) .background_color("#FFCFDD") .data(tnt.track.data() .update( tnt.track.retriever.sync() .retriever (function (loc) { return seq_info.slice(loc.from, loc.to); // return seq_info; }) ) ) .display(tnt.track.feature.sequence() .foreground_color("black") .sequence(function (d) { return d.nt; }) .index(function (d) { return d.pos; })); // Axis Track1 var axis_track = tnt.track() .height(30) .background_color("white") .display(tnt.track.feature.axis() .orientation("top") ); // Location Track1 var loc_track = tnt.track() .height(30) .background_color("white") .display(tnt.track.feature.location()); board .right (seq.length) .from (0) .to(50) .zoom_out(100) .zoom_in(50) .add_track(loc_track) .add_track(axis_track) .add_track(sequence_track); board.start(); }; return theme; }; var seq = 'ACCGTGAGAGCCCCTTTGGCGGAGCGAGCATTATTACGCGCGAATCTAGCATGCTAGGCGCGATTTATCCTGCGCGCGCAGATATTCTCTCGCGCGAGACGTACGATCGGCGCGATCGATGCTAGCCGGCGCTAGCTAGTCGAGCGCGCTAGTCGATGCCGGCGCGCATATATATTAGCGCGATCGATCGATGCTAGTACGTAGCTGCGCGCGCGATAATTATTATCGCGCGCGAGCGTACGATGCTACGTGCGCGCGCGCGAGATTATATTATTTATTTATATATTCCTTCTCGCGCGCGCGGAGGATATTTATCGATCGATCGTAGCTAGCTAGCTAGCTAGCTGATCATGCTAGCTAGCTAGCTAGCTACGTAGTCAGCTGTCAGATGCTAGCTAGCTAGTAGCTAGCTAGTCGATCGTAGCTAGCTCGTAGCTATATATCTCTCTCTCTCATGAGGATCGTAGCTCGTAGGAGAGTAGCTCGTAGCTAGCTACGTAGCATGCTAGCTAGCACGTATGCTAGCTGAGTCGCCGCATTATACTGAAATATTATTCGCGATCGGCGCATTCACGATCGATGCAGCCGCGCGGCGGCGGCGCGCGATATATTCGGC';
import React, { Component } from 'react'; import './App.css'; import Restaurants from './Restaurants'; import ReactDOM from 'react-dom'; class Authentication extends Component { /************************************************************** * Objective: Constructor * * State variables: * email: email address * password: user password * * Added binding to 3 methods that will use the state props * handleEmailChange * handlePasswordChange * handleLogin * * Author: Felipe Iserte Bonfim (felipe.iserte@gmail.com) * * Date: 16th March, 2018 - 6:39 PM ***************************************************************/ constructor(props) { super(props); this.state = { email: '', password: '', authResponse: '' }; this.handleEmailChange = this.handleEmailChange.bind(this); this.handlePasswordChange = this.handlePasswordChange.bind(this); this.handleLogin = this.handleLogin.bind(this); } /************************************************************** * Objective: Handle Text change * * Update the State variable 'value' * Prevent default method acation * * Author: Felipe Iserte Bonfim (felipe.iserte@gmail.com) * * Date: 16th March, 2018 - 6:41 PM ***************************************************************/ handleEmailChange(event) { this.setState({email: event.target.value}); event.preventDefault(); } /************************************************************** * Objective: Handle Text change * * Update the State variable 'value' * Prevent default method acation * * Author: Felipe Iserte Bonfim (felipe.iserte@gmail.com) * * Date: 16th March, 2018 - 6:41 PM ***************************************************************/ handlePasswordChange(event) { this.setState({password: event.target.value}); event.preventDefault(); } /************************************************************** * Objective: Handle Search / form submit calls this function * * Call a Rest get web service to get information regarding all restaurants * Filter the list with the searched text * * Author: Felipe Iserte Bonfim (felipe.iserte@gmail.com) * * Date: 16th March, 2018 - 7:41 PM ***************************************************************/ handleLogin(event) { fetch("http://localhost:8080/userAuthentication?email="+ this.state.email +"&password=" + this.state.password, { method: 'POST', headers: new Headers({ 'Content-Type': 'application/json', // <-- Specifying the Content-Type }) }).then((response) => response.json()) .then((responseText) => { console.info(responseText); if(responseText.authenticated === true) { window.sessionStorage.setItem("loggedCustomerId", responseText.customer.id); window.sessionStorage.setItem("loggedCustomer", JSON.stringify(responseText.customer)); ReactDOM.render(<Restaurants />, document.getElementById('root')) } else { document.getElementById("msg").innerHTML = responseText.errorMessage; } }) .catch((error) => { console.error(error); document.getElementById("msg").innerHTML = "Error trying to connect to the server. Please contact the admin."; }); event.preventDefault(); } /************************************************************** * Objective: Render the App Component * * Creates a form, a input text box, a submit button and the result. * * Author: Felipe Iserte Bonfim (felipe.iserte@gmail.com) * * Date: 16th March, 2018 - 6:14 PM ***************************************************************/ render() { return ( <div className="Authentication"> <div className="App-header"> <div className="App-title">SKIP the DISHES</div> </div> <div className="loginPage" id="loginPage"> <h1 className="title-lg text-light">Login</h1> <form onSubmit={this.handleLogin}> <input type="text" onChange={this.handleEmailChange} placeholder="Email address" /> <br/> <input type="password" onChange={this.handlePasswordChange} placeholder="Password" /> <br/> <input type="submit" value="Login" /> <div id="msg" /> </form> </div> </div> ); } } export default Authentication;
/* * Context 為統一格式的訊息上下文 * * 訊息的完整格式設定: * { * from: "", * to: "", * nick: "", * text: "", * isPrivate: false, * command: "", * param: "", * extra: { // 備註:本程式為淺層拷貝 * clients: 3, // 本次傳送有幾個群互聯?(由 bridge 發送) * clientName: { * shortname: '' * fullname: '' * } * mapto: [ // 對應到目標群組之後的 to(由 bridge 發送) * "irc/#aaa", * ... * ], * reply: { * nick: "", * username: "", * message: "", * isText: true, * }, * forward: { * nick: "", * username: "", * }, * files: [ * { * client: "Telegram", // 用於區分 * type: ... * ... * } * ] * uploads: [ // Telegram:檔案上傳用,由 bridge 發送 * { * url: "", * type: "photo" // photo/audio/file * } * ], * }, * handler: 訊息來源的 handler, * _rawdata: 處理訊息的機器人所用的內部資料,應避免使用, * } */ 'use strict'; let msgId = 0; const getMsgId = () => { msgId++; return msgId; }; class Context { constructor( options = {}, overrides = {} ) { this.from = null; this.to = null; this.nick = ''; this.text = ''; this.isPrivate = null; this.extra = {}; this.handler = null; this._rawdata = null; this.command = ''; this.param = ''; this._msgId = getMsgId(); // TODO 雖然這樣很醜陋,不過暫時先這樣了 for ( let k of [ 'from', 'to', 'nick', 'text', 'isPrivate', 'extra', 'handler', '_rawdata', 'command', 'param' ] ) { if ( overrides[ k ] !== undefined ) { this[ k ] = overrides[ k ]; } else if ( options[ k ] !== undefined ) { this[ k ] = options[ k ]; } } if ( overrides.text !== undefined ) { this.command = overrides.command || ''; this.param = overrides.param || ''; } } say( target, message, options ) { if ( this.handler ) { this.handler.say( target, message, options ); } } reply( message, options ) { if ( this.handler ) { this.handler.reply( this, message, options ); } } get msgId() { return this._msgId; } } module.exports = Context;
// Different types of errors const errorTypes = { validationError: (errors) => { const error = new Error(); error.status = 400; error.message = 'Validation error'; error.description = 'Validation error for the current request'; error.information = errors; return error; }, notFoundError: () => { const error = new Error(); error.status = 404; error.message = 'Page not found'; error.description = 'Page was not found in our server'; return error; }, unauthorizedError: () => { const error = new Error(); error.status = 401; error.message = 'Unauthorized'; return error; }, versionError: () => { const error = new Error(); error.status = 404; error.message = 'Version not found'; error.description = 'Accept-Version contains a not valid version of the application'; return error; }, deprecatedVersionError: () => { const error = new Error(); error.status = 404; error.message = 'Deprecated version'; error.description = 'Accept-Version contains a deprecated version of the application, please update it'; return error; }, }; export default errorTypes;
const initialState = '' const filterReducer = (state = initialState, action) => { switch(action.type) { case 'FILTER': return action.value default: return state } } export const filterBy = (filter) => { return { type : 'FILTER', value : filter } } export default filterReducer
var express = require('express'); var router = express.Router(); var pool = require('../config/connection.js'); var vendorFunctions = require('../functions/vendorFunctions.js') // Display all Vendors router.get('/', function (req, res) { vendorFunctions.GetAllVendors(function (allVendors) { res.render('allVendors', { title: 'List of Vendors', vendors: allVendors }); }); }); // Add new Vendor router.get('/new', function (req, res) { res.render('addVendor', { title: 'Add new Vendor' }); }); // --- POST router.post('/new' , function (req, res) { vendorFunctions.InsertVendor(req.body, function (result) { res.redirect('/Vendors/' + result.insertId); }); }); // View Vendor router.get('/:id/', function (req, res) { vendorFunctions.GetVendor(req.params.id, function (results) { if (results.length == 0) { res.send('Vendor does not exist <br> <a href=/Vendors>Go back</a>');} else { vendorFunctions.VendorProduct(req.params.id, function (products) { res.render('viewVendor', { title: 'View Vendor', vendor: results, vendor_product: products }); }); } }); }); // Edit Vendor router.get('/Edit/:id', function (req, res) { vendorFunctions.GetVendor(req.params.id, function (results) { if (results.length == 0) { res.send('Vendor does not exist <br> <a href=/Vendors>Go back</a>'); } else { res.render('editVendor', { title: 'View Vendor', vendor: results }); } }); }); // --- POST router.post('/Edit/:id', function (req, res) { var Vendor = req.body; vendorFunctions.UpdateVendor(Vendor, function () { res.redirect('/Vendors/' + req.params.id); }); }); module.exports = router;
import React, { Component } from 'react'; import { ScrollView, View, TouchableOpacity, Text } from 'react-native'; import { Tabs, Tab, Icon, Button } from 'react-native-elements' export default class ScreenA extends Component { constructor() { super() this.state = { hideTabBar: true, } } hideTabBar(value) { this.setState({ hideTabBar: value }); } render() { let tabBarStyle = {}; let sceneStyle = {}; if (this.state.hideTabBar) { tabBarStyle.height = 0; tabBarStyle.overflow = 'hidden'; sceneStyle.paddingBottom = 0; } return ( <View hideTabBar={this.hideTabBar.bind(this)}> <Button title='BUTTON' /> <Button raised icon={{ name: 'cached' }} title='BUTTON WITH ICON' /> <Button large iconRight icon={{ name: 'code' }} title='LARGE WITH RIGHT ICON' /> <Button large icon={{ name: 'envira', type: 'font-awesome' }} title='LARGE WITH RIGHT ICON' /> <Button large icon={{ name: 'squirrel', type: 'octicon' }} title='OCTICON' /> </View> ) } }
import Conversions from "../Conversions"; import Fretboard from "../Fretboard"; import standardShapes from "./standardShapes"; import substitutions from "./substitutions.json"; import { ALL, NON_NATURALS } from "../Note"; class Chord { constructor(props) { props = props || {}; this.name = props.name; // Doesn't include root, example would be Maj7 this.label = props.label || ""; this.singles = props.singles || []; this.barres = props.barres || []; this.inversion = props.inversion || 0; this.root = props.root; this.notes = Chord._getNotes(this.singles, this.barres); this.intervals = Chord._getIntervals(this.notes, this.root); this.canonicalName = this.inversion === 0 ? `${this.root}${this.name}` : `${this.root}${this.name}/${Conversions.distanceFromCToNote(Conversions.noteToDistanceFromC(this.root) + this.inversion)}` } static _getNotes(singles, barres) { const notes = Array(6); for (let singleIdx in singles) { const single = singles[singleIdx]; const note = Fretboard.standard().getNoteG(single.string, single.fret); notes[6 - single.string] = note; } for (let barreIdx in barres) { const barre = barres[barreIdx]; for (let voicedStringIdx in barre.voicedStrings) { const voicedString = barre.voicedStrings[voicedStringIdx]; notes[6 - voicedString] = Fretboard.standard().getNoteG(voicedString, barre.fret); } } return notes; } static _getIntervals(notes, root) { const intervals = Array(6); for (const noteIdx in notes) { const note = notes[noteIdx]; if (note === null) { intervals[noteIdx] = null; continue; } intervals[noteIdx] = Conversions.intervalBetweenNotes(root, note.name); } return intervals; } transpose(newRoot) { const transposeDistance = Conversions.mod12(Conversions.noteToDistanceFromC(newRoot) - Conversions.noteToDistanceFromC(this.root)); const lowestFret = Math.min(...this.singles.map((single) => single.fret), ...this.barres.map((barre) => barre.fret)); const transposeDown = (lowestFret + transposeDistance) >= 13; const newSingles = this.singles.map((single) => Object.assign({}, single)); const newBarres = this.barres.map((barre) => Object.assign({}, barre)); newSingles.forEach((single) => single.fret = transposeDown ? Conversions.mod12(single.fret + transposeDistance): single.fret + transposeDistance); newBarres.forEach((barre) => barre.fret = transposeDown ? Conversions.mod12(barre.fret + transposeDistance): barre.fret + transposeDistance); return new Chord({ name: this.name, singles: newSingles, barres: newBarres, inversion: this.inversion, root: newRoot, label: this.label }); } } let STANDARD_CHORD_LIBRARY = null; class ChordLibrary { constructor() { this.chordsByName = {} this.autocompleteChordNames = []; } register(name, chord) { if (!this.chordsByName[name]) { this.chordsByName[name] = []; this.autocompleteChordNames.push(...ALL.map((note) => `${note}${name}`)); this.autocompleteChordNames = this.autocompleteChordNames.sort(); } this.chordsByName[name].push(chord); } get_autocomplete_dictionary() { return this.autocompleteChordNames; } get_all_types() { return Object.keys(this.chordsByName).sort(); } get_all_by_name(name, withSubstitutions) { let root; let shapeName; if (NON_NATURALS.some((note) => name.startsWith(note))) { root = name.substring(0, 2); shapeName = name.substring(2); } else { root = name.substring(0, 1); shapeName = name.substring(1); } return this.get_all_by_root_and_name(root, shapeName, withSubstitutions); } get_all_by_root_and_name(root, shapeName, withSubstitutions) { const shapeNames = [shapeName]; if (withSubstitutions && substitutions[shapeName]) { shapeNames.push(...substitutions[shapeName]) } const chords = []; shapeNames.forEach((iShapeName) => { if (this.chordsByName[iShapeName]) { chords.push(...this.chordsByName[iShapeName]); } }); return (root === "C") ? chords : chords.map((chord) => chord.transpose(root)); } get_by_root_name_and_label(root, shapeName, label) { const matches = this.get_all_by_root_and_name(root, shapeName, false).filter((chord) => chord.label === label); return matches.length === 1 ? matches[0] : null; } static standard() { if (STANDARD_CHORD_LIBRARY === null) { STANDARD_CHORD_LIBRARY = initializeStandardChordLibrary(); } return STANDARD_CHORD_LIBRARY; } } function initializeStandardChordLibrary() { const library = new ChordLibrary(); for (let name in standardShapes.standardShapes) { for (let idx in standardShapes.standardShapes[name]) { let chordJson = standardShapes.standardShapes[name][idx]; library.register(name, new Chord(Object.assign({name: name, root: "C", singles: [], barres: [], withAnnotations: true}, chordJson))); } } return library; } export { Chord, ChordLibrary }
let x = new Vue({ el: '#app', data: { taskToDo: 'testing', listTasksToDo: [ {text: 'create new task', complete: false, priority: true}, {text: 'show videos', complete: false, priority: true}, {text: 'show api', complete: false, priority: false}, ], users : [ { name: 'Andres', role: 'admin', priority: 1 }, { name: 'Pablo', role: 'user', priority: 2 } ], }, methods: { addTaskToDo: function () { if (this.taskToDo && this.taskToDo != '') this.listTasksToDo.push({ text: this.taskToDo, complete: false, priority : true }); this.taskToDo = ''; }, completeTask: function (task) { console.log(task); task.complete = !task.complete; }, changePriority(task){ console.log(task); task.priority = !task.priority; } }, computed:{ priorityTasks(){ return this.listTasksToDo.filter((task) => task.priority ) }, taskForUser(){ user.name = 'Andres'; return this.listTasksToDo.filter((user) => user.name); } } });