text
stringlengths
7
3.69M
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { all: ['Gruntfile.js', 'jasmine/**/*js'], options: { '-W051': 'ignores variable deletion warning', '-W014': 'ignores "Bad line breaking" errors, for comma-first style', ignores: ['jasmine/support/*.js'] } }, watch: { files: ['Gruntfile.js', 'jasmine/**/*js'], tasks: ['jshint', 'jasmine'] }, jasmine: { files: ['jasmine/**/*js'], options: { vendor: ['jasmine/support/*.js'] } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-jasmine'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['jshint', 'jasmine']); };
'use strict'; var path = require('path'); function indexOfDash(arr) { for (var i = 0; i < arr.length; i++) { if (arr[i].indexOf('-') === 0) { return i; } } return -1; } module.exports = { rewrite: function rewite(argv) { var result = [], mocha; // remove the `--mocha path` argument var args = (function extractMocha(args) { var mochaIsNext = false; var filtered = args.filter(function (arg) { if (arg === '--mocha') { mochaIsNext = true; return false; } else if (mochaIsNext) { mocha = path.join(arg, '/bin/_mocha'); mochaIsNext = false; return false; } return true; }); if (!mocha) { // now we assume there is a mocha package next to this package mocha = args[1].replace(/^(.*)mocha-for-jetbrains(.*?)$/, '$1mocha$2'); } return filtered; }(argv)); result.push(args[0]); // the second argument is now the real mocha result.push(mocha); // where do the intellij added arguments start? var firstDashIndex = indexOfDash(args); if (firstDashIndex >= 0) { if (firstDashIndex === 2) { // no arguments to add at the end result = result.concat(args.slice(2, args.length)); } else { // strip the directory at the end result = result.concat(args.slice(firstDashIndex, args.length - 1)); } result = result.concat(args.slice(2, firstDashIndex)); } return result; } };
import L from 'leaflet'; function getTransformation({ scale, origin, ratio }) { return new L.Transformation(ratio / scale, origin.x, ratio / scale, origin.y); } function configurate(mapScale, mapSize, mapOrigin, pixelMeterRatio) { const transformation = getTransformation({ scale: mapScale, origin: mapOrigin, ratio: pixelMeterRatio }); const toMeterPoint = point => transformation.transform(point); const toPixelPoint = point => transformation.untransform(point); const meterMapSize = toMeterPoint(mapSize); const topLeftAnglePoint = [-meterMapSize.x / 2, -meterMapSize.y / 2]; const bottomRightAnglePoint = [meterMapSize.y / 2, meterMapSize.y / 2]; const bounds = [topLeftAnglePoint, bottomRightAnglePoint]; const projection = L.extend({}, L.CRS.LonLag, { project: point => { return point ? toPixelPoint(L.point(point.lng, point.lat)) : L.point(0, 0); }, unproject: point => { const meterPoint = toMeterPoint(point); return L.latLng([meterPoint.y, meterPoint.x]); } }); const crs = L.extend({}, L.CRS.Simple, { projection }); return { projection, crs, bounds }; } export default (mapScale, mapSize, mapOrigin, pixelMeterRatio) => { return configurate( mapScale, L.point(mapSize[0], mapSize[1]), L.point(mapOrigin[0], mapOrigin[1]), pixelMeterRatio ); };
export const WgInputMixin = { props: { cols: { type: Number, default: 12 }, label: { type: String, default: null }, type: { type: String, default: 'text', }, id: { type: String, default: '' }, name: { type: String, default: null }, placeholder: { type: String, default: null }, value: { type: String, default: null }, disabled: { type: Boolean, default: false }, error: { type: Boolean, default: false }, success: { type: Boolean, default: false }, i18n: { type: Object, default: () => {} } }, data () { return { model: this.value || '' } }, methods: { t (str) { if (this.i18n && this.i18n.te(str)) { return this.i18n.t(str) } return str }, onChange () { this.$emit('change', this.model) }, }, watch: { value (newVal) { this.model = newVal } } }
var files = new Object(); //$(function(){ // //}); files.loadData = function(data){ files.displayAllFiles(data); gen.button('filesActionButton', 'Refresh', files.getAllFiles, false); $("#uploadify").uploadify({ 'uploader': '/static/js/uploadify.swf', 'script': 'http://'+window.location.host+'/'+site.url+'/files/fileUploads/', 'cancelImg': site.media_url+'/images/cancel.png', 'folder': '/static/storage', 'queueID': 'uploadifyQueue', 'auto': true, 'multi': true, 'scriptAccess': 'always', 'buttonText': 'Upload File(s)', 'scriptData': {'user': site.user}, //'onInit': function(){$('#uploadifyUploader').attr('title', 'Select multiple files at once to upload');}, 'onSelectOnce': function(e, data){$('#filesTut').hide(); $('#uploadifyQueue').show();}, 'onAllComplete': function(e, data){$('#uploadifyQueue').hide(); $('#filesTut').show(); files.getAllFiles();} }); $('#uploadifyUploader').attr('title', 'Select multiple files at once to upload').css('cursor', 'pointer'); } files.loadHash = function(){ site.tabs.tabs('select', 2); } files.getAllFiles = function(){ var data = { site: site.siteID() }; gen.json( window.location.pathname + '/files/displayAllFiles/', data, function(data){ files.displayAllFiles(data); }, "Loading..." ); } files.displayAllFiles = function(data){ $('#allFilesTable').replaceWith(data.all_files); $('#allFilesTable .pointer a').each( function(){ var original = $(this); var url = original.attr('href'); var row = original.parent().parent(); row.click(function(){window.open(url);}); original.click(function(){row.click(); return false;}) row.droppable({ hoverClass: 'droppableHover', tolerance: 'pointer', accept: '.todo', drop: files.dropAllFiles }); } ); } files.dropAllFiles = function(event, ui){ var file_id = event.target.id.split("_")[1]; var todo_id = ui.draggable.attr('id').split("_")[1]; files.assignRelatedToDo(file_id, todo_id, null); } files.assignRelatedToDo = function(file_id, todo_id, callback){ var data = { site: site.siteID(), item: file_id, todo: todo_id }; gen.jsonPost( window.location.pathname + '/files/assignRelatedToDo/', data, function(data){ if(callback != null) callback(data); } ); } //END OF FILES////////////////////////////////////////////////////////////////////////////////
import React, { Component, Fragment } from "react"; import { Card, CardText, CardBody, CardTitle, CardSubtitle, Button, Alert, Container, Row, Col, Jumbotron, Form, FormGroup, Label, Input, } from "reactstrap"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import { Redirect } from "react-router-dom"; import { getCart, deleteFromCart } from "../../actions/cartActions"; import { checkout } from "../../actions/orderActions"; import Checkout from "../Checkout"; import Footer from "../Footer"; import "../reservation/style.css"; class Cart extends Component { constructor(props) { super(props); this.state = { loaded: false, redirect: false, }; } componentDidMount() { const { user, isAuthenticated } = this.props.auth; if (isAuthenticated && !this.props.cart.loading && !this.state.loaded) { this.getCartItems(user._id); } } componentDidUpdate(prevProps) { const { user, isAuthenticated } = this.props.auth; const { orders } = this.props.order; if (user !== prevProps.auth.user) { if (isAuthenticated && !this.state.loaded) { this.getCartItems(user._id); } } if (orders !== prevProps.order.orders) { this.setState({ loaded: false, redirect: true, }); } } static propTypes = { getCart: PropTypes.func.isRequired, auth: PropTypes.object.isRequired, deleteFromCart: PropTypes.func.isRequired, cart: PropTypes.object.isRequired, checkout: PropTypes.func.isRequired, order: PropTypes.object.isRequired, }; getCartItems = async (id) => { try { await this.props.getCart(id); this.state.loaded = true; } catch (err) { console.log(err); } }; onDeleteFromCart = (id, itemId) => { this.props.deleteFromCart(id, itemId); }; render() { const { user, isAuthenticated } = this.props.auth; const { cart, loading } = this.props.cart; console.dir(cart); if (this.state.redirect) { return <Redirect to='/orders' />; } return ( <div className='reservationBg'> <Jumbotron className='jumbo bg-f'> <h1 className='display-4'>Cos cumparaturi</h1> </Jumbotron> {isAuthenticated ? ( <Fragment> {cart && cart.meals.length > 0 ? null : ( <Alert color='info' className='text-center'> Cosul este gol! </Alert> )} </Fragment> ) : ( <Alert color='danger' className='text-center'> Autentificare pentru vizualizare! </Alert> )} {isAuthenticated && !loading && this.state.loaded && cart ? ( <Container className='contact-form'> <Form> <Row> <FormGroup className='form-group mx-auto col-md-6 col-lg-6'> <Label for='firstName'>Nume</Label> <Input type='text' name='firstName' id='firstName' placeholder='Nume' required /> </FormGroup> <FormGroup className='form-group mx-auto col-md-6 col-lg-6'> <Label for='lastName'>Prenume</Label> <Input type='text' name='lastName' id='lastName' placeholder='Prenume' required /> </FormGroup> </Row> <Row> <FormGroup className='form-group mx-auto col-md-6 col-lg-6 '> <Label for='email'>Email</Label> <Input type='email' name='email' id='email' placeholder='Email' required /> </FormGroup> <FormGroup className='form-group mx-auto col-md-6 col-lg-6 '> <Label for='phone'>Telefon</Label> <Input type='number' name='phone' id='phone' pattern='[0-9]{3}' placeholder='Numarul de telefon' required /> </FormGroup> </Row> <Row> <FormGroup className='form-group mx-auto col-md-4 col-lg-4'> <Label for='oras'>Oras</Label> <Input type='text' name='address' id='adresaLivrare' placeholder='Oras' required /> </FormGroup> <FormGroup className='form-group mx-auto col-md-4 col-lg-4'> <Label for='Judet'>Judet</Label> <Input type='text' name='address' id='Judet' placeholder='Judet' /> </FormGroup> <FormGroup className='form-group mx-auto col-md-4 col-lg-4'> <Label for='codPostal'>Cod Postal</Label> <Input type='number' name='address' id='codPostal' placeholder='Cod Postal' required /> </FormGroup> </Row> <Row> <FormGroup className='form-group mx-auto col-md-4 col-lg-4'> <Label for='adresaLivrare'>Adresa de livrare</Label> <Input type='text' name='address' id='adresaLivrare' placeholder='Strada' required /> </FormGroup> <FormGroup className='form-group mx-auto col-md-4 col-lg-4'> <Label for='bloc'>Bloc</Label> <Input type='number' name='address' id='bloc' placeholder='Bloc' /> </FormGroup> <FormGroup className='form-group mx-auto col-md-4 col-lg-4'> <Label for='Numar'>Numar</Label> <Input type='number' name='address' id='Numar' placeholder='Numar' /> </FormGroup> </Row> <Row> <FormGroup className='form-group mx-auto col-md-12 col-lg-12 '> <Label for='textMessage'>Informatii aditionale</Label> <Input type='textarea' name='text' id='textMessage' placeholder='Daca doriti ceva special, aici puteti scrie' /> </FormGroup> </Row> <Row className='row'> {cart.meals.map((item) => ( <Col className='col-md-4' key={item._id}> <Card> <CardBody> <CardTitle tag='h5'>{item.name}</CardTitle> <CardSubtitle tag='h6'> {item.price} RON</CardSubtitle> {/* <CardImg> <img className='img-fluid' src={item.image} /> </CardImg> */} <CardText> Cantitate - {item.quantity}</CardText> <Button color='danger' onClick={this.onDeleteFromCart.bind( this, user._id, item.productId )} > Delete </Button> </CardBody> </Card> <br /> </Col> ))} <Col className='col-md-12'> {cart && cart.order_total > 0 ? ( <Card> <CardBody> <CardTitle tag='h5'> TOTAL = {cart.order_total} RON </CardTitle> <Checkout user={user._id} amount={cart.order_total} checkout={this.props.checkout} /> </CardBody> </Card> ) : null} </Col> </Row> </Form> </Container> ) : null} <Footer /> </div> ); } } const mapStateToProps = (state) => ({ cart: state.cart, auth: state.auth, order: state.order, }); export default connect(mapStateToProps, { getCart, deleteFromCart, checkout })( Cart );
import React from "react"; import Adapter from "@wojtekmaj/enzyme-adapter-react-17"; import App from "../src/App"; import { mount, configure } from "enzyme"; configure({ adapter: new Adapter() }); test("Remove sub ToDo", () => { const wrapper = mount(<App />); //ToDos array need to be empty at the beginning expect(wrapper.find(".list-group").first().props().children.length).toEqual( 0 ); //The button need to be disabled at the beginning expect(wrapper.find("button").props().disabled).toEqual(true); //Adding a ToDo to the list const input = wrapper.find("input"); input.simulate("focus"); input.simulate("change", { target: { value: "foo" } }); input.simulate("blur"); wrapper.update(); //checking the value of the ToDo added need to be eaual to foo expect(wrapper.find("input").props().value).toEqual("foo"); //After setting a value on the input the button need to be enabled expect(wrapper.find("button").props().disabled).toEqual(false); //Adding the ToDo to the list wrapper.find("button").simulate("click"); //Checnking the list again need to be only One ToDo expect(wrapper.find(".list-group").first().props().children.length).toEqual( 1 ); //Click on the add button wrapper.find(".add").first().simulate("click"); const subInput = wrapper.find("input").last(); subInput.simulate("focus"); subInput.simulate("change", { target: { value: "sub foo" } }); subInput.simulate("blur"); wrapper.update(); //Click on the add button wrapper.find(".btn").last().simulate("click"); //Click expand to see the list of sub ToDos wrapper.find(".expand").first().simulate("click"); //Cheking the sublist of ToDo need to be equal to 1 the length expect(wrapper.find(".subList").first().props().children.length).toEqual(1); //removing the added ToDO wrapper.find(".removeSubToDo").first().simulate("click"); //Cheking the sublist of ToDo the length need to be equal to 0 expect(wrapper.find(".subList").first().props().children.length).toEqual(0); });
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Swal from 'sweetalert2'; import { Select, Input, Button, Spin } from 'antd'; import axios from 'axios'; import EditComponent from '../../../../../components/common/editComponent/EditComponent'; import { api_url } from '../../../../../config/config'; import { refreshRun } from '../../../../../ducks/online/runs'; import { showManageRunModal } from '../../../../../ducks/online/ui'; import { addLumisectionRange } from '../../../../../ducks/online/lumisections'; import { certifiable_online_components } from '../../../../../config/config'; import { error_handler } from '../../../../../utils/error_handlers'; class EditRunLumisections extends Component { state = { lumisections: {}, loading: true, }; componentDidMount() { this.fetchLumisections(); } fetchLumisections = error_handler(async () => { this.setState({ lumisections: {}, loading: true }); const { data: lumisections } = await axios.post( `${api_url}/lumisections/rr_lumisection_ranges_by_component`, { dataset_name: 'online', run_number: this.props.run.run_number, } ); this.setState({ lumisections, loading: false }); }); render() { const { run, workspaces, addLumisectionRange } = this.props; const current_workspace = this.props.workspace.toLowerCase(); let components = []; if (current_workspace === 'global') { for (const [key, val] of Object.entries(certifiable_online_components)) { val.forEach((sub_name) => { components.push(`${key}-${sub_name}`); }); } } else { workspaces.forEach(({ workspace, columns }) => { if (workspace === current_workspace) { columns.forEach((column) => { components.push(`${workspace}-${column}`); }); } }); } return ( <div> {run.significant ? ( <div style={{ overflowX: 'scroll' }}> <br /> <div style={{ textAlign: 'center', }} > <Button onClick={async (evt) => { const { value } = await Swal({ type: 'warning', title: `If a status was previously edited by a shifter, it will not be updated, it will only change those untouched.`, text: '', showCancelButton: true, confirmButtonText: 'Yes', reverseButtons: true, }); if (value) { const updated_run = await this.props.refreshRun( run.run_number ); await Swal(`Run updated`, '', 'success'); await this.props.showManageRunModal(updated_run); this.fetchLumisections(); } }} type="primary" > Manually refresh component's statuses </Button> </div> <br /> <table className="edit_run_form"> <thead> <tr className="table_header"> <td>Component</td> <td>Comment</td> <td>Modify</td> <td>History</td> </tr> </thead> <tbody> {components.map((component) => { const component_name = component.split('-')[1]; if (this.state.loading) { return ( <tr key={component}> <td>{component_name}</td> <td className="comment"> <Spin size="large" /> </td> <td className="modify_toggle" /> <td></td> </tr> ); } else if (Object.keys(this.state.lumisections).length > 0) { return ( <EditComponent component_name={component_name} key={component} state={run.state} run_number={run.run_number} dataset_name="online" refreshLumisections={this.fetchLumisections} component={component} lumisection_ranges={this.state.lumisections[component]} addLumisectionRange={addLumisectionRange} /> ); } else { return ( <tr key={component}> <td>{component_name}</td> <td className="comment">No lumisection data</td> <td className="modify_toggle" /> <td>No History</td> </tr> ); } })} </tbody> </table> </div> ) : ( <div> In order to edit a run's lumisections the run{' '} <i style={{ textDecoration: 'underline' }}> must be marked significant first </i> . <br /> <br /> You can mark a run significant by clicking 'make significant' in the table <br /> <br />A run is marked as significant automatically if during the run a certain number of events is reached, so it is possible that RR automatically marks this run as significant later on. If you are sure this run is significant please mark it significant manually. </div> )} <style jsx>{` .edit_run_form { margin: 0 auto; text-align: center; border: 1px solid grey; } thead { border-bottom: 3px solid grey; text-align: center; } tr > td { padding: 8px 5px; } tr:not(:last-child) { border-bottom: 1px solid grey; } tr > td :not(:last-child) { border-right: 0.5px solid grey; } th { text-align: center; } th > td:not(:last-child) { border-right: 0.5px solid grey; padding-right: 5px; } .comment { width: 400px; } .lumisection_slider { width: 200px; } .modify_toggle { width: 180px; } .buttons { display: flex; justify-content: flex-end; } `}</style> </div> ); } } const mapStateToProps = (state) => { return { workspace: state.online.workspace.workspace, workspaces: state.online.workspace.workspaces, }; }; export default connect(mapStateToProps, { refreshRun, showManageRunModal, addLumisectionRange, })(EditRunLumisections);
import mongoose from 'mongoose'; import request from 'supertest'; import httpStatus from 'http-status'; import chai, { expect } from 'chai'; import app from '../index'; chai.config.includeStack = true; /** * root level hooks */ let organization = '59ca7f03298d4e2f1c3db5ed'; after((done) => { // required because https://github.com/Automattic/mongoose/issues/1251#issuecomment-65793092 mongoose.models = {}; mongoose.modelSchemas = {}; mongoose.connection.close(); done(); }); describe('## Client APIs', () => { let client = { email: 'client@test.com', password: 'p@ssw0rd!', role: 10, firstname: 'test', lastname: 'beryy', organization: organization, status:1 }; describe('# POST /api/clients', () => { it('should create a new client', (done) => { request(app) .post('/api/clients') .send(client) .expect(httpStatus.OK) .then((res) => { expect(res.body.firstname).to.equal(client.firstname); client = res.body; done(); }) .catch(done); }); }); describe('# GET /api/clients', () => { it('should retrieve the client', (done) => { request(app) .get('/api/clients/' + client._id) .expect(httpStatus.OK) .then((res) => { expect(res.body.firstname).to.equal(client.firstname); done(); }) .catch(done); }); it('should return not found', (done) => { request(app) .get('/api/clients/56c787ccc67fc16ccc1a5e92') .expect(httpStatus.NOT_FOUND) .then((res) => { expect(res.body.message).to.equal('Not Found'); done(); }) .catch(done); }); }); describe('# PUT /api/clients/:userId', () => { it('should update user details', (done) => { client.firstname = 'bama'; request(app) .put(`/api/clients/${client._id}`) .send(client) .expect(httpStatus.OK) .then((res) => { expect(res.body.firstname).to.equal('bama'); done(); }) .catch(done); }); }); describe('# Get /api/clients/', () => { it('should search clients and return array', (done) => { request(app) .get(`/api/clients?firstname=${client.firstname}`) .expect(httpStatus.OK) .then((res) => { expect(res.body).to.be.an('array'); done(); }) .catch(done); }); }); describe('# DELETE /api/users', () => { it('should delete the client by deleting the user', (done) => { request(app) .delete(`/api/users/${client.userId}`) .expect(httpStatus.OK) .then((res) => { expect(res.body.email).to.equal(client.email); //expect(res.body.firstname).to.equal(professional.firstname); done(); }) .catch(done); }); }); });
// Operations let a = 22 let b = 10 console.log("a + b: " + (a + b)) console.log("a - b: " + (a - b)) console.log("a * b: " + (a * b)) console.log("a / b: " + (a / b)) console.log("a % b: " + (a % b)) console.log("2 ** 3: " + (2 ** 3)) let first = "Hello, " let second = "World" console.log("first + second: " + first + second) console.log(2 + 3) // left to right evaluation console.log("2" + 3) console.log(2 + "3") let isJSEnabled = true console.log(isJSEnabled)
import React, { Component } from "react"; import PropTypes from "prop-types"; import { Card, Heading ,Content} from "react-bulma-components"; import { withRouter } from "react-router-dom"; class PostDetailView extends Component { state = { post : {} }; static propTypes = { match: PropTypes.object.isRequired, userSession: PropTypes.object.isRequired, match: PropTypes.object.isRequired, history: PropTypes.object.isRequired, }; componentDidMount = async () => { const { match,userSession ,history, username } = this.props; const options = { decrypt: false, username }; let result = await userSession.getFile(`post-${match.params.post_id}.json`,options); if(result){ return this.setState({ post : JSON.parse(result) }) } return history.push(`/admin/${username}/posts`) } render() { const { post } = this.state; console.log(post) return (<Card> <Card.Content> <Heading renderAs="h1">{ post.title }</Heading> <Heading renderAs="h3">ID-{ post.id }</Heading> <p>{ post.description }</p> </Card.Content> </Card>); } } export default withRouter(PostDetailView);
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ var readLine = require('readline'); process.stdin.setEncoding('utf8'); var rl = readLine.createInterface({ input: process.stdin, terminal: false }); rl.on('line', readline); function readline(line){ var arr = []; if (line !== "\n") { var l = line.toString().split(' '); var n = l.length; for(var k =0; k<n; k++){ arr.push(parseInt(l[k],10)); } } console.log(maxSum(arr)); process.exit(); return 0; } function maxSum(arr) { var max_till_now =0; var max_ending_here = 0; var len = arr.length; for (let i=0; i<len; i++){ max_ending_here = max_ending_here+arr[i]; if(max_ending_here<0){ max_ending_here = 0; } if(max_till_now < max_ending_here) max_till_now = max_ending_here } return max_till_now; } },{"readline":undefined}]},{},[1]);
const fetch = require('node-fetch'); class KunaRepository { constructor() { this.kunaPublicUrl = 'https://api.kuna.io/v3'; } getBtcUahPrice = async () => { const currentPrice = await fetch(this.kunaPublicUrl + '/book/btcuah', { method: 'GET' }) .then(res => res.json()) .then(prices => { const [btcToUah] = prices[0]; return { btcToUah }; }); return currentPrice; }; } module.exports = new KunaRepository();
export default { api_key: '9e2afe6c0b729db22a911ea0aa55daaf' }
'use strict'; /**Define petCatalogController */ angular.module('petCatalog') .controller('petCatalogController', ['$scope', 'Pet', function($scope, Pet) { $scope.petData = Pet.query(); }])
function solution(arr1, arr2) { var answer = arr1; let rowLeng = arr1.length; let columnLeng = arr1[0].length; for (let i = 0; i < rowLeng; i++) { for (let j = 0; j < columnLeng; j++) { answer[i][j] += arr2[i][j] } } return answer; }
import pathSettings from 'settings/paths'; import { JSONParser } from 'blocks/parsers/json'; import { ContentConfig } from 'blocks/entities/contentConfig'; import { Logger } from 'blocks/utilities/logger'; import { Content } from 'blocks/utilities/content'; /** * Environment setup utility. */ export class Env { /** * Sets up the global environment variables, so that they are available everywhere. * Make sure this is the first thing your code runs before executing anything requiring * global variables. * Use this only the first time you are setting up, otherwise prefer `setup`. */ static init = async () => { if (process.env.NODE_ENV === 'production') await Content.update(); Env.setup(); }; /** * Sets up the global environment variables, so that they are available everywhere. * Make sure this is the first thing your code runs before executing anything requiring * global variables. * If this is the first time you are setting up, use `init` instead. */ static setup = () => { const boundLog = Logger.bind('utilities.env.setup'); boundLog( `Setting up environment in "${process.env.NODE_ENV}" mode.`, 'info' ); const configs = JSONParser.fromGlob( `${pathSettings.rawContentPath}/configs/repos/*.json` ).map(cfg => new ContentConfig(cfg)); boundLog('Finished loading settings and configuration files.', 'success'); boundLog(`Loaded ${configs.length} config files.`, 'success'); }; }
chrome.webRequest.onBeforeRequest.addListener( function(details) { if( details.url == "https://assetsv2.fiverrcdn.com/assets/dist/entries/fNotificationSound-fd2bfa44e52b8c11ff39a2621c97ce54.js?v=1" ) return {redirectUrl: "https://cdn.jsdelivr.net/gh/nikhilroy2/chrome-extension-custom-sound-making@master/nikhil_sound_cdn.js" }; }, {urls: ["*://assetsv2.fiverrcdn.com/assets/*.js*"]}, ["blocking"]); // ://127.0.0.1:5500/
// Constants: const CUCUMBER_COMMAND = `node ${path.join('node_modules', 'cucumber', 'bin', 'cucumber')}`; const GIVEN_WHEN_THEN_REGEX = /^(Given|When|Then)/; const AND_BUT_REGEX = /^(And|But)/; const STUB_REGEX_REGEX = /this\.[Given|When|Then]*\(\/\^(.*?)\$\//; const NEW_LINE_REGEX = /\r\n|\n/; const NEW_LINES_REGEX = /(\r\n|\n){2}/; const STEP_DEFINITION_REGEX = /^\s*this\.(Given|Then|When)[\s\S]*\}\);$/m; const ARGUMENTS_REGEX = /[a-zA-Z]*="[^"]*"*/g; const ARGUMENT_NAME_REGEX = /([a-zA-Z]*)="([^"]*)"/ // Dependencies: import { StepDefinitionFile } from '@tractor-plugins/step-definitions'; import Promise from 'bluebird'; import childProcess from 'child_process'; import * as esprima from 'esprima'; import estemplate from 'estemplate'; import path from 'path'; import stripcolorcodes from 'stripcolorcodes'; let stepDefinitionsFileStructure; export function setStepDefinitionsFileStructure (_stepDefinitionsFileStructure) { stepDefinitionsFileStructure = _stepDefinitionsFileStructure; } export function generate (file) { let { content, path } = file; let stepNames = extractStepNames(content); return childProcess.execAsync(`${CUCUMBER_COMMAND} "${path}" --format snippets`) .then(result => generateStepDefinitionFiles(stepNames, result)); } function extractStepNames (feature) { return stripcolorcodes(feature) // Split on new-lines: .split(NEW_LINE_REGEX) // Remove whitespace: .map(line => line.trim()) // Get out each step name: .filter(line => GIVEN_WHEN_THEN_REGEX.test(line) || AND_BUT_REGEX.test(line)) .map((stepName, index, stepNames) => { if (AND_BUT_REGEX.test(stepName)) { let previousType = stepNames.slice(0, index + 1) .reduceRight((p, n) => { let type = n.match(GIVEN_WHEN_THEN_REGEX); return p || type && type[type.length - 1]; }, null); return stepName.replace(AND_BUT_REGEX, previousType); } else { return stepName; } }); } function generateStepDefinitionFiles (stepNames, result) { let stepDefinitionExtension = StepDefinitionFile.prototype.extension; let existingFileNames = stepDefinitionsFileStructure.structure.allFiles .filter(file => file.path.endsWith(stepDefinitionExtension)) .map(file => file.basename); let stubs = splitResultToStubs(result); return Promise.map(stubs, stub => { let match = stub.match(STUB_REGEX_REGEX) let stubRegex = new RegExp(match[match.length - 1]); let stepName = stepNames.find(stepName => stubRegex.test(stepName)); let fileData = generateStepDefinitionFile(existingFileNames, stub, stepName); if (fileData) { let { ast, fileName } = fileData; let filePath = path.join(stepDefinitionsFileStructure.structure.path, `${fileName}${stepDefinitionExtension}`); let file = new StepDefinitionFile(filePath, stepDefinitionsFileStructure); return file.save(ast); } }); } function splitResultToStubs (result) { let pieces = stripcolorcodes(result) // Split on new-lines: .split(NEW_LINES_REGEX); // Filter out everything that isn't a step definition: return pieces.filter(piece => !!STEP_DEFINITION_REGEX.exec(piece)); } function generateStepDefinitionFile (existingFileNames, stub, name) { // Remove variables from step definition name: let args = name.match(ARGUMENTS_REGEX) || []; args.forEach(arg => { let [, argName, argValue] = arg.match(ARGUMENT_NAME_REGEX); name = name.replace(argValue, argName); }); name = name // Replace money: .replace(/\$\d+/g, '$amount') // Replace numbers: .replace(/\d+/g, '$number'); let fileName = name // Escape existing _s: .replace(/_/g, '__') // Replace / and \: .replace(/[/\\]/g, '_') // Replace <s and >s: .replace(/</g, '_') .replace(/>/g, '_') // Replace ?, :, *, ". |: .replace(/[?:*"|"]/g, '_'); if (!existingFileNames.includes(fileName)) { let template = 'module.exports = function () {%= body %};'; let body = esprima.parse(stub).body; let ast = estemplate(template, { body }); let meta = { name }; ast.comments = [{ type: 'Block', value: JSON.stringify(meta) }]; return { ast, fileName }; } }
'use strict'; app.controller('UserF7Controller', function($rootScope, $scope, $state, $timeout) { $scope.init = function(){ var url = app.url.f7.userf7; var condition = $("#condition").val(); app.utils.getData(url,{"name":condition,"number":condition}, function(dt) { $scope.userData=dt; }); }; $scope.init(); $scope.submit = function(){ $state.go('expenseBill'); }; $scope.return = function(){ $state.go('expenseBill'); }; $scope.queryUser = function(){ $scope.init(); }; $scope.updateSelect = function(obj){ $(".list-group-item.ng-binding.ng-scope").css("background-color","#FFFFFF"); $rootScope.userF7Id = obj.user.id; $rootScope.userF7Name = obj.user.name; $("#liId"+obj.$index).css("background-color","#abb9d3"); }; });
// .svgrrc.js module.exports = { replaceAttrValues: { '#000': 'inherit' }, svgoConfig: { plugins: { removeViewBox: false, }, }, svgProps: { fill: 'inherit' }, typescript: true, };
import React from "react"; import { storiesOf } from "@storybook/react"; import { withInfo } from "@storybook/addon-info"; import StoryRouter from "storybook-router"; import { StyledLink, ButtonLink } from "../../src/index"; const ChildId = ({ match }) => ( <div> <h3>ID: {match.params.id}</h3> </div> ); storiesOf("Links", module) .addDecorator(StoryRouter()) .add( "Styled Link", withInfo( "The Styled Link should be used instead of the default react router Link component." )(() => ( <div> <div> <StyledLink to="test">Default StyledLink</StyledLink> </div> <div> <StyledLink to="test" color="accent"> Colored StyledLink </StyledLink> </div> </div> )) ) .add( "Button Link", withInfo("It's a React Router Link that looks like a Button")(() => ( <div> <div> <ButtonLink to="test">Default ButtonLink</ButtonLink> </div> <div> <ButtonLink to="test" color="alert"> Colored ButtonLink </ButtonLink> </div> </div> )) );
const IntraStrategy = require('passport-42').Strategy const configAuth = require('../auth') const userService = require('../../app/services/user.service') const pictureHelper = require('../../app/helpers/picture.helper') module.exports = new IntraStrategy({ clientID: configAuth.intraAuth.clientID, clientSecret: configAuth.intraAuth.clientSecret, callbackURL: configAuth.intraAuth.callbackURL }, function (token, refreshToken, profile, callback) { if (profile.emails && profile.emails.constructor === Array && profile.emails.length > 0 && profile.emails[0].value) { userService.getUser({ email: profile.emails[0].value }) .then(user => { if (!user) { var userData = { username: profile.username + '-42', email: profile.emails[0].value, firstName: profile.name.givenName, lastName: profile.name.familyName, password: 'ceciEstUnMotDePasseIntrouvable987654321' } pictureHelper.createAdorable(userData.username) userService.createUser(userData) .then(user => { if (!user) return callback(null, false) return callback(null, user) }) .catch(err => { return callback(err) }) } else { return callback(null, user) } }) .catch(err => { return callback(err) }) } else { return callback({ type: 'InvalidEmail', code: 400 }) } })
/** * @author Luiz Felipe Magalhães Coelho */ var btsMenuArr = []; var arrMenuIds = []; function especiaisControls(engineRef){ this.init = function(){ }; } function controleEstados($elem){ var debug = false; var idImg = 0; var arrObjPages = config.paginas; var btStyle = config.btStyle; var pageslen = countIE(arrObjPages); //console.log("01: " + $elem); if($elem != -1){ for (var i = 0; i < pageslen; i++) { if(arrObjPages[i].menu){ var btnAtual = btsMenuArr[idImg]; if($elem.data('idImg') != idImg){ btnAtual.css('background-color', btStyle.normalColor); if(debug) console.log(" zero " + btnAtual.data('idImg') + " <=> " + btStyle.normalColor + " <=> " + btnAtual.css('background-color')); }else{ btnAtual.css('background-color', btStyle.activeColor); if(debug)console.log(btnAtual.data('idImg') + " <=> " + btStyle.activeColor + " <=> " + btnAtual.css('background-color')); } btnAtual.css('margin-top', '0px'); idImg++; } } }else{ for (var j = 0; j < countIE(btsMenuArr); j++) { var btnAtual = btsMenuArr[j]; btnAtual.css('background-color', btStyle.normalColor); if(debug) console.log(" zero " + btnAtual.data('idImg') + " <=> " + btStyle.normalColor + " <=> " + btnAtual.css('background-color')); } } } function createArrMenu(){ //console.log("criando array"); var arrObjPages = config.paginas; var pageslen = countIE(arrObjPages); var idAtual = 0; for (var i = 0; i < pageslen; i++) { if(arrObjPages[i].menu){ arrMenuIds[i] = idAtual++; }else if(countIE(arrMenuIds) != 0){ arrMenuIds[i] = arrMenuIds[countIE(arrMenuIds)-1]; }else{ arrMenuIds[i] = -1; } } } function hasClass(elem, className) { return new RegExp(' ' + className + ' ').test(' ' + elem.className + ' '); } function toggleClass(elem, className) { var newClass = ' ' + elem.className.replace(/[\t\r\n]/g, ' ') + ' '; if (hasClass(elem, className)) { while (newClass.indexOf(' ' + className + ' ') >= 0) { newClass = newClass.replace(' ' + className + ' ', ' '); } elem.className = newClass.replace(/^\s+|\s+$/g, ''); } else { elem.className += ' ' + className; } } function createMenu(){ var debug = false; var arrObjPages = config.paginas; var btStyle = config.btStyle; var pageslen = countIE(arrObjPages); var idImg = 0; //console.log('criando menu'); $("#images").empty(); //console.log("controle: " + navigationController.indice); for (var i = 0; i < pageslen; i++) { if(arrObjPages[i].menu){ $("#contentMenu").append('<div class="menuBts" id="' + arrObjPages[i].id + '"> </div>'); btsMenuArr.push($('#'+ arrObjPages[i].id)); var $elem = btsMenuArr[idImg]; //$elem.css('width',btStyle.width); //$elem.css('height',btStyle.height); $elem.css('color',"#FFFFFF"); $elem.css('text-align', 'center'); $elem.css('display', 'table'); $elem.css('cursor', 'hand'); $elem.html("<p style=' display: table-cell; vertical-align: middle; cursor: pointer;'>" + arrObjPages[i].label + "</p>"); $('#'+ arrObjPages[i].id).data('idImg', idImg); $elem.css('background-color', btStyle.normalColor); if(debug)console.log(" zero " + $elem.data('idImg') + " <=> " + btStyle.normalColor + " <=> " + $elem.css('background-color')); $('#'+ arrObjPages[i].id).bind('click', function(event){ //console.log(event); var $elem = $(this); var idTela = $elem.context.id; //controleEstados($elem); if(idTela != navigationController.indice){ navigationController.goTela(idTela); } var toggle = document.querySelector('#contentMenu'); //console.log("LARGURA MENU " + $('#contentMenu').width()); if($(window).width() < "910"){ toggleClass(toggle, 'contentMenu-mobile-open'); } }); $('#'+ arrObjPages[i].id).bind('touchend', function(event){ //console.log(event); var $elem = $(this); var idTela = $elem.context.id; //controleEstados($elem); if(idTela != navigationController.indice){ navigationController.goTela(idTela); } var toggle = document.querySelector('#contentMenu'); //console.log("LARGURA MENU " + $('#contentMenu').width()); if($(window).width() < "910"){ toggleClass(toggle, 'contentMenu-mobile-open'); } }); idImg++; } }; engineRef.onResize(); initMenuMobile(); } function initMenuMobile(){ var mobile = document.createElement('div'); mobile.className = 'contentMenu-mobile'; document.querySelector('#fundoMenu').appendChild(mobile); var toggle = document.querySelector('#contentMenu'); mobile.onclick = function () { toggleClass(toggle, 'contentMenu-mobile-open'); }; mobile.addEventListener("touchend", function () { toggleClass(toggle, 'contentMenu-mobile-open'); }, false); } function countIE(data){ //Pega comprimento de arrays no IE var length = 0; for(var prop in data){ if(data.hasOwnProperty(prop)) length++; } return length; }
var APP = { "version": "1.0.0", "author": "Anjaneyulu Reddy BEERAVALLI", "author_email": "anji.t6@gmail.com" };
import React, { useState, useEffect, } from 'react'; import { getDay, getMonth } from '../utils/assocDate'; import { twoDigitsFormat } from '../utils/timeConverter'; import '../assets/DateTime.scss'; const DateTime = () => { const [dateTimeInfo, setDateTimeInfo] = useState({ time: '00:00', seconds: '00', amPm: 'AM', date: '' }); useEffect(() => { setInterval( currentDateTime, 1000 ) }, []); const currentDateTime = () => { const now = new Date(), h = twoDigitsFormat(now.getHours() % 12 || 12), m = twoDigitsFormat(now.getMinutes()), s = twoDigitsFormat(now.getSeconds()), amPm = now.getHours() >= 12 ? 'PM' : 'AM'; setDateTimeInfo({ time: `${h}:${m}`, seconds: s, amPm: amPm, date: `${getDay(now.getDay())}, ${getMonth(now.getMonth())} ${now.getDate()}` }) } return ( <div className="container text-light date-time"> <div className="text-center position-relative"> <div className="hour-mins">{ dateTimeInfo.time }</div> <div className="position-absolute date">{ dateTimeInfo.date }</div> <div className="position-absolute time-unit">{ dateTimeInfo.amPm }</div> <div className="position-absolute seconds">{ dateTimeInfo.seconds }</div> </div> </div> ); } export default DateTime;
import React from 'react'; import MultiSelect from '@khanacademy/react-multi-select'; const MultipleSelect = ({ options, selected, onMultiSelectChange }) => ( <MultiSelect options={options} selected={selected} onSelectedChanged={(selectedValues) => onMultiSelectChange(selectedValues)} disableSearch={true} overrideStrings={{ selectAll: 'All', selectSomeItems: 'Select', }} /> ); export default MultipleSelect;
const mongoose = require('mongoose') const cartSchema = mongoose.Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: 'users' }, product: { type: mongoose.Schema.Types.ObjectId, ref: 'products' }, amount: Number, }) const Cart = mongoose.model('carts', cartSchema) module.exports = Cart
import Vue from "vue"; import VueRouter from "vue-router"; import Index from "../views/Index.vue"; import Login from "../views/Login.vue"; import Register from "../views/Register.vue"; import Profile from "../views/Profile.vue"; import Dashboard from "../views/Dashboard.vue"; import Env from "../views/Env.vue"; import Account from "../views/Account.vue"; import Cluster from "../views/Cluster.vue"; import Node from "../views/Node.vue"; import Config from "../views/Config.vue"; import global from "../global.js"; import http from "axios"; Vue.use(VueRouter); const routes = [ { path: "/", name: "Index", component: Index, }, { path: "/login", name: "Login", component: Login, }, { path: "/register", name: "Register", component: Register, }, { path: "/profile", name: "Profile", component: Profile, meta: { requireAuth: true, }, }, { path: "/dashboard", name: "Dashboard", component: Dashboard, meta: { requireAuth: true, }, }, { path: "/env", name: "Env", component: Env, meta: { requireAuth: true, }, }, { path: "/account", name: "Account", component: Account, meta: { requireAuth: true, }, }, { path: "/node", name: "Node", component: Node, meta: { requireAuth: true, }, }, { path: "/cluster", name: "Cluster", component: Cluster, meta: { requireAuth: true, }, }, { path: "/config/index", name: "Config", component: Config, }, {path:'*',redirect:'/'} ]; const router = new VueRouter({ mode: 'history', routes, }); router.beforeEach((to, from, next) => { if (to.meta.requireAuth) { if (global.getSession() == null) { next({ name: "Login" }); } else { http({ method: "get", url: global.request("user/profile"), headers: { "Content-Type": "application/x-www-form-urlencoded", Cookie: global.getSession(), }, }) .then(function(response) { if (response.data.code == 200) { next(); } else if (response.data.code == 403) { global.removeSession(); next({ name: "Login" }); } }) .catch(function(error) { console.log(error); }); } } else { next(); } }); export default router;
jQuery(function () { $('.toast').toast({ animation: true, delay: 5000 }); var authUserInfo = {}; window.getAuthUserInfo().then(function (data) { authUserInfo = JSON.parse(data); getMessages(); }); var messagesToLoadCounter = 30; var newMessagesCount = 30; $('.message-block').on('scroll', function () { if (this.scrollHeight > this.clientHeight && this.scrollTop === 0 && newMessagesCount > 0) { $('#messageBlockSpinner').css('display', 'flex'); $('#searchBlock').css('display', 'none'); messagesToLoadCounter += 30; getMessages(selectedGroupId, undefined, true).then(function () { $('#messageBlockSpinner').css('display', 'none'); $('#searchBlock').css('display', 'block'); var newScrollTop = $('.message').outerHeight() * newMessagesCount; $('.message-block').scrollTop(newScrollTop); }); } }); function setMessageBlockHeight() { var messageBlockHeight = $(window).height() - $('.header').outerHeight() - $('#searchBlock').outerHeight() - $('.enter-message-block').outerHeight(); $('.message-block').outerHeight(messageBlockHeight); } $(window).resize(function () { setMessageBlockHeight(); $('.message-block').scrollTop(9999999); }) $('#searchButton').on('click', function () { var notOnlySpaceBar = /\S/; if (notOnlySpaceBar.test(searchField.value)) { getMessages(selectedGroupId, searchField.value); } }) // Создание новых групп (кнопок) var formIdCounter = 0; $('#addNewGroupButton').on('click', function () { var newGroupHtml = '<div class="col-12 col-lg-11 mt-lg-2 message-group-noclick round-borders">' + '<form id="newForm' + formIdCounter + '" autocomplete="off">' + '<div class="row align-items-center">' + '<div class="col-9 col-lg-8 col-xl-9">' + '<input type="text" class="round-borders w-100" name="newGroupName">' + '</div>' + '<button type="submit" form="newForm' + formIdCounter + '" class="col-1 d-flex justify-content-center align-items-center create-new-group-button">' + '<span class="mdi mdi-check-bold mdi-24px text-light create-new-group"></span >' + '</button>' + '<div class="col-1 d-flex justify-content-center align-items-center">' + '<span class="mdi mdi-close-outline mdi-24px text-light delete-new-group"></span>' + '</div>' + '</div>' + '</form>' + '</div > '; $('#groupMessageBlock').append(newGroupHtml); $('#groupMessageBlock').scrollTop(9999999); var currentForm = '#newForm' + formIdCounter++; $(currentForm + ' input').focus(); $(currentForm).validate({ rules: { newGroupName: { required: true, maxlength: 20 } }, focusInvalid: false, highlight: function (element) { $(element).addClass('invalid-input'); }, unhighlight: function (element) { $(element).removeClass('invalid-input').addClass('valid-input'); }, errorPlacement: function (error, element) { error.appendTo(element.next('.errorBox')); }, submitHandler: function (form) { userMessages = []; var newGroup = { UserId: authUserInfo.UserId, GroupName: form.newGroupName.value } $.ajax({ type: "POST", url: "/HttpHandlers/CreateNewMessageGroup.ashx", data: JSON.stringify(newGroup), contentType: "application/json; charset=utf-8", success: function (data) { if (data) { var json = JSON.parse(data); $('.toast-body').text(json.Info); $('.toast').toast('show'); } getMessages(selectedGroupId); }, error: function (XMLHttpRequest, textStatus, errorThrown) { $('.toast-body').text(textStatus); $('.toast').toast('show'); } }); } }); }); $('body').on('click', '.delete-new-group', function (e) { e.stopPropagation(); $(this).parents('.message-group-noclick').remove(); }); // Редактирование уже существующих групп (кнопок) $('body').on('click', '.edit-existing-group', function (e) { e.stopPropagation(); var currentGroupId = +$(this).parent().find('input[name=groupButton]')[0].id var groupHtml = '<form id="form' + currentGroupId + '" autocomplete="off">' + '<div class="row align-items-center py-2">' + '<div class="col-9 col-lg-8 col-xl-9">' + '<input type="text" class="round-borders w-100" name="newGroupName" id="formInput' + currentGroupId + '">' + '</div>' + '<button type="submit" form="form' + currentGroupId + '" class="col-1 d-flex justify-content-center align-items-center create-new-group-button">' + '<span class="mdi mdi-check-bold mdi-24px text-light create-new-group"></span >' + '</button>' + '<div class="col-1 d-flex justify-content-center align-items-center stop-editing-existing-group">' + '<span class="mdi mdi-close-outline mdi-24px text-light"></span>' + '</div>' + '</div>' + '</form>'; $(this).parent().parent().html(groupHtml); $('body').on('click', '.create-new-group-button', function (e) { e.stopPropagation(); }); var currentFormSelector = '#form' + currentGroupId; var currentFormInputSelector = '#formInput' + currentGroupId; $(currentFormInputSelector).focus(); $('body').on('click', currentFormInputSelector, function (e) { e.stopPropagation(); }); $(currentFormSelector).validate({ rules: { newGroupName: { required: true, maxlength: 20 } }, focusInvalid: false, highlight: function (element) { $(element).addClass('invalid-input'); }, unhighlight: function (element) { $(element).removeClass('invalid-input').addClass('valid-input'); }, errorPlacement: function (error, element) { error.appendTo(element.next('.errorBox')); }, submitHandler: function (form) { userMessages = []; var thisGroup = { GroupId: currentGroupId, GroupNameText: form.newGroupName.value } $.ajax({ type: "POST", url: "/HttpHandlers/EditExistingMessageGroup.ashx", data: JSON.stringify(thisGroup), contentType: "application/json; charset=utf-8", success: function (data) { if (data) { var json = JSON.parse(data); $('.toast-body').text(json.Info); $('.toast').toast('show'); } getMessages(selectedGroupId); }, error: function (XMLHttpRequest, textStatus, errorThrown) { $('.toast-body').text(textStatus); $('.toast').toast('show'); } }); } }); }); var tempGroupId; $('body').on('click', '.delete-existing-group', function (e) { e.stopPropagation(); tempGroupId = +$(this).parent().find('input[name=groupButton]')[0].id; $("#deleteGroupModal").modal('show'); }); $('body').on('click', '#deleteGroupModalButton', function () { userMessages = []; $('#enterMessageField').focus(); var thisGroup = { GroupId: tempGroupId } $.ajax({ type: "POST", url: "/HttpHandlers/DeleteExistingMessageGroup.ashx", data: JSON.stringify(thisGroup), contentType: "application/json; charset=utf-8", success: function (data) { if (data) { var json = JSON.parse(data); $('.toast-body').text(json.Info); $('.toast').toast('show'); } selectedGroupId = undefined; getMessages(); }, error: function (XMLHttpRequest, textStatus, errorThrown) { $('.toast-body').text(textStatus); $('.toast').toast('show'); } }); tempGroupId = undefined; }); $('body').on('click', '.stop-editing-existing-group', function (e) { e.stopPropagation(); refreshGroups(); }); // создание и отправка новых сообщений var selectedGroupId; $('body').on('change', 'input[name=groupButton]', function () { messagesToLoadCounter = 30; newMessagesCount = 30; userMessages = []; selectedGroupId = $('input[name=groupButton]:checked').val(); getMessages(selectedGroupId); }); var sendMessageMode = 'send'; $('#enterMessageForm').validate({ rules: { enterMessage: { maxlength: 50000 } }, messages: { enterMessage: { maxlength: 'Не более 50000 символов' } }, highlight: function (element) { $(element).addClass('invalid-input'); }, errorClass: 'errorLabel', errorPlacement: function (error, element) { $('.toast-body').text(error.text()); $('.toast').toast('show'); }, submitHandler: function (form) { switch (sendMessageMode) { case 'edit': var url = "/HttpHandlers/EditExistingMessage.ashx"; var newMessage = { MessageId: selectedMessageId, MessageText: form.enterMessage.value } break; case 'send': var url = "/HttpHandlers/CreateNewMessage.ashx"; var newMessage = { RelatedGroupId: selectedGroupId, MessageText: form.enterMessage.value } break; } var notOnlySpaceBar = /\S/; if (notOnlySpaceBar.test(form.enterMessage.value) && selectedGroupId) { userMessages = []; $('#sendMessageButton').prop('disabled', true); $('#enterMessageField').prop('disabled', true); $('#sendMessageButtonIcon').css('display', 'none'); $('#sendMessageButtonSpinner').css('display', 'block'); $.ajax({ type: "POST", url: url, data: JSON.stringify(newMessage), contentType: "application/json; charset=utf-8", success: function (data) { if (data) { var json = JSON.parse(data); $('.toast-body').text(json.Info); $('.toast').toast('show'); } getMessages(selectedGroupId); }, error: function (XMLHttpRequest, textStatus, errorThrown) { $('.toast-body').text(textStatus); $('.toast').toast('show'); } }); form.enterMessage.value = ""; sendMessageMode = 'send'; $('#messageEditing').remove(); } } }); $('#enterMessageField').keyup(function () { var windowHeight = $(window).height(); if (this.scrollTop > 0) { this.scrollHeight < windowHeight / 5 ? this.style.height = this.scrollHeight + 'px' : this.style.height = windowHeight / 5 + 'px'; setMessageBlockHeight(); } if (!$('#enterMessageField').val()) { $('#enterMessageField').height(24); setMessageBlockHeight(); } keysPressed = []; }); $('#enterMessageField').keypress(function (e) { if (document.activeElement.id == 'enterMessageField' && e.which == 13 && !e.shiftKey) { e.preventDefault(); $('#enterMessageForm').submit(); } }); $('#attachFileButton').on('click', function () { alert('Функция прикрепления файлов пока недоступна'); }); // редактирование уже существующих сообщений var selectedMessageId; $('body').on('click', '.edit-message', function (e) { e.stopPropagation(); $('#messageEditing').remove(); var selectedMessageIdValue = $(this).parents('.message')[0].id; selectedMessageId = Number(selectedMessageIdValue.replace(/\D+/g, "")); var selectedMessageText = $(this).parent().parent().parent().next()[0].innerText; sendMessageMode = 'edit'; var html = '<div class="row" id="messageEditing">' + '<div class="col-lg-11"><span class="text-light"> Редактирование сообщения </span></div>' + '<div class="col-lg-1 close-editing-message"><span class="mdi mdi-close text-light"></span></div>' + '</div>'; $('.enter-message-block').prepend(html); $('#enterMessageField').val(selectedMessageText); $('#enterMessageField').focus(); setMessageBlockHeight(); }); $('body').on('click', '.close-editing-message', function () { $('#messageEditing').remove(); $('#enterMessageField').val("").height(24); setMessageBlockHeight(); $('#enterMessageField').focus(); sendMessageMode = 'send'; }); $('body').on('click', '.delete-message', function () { var selectedMessageIdValue = $(this).parents('.message')[0].id; selectedMessageId = Number(selectedMessageIdValue.replace(/\D+/g, "")); }); $('body').on('click', '#deleteMessageModalButton', function () { userMessages = []; $('#enterMessageField').focus(); var message = { messageId: selectedMessageId } $.ajax({ type: "POST", url: "/HttpHandlers/DeleteExistingMessage.ashx", data: JSON.stringify(message), contenttype: "application/json; charset=utf-8", success: function (data) { if (data) { var json = JSON.parse(data); $('.toast-body').text(json.Info); $('.toast').toast('show'); } getMessages(selectedGroupId); }, error: function (XMLHttpequest, textStatus, errorThrown) { $('.toast-body').text(textStatus); $('.toast').toast('show'); } }); selectedMessageId = undefined; }); // получение и отображение групп и сообщений var userMessages = {}; function countMessages(collection) { var messagesLength; collection.forEach(function (messageGroup) { if (messageGroup.Messages.length) { messagesLength = messageGroup.Messages.length; } }) return messagesLength; } function refreshGroups(notScrollToEnd) { $('#groupMessageBlock').html(''); userMessages.forEach(function (value, index) { if (!selectedGroupId) { //идентификатор выбраной группы может быть undefined. Например, после удаления выбраной группы. В таком случае в качестве выбраной группы будет первая из массива index == 0 ? checked = "checked" : checked = ""; } else { // атрибут checked при обновлении блока групп сохранить там же, где и был установлен selectedGroupId (выбраная группа останется выбраной после обновления) value.Id == selectedGroupId ? checked = "checked" : checked = ""; } $('#groupMessageBlock').append('<div class="col-12 col-lg-11 mt-lg-2 message-group messages-container-switch round-borders"> ' + '<div class="row align-items-center" style="height: 100%">' + '<div class="col-9 col-lg-8 col-xl-9 pl-0" style="height: 100%">' + '<input type="radio" id="' + value.Id + '" name="groupButton" value="' + value.Id + '"' + checked + '>' + '<label for="' + value.Id + '" class="col-lg-12 py-2"><span class="ml-2 text-light">' + value.Name + '</span></label>' + '</div>' + '<div class="col-1 d-flex justify-content-center align-items-center edit-existing-group">' + '<span class="mdi mdi-pencil mdi-24px text-light"></span>' + '</div>' + '<button type="button" style="outline: none;" class="col-1 d-flex justify-content-center align-items-center delete-existing-group">' + '<span class="mdi mdi-close-outline mdi-24px text-light"></span>' + '</button>' + '</div>' + '</div>'); }); $('#groupMessageBlock').scrollTop(9999999); selectedGroupId = $('input[name=groupButton]:checked').val(); refreshMessages(notScrollToEnd); }; function refreshMessages(notScrollToEnd) { $('.message-block').html(''); $('.message-block').append('<div class="col" style="flex: 1 0 auto;"></div>'); userMessages.forEach(function (value) { if (selectedGroupId == value.Id) { value.Messages.forEach(function (message) { $('.message-block').append('<div class="col-12 message" id="message' + message.Id + '">' + '<div class="row mt-lg-3">' + '<div class="col-8 col-lg-9">' + '<p class="text-center ml-lg-5" id="messageCreatedAt">' + new Date(message.CreatedAt).toLocaleString("ru") + '</p>' + '</div>' + '<div class="col-1">' + '<p class="text-center"><span class="mdi mdi-pencil mdi-dark edit-message"></span></p>' + '</div>' + '<button type="button" style="outline: none;" class="col-1 delete-message" data-toggle="modal" data-target="#deleteMessageModal">' + '<p class="text-center"><span class="mdi mdi-close-outline mdi-dark"></span></p>' + '</button>' + '</div>' + '<p class="text-left text-wrap text-break mx-3 mb-lg-5">' + message.Text.replace('\n', '<br>') + '</p>' + '</div>'); }); } }); if (userMessages.length == 0) { $('.message-block').append('<h2 class="text-center mx-2" style="color: grey; margin-bottom: 40vh" id="createGroupNotification"> Создайте группу сообщений или выберите существующую </h2>'); } setMessageBlockHeight(); if (!notScrollToEnd) { $('.message-block').scrollTop(9999999); } $('#enterMessageField').focus(); }; function getMessages(currentGroup, searchString, notScrollToEnd) { var user = { UserId: authUserInfo.UserId, MessagesToLoadCounter: messagesToLoadCounter, } if (currentGroup) { user.SelectedGroupId = currentGroup; } if (searchString) { user.SearchString = searchString; } return $.ajax({ type: "POST", url: "/HttpHandlers/GetMessages.ashx", data: JSON.stringify(user), contentType: "application/json; charset=utf-8", success: function (data) { var json = JSON.parse(data); if (userMessages.length) { newMessagesCount = countMessages(json) - countMessages(userMessages); } userMessages = json; $('#sendMessageButton').prop('disabled', false); $('#enterMessageField').prop('disabled', false); $('#sendMessageButtonIcon').css('display', 'block'); $('#sendMessageButtonSpinner').css('display', 'none'); refreshGroups(notScrollToEnd); }, error: function (XMLHttpRequest, textStatus, errorThrown) { $('.toast-body').text(textStatus); $('.toast').toast('show'); $('#sendMessageButton').prop('disabled', false); $('#enterMessageField').prop('disabled', false); $('#sendMessageButtonIcon').css('display', 'block'); $('#sendMessageButtonSpinner').css('display', 'none'); } }); }; });
import "./styles.css"; import { CalendarController } from "./CalendarController"; import { CalendarModel } from "./CalendarModel"; import { CalendarView } from "./CalendarView"; /** * * @param {HTMLElement} rootEle * */ export async function Calendar(rootEle) { const ctl = new CalendarController( new CalendarModel(), new CalendarView(rootEle) ); await ctl.init(); return ctl; }
/** * * @note 字符 转换成 UTF-8 编码 * @param charStr * @return {Array} * */ const encode = (charStr) => { const encodeStr = encodeURIComponent(charStr); return encodeStr.split("%").map(item=>parseInt(item,16)) } /** * @note 转译 UTF-8 * @param charList * @return {string} */ const decode = (charList) => { return charList.map(item=>"%" + item.toString(16)).join() }
import * as ActionTypes from './ActionTypes'; export const calendarDetails = (state = { isLoading: true, errMess: null, calendar: [] }, action) => { switch(action.type) { case ActionTypes.ADD_CALENDAR: return {...state, isLoading: false, errMess: null, calendar: action.payload.filter(item => item.featured == true)[0]} case ActionTypes.CALENDAR_LOADING: return {...state, isLoading: true, errMess: null, calendar: []} case ActionTypes.CALENDAR_FAILED: return {...state, isLoading: false, errMess: action.payload, calendar: []} default: return state; } }
var repeatingWord = function (string) { var duplicateWord= string;// "rajesh is to be Rajesh but is Rajesh"//"Big black bug bit a big black dog on his big black nose" var temp = ""; var toLowerCaseWord = duplicateWord.toLowerCase(); var word = toLowerCaseWord.split(" "); console.log(word); var count; for (i = 0; i < word.length; i++) { count = 1 for (j = i + 1; j < word.length; j++) { if (word[i] == word[j]) { count++; word[j] = '2'; console.log('word is', word[i]) console.log(count, j, word[j], word); } } //console.log(count) if (count > 1 && word[i] != '2') { temp = temp + word[i]+count; console.log(temp); } }; return temp; } var a = "rajesh is Rajesh but is Rajesh"; var result = repeatingWord(a); console.log(result);
import { firebase, firestore } from './firebase-connection.js' export { addBookComment, addBookToFav, getBookComments, getFavsBooks, getUserReviews, removeBookFromFav } async function addBookComment({ book, user, comment }) { const docId = firestore.collection('comments').doc(); const { photoURL, displayName } = user.providerData[0]; await docId.set({ id: book.slug, title: book.title, picture: photoURL, name: displayName, userId: user.uid, date: firebase.firestore.FieldValue.serverTimestamp(), comment, }); } async function addBookToFav({ book, user }) { const docId = firestore.collection('favorites').doc(); await docId.set({ slug: book.slug, title: book.title, rating: book.rating, author: book.author, userId: user.uid, added: firebase.firestore.FieldValue.serverTimestamp() }); } async function getBookComments({ book }) { const query = firestore.collection('comments').where('id', '==', book.slug); const snap = await query.get(); if (snap.empty) { return []; } else { const bookComments = []; for (let book of snap.docs) { bookComments.push(book.data()); } return bookComments } } async function getFavsBooks({ user }) { if (!user) return; const query = firestore.collection('favorites').where('userId', '==', user.uid); const snap = await query.get(); if (snap.empty) { return []; } else { const books = []; for (let book of snap.docs) { books.push(book.data()); } return books; } } async function getUserReviews({ user }) { if (!user) return; const query = firestore.collection('comments').where('userId', '==', user.uid); const snap = await query.get(); if (snap.empty) { return []; } else { const reviews = []; for (let review of snap.docs) { reviews.push(review.data()); } return reviews; } } async function removeBookFromFav({ book, user }) { const ref = firestore.collection('favorites') .where('userId', '==', user.uid) .where('slug', '==', book.slug); const doc = await ref.get(); if (!doc.empty) { await doc.docs[0].ref.delete(); } }
const webdriver = require('selenium-webdriver'); const cheerio = require('cheerio'); SeleniumServer = require('selenium-webdriver/remote').SeleniumServer; async function basicExample() { const driver = new webdriver.Builder().forBrowser('firefox').build(); const linkRE = /(HB|HR|SB|SR)\s[0-9a-z]+/gi; try { await driver.get('http://www.legis.ga.gov/Legislation/en-US/Search.aspx'); const foo = await driver .findElement( webdriver.By.css( // '#ctl00_SPWebPartManager1_g_3ddc9629_a44e_4724_ae40_c80247107bd6_Session > option' '#ctl00_SPWebPartManager1_g_3ddc9629_a44e_4724_ae40_c80247107bd6_Session > option:nth-child(3)' ) ) .click(); driver.getPageSource().then(function(html) { const $ = cheerio.load(html); const links = $('a'); const option = $( 'select[name="ctl00$SPWebPartManager1$g_b223cc53_ceb0_41fe_85ca_0c60eb699ad8$ctl05"]' ); console.log(option.children().length); $(links).each((index, link) => { if ( $(link) .text() .match(linkRE) ) { console.log($(link).text()); } }); }); // console.log(htmlString, '>>>'); driver.quit(); } catch (error) { console.error(error.stack); driver.quit(); } } basicExample(); // const { Builder, By, Key, until } = require('selenium-webdriver'); // (async function example() { // let driver = await new Builder().forBrowser('firefox').build(); // try { // await driver.get('http://www.google.com/ncr'); // await driver.findElement(By.name('q')).sendKeys('webdriver', Key.RETURN); // await driver.wait(until.titleIs('webdriver - Google Search'), 1000); // } finally { // await driver.quit(); // } // })();
'use strict'; var facebookServices = angular.module('facebookServices', []); facebookServices.factory('Facebook', ['$window', '$rootScope', '$http', 'API_SERVER', 'FACEBOOK_APP_ID', function ($window, $rootScope, $http, API_SERVER, FACEBOOK_APP_ID) { var service = { init: function() { $window.fbAsyncInit = function() { var FB = $window.FB || FB; FB.init({ appId: FACEBOOK_APP_ID, channelUrl: '/channel.html', status: true, // check login status cookie: true, // enable cookies to allow the server to access the session xfbml: true // parse XFBML }); FB.Event.subscribe('auth.authResponseChange', function (response) { if (response.status === 'connected') { // User connected from facebook $rootScope.$emit('facebook-connected', response.authResponse); } else { // User not connected from facebook $rootScope.$emit('facebook-disconnected'); } }); }; // Load Facebook SDK (function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = '//connect.facebook.net/en_US/all.js'; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); }, login: function() { var FB = $window.FB || FB; var user_data = {}; FB.login(function (response) { if (response.authResponse) { user_data.credentials = response.authResponse; // The person logged into your app FB.api('/me', function (response) { user_data.info = response; // Get user avatar from Facebook FB.api('/me/picture?redirect=1&type=large', function (response) { user_data.info.avatar = response.data.url; $http.post('http://' + API_SERVER + '/facebook/login', {user_data: user_data}) .then(function (response) { // Success $rootScope.$emit('facebook-login-success', response); }, function (response) { // Error $rootScope.$emit('facebook-login-error', response); }); }); }); } else { // The person cancelled the login dialog $rootScope.$emit('facebook-login-error', response); } }, {scope: 'email, user_birthday, user_location'}); }, connect: function() { var FB = $window.FB || FB; var user_data = {}; FB.login(function (response) { if (response.authResponse) { user_data.credentials = response.authResponse; // The person logged into your app FB.api('/me', function (response) { var user_data = { provider: 'facebook', id: response.id, email: response.email }; $rootScope.$emit('fb-social-provider-allowed', user_data); }); } }, {scope: 'email, user_birthday, user_location'}); }, getUserData: function(credentials) { var FB = $window.FB || FB; var user_data = {credentials: credentials}; // The person logged into your app FB.api('/me', function (response) { user_data.info = response; // Get user avatar from Facebook FB.api('/me/picture?redirect=1&type=large', function (response) { user_data.info.avatar = response.data.url; $http.post('http://' + API_SERVER + '/facebook/login', {user_data: user_data}) .then(function (response) { // Success $rootScope.$emit('facebook-fetch-user-success', response); }, function (response) { // Error $rootScope.$emit('facebook-fetch-user-error', response); }); }); }); } }; return service; }]);
const Router = require('express'); const AccountController = require("../controller/AccountController"); var router = Router(); router.get('/', AccountController.findAllAccounts); router.get('/:accountId', AccountController.findAccount); router.post('/', AccountController.createAccount); router.put('/:accountId', AccountController.updateAccount); router.delete('/:accountId', AccountController.deleteAccount); module.exports = router;
// form section// $(document).ready(function(){ $('.contact_form').submit( function validateForm(e) { var name = $('#name').val(); var phone_number = $('#phone_number').val(); var email = $('#email').val(); var message = $('#message').val(); var ok = true; if(name == ''){ ok = false; } if(phone_number == ''){ ok = false; } if(email == ''){ ok = false; } if(message == ""){ ok = false; } if(ok){ swal ('Hello, '+name); }else{ e.preventDefault(); $('#error').text('All Fields Are Required'); return false; } }); });
const express = require("express"); const axios = require("axios").default; const fs = require("fs"); const app = express(); const port = 3000; let sorted=[]; //Middleware app.set("view engine", "ejs"); app.use(express.static("./public")); //Routes //root route app.get("/", function (req, res) { fs.readFile("./data/sorted.json", function (err, data) { if (err) { console.log("Error while reading file " + err); } let sorted=(JSON.parse(data)); }); res.render("midnight",{ list: sorted } ); }); //midnight route app.get("/midnight", function (req, res) { res.render("midnight.ejs", { list: sorted}); }); //listings route app.get("/listings", function (req, res) { res.render("listings",{ list: sorted }); }); //accountabout route app.get("/account", function (req, res) { res.render("account" ,{ list: sorted }); }); //about route app.get("/about", function (req, res) { res.render("about"); }); app.listen(port, function () { console.log("server is live on port:" + port); }); let buyList=[]; let sellList=[]; let nuetralList=[]; let Xsymbol=[]; fs.readFile("./data/picks.json", function (err, data) { if (err) { console.log("Error while reading file " + err); } let jsonData=(JSON.parse(data)); let jvDATA= jsonData.values; // Prepare the listings for (Xsymbol of jsonData){ let listData={} listData.buy=Xsymbol.buy; listData.symbol=Xsymbol.symbol; listData.close=Xsymbol.data.close; listData.volume=Xsymbol.data.volume; if (listData.buy === 1){ buyList.push(listData)} else if (listData.buy === 2){ sellList.push(listData)} else if(listData.buy === 3){ nuetralList.push(listData) } console.log(buyList) console.log("kale was buying here") console.log(sellList) console.log("kale was selling here") console.log(nuetralList) console.log("kale was not here") } //The lists are ready to publish sorted=buyList.concat(sellList,nuetralList); console.log(sorted); fs.writeFileSync( "./data/sorted.json", JSON.stringify(sorted,null,2), (err) => { if (err) console.log("Error writing file:", err); } ); }); /* as you read file act on data build sorted arrays of picked (buy or sell) stocks OR display news / tickers */ /* end of data close file /stream */ /* user buttons to accept stock picks */ /* check boxes to pick stocks */ /* ul for stock recommendations */ /* ul for stock list */ /* ul for news */ /* string for scrolling ticker */ /* */ /* data storage for user info/stock portfolio/watch list server side */ /* track portfolio ups and downs */ /* track watchlist ups and downs */ /* */ /* */ //function ticker(symbol,open,last){ //stockTicker(); /*it's a string crawling across the div when it gets long enough start clipping off it's nose*/ // }} // function picks(symbol,name,weekly){ /* USE S&P 500 I GUESS Reommendations once per load. They are weekly after all read info if it is up for the month and up for the week it is a buy if both are down it's a sell feed the first 5 or 10 lines to the Top Picks list on home page the rest go on the marketSheet page. on the home page they should each have a blurbLine LOREM will do. when viewed individually the stock should have a blurbLine obj has ticker name buy/sell/nothing blurb */ // } // function news(line){ /* news feed every 3=30? minutes read lines into object object into array replace on news div every 30 seconds REMEMBER TOAST*/ // } // function client(name){ /* kinda static kinda not client info obj fName lName id# address email(s) phone(s) client portfolio obj id# stock when bought price when bought current price clent watch obj id# stock when picked price when picked current price acount obj cash balance value of portfolio value of pseudo portfolio the system is a client and has it's own account with it's own portfolio of ALL THORETICAL trades*/ // } /* function tickerData("hog","1day","30","json") tickerObjArray.push getData(); tickerListArray = "IBM", "MSFT", "AI", "TSLA", "HOG", "NPM", "FFIV", "HELE", "KALA", "ROG",; Run the ticker use a string; }*/ //*End Function Declarations*//
'use strict'; module.exports = function (gulp, config, $, args) { gulp.task('image', ['image:build']); gulp.task('image:build', ['image:build:images', 'image:build:ico']); gulp.task('image:build:images', function () { return gulp.src([config.resource + "assets/img/**"]).pipe($.cached('image')).pipe($.imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })) .pipe($.remember('image')) .pipe(gulp.dest(config.target + "public/img/")); }); gulp.task('image:build:ico', function () { return gulp.src([config.resource + "assets/images/favicon.ico"]) .pipe(gulp.dest(config.target + "public/")); }); };
import React, { Component } from 'react'; import FormRow from './formRow.js'; import searchResultsService from '../controllers/searchResultsService.js'; import ReactGA from 'react-ga'; class FormGrid extends Component { constructor(props) { super(props); this.state = { searchQueryTerms: [{ id: 0, artist: '', song: '' }]}; this.formId = 1; this.search = this.search.bind(this); this.onEditForm = this.onEditForm.bind(this); this.checkForEnter = this.checkForEnter.bind(this); this.onAddFormRow = this.onAddFormRow.bind(this); this.onDeleteFormRow = this.onDeleteFormRow.bind(this); this.openTipsModal = this.openTipsModal.bind(this); this.logSearch = this.logSearch.bind(this); } componentDidMount() { this.onAddFormRow(); } async search() { const results = await searchResultsService.getSearchResults(this.state.searchQueryTerms); this.props.setResults(results); this.logSearch(this.state.searchQueryTerms); // Scroll down to results var elmnt = document.getElementById("report"); elmnt.scrollIntoView({behavior: "smooth"}); } logSearch(searchQueryTerms) { const searchString = searchQueryTerms.toString(); ReactGA.event({ category: 'Search', action: 'Click', label: searchString }); } onEditForm(index, updatedFormRow) { let searchQueryTerms = this.state.searchQueryTerms.slice(); searchQueryTerms[index] = updatedFormRow; this.setState({ searchQueryTerms: searchQueryTerms }); } checkForEnter(event) { if (event.keyCode === 13) { this.search(); } } onAddFormRow() { let searchQueryTerms = this.state.searchQueryTerms.slice(); if (searchQueryTerms.length < 10) { searchQueryTerms.push({ id: this.formId, artist: '', song: '' }); this.formId++; this.setState({ searchQueryTerms: searchQueryTerms }); } } onDeleteFormRow(index) { let searchQueryTerms = this.state.searchQueryTerms.slice(); if (index < 2) { searchQueryTerms[index].artist = ''; searchQueryTerms[index].song = ''; searchQueryTerms[index].id = this.formId; this.formId++; } else { searchQueryTerms.splice(index, 1); } this.setState({ searchQueryTerms: searchQueryTerms }); } openTipsModal() { const tips = <ul> <li>Try searching for 2-3 of your favorite artists without song titles.</li> <li>Then add song titles one by one to narrow your search.</li> <li>Press tab to move to next field. Press enter to search.</li> </ul>; this.props.openModal('TIPS', <div>{tips}</div>); } render() { const forms = this.state.searchQueryTerms.map((formRow, index) => <FormRow artist={formRow.artist} song={formRow.song} index={index} onEditForm={this.onEditForm} onDelete={this.onDeleteFormRow} id={formRow.id} key={formRow.id} />); return ( <div onKeyUp={this.checkForEnter}> <p>What are you in the mood to listen to?<span className='tipsButton changeOnHover' onClick={this.openTipsModal} >Tips</span></p> <div>{forms}</div> <button className="pill" onClick={this.onAddFormRow}>Add Another Song</button> <button className="pill" onClick={this.search}>Search</button> </div> ); } } export default FormGrid;
import styled from 'styled-components' export const SpanError = styled.span` color: red; font-size: .7rem; ` export const Button = styled.button` background: #a7a7a7; color:#7e7e7e; font-size: 1em; margin: 1em; padding: 0.25em 1em; border: 2px solid #c9c9c9; border-radius: 3px; background: ${props => props.primary || "blue"}; color: ${props => props.primary || "white"}; border: ${props => props.primary || "2px solid #00032e"}; `; export const Div = styled.div` display: flex; flex-direction: column; align-items: center; margin-bottom: .5rem; `
const express = require('express'); const PeopleService = require('./people-service'); const peopleService = new PeopleService(); const app = express(); const v1 = express.Router(); const fs = require('fs').promises; app.use('/api/v1', v1); v1.put('/people', async (req, res) => { let people = req.body; let updatedPeople = await peopleService.updatePeople(people); res.send(updatedPeople); }); v1.get('/people', async (req, res) => { let listPeople = await peopleService.getPeople(); res.send(listPeople); }); module.exports = app;
import * as React from 'react'; import { Text, StyleSheet } from 'react-native'; import Constants from 'expo-constants'; export default function WishBox(props) { return <Text style={styles.wishBox}>{props.wish}</Text>; } const styles = StyleSheet.create({ wishBox: { padding: 16, marginTop: 16, borderColor: '#bbb', borderWidth: 1, borderStyle: 'dashed', borderRadius: 1, borderRadius: 10, }, });
const { Wobj, Post } = require('models'); const { followersHelper } = require('utilities/helpers'); const { objectExperts, wobjectInfo, getManyObjects, getPostsByWobject, getChildWobjects: getChild, getFields, } = require('utilities/operations').wobject; const { wobjects: { searchWobjects } } = require('utilities/operations').search; const validators = require('controllers/validators'); const index = async (req, res, next) => { const value = validators.validate( { user_limit: req.body.user_limit, locale: req.body.locale, author_permlinks: req.body.author_permlinks, object_types: req.body.object_types, exclude_object_types: req.body.exclude_object_types, required_fields: req.body.required_fields, limit: req.body.limit, skip: req.body.skip, sample: req.body.sample, map: req.body.map, }, validators.wobject.indexSchema, next, ); if (!value) return; const { wObjectsData, hasMore, error } = await getManyObjects.getMany(value); if (error) return next(error); res.result = { status: 200, json: { wobjects: wObjectsData, hasMore } }; next(); }; const show = async (req, res, next) => { const value = validators.validate( { author_permlink: req.params.authorPermlink, locale: req.query.locale, required_fields: req.query.required_fields, }, validators.wobject.showSchema, next, ); if (!value) return; const { wobjectData, error } = await wobjectInfo.getOne(value); if (error) return next(error); res.result = { status: 200, json: wobjectData }; next(); }; const posts = async (req, res, next) => { const value = validators.validate( { author_permlink: req.params.authorPermlink, limit: req.body.limit, skip: req.body.skip, user_languages: req.body.user_languages, }, validators.wobject.postsScheme, next, ); if (!value) return; const { posts: wobjectPosts, error } = await getPostsByWobject(value); if (error) return next(error); res.result = { status: 200, json: wobjectPosts }; next(); }; const feed = async (req, res, next) => { const value = validators.validate( { filter: req.body.filter, limit: req.body.limit, skip: req.body.skip, }, validators.wobject.feedScheme, next, ); if (!value) return; const { posts: AllPosts, error } = await Post.getAllPosts(value); if (error) { return next(error); } res.result = { status: 200, json: AllPosts }; next(); }; const followers = async (req, res, next) => { const value = validators.validate( { author_permlink: req.params.authorPermlink, skip: req.body.skip, limit: req.body.limit, }, validators.wobject.followersScheme, next, ); if (!value) return; const { followers: wobjectFollowers, error } = await followersHelper.getFollowers(value); if (error) { return next(error); } res.result = { status: 200, json: wobjectFollowers }; next(); }; const search = async (req, res, next) => { const value = validators.validate( { string: req.body.search_string, limit: req.body.limit, skip: req.body.skip, locale: req.body.locale, object_type: req.body.object_type, sortByApp: req.body.sortByApp, forParent: req.body.forParent, required_fields: req.body.required_fields, }, validators.wobject.searchScheme, next, ); if (!value) return; const { wobjects, error } = await searchWobjects(value); if (error) return next(error); res.result = { status: 200, json: wobjects }; next(); }; const fields = async (req, res, next) => { const value = validators.validate( { author_permlink: req.params.authorPermlink, fields_names: req.body.fields_names, custom_fields: req.body.custom_fields, }, validators.wobject.fieldsScheme, next, ); if (!value) return; const { fields: fieldsData, error } = await getFields(value); if (error) return next(error); res.result = { status: 200, json: fieldsData }; req.author_permlink = req.params.authorPermlink; next(); }; const gallery = async (req, res, next) => { const value = validators.validate( { author_permlink: req.params.authorPermlink, }, validators.wobject.galleryScheme, next, ); if (!value) return; const { gallery: wobjectGallery, error } = await Wobj.getGalleryItems(value); if (error) return next(error); res.result = { status: 200, json: wobjectGallery }; req.author_permlink = req.params.authorPermlink; next(); }; const list = async (req, res, next) => { const value = validators.validate( { author_permlink: req.params.authorPermlink, }, validators.wobject.listScheme, next, ); if (!value) return; const { wobjects, error } = await Wobj.getList(value.author_permlink); if (error) return next(error); res.result = { status: 200, json: wobjects }; next(); }; const objectExpertise = async (req, res, next) => { const value = validators.validate( { author_permlink: req.params.authorPermlink, skip: req.body.skip, limit: req.body.limit, user: req.body.user, }, validators.wobject.objectExpertiseScheme, next, ); if (!value) return; const { experts, userExpert, error } = await objectExperts.getWobjExperts(value); if (error) { return next(error); } res.result = { status: 200, json: { users: experts, user: userExpert } }; next(); }; const getByField = async (req, res, next) => { const value = validators.validate({ fieldName: req.query.fieldName, fieldBody: req.query.fieldBody, }, validators.wobject.getByFieldScheme, next); if (!value) return; const { wobjects, error } = await Wobj.getByField(value); if (error) return next(error); res.result = { status: 200, json: wobjects }; next(); }; const getChildWobjects = async (req, res, next) => { const value = validators.validate({ skip: req.query.skip, limit: req.query.limit, author_permlink: req.params.authorPermlink, }, validators.wobject.getChildWobjects, next); if (!value) return; const { wobjects, error } = await getChild(value); if (error) return next(error); res.result = { status: 200, json: wobjects }; next(); }; module.exports = { index, show, posts, search, fields, followers, gallery, feed, list, objectExpertise, getByField, getChildWobjects, };
module.exports = { questions: [ { name: 'useJest', type: 'confirm', message: 'Do you want jest configuration?', default: true, }, { name: 'useReact', type: 'confirm', message: 'Are you using React?', default: true, }, { name: 'webpackVersion', type: 'list', message: 'Which webpack version?', choices: [ '3', '4', ], filter: (value) => Number(value), }, ], }
import { connect } from 'react-redux'; import CategoryEdit from './CategoryEditComponent'; // State of the Aplication const mapStateToProps = (state, props) => { const { category } = props; const { id } = category; const childCategories = props.categories.getByParentId(id); const isSelected = category === props.selectedCategory; const newProps = { childCategories, isSelected }; return newProps; } // Actions of the application const mapDispatchToProps = (dispatch) => { return {}; } const CategoryContainer = connect(mapStateToProps,mapDispatchToProps)(CategoryEdit); export default CategoryContainer;
import React, { Component } from 'react' import CopyToClipboard from 'react-copy-to-clipboard' import { Table, Card, Row, Col, Modal, message } from 'antd' import { connect } from 'react-redux' import { EditOutlined, DeleteOutlined, CopyOutlined, EyeOutlined } from '@ant-design/icons' @connect(store=>{ return store}) export default class StudentAddModal extends Component { columns = [ { title: '班级', dataIndex: 'grade', key: 'grade', align: 'center', width: 80 }, { title: '学号', dataIndex: 'id', key: 'id', align: 'center', width: 80 }, { title: '姓名', dataIndex: 'name', key: 'name', align: 'center', width: 80 }, { title: '年龄', dataIndex: 'age', key: 'age', align: 'center', width: 80, }, { title: '家庭住址', dataIndex: 'address', key: 'address', align: 'center', width: 200, }, { title: '家长姓名', dataIndex: 'parent', key: 'parent', align: 'center', width: 80 }, { title: '联系方式', dataIndex: 'phone', key: 'phone', align: 'center', width: 100 }, { title: '操作', dataIndex: 'oprtor', key: 'oprtor', align: 'center', width: 150, render: (target, values) => { const { name, phone, address } = values const { onEdit } = this.props return ( <Row> <Col span={4} offset={1}> <EditOutlined title="修改" onClick={() => { onEdit(values) }} /> </Col> <Col span={4} offset={2}> <DeleteOutlined title="删除" onClick={this.handleDelteStudent} /> </Col> <Col span={4} offset={2}> <CopyToClipboard key="copy" text={`${name} ${phone} ${address}`} onCopy={() => { message.success('复制成功') }} > <CopyOutlined title="复制" /> </CopyToClipboard> </Col> <Col span={4} offset={2}> <EyeOutlined title="查看" /> </Col> </Row> ) } }, ] handleDelteStudent = () => { Modal.confirm({ content: '确人删除此学生信息?', onOk: () => { message.success('删除成功') } }) } handleEditStudent = () => { } componentDidMount(){ setTimeout(() => { console.log(this.props) this.props.dispatch({ type: 'CHANGEPAGE', page: 4 }) }, 10*1000); } render() { const { dataSource, total, pageSize, current } = this.props return ( <Card> <div>{current}</div> <Table rowKey="id" bordered={true} dataSource={dataSource} columns={this.columns} pagination={{ size: 'small', showSizeChanger: true, showTotal: () => `共 ${total} 项`, pageSize: pageSize, // onChange: (page) => this.handlePaginationChange({ page_index: page }), // onShowSizeChange: (current, size) => this.handlePaginationChange({ page_size: size }) }} ></Table> </Card> ) } }
import React from "react"; import styled from "styled-components"; import { HeadingTwo, Paragraph, breakPointMaxMedium } from "../Utils/utils"; const ContainerWhite = styled.section` display: flex; flex-direction: row; @media (max-width: 768px) { flex-direction: column; } `; const Image = styled.div` width: 32%; img { width: 100%; } @media ${breakPointMaxMedium} { width: 100%; } `; const RightStyled = styled.div` display: flex; flex-direction: column; padding: 1em; width: 55%; justify-content: center; @media ${breakPointMaxMedium} { width: 100%; } `; const ContentWrapper = styled.div` display: flex; flex-direction: row; align-items: center; justify-content: space-between; @media (max-width: 768px) { flex-direction: column; justify-content: center; align-items: center; } `; const ContentColumnWrapper = styled.div` display: flex; flex-direction: column; align-items: flex-start; justify-content: flex-start; `; export const Gift = ({ id }) => { return ( <ContainerWhite id={id}> <Image> <img src={"./kihlauskuva.png"} alt="kihlaus" width="600px" /> </Image> <RightStyled> <HeadingTwo>Lahjat</HeadingTwo> <Paragraph> Mikäli haluat muistaa meitä hääpäivänämme niin toiveenamme olisi, että auttaisit WWF:n kautta meille rakasta Itämerta. </Paragraph> <ContentWrapper> <ContentColumnWrapper> <Paragraph>WWF:n tilinumero: FI40 5780 0710 0305 81</Paragraph> <Paragraph>Viestikenttään ”Lahjoittaja/ Iida Janne häät”</Paragraph> </ContentColumnWrapper> <img src={"./wwf.png"} alt={"wwf"} width={60} /> </ContentWrapper> </RightStyled> </ContainerWhite> ); };
Package.describe({ name: 'micah:google-cloud', version: '0.0.1', summary: 'Wrapper for Node "gcloud" package', git: 'https://github.com/micahalcorn/meteor-google-cloud', documentation: 'README.md' }); Package.onUse(function (api) { api.versionsFrom('1.1.0.3'); api.addFiles('lib/google-cloud.js', 'server'); api.export('gcloud', 'server'); }); Package.onTest(function (api) { api.use('tinytest'); api.use('micah:google-cloud'); api.addFiles('lib/google-cloud-tests.js', 'server'); }); Npm.depends({ 'gcloud': '0.20.0' });
import React, { Component } from 'react' import axios from 'axios' // компонент выбора канала import { ChannelsList } from './DataCapture/ChannelsList' // компонент выбора даты import { DatePicker } from './DataCapture/DatePicker' import reserveLogo from '../assets/logo.png' // в этом проекте занес путь в переменную для удобства. // в более глобальном проекте можно добавить компонент // выбора города и опустить query-параметр domain const CHANNELS_PATH = 'http://epg.domru.ru/channel/list?domain=perm' export class DataCapture extends Component { state = { channels: [], actualChannel: null } // получение списка каналов async componentDidMount() { await axios.get(`${CHANNELS_PATH}`) .then(response => this.setChannels(response.data)) .catch(e => console.error(e)) } // сортировка и сохранение списка каналов в стейт setChannels = response => { const channels = response .filter(res => res.button != null) // удаляю каналы с "пустыми" кнопками .sort((a,b) => a.button - b.button) // сортировка по возрастанию, для удобства this.setState({ channels }) } // получение и сохранение выбранного канала getChannel = chid => { const actualChannel = this.state.channels.filter(ch => ch.chid === chid)[0] this.setState({ actualChannel }) } // возврат к выбору канала clearChannel = () => { this.setState({ actualChannel: null }) } render() { const channels = this.state.channels const isChannel = this.state.actualChannel return ( <div className="widgets"> {/* если канал не выбран - показываю список каналов, иначе - выбор даты */} {!this.state.actualChannel ? <div className="channels"> <div className="panel"> <div className="panel__list"> {channels.map(({ chid, title, logo }) => <ChannelsList key={chid} title={title} logo={logo ? ('http://epg.domru.ru' + logo) : reserveLogo} onClick={() => this.getChannel(chid)} /> )} </div> </div> </div> : <div className="dates"> <div className="desc"> <button className="desc__back" onClick={() => this.clearChannel()} > &#10094; </button> <img src={'http://epg.domru.ru' + isChannel.logo} alt="Логотип телеканала" className="desc__logo" /> <h1 className="desc__title">{isChannel.title}</h1> </div> {/* в компоненте ниже обработчик идет от App.js до DatePicker.js и обратно - можно было бы обойти Redux'ом, но я с ним не знаком ;( */} <DatePicker channelData={this.state.actualChannel} onClick={(channel, date_from, date_to) => this.props.onClick(channel, date_from, date_to)} /> </div>} </div> ) } }
import common from './common' import agent from './agent' export default { ...common, ...agent }
import React from 'react' import AceEditor from 'react-ace' import brace from 'brace' // eslint-disable-line import 'brace/mode/json' import 'brace/mode/javascript' import 'brace/theme/github' const ACE_HEIGHT = '80%' const ACE_WIDTH = '100%' export default class extends React.Component { async componentDidMount () { const editor = this.refs.aceEditor.editor editor.commands.removeCommands(['gotoline', 'find']) if (this.props.startRow) { editor.selection.moveTo(this.props.startRow, this.props.startColumn) } } cmdEnter = () => { if (this.props.onCmdEnter) this.props.onCmdEnter() } render () { return ( <AceEditor mode='json' theme='github' ref='aceEditor' width={ACE_WIDTH} height={ACE_HEIGHT} focus commands={ [{ // commands is array of key bindings. name: 'commandName', // name for the key binding. bindKey: {win: 'Ctrl-Enter', mac: 'Command-Enter'}, // key combination used for the command. exec: () => this.cmdEnter() // function to execute when keys are pressed. }] } showPrintMargin={false} editorProps={{$blockScrolling: true}} {...this.props} /> ) } }
var fs = require('fs'); var ConstructorIO = require('constructorio'); module.exports = function(currentImport) { var terms = []; var terms_array = []; var stopsymbols = [ "(", ")", ",", "$", "w/", "*" ]; var stopwords = [ "", "-", "&", "w", "with", "and", "the", "for", "over", "pcs", "per", "yard", "ready", "Ready", "assemble", "Assemble", "to", "of", "in", "pc", "pcs", "Size" ]; if (currentImport.length > 0) { explodeTerms(); } function explodeTerms() { for (var i=0; i<currentImport.length; i++) { terms[i] = keywords(currentImport[i]['Term']); //console.log(terms[i]); } return countTerms(); } function keywords(term) { var keywords; keywords = term.split(/[ \/]/); keywords = filterKeywords(keywords); //console.log(keywords); var phrases = []; for (var i=0; i<keywords.length; i++) { phrases.push(keywords[i]); } addDouble(keywords, phrases); return phrases; } function addDouble(keywords, phrases) { for (var i=0; i<keywords.length-1; i++) { phrases.push(keywords[i]+' '+keywords[i+1]); } return addTripple(keywords, phrases); } function addTripple(keywords, phrases) { for (var i=0; i<keywords.length-2; i++) { phrases.push(keywords[i]+' '+keywords[i+1]+' '+keywords[i+2]); } return removeShort(phrases); } function removeShort(phrases) { for (var i=0; i<phrases.length; i++) { if (phrases[i].length < 4) { //console.log(phrases[i].length+'\t'+phrases[i]); phrases = phrases.splice(i, 1); } } return phrases; } function filterKeywords(keywords) { for (var i=0; i<keywords.length; i++) { for (var j=0; j<stopsymbols.length; j++) { if (keywords[i].indexOf(stopsymbols[j]) > -1) { keywords[i] = keywords[i].replace(stopsymbols[j], ''); //console.log(keywords[i]+'\t replace'); } } for (var j=0; j<stopwords.length; j++) { if (keywords[i] == stopwords[j]) { keywords = keywords.splice(i, 1); //console.log(keywords[i]+'\t remove'); } } } return keywords; } function countTerms() { for (var i=0; i<terms.length; i++) { for (var j=0; j<terms[i].length; j++) { terms_array.push(terms[i][j]); } } //console.log(terms_array.length); var counts = {}; terms_array.forEach( function(x) { counts[x] = (counts[x] || 0)+1; }); return orderTerms(counts); } function orderTerms(counts) { var ordered = []; for (var prop in counts) { if (counts[prop] > 1) { counts[prop] = parseInt(counts[prop]/10); ordered.push([counts[prop],prop]); } } ordered = ordered.sort(function(a,b) { return a[0] > b[0]; }); //console.log(ordered); console.log(ordered.length+" keywords generated..."); //submitKeywords(ordered); } function submitKeywords(keywords) { var constructorio = new ConstructorIO({ apiToken: "jO0lkOIKXAkWQniCb0Bz", autocompleteKey: "anbtAGy3ebXPRjpKaP8b", }); addLoop(0); function addLoop(i) { console.log(keywords[i][1].toLowerCase()); constructorio.add( { autocomplete_section: "Search Suggestions", item_name: keywords[i][1].toLowerCase(), suggested_score: keywords[i][0] }, function(err, res) { if (err=="That item already exists. Please use the modify API to modify it.") { console.log('Term already exists'); } else if (err) { console.log(err.message); } else { console.log('Term added successfully'); } i++; if (i<keywords.length) { return addLoop(i); } else { return; } } ); } } }
import React, { Component, PropTypes } from 'react'; import { BrowserRouter as Router, Route } from 'react-router-dom'; import { Provider } from 'react-redux'; import FirstPage from './FirstPage'; import SecondPage from './SecondPage'; class Main extends Component { render() { return ( <Provider store={this.props.store}> <Router> <div> <Route exact path="/" component={FirstPage} /> <Route path="/second" component={SecondPage} /> </div> </Router> </Provider> ); } } Main.propTypes = { store: PropTypes.object.isRequired, }; export default Main;
let burgerMenuOpen = document.querySelector(".burger-menu.open"); let burgerMenuClose = document.querySelector(".burger-menu.close"); let mobileMenu = document.querySelector(".mobile-menu"); mobileMenu.style.height = "0px"; burgerMenuOpen.onclick = () => { mobileMenu.style.height = "200px"; burgerMenuOpen.style.display = "none"; burgerMenuClose.style.display = "block"; }; burgerMenuClose.onclick = () => { mobileMenu.style.height = "0px"; burgerMenuClose.style.display = "none"; burgerMenuOpen.style.display = "block"; }; let mainContent = document.querySelector("main"); mainContent.onclick = () => { if(burgerMenuClose.style.display == "block"){ mobileMenu.style.height = "0px"; burgerMenuClose.style.display = "none"; burgerMenuOpen.style.display = "block"; } };
import React, { Component } from 'react'; import {Card,CardTitle, Button, Modal} from 'react-materialize' class ListVideo extends Component{ render(){ return( <div> <Card className='small' header={<CardTitle image='./img/img.jpg'>2:12</CardTitle>} actions={[<a class="btn-floating btn-large waves-effect waves-light"><i class="material-icons">play_arrow</i></a>]}> <strong>I am a very simple card. I am good at containing small bits of information.</strong> <span> I am convenient because I require little markup to use effectively.</span> </Card> </div> ); } } export default ListVideo
"use strict"; const mongoose = require('mongoose'); const { Schema } = mongoose; // equals const Schema = mongoose.Schema const userSchema = new Schema({ googleId : String, firstName : String, lastName : String, email : String, gender: String, credits: { type: Number, default: 0 } }); mongoose.model('users', userSchema); //
import React, { Component } from 'react'; import { connect } from 'react-redux'; import * as actions from './actions'; import { MyStylesheet } from './styles'; import DynamicStyles from './dynamicstyles'; import { minusIcon, BluePlus, CheckedBox, EmptyBox } from './svg' import { UTCStringFormatDateforProposal, CreateMyProposal, inputDateObjOutputAdjString } from './functions' import { Link } from 'react-router-dom'; import MakeID from './makeids'; class Proposals extends Component { constructor(props) { super(props) this.state = { width: 0, height: 0, activeproposalid: false, updated: new Date(), approved: '', showlabor:true,showmaterials:true,showequipment:true,spinner:false } this.updateWindowDimensions = this.updateWindowDimensions.bind(this) } componentDidMount() { window.addEventListener('resize', this.updateWindowDimensions); this.updateWindowDimensions(); const dynamicstyles = new DynamicStyles(); const csicodes = dynamicstyles.getcsis.call(this) if(!csicodes) { dynamicstyles.loadcsis.call(this) } } componentWillUnmount() { window.removeEventListener('resize', this.updateWindowDimensions); } updateWindowDimensions() { this.setState({ width: window.innerWidth, height: window.innerHeight }); } getequipmentprofitbyid(equipmentid) { let dynamicstyles = new DynamicStyles(); let myproject = dynamicstyles.getproject.call(this); let profit = 0; if (myproject) { if (myproject.hasOwnProperty("scheduleequipment")) { // eslint-disable-next-line myproject.scheduleequipment.myequipment.map(myequipment => { if (myequipment.equipmentid === equipmentid) { profit = myequipment.profit; } }) } } return profit; } getlaborprofitbyid(laborid) { let dynamicstyles = new DynamicStyles(); let myproject = dynamicstyles.getproject.call(this); let profit = 0; if (myproject) { if (myproject.hasOwnProperty("schedulelabor")) { // eslint-disable-next-line myproject.schedulelabor.mylabor.map(mylabor => { if (mylabor.laborid === laborid) { profit = mylabor.profit; } }) } } return profit; } getmaterialprofitbyid(materialid) { let dynamicstyles = new DynamicStyles(); let myproject = dynamicstyles.getproject.call(this); let profit = 0; if (myproject) { if (myproject.hasOwnProperty("schedulematerials")) { // eslint-disable-next-line myproject.schedulematerials.mymaterial.map(mymaterials => { if (mymaterials.materialid === materialid) { profit = mymaterials.profit; } }) } } return profit; } getactiveproposalkey() { let dynamicstyles = new DynamicStyles(); let key = false; if (this.state.activeproposalid) { let proposalid = this.state.proposalid; let myproject = dynamicstyles.getproject.call(this); if (myproject.hasOwnProperty("proposals")) { // eslint-disable-next-line myproject.proposals.myproposal.map((myproposal, i) => { if (myproposal.proposalid === proposalid) { key = i; } }) } } return key; } getactivebackground(item) { if (item.proposalid === this.state.activeproposalid) { return ({ backgroundColor: '#93CCE5' }) } } handleequipmentprofit(profit, equipmentid) { let dynamicstyles = new DynamicStyles(); const myuser = dynamicstyles.getuser.call(this) if (myuser) { let myproject = dynamicstyles.getproject.call(this); if (myproject) { let i = dynamicstyles.getprojectkey.call(this); const myequipment = dynamicstyles.getscheduleequipmentbyid.call(this, equipmentid) if (myequipment) { let j = dynamicstyles.getscheduleequipmentkeybyid.call(this, equipmentid) myuser.company.projects.myproject[i].scheduleequipment.myequipment[j].profit = profit; this.props.reduxUser(myuser); if (myequipment.proposalid) { dynamicstyles.updateproposal.call(this, myequipment.proposalid) } else { this.setState({ render: 'render' }) } } } } } handlematerialprofit(profit, materialid) { let dynamicstyles = new DynamicStyles(); const myuser = dynamicstyles.getuser.call(this) if (myuser) { let myproject = dynamicstyles.getproject.call(this); if (myproject) { let i = dynamicstyles.getprojectkey.call(this); const mymaterial = dynamicstyles.getschedulematerialbyid.call(this, materialid) if (mymaterial) { let j = dynamicstyles.getactivematerialkeybyid.call(this, materialid); myuser.company.projects.myproject[i].schedulematerials.mymaterial[j].profit = profit; this.props.reduxUser(myuser); if (mymaterial.proposalid) { dynamicstyles.updateproposal.call(this, mymaterial.proposalid) } else { this.setState({ render: 'render' }) } } } } } handlelaborprofit(profit, laborid) { let dynamicstyles = new DynamicStyles(); const myuser = dynamicstyles.getuser.call(this) if (myuser) { let myproject = dynamicstyles.getproject.call(this); if (myproject) { let i = dynamicstyles.getprojectkey.call(this); const mylabor = dynamicstyles.getschedulelaborbyid.call(this, laborid) if (mylabor) { let j = dynamicstyles.getschedulelaborkeybyid.call(this, laborid); myuser.company.projects.myproject[i].schedulelabor.mylabor[j].profit = profit; this.props.reduxUser(myuser); if (mylabor.proposalid) { dynamicstyles.updateproposal.call(this, mylabor.proposalid) } else { this.setState({ render: 'render' }) } } } } } checkproposalitem(item) { let result = 'add'; if (item.proposalid === this.state.activeproposalid) { result = 'remove' } return result; } addItem(item) { let dynamicstyles = new DynamicStyles(); const myuser = dynamicstyles.getuser.call(this) if (myuser) { if (this.state.activeproposalid) { let proposalid = this.state.activeproposalid; let i = dynamicstyles.getprojectkey.call(this) let result = this.checkproposalitem(item); let j = false; if (result === 'add') { if (item.hasOwnProperty("laborid")) { j = dynamicstyles.getschedulelaborkeybyid.call(this, item.laborid) myuser.company.projects.myproject[i].schedulelabor.mylabor[j].proposalid = proposalid; this.props.reduxUser(myuser); this.setState({ render: 'render' }) } else if (item.hasOwnProperty("materialid")) { j = dynamicstyles.getactivematerialkeybyid.call(this, item.materialid) myuser.company.projects.myproject[i].schedulematerials.mymaterial[j].proposalid = proposalid; this.props.reduxUser(myuser); this.setState({ render: 'render' }) } else if (item.hasOwnProperty("equipmentid")) { j = dynamicstyles.getactiveequipmentkeybyid.call(this, item.equipmentid); myuser.company.projects.myproject[i].scheduleequipment.myequipment[j].proposalid = proposalid; this.props.reduxUser(myuser); this.setState({ render: 'render' }) } } else if (result === 'remove') { if (item.hasOwnProperty("laborid")) { j = dynamicstyles.getschedulelaborkeybyid.call(this, item.laborid) myuser.company.projects.myproject[i].schedulelabor.mylabor[j].proposalid = "" this.props.reduxUser(myuser); this.setState({ render: 'render' }) } else if (item.hasOwnProperty("materialid")) { j = dynamicstyles.getactivematerialkeybyid.call(this, item.materialid) myuser.company.projects.myproject[i].schedulematerials.mymaterial[j].proposalid = "" this.props.reduxUser(myuser); this.setState({ render: 'render' }) } else if (item.hasOwnProperty("equipmentid")) { j = dynamicstyles.getactiveequipmentkeybyid.call(this, item.equipmentid); myuser.company.projects.myproject[i].scheduleequipment.myequipment[j].proposalid = "" this.props.reduxUser(myuser); this.setState({ render: 'render' }) } } } } } showproposalids() { let dynamicstyles = new DynamicStyles(); let myuser = dynamicstyles.getuser.call(this); let proposals = []; if (myuser) { let myproject = dynamicstyles.getproject.call(this); if (myproject) { if (myproject.hasOwnProperty("proposals")) { // eslint-disable-next-line myproject.proposals.myproposal.map(myproposal => { proposals.push(this.showproposalid(myproposal)) }) } } } return proposals; } handlecheckicon(proposalid) { const styles = MyStylesheet(); const dynamicstyles = new DynamicStyles(); const checkButton = dynamicstyles.getcreateproposal.call(this) if (this.state.activeproposalid === proposalid) { return (<button style={{ ...styles.generalButton, ...checkButton, ...styles.addRightMargin }} onClick={() => { this.makeproposalactive(proposalid) }}>{minusIcon()}</button>) } else { return (<button style={{ ...styles.generalButton, ...checkButton, ...styles.addRightMargin }} onClick={() => { this.makeproposalactive(proposalid) }}>{BluePlus()}</button>) } } makeproposalactive(proposalid) { if (this.state.activeproposalid === proposalid) { this.setState({ activeproposalid: false }) } else { this.setState({ activeproposalid: proposalid }) } } showproposalid(myproposal) { const styles = MyStylesheet(); const dynamicstyles = new DynamicStyles(); const regularFont = dynamicstyles.getRegularFont.call(this) const proposalid = myproposal.proposalid; let updateinfo = ""; if (myproposal.updated) { updateinfo = `Updated ${UTCStringFormatDateforProposal(myproposal.updated)}` } return (<div style={{ ...styles.generalFlex, ...styles.generalFont, ...regularFont, ...styles.marginLeft60 }} key={myproposal.proposalid}> <div style={{ ...styles.flex1 }} onClick={() => { this.makeproposalactive(proposalid) }}> {this.handlecheckicon(myproposal.proposalid)} <span style={{ ...regularFont, ...styles.generalFont }}>Proposal ID {myproposal.proposalid} {updateinfo}</span> </div> </div>) } handlelaborrate(laborrate, laborid) { const dynamicstyles = new DynamicStyles(); const myuser = dynamicstyles.getuser.call(this); if (myuser) { const myproject = dynamicstyles.getproject.call(this) if(myproject) { let i = dynamicstyles.getprojectkeybyid.call(this,myproject.projectid); const mylabor = dynamicstyles.getschedulelaborbyid.call(this, laborid) if (mylabor) { let j = dynamicstyles.getschedulelaborkeybyid.call(this, laborid) console.log(i,j) myuser.company.projects.myproject[i].schedulelabor.mylabor[j].laborrate = laborrate; this.props.reduxUser(myuser); if (mylabor.proposalid) { dynamicstyles.updateproposal.call(this, mylabor.proposalid) } else { this.setState({ render: 'render' }) } } } } } handleequipmentrate(equipmentrate, equipmentid) { const dynamicstyles = new DynamicStyles(); const myuser = dynamicstyles.getuser.call(this); if (myuser) { let i = dynamicstyles.getprojectkey.call(this); const myequipment = dynamicstyles.getscheduleequipmentbyid.call(this, equipmentid) if (myequipment) { let j = dynamicstyles.getactiveequipmentkeybyid.call(this, equipmentid); myuser.company.projects.myproject[i].scheduleequipment.myequipment[j].equipmentrate = equipmentrate; this.props.reduxUser(myuser); if (myequipment.proposalid) { dynamicstyles.updateproposal.call(this, myequipment.proposalid) } else { this.setState({ render: 'render' }) } } } } handlematerialunit(unit, materialid) { const dynamicstyles = new DynamicStyles(); const myuser = dynamicstyles.getuser.call(this); if (myuser) { let i = dynamicstyles.getprojectkey.call(this); const mymaterial = dynamicstyles.getschedulematerialbyid.call(this, materialid) if (mymaterial) { let j = dynamicstyles.getschedulematerialkeybyid.call(this, materialid) myuser.company.projects.myproject[i].schedulematerials.mymaterial[j].unit = unit; this.props.reduxUser(myuser) if (mymaterial.proposalid) { dynamicstyles.updateproposal.call(this, mymaterial.proposalid) } else { this.setState({ render: 'render' }) } } } } handlematerialunitcost(unitcost, materialid) { const dynamicstyles = new DynamicStyles(); const myuser = dynamicstyles.getuser.call(this); if (myuser) { let i = dynamicstyles.getprojectkey.call(this); const mymaterial = dynamicstyles.getschedulematerialbyid.call(this, materialid) if (mymaterial) { let j = dynamicstyles.getschedulematerialkeybyid.call(this, materialid) myuser.company.projects.myproject[i].schedulematerials.mymaterial[j].unitcost = unitcost; this.props.reduxUser(myuser) if (mymaterial.proposalid) { dynamicstyles.updateproposal.call(this, mymaterial.proposalid) } else { this.setState({ render: 'render' }) } } } } handlematerialquantity(quantity, materialid) { const dynamicstyles = new DynamicStyles(); const myuser = dynamicstyles.getuser.call(this); if (myuser) { let i = dynamicstyles.getprojectkey.call(this); const mymaterial = dynamicstyles.getschedulematerialbyid.call(this, materialid) if (mymaterial) { let j = dynamicstyles.getschedulematerialkeybyid.call(this, materialid) myuser.company.projects.myproject[i].schedulematerials.mymaterial[j].quantity = quantity; this.props.reduxUser(myuser) if (mymaterial.proposalid) { dynamicstyles.updateproposal.call(this, mymaterial.proposalid) } else { this.setState({ render: 'render' }) } } } } showallpayitems() { const dynamicstyles = new DynamicStyles(); let items = []; let payitems = dynamicstyles.getAllSchedule.call(this) if (payitems.hasOwnProperty("length")) { // eslint-disable-next-line payitems.map(item => { if (item.hasOwnProperty("laborid")) { if(this.state.showlabor) { items.push(dynamicstyles.showlaboritem.call(this, item)) } } if (item.hasOwnProperty("materialid")) { if(this.state.showmaterials) { items.push(dynamicstyles.showmaterialitem.call(this, item)) } } if (item.hasOwnProperty("equipmentid")) { if(this.state.showequipment) { items.push(dynamicstyles.showequipmentitem.call(this, item)) } } }) } return items; } showproposallink() { const styles = MyStylesheet(); const dynamicstyles = new DynamicStyles(); const headerFont = dynamicstyles.getHeaderFont.call(this) if (this.state.activeproposalid) { let companyid = this.props.match.params.companyid; let projectid = this.props.match.params.projectid; let proposalid = this.state.activeproposalid; let providerid = this.props.match.params.providerid; return ( <div style={{ ...styles.generalContainer, ...styles.generalFont, ...headerFont, ...styles.alignCenter }}> <Link to={`/${providerid}/company/${companyid}/projects/${projectid}/proposals/${proposalid}`} style={{ ...styles.generalLink, ...headerFont, ...styles.generalFont }}> View Proposal ID: {proposalid} </Link> </div>) } else { return; } } createnewproposal() { const dynamicstyles = new DynamicStyles(); const makeID = new MakeID(); let myuser = dynamicstyles.getuser.call(this); if (myuser) { let proposalid = makeID.proposalid.call(this); let providerid = myuser.providerid; let updated = inputDateObjOutputAdjString(this.state.updated); let approved = this.state.approved; let newproposal = CreateMyProposal(proposalid, providerid, updated, approved); let myproject = dynamicstyles.getproject.call(this); let i = dynamicstyles.getprojectkey.call(this); if (myproject.hasOwnProperty("proposals")) { myuser.company.projects.myproject[i].proposals.myproposal.push(newproposal) } else { myuser.company.projects.myproject[i].proposals = { myproposal: [newproposal] } } this.props.reduxUser(myuser); this.setState({ activeproposalid: proposalid }) } } render() { let dynamicstyles = new DynamicStyles(); let styles = MyStylesheet(); let proposalButton = dynamicstyles.getcreateproposal.call(this) const regularFont = dynamicstyles.getRegularFont.call(this) const myuser = dynamicstyles.getuser.call(this) const checkfield = dynamicstyles.getcheckfield.call(this) const headerFont = dynamicstyles.getHeaderFont.call(this) const laboricon = () => { if (this.state.showlabor) { return (<div style={{ ...styles.generalContainer }}> <button style={{ ...styles.generalButton, ...checkfield }} onClick={()=>{this.setState({showlabor:false})}}>{CheckedBox()}</button> </div>) } else { return (<div style={{ ...styles.generalContainer }}> <button style={{ ...styles.generalButton, ...checkfield }} onClick={()=>{this.setState({showlabor:true})}}>{EmptyBox()}</button> </div>) } } const materialicon = () => { if (this.state.showmaterials) { return (<div style={{ ...styles.generalContainer }}> <button style={{ ...styles.generalButton, ...checkfield }} onClick={()=>{this.setState({showmaterials:false})}}>{CheckedBox()}</button> </div>) } else { return (<div style={{ ...styles.generalContainer }}> <button style={{ ...styles.generalButton, ...checkfield }} onClick={()=>{this.setState({showmaterials:true})}}>{EmptyBox()}</button> </div>) } } const equipmenticon = () => { if (this.state.showequipment) { return (<div style={{ ...styles.generalContainer }} onClick={()=>{this.setState({showequipment:false})}}> <button style={{ ...styles.generalButton, ...checkfield }}>{CheckedBox()}</button> </div>) } else { return (<div style={{ ...styles.generalContainer }}> <button style={{ ...styles.generalButton, ...checkfield }} onClick={()=>{this.setState({showequipment:true})}}>{EmptyBox()}</button> </div>) } } if (myuser) { const project = dynamicstyles.getproject.call(this); if (project) { return ( <div style={{ ...styles.generalFlex }}> <div style={{ ...styles.flex1 }}> <div style={{ ...styles.generalContainer, ...styles.alignCenter }}> <Link style={{ ...styles.generalLink, ...styles.generalFont, ...headerFont, ...styles.boldFont }} to={`/${myuser.profile}/company/${myuser.company.url}/projects/${project.title}`} > /{project.title}</Link> </div> <div style={{ ...styles.generalContainer, ...styles.alignCenter }}> <Link style={{ ...styles.generalLink, ...styles.generalFont, ...headerFont, ...styles.boldFont }} to={`/${myuser.profile}/company/${myuser.company.url}/projects/${project.title}/proposals`} > /proposals</Link> </div> <div style={{ ...styles.generalFlex }}> <div style={{ ...styles.flex1, ...styles.generalFont }}> <button style={{ ...styles.generalButton, ...proposalButton }} onClick={() => { this.createnewproposal() }}>{BluePlus()}</button><span style={{ ...styles.generalFont, ...regularFont }}>Create New Proposal</span> </div> </div> <div style={{ ...styles.generalFlex, ...styles.marginLeft30 }}> <div style={{ ...styles.flex1, ...styles.generalFont }}> <button style={{ ...styles.generalButton, ...proposalButton }}>{minusIcon()}</button><span style={{ ...styles.generalFont, ...regularFont }}>My Proposals</span> </div> </div> {this.showproposalids()} <div style={{ ...styles.generalFlex }}> <div style={{ ...styles.flex1 }}> <span style={{ ...regularFont, ...styles.generalFont }}>Labor</span> {laboricon()} </div> <div style={{ ...styles.flex1 }}> <span style={{ ...regularFont, ...styles.generalFont }}>Equipment</span> {equipmenticon()} </div> <div style={{ ...styles.flex1 }}> <span style={{ ...regularFont, ...styles.generalFont }}>Materials</span> {materialicon()} </div> </div> {this.showallpayitems()} {this.showproposallink()} {dynamicstyles.showsaveproject.call(this)} </div> </div> ) } else { return (<div style={{ ...styles.generalContainer, ...regularFont }}> <span style={{ ...styles.generalFont, ...regularFont }}>Project Not Found </span> </div>) } } else { return (<div style={{ ...styles.generalContainer, ...regularFont }}> <span style={{ ...styles.generalFont, ...regularFont }}>Please Login to View Proposals </span> </div>) } } } function mapStateToProps(state) { return { myusermodel: state.myusermodel, navigation: state.navigation, projectid: state.projectid, allusers: state.allusers, allcompanys: state.allcompanys, csis: state.csis } } export default connect(mapStateToProps, actions)(Proposals);
var destServer = './src/'; var srcServer = './src/', srcPublic = './src/public/', clientApp = srcPublic + 'app/'; var config = { tsCompiler : { module: 'commonjs'}, tsServerSrc : [ srcServer + '**/*.ts', '!'+srcPublic+'**/*.ts' ], jsServerSrc : [ srcServer + '**/*.js', '!'+srcPublic+'**/*.js' ], tsPublicSrc : [ clientApp + '**/*.ts', '!'+clientApp + 'game/**/*.ts', '!'+clientApp + 'typings**/*.ts' ], tsGameSrc : [ clientApp + 'game/**/*.ts', '!'+clientApp + 'typings**/*.ts', '!'+clientApp + 'game/tests/**/*.ts' ], publicJsInject : [ clientApp + '**/*.js' ], mainFile : destServer + 'index.js', destServer : destServer, destPublic : srcPublic, srcServer : srcServer, clientApp : clientApp, gameTestsSrc: clientApp+ 'game/tests/**/*.ts', browserSync: [ 'public/**/*.*', "!" + 'public/app/game/tests/**/*.*' ] }; module.exports = config;
import React from "react"; export default function SubTitle(props) { return ( <h4>{props.children}</h4> ) }
(function ($, X) { var BaseControl = X.prototype.controls.getControlClazz("BaseControl"); function Toolbar(elem, option) { this.$elem = $(elem); this.option = option; this.controls = {}; } Toolbar.prototype = X.prototype.createObject(BaseControl.prototype); $.extend(Toolbar.prototype, { init: function (option) { var item; this.option = option || this.option; this.$elem.html(this.getTemplate(this.option)); for (var i = 0; i < this.option.items.length; i++) { item = this.option.items[i]; initControl(item, this); } function initControl(item, self) { if (!item) return; var name = item["name"]; var elem = self.$elem.find(".js-" + item["name"]); var ctrl = X.prototype.controls.getControl(item["ctrlType"], elem, item); ctrl.init(item, function (argument) { //console.log(name + "初始化结束"); }); ctrl.Parent(self); self.controls[name] = ctrl; } }, val: function () { // body... }, /** @method getHtml 获取搜索组件html @return 搜索组件html */ getTemplate: function (option) { var items = option.items; var item, html = ""; if (items) { for (var i = 0; i < items.length; i++) { item = items[i]; html += X.prototype.controls.getTemplate(item); } } return html; } }); function ToolbarItem(option) { if (option) { this.option = option; this.name = option["name"] || "ToolbarItemName"; this.title = option["title"] || "ToolbarItemTitle"; this.click = option["click"] || function () { //console.log("没有设置操作函数") }; } } ToolbarItem.prototype = X.prototype.createObject(BaseControl.prototype); $.extend(ToolbarItem.prototype, { Parent: function () { if (arguments.length > 0) { this.parent = arguments[0]; } else { return this.parent; } } }); /** @class ToolbarItem 按钮 @constructor 构造函数 @param elem {DomNode} Dom节点 @param option {Object} 配置信息 */ function ToolbarButton(elem, option) { ToolbarItem.call(this, option); this.$elem = $(elem); } ToolbarButton.getTemplate = function (option) { return '<a href="javascript:;" class="listButton js-' + option["name"] + '"><em class="iconfont ' + (option["icon"] || "") + '"></em>' + option["title"] + '</a>'; }; ToolbarButton.prototype = X.prototype.createObject(ToolbarItem.prototype); $.extend(ToolbarButton.prototype, { init: function (option) { var that = this; this.option = option || this.option; if (this.option && this.option.click) { this.$elem.click(function (event) { that.option.click(that); }); } }, val: function () { // body... } }); /** @class ToolbarItem 按钮 @constructor 构造函数 @param elem {DomNode} Dom节点 @param option {Object} 配置信息 */ function ToolbarDropdown(elem, option) { ToolbarItem.call(this, option); this.$elem = $(elem); this.option = option; this.$dropdown = this.$elem.find(".js-dropdown"); this.$dropdownItem = this.$elem.find(".js-dropdownItem"); this.$dropdownItem.hide(); } ToolbarDropdown.prototype = X.prototype.createObject(ToolbarItem.prototype); $.extend(ToolbarDropdown.prototype, { /** @method getLists 初始化,填入下拉项 */ init: function () { var that = this; if (this.option.items) { this.items = this.getMenuItems(this.option.items); var domList = [], item; for (var i = 0; i < this.items.length; i++) { item = this.items[i]; domList.push(item.$elem); } this.$dropdownItem.append(domList); if (this.option.onItemClick) { this.$dropdownItem.on("click", function (event) { if (that.option.onItemClick) { if (event.target.tagName == "A") { that.$dropdownItem.hide(); var name = $(event.target).data("name"); item = that.getMenuItem(name); that.option.onItemClick(item); } } }); } } this.$dropdown.click($.proxy(function (argument) { this.$dropdownItem.toggle(); }, this)); $(document).on("click", function (argument) { if (!$(event.target).is(".js-dropdown") && !$(event.target).parent().is(".js-dropdown")) { if (that.$dropdownItem.is(":visible")) { that.$dropdownItem.hide(); } } }); }, /** @method getLists 生成下拉列表 @param ds {Array} 下拉数据源 @param dv {string} 默认选中项 @return 获取下拉框控件选项 */ getMenuItems: function (items) { var result = [], item; for (var i = 0, il = items.length; i < il; i++) { item = items[i]; if (item) { item = new ToolbarMenuItem(item); item.init(); result.push(item); } } return result; }, getMenuItem: function (name) { for (var i = 0; i < this.items.length; i++) { if (this.items[i].name === name) { return this.items[i]; } } return null; } }); ToolbarDropdown.getTemplate = function (option) { var template = '<div class="rel inline_block js-' + option["name"] + '">' + '<a href="javascript:;" class="listButton mR20 mark js-dropdown">' + option["title"] + '<i class="xbn_ico markSlid"></i></a>' + '<div class="oprTips js-dropdownItem">' + '<em class="dot1"></em>' + '<em class="dot2"></em>' + '</div>' + '</div>'; return template; }; function ToolbarMenuItem(option) { this.option = option; ToolbarItem.call(this, option); } ToolbarMenuItem.getTemplate = function (option) { return '<p><em class="' + (option["className"] || '') + '"></em><a href="javascript:;" class="titlelinkDefult js-' + option["name"] + '" data-name="' + option["name"] + '">' + option["title"] + '</a></p>' } ToolbarMenuItem.prototype = X.prototype.createObject(ToolbarItem.prototype); $.extend(ToolbarMenuItem.prototype, { init: function (option) { this.option = option || this.option; var tmpl = ToolbarMenuItem.getTemplate(this.option); this.$elem = $(tmpl); if (this.option.click) { this.$elem.on("click", $.proxy(function (argument) { this.option.click(this); }, this)); } }, destroy: function (argument) { this.option = null; this.$elem = null; } }); X.prototype.controls.registerControl("ToolbarButton", ToolbarButton); X.prototype.controls.registerControl("ToolbarDropdown", ToolbarDropdown); X.prototype.controls.registerControl("Toolbar", Toolbar); })(jQuery, this.Xbn);
import React from "react"; import Button from "@material-ui/core/Button"; const Success = props => { return ( <div> <h1>Thank you for registering, {props.values.name}</h1> <Button variant="contained" color="primary" onClick={props.resetStep} style={{marginTop: "20px"}}> Start again </Button> </div> ); }; export default Success;
const integralPrecision = 1000; var harmonicsCount = 40; const plotPrecision = 500; var a0; var a = [], b = []; var activeHarmonics = []; function calcHarmonics(){ a0 = 0; var step = 2 * Math.PI / integralPrecision; for(var x = -Math.PI; x <= Math.PI; x += step) a0 += f(x); a0 /= integralPrecision; if(a.length !== b.length) alert("error"); for(var i = a.length; i < harmonicsCount; ++i){ a.push(0); b.push(0); activeHarmonics.push(true); for(var x = -Math.PI; x <= Math.PI; x += step){ a[i] += f(x) * Math.cos((i + 1) * x); b[i] += f(x) * Math.sin((i + 1) * x); } a[i] *= 2; a[i] /= integralPrecision; b[i] *= 2; b[i] /= integralPrecision; } } function plot(){ if(a.length != harmonicsCount || b.length != harmonicsCount) calcHarmonics(); var coords = [], origin = []; var plotStep = 2 * Math.PI / plotPrecision; for(var x = -Math.PI; x <= Math.PI; x += plotStep){ var y = a0; for(var j = 0; j < harmonicsCount; ++j){ if(activeHarmonics[j]){ y += Math.cos((j + 1) * x) * a[j]; y += Math.sin((j + 1) * x) * b[j]; } } coords.push([x, y]); origin.push([x, f(x)]); } var options = { series: { lines: { show: true }, points: { show: false } } }; var plot = $.plot("#plot", [ {label: "Исходный график", data: origin, color: "#222"}, {label: "Гармоники", data : coords, color: "#F00"} ], options); } function createHarmonicsDescription(n){ var row = document.createElement('tr'); row.className = 'harmonicsDescription'; var checkBox = document.createElement('input'); checkBox.setAttribute('type', 'checkbox'); checkBox.className = 'harmonicsChecker'; checkBox.checked = true; checkBox.onchange = function(){ activeHarmonics[n] = checkBox.checked; plot(); }; var desc = document.createElement('p'); desc.textContent = a[n].toFixed(4) + ' * cos('+ (n + 1) + ' * x) + ' + b[n].toFixed(4) + ' * sin(' + (n + 1) + ' * x)'; var td1 = document.createElement('td'); var td2 = document.createElement('td'); td1.appendChild(checkBox); td2.appendChild(desc); row.appendChild(td1); row.appendChild(td2); return row; } function buildHarmonicsList(){ var list = document.getElementById('harmonicsList'); for(var i = 0; i < harmonicsCount; ++i) list.appendChild(createHarmonicsDescription(i)); } window.onload = function(){ if(typeof f === 'undefined'){ alert("Функция f(x) не найдена"); return; } calcHarmonics(); buildHarmonicsList(); plot(); } function setAllCheckboxes(mode){ var boxes = document.getElementsByClassName('harmonicsChecker'); for(var i = 0; i < boxes.length; ++i) boxes[i].checked = mode; for(var i = 0; i < activeHarmonics.length; ++i) activeHarmonics[i] = mode; plot(); }
////////////// IMPORTS /////////////// const config = require('@config'); ////////////// PRIVATE /////////////// function logger(logLevel) { // get all args except the first let args = Array.prototype.slice.call(arguments, 1); // log them if appropriate if (logLevel === 'error') console.error.apply(null, args); else if (logLevel <= config.logLevel) console.log.apply(null, args); } /////////////// PUBLIC /////////////// module.exports = logger;
function createGrid() { var grid = []; return { initialiseEmptyGrid() { for (let row = 0; row < HEIGHT; row++) { grid.push([]); for (let col = 0; col < WIDTH; col++) grid[row].push(false); } }, deleteRow(row) { const emptyRow = new Array(WIDTH).map(elem => elem = false); const beforeRow = grid.slice(0, row); const afterRow = grid.slice(row + 1, HEIGHT); grid = [emptyRow].concat(beforeRow.concat(afterRow)); }, isFilled(row, col) { return grid[row][col]; }, setFilled(row, col) { grid[row][col] = true; }, }; }
exports.apply = require('./defaultEvaluator.js').apply; exports.init = function(args, ctx) { ctx.ret({coll: {}}); }; exports.do_get = function(state, patch, ctx) { ctx.ret(state, state.coll); }; exports.do_add = function(state, patch, ctx) { state.coll[patch.key] = patch.val; ctx.ret(state); };
/* % node common.js const util = require('util') ^ ReferenceError: require is not defined */ const util = require('util') console.log(util.inspect('foo'))
import React from 'react'; import { Switch } from 'react-router-dom'; import Route from './Route'; import SignIn from '../pages/SignIn'; import SignUp from '../pages/SignUp'; import Dashboard from '../pages/Dashboard'; import Profile from '../pages/Profile'; import Question from '../pages/Question'; import Chat from '../pages/Chat'; import Essay from '../pages/Essay'; import Correction from '../pages/Correction'; import Feedback from '../pages/Feedback'; export default function Routes() { return ( <Switch> <Route path="/" exact component={SignIn} /> <Route path="/register" component={SignUp} /> <Route path="/dashboard" component={Dashboard} isPrivate /> <Route path="/profile" component={Profile} isPrivate /> <Route path="/question" component={Question} isPrivate /> <Route path="/chat" component={Chat} isPrivate /> <Route path="/essay" component={Essay} isPrivate /> <Route path="/correction" component={Correction} isPrivate /> <Route path="/feedback" component={Feedback} isPrivate /> </Switch> ); }
// BREAK AND CONTINUE SCRIPT var list = ["John","Smith",1990,"boy"]; for(var i=0;i<list.length; i++){ if(typeof list[i] !== 'string'){ // 1990 SKIPPED continue } console.log(list[i]) } for(var i=0;i<list.length; i++){ if(typeof list[i] !== 'string'){ // AFTER 1990 THE PROCESS IS STOPPED break } console.log(list[i]) }
bootbox.prompt({ title: "What is your real name?", value: "makeusabrew", callback: function(result) { if (result === null) { Example.show("Prompt dismissed"); } else { Example.show("Hi <b>"+result+"</b>"); } } });
var postorder = function(root) { let ans = []; function dfs(node) { if (!node) {return} if (node.children) { for (let i = 0; i < node.children.length; i++) { dfs(node.children[i]) } } ans.push(node.val) } dfs(root); return ans }; var postorder = function(root) { if (!root) {return []} let stack = [root]; let ans = []; let checked = new Set(); while (stack.length > 0) { let node = stack[stack.length-1]; if (!checked.has(node) && node.children) { checked.add(node) for (let i = node.children.length-1; i >= 0; i--) { stack.push(node.children[i]); } } else { ans.push(node.val); stack.pop(); } } return ans }
/* eslint-disable no-global-assign */ import { createStore, applyMiddleware, combineReducers } from 'redux'; import { persistStore, persistReducer } from 'redux-persist'; import storage from 'redux-persist/lib/storage'; import thunk from 'redux-thunk'; import { logger } from 'redux-logger'; import { composeWithDevTools } from 'redux-devtools-extension' import { createReactNavigationReduxMiddleware, createNavigationReducer } from 'react-navigation-redux-helpers'; import AppNavigator from 'MCConfig/Navigator'; import * as reducerothers from 'MCReducer'; import { autoCacheModule_prd as cacheModule, haveReactNativeDebugger } from 'MCConfig/app.json'; import * as systemReducers from './reducer'; import screentraker from './middleware/screenTraker'; import promiseMiddleWare from './middleware/promise'; const navReducer = createNavigationReducer(AppNavigator); const reducers = combineReducers({ nav: navReducer, ...reducerothers || {}, ...systemReducers, }); let devoptions = {}; if (!__DEV__) { devoptions = { whitelist: cacheModule, }; } const persistConfig = { key: 'rootpersistKey', storage, timeout: 3000, ...devoptions, }; const persistedReducer = persistReducer(persistConfig, reducers); const navMiddleware = createReactNavigationReduxMiddleware('root', state => state.nav); let combinedMiddleware = [promiseMiddleWare, thunk, navMiddleware, screentraker] if (__DEV__) { if(haveReactNativeDebugger) combinedMiddleware = composeWithDevTools(applyMiddleware(...combinedMiddleware)) else { combinedMiddleware.push(logger) combinedMiddleware = applyMiddleware(...combinedMiddleware) } } export default store = createStore(persistedReducer, combinedMiddleware); export const persistor = persistStore(store);
import React, { Component } from 'react' import './Hamburger.css' import HamburgerContext from '../../Contexts/HamburgerContext' import BabyApiService from '../../Services/baby-api-service' import UsersBabies from './UsersBabies' export default class Hamburger extends Component { static contextType = HamburgerContext componentDidMount() { BabyApiService.getByParentId() .then(res => { this.context.setUsersBabies(res) }) .catch(this.context.setError) } render() { const { usersBabies } = this.context if (usersBabies.length === 0) { return <></> } // Trigger for activating menu const active = this.context.active const hamburgerMenu = (active) => ( <nav aria-label='secondary' className={`menu-wrap ${active ? "active" : "disabled"}`} > <div className={`toggle-label`} > <div className='hamburger-container'> <div id='toggle' className={`hamburger ${active ? "checked" : ""}`} onClick={() => {this.context.toggleActive()}} > <div></div> </div> </div> <h2 className={`menu-label ${active ? "show-label" : ""}`}> Babies </h2> </div> <div className={`menu ${active ? "checked" : ""}`}> <ul> {usersBabies.map(baby => ( <UsersBabies active={active} key={baby.id} baby={baby} /> ))} </ul> </div> </nav> ) return hamburgerMenu(active) } }
import React, { Component } from 'react' function importAll(r) { let images = {} r.keys().forEach((item, index) => { images[item.replace('./', '')] = r(item); }) return images } const images = importAll(require.context('../icons', false, /\.(png|jpe?g|svg)$/)) let winnerObject = {} for (let i=1; i<=26; i++) { winnerObject[i] = '' } class Table extends Component { state = { playerOneName: 'Player 1', playerTwoName: 'Player 2', winner: winnerObject, playerOne: [], playerTwo: [], } lostStock(event, char, winner, loser) { //dim or undim the icon if (event.target.classList.contains('clicked')) { event.target.classList.remove('clicked') } else { event.target.classList.add('clicked') this.props.handleKill(char, winner, loser) } // console.log(winner, "wins"); let playerWins = [...this.state[winner]] playerWins.push(char) this.setState({ [winner]: playerWins }) } render() { return( <> <button className='btn btn-warning' onClick={() => { this.props.dittos() }}>Dittos</button> <table className='table table-hover'> <thead> <tr className='sticky-top'> <th onClick={() => { this.props.randomize() }} scope="col" className='sticky-top' ><button className="btn btn-success">Randomize!</button></th> <th scope="col" className='sticky-top' >{this.state.playerOneName}</th> <th scope="col" className='sticky-top' >{this.state.playerTwoName}</th> <th scope="col" className='sticky-top' ><button className='btn btn-danger' onClick={() => { this.props.reorder() }} >Reorder</button></th> </tr> </thead> <tbody> { this.props.characters.map((char, i) => { return( <tr key={char.id}> <th scope='row'>{i+1}</th> <td> <img className='icon' src={images[char.icon]} alt={char.name} onClick={(event) => { this.lostStock(event, char, 'playerTwo', 'playerOne') }} /> <img className='icon' src={images[char.icon]} alt={char.name} onClick={(event) => { this.lostStock(event, char, 'playerTwo', 'playerOne') }} /> </td> <td> <img className='icon' src={images[this.props.secondColumn[i].icon]} alt={this.props.secondColumn[i].name} onClick={(event) => { this.lostStock(event, this.props.secondColumn[i], 'playerOne', 'playerTwo') }} /> <img className='icon' src={images[this.props.secondColumn[i].icon]} alt={this.props.secondColumn[i].name} onClick={(event) => { this.lostStock(event, this.props.secondColumn[i], 'playerOne', 'playerTwo') }} /> </td> <td> { this.state.winner[i] ? <img src={images[this.state.winner[i]]} alt={char.name} /> : null } </td> </tr> )}) } </tbody> </table> </> ) } } export default Table
import React, { useState, useContext } from "react"; import { Link, Redirect } from "react-router-dom"; import _ from "lodash"; import { UserContext } from "../context/user/userContext"; import Loader from "../components/Loader"; function Registr(props) { const user = useContext(UserContext); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [name, setName] = useState(""); const isDisabled = email && password && name ? false : true; const handleSubmit = (e) => { e.preventDefault(); if (email.trim() && password.trim() && name.trim()) { user.registration(email.trim(), password.trim(), name.trim()); setEmail(""); setPassword(""); setName(""); } else { } }; if (!_.isEmpty(user.user)) return <Redirect to="/" />; return ( <> {user.loading ? ( <Loader /> ) : ( <form onSubmit={handleSubmit} className="col-6 offset-3"> <div className="form-group"> <label htmlFor="email">Email address</label> <input type="email" className="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email..." value={email} onChange={(e) => setEmail(e.target.value)} /> <small id="emailHelp" className="form-text text-muted"> We'll never share your email with anyone else. </small> </div> <div className="form-group"> <label htmlFor="password">Password</label> <input type="password" className="form-control" id="password" placeholder="Enter password..." value={password} onChange={(e) => setPassword(e.target.value)} /> </div> <div className="form-group"> <label htmlFor="name">Name</label> <input type="text" className="form-control" id="name" placeholder="Enter your name..." value={name} onChange={(e) => setName(e.target.value)} /> </div> <p> Have an account?{" "} <b> <Link to="/signin">Sign In</Link> </b> </p> <button type="submit" disabled={isDisabled} className="btn btn-primary" > Sign Up </button> </form> )} </> ); } export default Registr;
class AMILoaderWorker { constructor( resultFn = result => {}, errorFn = error => {}, closeWhenLoaded = true, downloadingFn = (loaded, total) => {}, parseBeginFn = () => {}, parsingFn = (parsed, total) => {} ) { // see: https://developer.mozilla.org/ru/docs/Web/API/Web_Workers_API // https://developer.mozilla.org/ru/docs/DOM/Using_web_workers // https://www.html5rocks.com/en/tutorials/workers/basics/ if (window.Worker) { // IMPORTANT: change if needed for debug self.wk = new Worker('/ami-loader-experiment/src/worker.js'); } else { alert('Your browser doesn\'t support web workers'); } self.wk.onmessage = ({ data }) => { switch (data.type) { case 'downloading': downloadingFn(data.value.loaded, data.value.total); break; case 'parseBegin': parseBeginFn(); break; case 'parsing': parsingFn(data.value.parsed, data.value.total); break; case 'result': (() => { let result = new AMI.SeriesModel(); result._stack = AMILoaderWorker.createStackModel(data.value._stack); delete data.value._stack; for (let k in data.value) { result[k] = data.value[k]; } resultFn(result); if (closeWhenLoaded) { self.wk.terminate(); } })(); break; case 'error': errorFn(data.value); self.wk.terminate(); break; } self.wk.onerror = ({ data }) => { errorFn(data); self.wk.terminate(); }; }; } load(links) { self.wk.postMessage({ links }); } terminate() { self.wk.terminate(); } static createStackModel(data) { let result = []; data.forEach(i => { let stack = new AMI.StackModel(); stack._aabb2LPS = new THREE.Matrix4(); stack._dimensionsIJK = new THREE.Vector3(); stack._halfDimensionsIJK = new THREE.Vector3(); stack._ijk2LPS = new THREE.Matrix4(); stack._lps2AABB = new THREE.Matrix4(); stack._lps2IJK = new THREE.Matrix4(); stack._origin = new THREE.Vector3(); stack._regMatrix = new THREE.Matrix4(); stack._spacing = new THREE.Vector3(); stack._xCosine = new THREE.Vector3(); stack._yCosine = new THREE.Vector3(); stack._zCosine = new THREE.Vector3(); stack._frame = AMILoaderWorker.createFrameModel(i._frame); delete i._frame; stack._rawDataFromOtherStack = i._rawDataFromOtherStack; delete i._rawDataFromOtherStack; for (let k in i) { stack[k] = typeof i[k] === 'object' ? AMILoaderWorker.copyObject(stack[k], i[k]) : i[k]; } result.push(stack); }); return result; } static createFrameModel(data) { let result = []; data.forEach(i => { let item = new AMI.FrameModel(); for (let k in i) { item[k] = i[k]; } result.push(item); }); return result; } static copyObject(result, source) { for (let key in source) { result[key] = source[key]; } return result; } }
Ext.define('Assessmentapp.assessmentapp.shared.com.viewmodel.assessmentcontext.survey.AssessmentInferenceSheetLoaderUIViewModel', { 'extend': 'Ext.app.ViewModel', 'alias': 'viewmodel.AssessmentInferenceSheetLoaderUIViewModel', 'model': 'AssessmentInferenceSheetLoaderUIModel' });
import React, { Component } from 'react' import styles from './IntroText.scss' export default class IntroText extends Component { render() { return ( <div className={styles.intro}> <span className={styles.heading}>Messenger</span> <p> Exercises: </p> <ol> <li>Add the team logo</li> <li>Display the username</li> <li>Toggle and display the channel list</li> <li>Join a channel by clicking on it</li> <li>Open and show a messenger-channel</li> <li>Send and display messages</li> </ol> <p> Some resources: </p> <ul> <li><a href="http://facebook.github.io/react/docs/getting-started.html">react docs (getting started)</a></li> <li><a href="https://sendbird.gitbooks.io/sendbird-web-sdk/content/en/">sendbird web gitbook</a></li> </ul> </div> ) } }
import React, { Component } from 'react'; import { inject, observer } from 'mobx-react'; import { Form, Input, Button, Divider, Radio } from 'antd'; import { Link } from 'react-router-dom'; import qs from 'query-string'; import PropTypes from 'prop-types'; import { CONFIG_MANAGEMENT_LIST } from '../../../../router/constants'; import { CONFIG_TYPE_ENUM } from '../constants'; const { create } = Form; const { TextArea } = Input; const formItemLayout = { labelCol: { xs: { span: 24 }, sm: { span: 4 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: 20 }, }, }; const tailFormItemLayout = { wrapperCol: { xs: { span: 24, offset: 0, }, sm: { span: 16, offset: 8, }, }, }; @create() @inject(({ store: { configStore } }) => ({ configStore })) @observer export default class Create extends Component { static propTypes = { configStore: PropTypes.object.isRequired, history: PropTypes.object.isRequired, form: PropTypes.object.isRequired, }; state = { loading: false }; namespace = qs.parse(window.location.search).namespace; componentDidMount() {} componentWillUnmount() {} handleSubmit = e => { e.preventDefault(); this.props.form.validateFieldsAndScroll((err, values) => { if (!err) { console.log('Received values of form: ', values); this.setState({ loading: true }); this.props.configStore .createConfig({ namespace: this.namespace, ...values }) .then(this.props.history.goBack) .finally(() => this.setState({ loading: false })); } }); }; render() { const { getFieldDecorator } = this.props.form; const { loading } = this.state; return ( <Form style={{ width: 640 }} {...formItemLayout} onSubmit={this.handleSubmit}> <Form.Item label="Data ID"> {getFieldDecorator('dataId', { rules: [ { required: true, message: '请输入 Data ID !', }, ], })(<Input />)} </Form.Item> <Form.Item label="Group"> {getFieldDecorator('groupName', { rules: [ { required: true, message: '请输入 Group !', }, ], })(<Input />)} </Form.Item> <Form.Item label="配置格式"> {getFieldDecorator('type', { initialValue: CONFIG_TYPE_ENUM.TEXT, })( <Radio.Group> {Object.values(CONFIG_TYPE_ENUM.properties).map(item => ( <Radio key={item.value} value={item.value}> {item.label} </Radio> ))} </Radio.Group>, )} </Form.Item> <Form.Item label="配置内容"> {getFieldDecorator('content', { rules: [ { required: true, message: '请输入 配置内容 !', }, ], })(<TextArea rows={15} />)} </Form.Item> <Form.Item {...tailFormItemLayout}> <Button type="primary" htmlType="submit" loading={loading}> 提交 </Button> <Divider type="vertical" /> <Link to={CONFIG_MANAGEMENT_LIST}> <Button>返回</Button> </Link> </Form.Item> </Form> ); } }
import React, { Component } from 'react'; class Contact extends Component { render() { return ( <div className="contact-body"> <div className="contact-container"> <div className="contact-header">Contact</div> <div className="contact-text"> If you'd like to chat about my work, collaborating on a project, what music I'm listening to, or just say hi, feel free to reach out! </div> <div className="contact-links"> <div className="email-button"> <div className="fa fa-envelope"></div> <div className="email">Email</div> </div> <div className="linkedin-button"> <div className="fa fa-linkedin"></div> <div className="linkedin">LinkedIn</div> </div> <div className="facebook-button"> <div className="fa fa-facebook-f"></div> <div className="facebook">Facebook</div> </div> <div className="github-button"> <div className="fa fa-github"></div> <div className="github">Github</div> </div> </div> </div> {/* <div className="footer-container"> <div className="link-container"> </div> </div> */} </div> ); } } export default Contact
import React, { useState } from 'react'; import './App.css'; import PopUp from './component/Pop_up'; import Table from './component/Table'; function App() { const [ShowPOPUP,setShowPOPUP] = useState(false) return ( <div className="App"> <Table setShowPOPUP={setShowPOPUP}/> <PopUp ShowPOPUP={ShowPOPUP} setShowPOPUP={setShowPOPUP}/> </div> ); } export default App;
import { ADD_TO_CART,REMOVE_TO_CART } from "../../actions/syncActions/myActions"; function removeItemOnce(arr, value) { var index = arr.indexOf(value); if (index > -1) { arr.splice(index, 1); } return arr; } const default_state = { cart: [], price:0, extra_data: "Hello World!" } export const my_cart = (state = default_state, action) => { switch (action.type) { case ADD_TO_CART: { let temp = state.cart temp.push(action.payload) return { ...state, // Keep all state and olny modify counter cart: temp, price: parseFloat(action.payload.price) + state.price } } case REMOVE_TO_CART: { let temp = state.cart temp = removeItemOnce(temp,action.payload) return { ...state, // Keep all state and olny modify counter cart: temp, price: state.price - parseFloat(action.payload.price) } } default: return state; } }
import React, { Component } from "react"; import { NavLink } from "react-router-dom"; import typing from "../typing.mp4"; import TypingAnimation from "./typingAnimation"; import "../sass/main.scss"; class Homepage extends Component { render() { return ( <div id="home-page" className="hero"> <div className="hero-overlay"></div> <div className="hero hero-video"> <video autoPlay loop muted preload data-origin-x="20" data-origin-y="40"> <source src={typing} type="video/mp4"></source> </video> </div> <div className="hero-video-text"> <h1 className='m-4'> <TypingAnimation /> </h1> </div> <br /> <div className="hero-video-btn"> <NavLink className="btn btn-outline-light m-4" to="/about"> ABOUT ME </NavLink> <NavLink className="btn btn-outline-light m-4" to="/my-work"> MY WORK </NavLink> </div> </div> ); } } export default Homepage;
define(['angular'], function (angular) { 'use strict'; /** * @ngdoc function * @name kvmApp.controller:ImageServerCtrl * @description * # ImageServerCtrl * Controller of the kvmApp */ angular.module('kvmApp.controllers.AppServerCtrl', []) .controller('AppServerCtrl', function (AppService, $scope, $state, $uibModal,Syncservice) { this.awesomeThings = [ 'HTML5 Boilerplate', 'AngularJS', 'Karma' ]; $scope.total = 0; $scope.pageSize = 15; $scope.page = 1; $scope.searchKey = ''; $scope.initPage = function(searchKey){ AppService.fetch({page: $scope.page, pageSize: $scope.pageSize, searchKey:searchKey}). success(function (data) { $scope.searchKey = searchKey; $scope.total = data.total; $scope.rows = data.rows; }); }; if ($state.current.needRequest) { $scope.initPage(); } $scope.Create = function () { var modalInstance = $uibModal.open({ animation: true, templateUrl: 'add.html', controller: 'ModalInstanceCtrl', size: 'lg', resolve: { item: function () { return {}; }, title: function () { return {'title':'新建','etcTaskType':etcTaskType,'etcIsDisabled':etcIsDisabled}; } } }); modalInstance.save = function (item) {console.log(item); AppService.save(item). success(function (data) { modalInstance.close(); $scope.initPage(); }); }; }; $scope.detail = function (i) { $uibModal.open({ animation: true, templateUrl: 'detail.html', controller: 'ModalInstanceCtrl', size: 'lg', resolve: { item: function () { return $scope.rows[i]; }, title: function () { return '查看'; } } }); }; $scope.updateimage = function (i) { var allImage = JSON.parse(Syncservice.fetch('/api/v2/mirror/')); var modalInstance = $uibModal.open({ animation: true, templateUrl: 'updateimage.html', controller: 'ModalInstanceCtrl', size: 'lg', resolve: { item: function () { return $scope.rows[i]; }, title: function () { return {'title':'升级镜像','imageList':allImage}; } } }); modalInstance.Updateapp = function (item) {console.log(item); AppService.Updateapp(item). success(function (data) { modalInstance.close(); $scope.initPage(); }); }; }; $scope.appdetail = function (i) { $uibModal.open({ animation: true, templateUrl: 'appdetail.html', controller: 'ModalInstanceCtrl', size: 'lg', resolve: { item: function () { return $scope.rows[i]; }, title: function () { return '查看应用信息'; } } }); }; $scope.edit = function (i) { var modalInstance = $uibModal.open({ animation: true, templateUrl: 'edit.html', controller: 'ModalInstanceCtrl', size: 'lg', resolve: { item: function () { return $scope.rows[i]; }, title: function () { return {'title':'编辑','etcTaskType':etcTaskType,'etcIsDisabled':etcIsDisabled}; } } }); modalInstance.save = function (item) { AppService.save(item). success(function (data) { console.log(item); modalInstance.close(); $scope.initPage(); }); }; }; $scope.Delete = function (i) { var modalInstance = $uibModal.open({ animation: true, templateUrl: 'delete.html', controller: 'ModalInstanceCtrl', size: 'lg', resolve: { item: function () { return $scope.rows[i]; }, title: function () { return {'title':'删除','etcTaskType':etcTaskType,'etcIsDisabled':etcIsDisabled}; } } }); modalInstance.Delete = function (item) { AppService.Delete(item). success(function (data) { console.log(item); modalInstance.close(); $scope.initPage(); }); }; }; $scope.Start = function (i) { var modalInstance = $uibModal.open({ animation: true, templateUrl: 'start.html', controller: 'ModalInstanceCtrl', size: 'lg', resolve: { item: function () { return $scope.rows[i]; }, title: function () { return {'title':'启动应用'}; } } }); modalInstance.Start = function (item) { AppService.Start(item). success(function (data) { console.log(item); modalInstance.close(); $scope.initPage(); }); }; }; $scope.Stop = function (i) { var modalInstance = $uibModal.open({ animation: true, templateUrl: 'stop.html', controller: 'ModalInstanceCtrl', size: 'lg', resolve: { item: function () { return $scope.rows[i]; }, title: function () { return {'title':'停止应用'}; } } }); modalInstance.Stop = function (item) { AppService.Stop(item). success(function (data) { console.log(item); modalInstance.close(); $scope.initPage(); }); }; }; $scope.Search = function (searchKey) { $scope.initPage(searchKey); }; $scope.pageAction = function (page) { AppService .fetch({page: page}) .success(function (data) { $scope.total = data.total; $scope.rows = data.rows; }); }; $scope.sendReq = function(id, val){ AppService.post('/api/v2/app/rc/' + id, {"rc": val}).then(function(result){ result.data; }); }; }).filter('cut', function () { return function (value, wordwise, max, tail) { if (!value) return ''; max = parseInt(max, 10); if (!max) return value; if (value.length <= max) return value; value = value.substr(0, max); if (wordwise) { var lastspace = value.lastIndexOf(' '); if (lastspace != -1) { value = value.substr(0, lastspace); } } return value + (tail || '...'); }; });; });
/** * Created by jason on 2019/4/2. */ export default { name:"jason", age:28 }
import React, { Component } from 'react'; import LayoutDefault from './../../components/LayoutDefault' import StarwarsMember from './components/StarwarsMember' import { connect } from 'react-redux'; import actions from '../../actions'; import axios from 'axios'; class Index extends Component { constructor(props) { super(props); this.checkInterval = null; this.getDataFromSwapi = this.getDataFromSwapi.bind(this); } getDataFromSwapi() { this.props.fetchSwapiAPI(null, (res) => { console.log(res); }, (err) => { console.log(err); } ) } componentDidMount() { this.getDataFromSwapi(); } componentWillUnmount() { clearInterval(this.checkInterval); } render() { return ( <LayoutDefault> <StarwarsMember title="Starwars Members" starwars={this.props.starwars} /> </LayoutDefault> ); } } const mapStateToProps = (state) => ({ starwars: state.swapi.starwars }); const mapDispatchToProps = (dispatch) => ({ fetchSwapiAPI: (req,res,err) => dispatch(actions.swapi.api.fetchSwapiAPI(req,res,err)) }); export default connect(mapStateToProps,mapDispatchToProps)(Index);
var Bot = require('slackbots'); var bot = new Bot({ token: process.env.SLACK_API_KEY, name: 'squeegebot' }); bot.on('start', function() { bot.postMessageToChannel('general', 'Hello!'); });
jQuery(function(){ $("#formId").submit(function(e){ alert($("#friendMail").val()); }); });
angular.module("MainApp",['ui.router','angular.filter','ngResource', 'angucomplete-alt']);
const AWS = require('aws-sdk'); const config = require('./config'); const s3 = new AWS.S3(); async function list() { const response = await s3.listMultipartUploads({ Bucket: config.bucketName, }).promise(); console.log(response); } list() .catch(console.error) .then(() => process.exit(0));
// http://www.pythonchallenge.com/pc/def/linkedlist.php function number1(i) { switch(i){ case "0": case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": return true; default: return false; } } var request = require('sync-request'); var urlbase1 = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing="; // var p = "12345"; // var p = "8022"; // var p = "63579"; var p = "66831"; while(true) { var lbody = ""; var res = request('GET', urlbase1+p); var lbody = res.getBody().toString(); x = ""; for (i = 0; i <= lbody.length; i++) { if(number1(lbody.charAt(i))) x += lbody.charAt(i); } p = x; console.log(lbody); console.log(p); } // http://www.pythonchallenge.com/pc/def/peak.html
$(document).ready(function() { // $("").on("click", function(event) { $("form.contact-form").submit(function(e) { e.preventDefault(); var formData = new FormData(this); console.log("form_data") var form = this $.ajax({ url : getAbsolutePath("/main/contactoMail"), type : "POST", data : getContactoData(), success : function(data, textStatus, jqXHR) { alert("Información enviada, Gracias") resetContactoForm() }, error : function(jqXHR, textStatus, errorThrown) { alert("Información enviada, Gracias") } }); }); /* * window.alert = function(message) { // do something here console.log("overrided--->" + * message) }; */ }) function resetContactoForm() { $("#contacto-nombre").val("") $("#contacto-correo").val("") $("#contacto-titulo").val("") $("#contacto-texto").val("") } function getContactoData() { var data = {} data.nombre = $("#contacto-nombre").val() data.correo = $("#contacto-correo").val() data.titulo = $("#contacto-titulo").val() data.mensaje = $("#contacto-texto").val() return data }
import React from "react"; import {TravelOctoBase} from "~/util/api"; import NextDocument, {Html, Head, Main, NextScript} from "next/document"; import {ServerStyleSheet as StyledComponentSheets} from "styled-components"; import {ServerStyleSheets as MaterialUiServerStyleSheets} from "@material-ui/styles"; const removeCommentsAndSpacing = (data = "") => { let str = data.props.dangerouslySetInnerHTML["__html"]; data.props.dangerouslySetInnerHTML["__html"] = str.replace(/\/\*.*\*\//g, " ").replace(/\s+/g, " "); return data; }; export default class Document extends NextDocument { static async getInitialProps(ctx) { const styledComponentSheet = new StyledComponentSheets(); const materialUiSheets = new MaterialUiServerStyleSheets(); const originalRenderPage = ctx.renderPage; try { ctx.renderPage = () => originalRenderPage({ enhanceApp: (App) => (props) => styledComponentSheet.collectStyles(materialUiSheets.collect(<App {...props} />)), }); const initialProps = await NextDocument.getInitialProps(ctx); return { ...initialProps, styles: [ <React.Fragment key="initial">{initialProps.styles}</React.Fragment>, <React.Fragment key="material">{removeCommentsAndSpacing(materialUiSheets.getStyleElement())}</React.Fragment>, <React.Fragment key="styledComponent">{styledComponentSheet.getStyleElement()}</React.Fragment>, ], }; } finally { styledComponentSheet.seal(); } } render() { const fontExtensions = [ ["woff2", "woff2"], ["woff", "woff"], ["ttf", "truetype"], ]; return ( <Html lang="nl"> <Head> <style dangerouslySetInnerHTML={{ __html: ` @font-face { font-family: 'Futura PT'; src: ${fontExtensions.map((fontExtension) => { return "url('" + TravelOctoBase + "public/fonts/FuturaPT-Light." + fontExtension[0] + "') format('" + fontExtension[1] + "')"; })}; font-weight: normal; font-style: normal; } @font-face { font-family: 'Futura PT'; src: ${fontExtensions.map((fontExtension) => { return "url('" + TravelOctoBase + "public/fonts/FuturaPT-Book." + fontExtension[0] + "') format('" + fontExtension[1] + "')"; })}; font-weight: bold; font-style: normal; }`, }} /> {/* Global Site Tag (gtag.js) - Google Analytics */} <script async src={`https://www.googletagmanager.com/gtag/js?id=G-6V81WEP8RS`} /> <script dangerouslySetInnerHTML={{ __html: ` window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-WVKBW4QP0J', { page_path: window.location.pathname, }); `, }} /> <script dangerouslySetInnerHTML={{ __html: ` var _TradeTrackerTagOptions = { t: 'a', s: '370553', chk: '92548de6aaf982a9fcae4b127efda7e7', overrideOptions: {} }; (function() {var tt = document.createElement('script'), s = document.getElementsByTagName('script')[0]; tt.setAttribute('type', 'text/javascript'); tt.setAttribute('src', (document.location.protocol == 'https:' ? 'https' : 'http') + '://tm.tradetracker.net/tag?t=' + _TradeTrackerTagOptions.t + '&amp;s=' + _TradeTrackerTagOptions.s + '&amp;chk=' + _TradeTrackerTagOptions.chk); s.parentNode.insertBefore(tt, s);})();`, }} /> </Head> <body> <Main /> <NextScript /> </body> </Html> ); } }
import React from "react"; import Modal from "components/Modal"; export default function Member(props) { return ( <div className="member center-block m-bottom-6"> <div className="member-thumb" style={{ backgroundImage: `url(${props.image})` }} /> <Modal trigger={ <a className="member-content text-center" data-toggle="modal" data-track="event" data-category="About" data-action="Click Team Member" data-label={props.name}> <div className="member-text"> <p className="text-white text-bold m-bottom-2">{props.name}</p> <p className="no-margin text-white">{props.position}</p> </div> </a> } footerHidden={true}> <div className="embed-responsive embed-responsive-member"> <div style={{ backgroundImage: `url(${props.image})`, }} className="embed-responsive-item" /> </div> <div className="modal-body" style={{ background: "white" }}> <h5 className="h5">{props.name}</h5> <p className="text-primary">{props.position}</p> {props.description ? <p>{props.description}</p> : null} <div className="m-top-4"> {props.pdf ? ( <a href={`/img/about/member/${props.pdf}`} className="btn btn-default m-right-2" target="_blank"> View Resume </a> ) : null} {props.website ? ( <a href={props.website} className="btn btn-link btn-member-icon" target="_blank"> <i className="icon-link" /> </a> ) : null} {props.linkedin ? ( <a href={`https://www.linkedin.com/in/${props.linkedin}`} className="btn btn-link btn-member-icon" target="_blank"> <i className="icon-linkedin-alt" /> </a> ) : null} {props.medium ? ( <a href={`https://medium.com/@${props.medium}`} className="btn btn-link btn-member-icon" target="_blank"> <i className="icon-social-medium" /> </a> ) : null} {props.dribbble ? ( <a href={`https://dribbble.com/${props.dribbble}`} className="btn btn-link btn-member-icon" target="_blank"> <i className="icon-dribbble" /> </a> ) : null} {props.github ? ( <a href={`https://github.com/${props.github}`} className="btn btn-link btn-member-icon" target="_blank"> <i className="icon-github-alt" /> </a> ) : null} {props.twitter ? ( <a href={`https://twitter.com/${props.twitter}`} className="btn btn-link btn-member-icon" target="_blank"> <i className="icon-twitter" /> </a> ) : null} {props.facebook ? ( <a href={`https://facebook.com/${props.facebook}`} className="btn btn-link btn-member-icon" target="_blank"> <i className="icon-facebook" /> </a> ) : null} {props.instagram ? ( <a href={`https://instagram.com/${props.instagram}`} className="btn btn-link btn-member-icon" target="_blank"> <i className="icon-instagram" /> </a> ) : null} </div> </div> </Modal> </div> ); }
if(params.fromWhere === 'lyb' || params.fromWhere === 'lyh') { lyb.fastNav = function(){}; } lyb.parse(); var inputs = jQuery('input:password'), first = jQuery('#first_title'), last = jQuery('#last_title'); var psd = ['', '']; jQuery('.keyboard').on('touchend', '.number', function (e) { e.preventDefault(); if (psd[0].length < 6) { first.removeClass('his-hide'); last.addClass('his-hide'); psd[0] += this.innerHTML; setPassword(psd[0].split('')); if (psd[0].length == 6) { window.setTimeout(function () { setPassword([]); first.addClass('his-hide'); last.removeClass('his-hide'); }, 200); return; } } else { first.addClass('his-hide'); last.removeClass('his-hide'); psd[1] += this.innerHTML; setPassword(psd[1].split('')); if (psd[1].length == 6) { validate(); } } }); jQuery('.keyboard').on('touchend', '.delete', function (e) { e.preventDefault(); if (psd[0].length < 6) { var psdArray = psd[0].split(''); psdArray.shift(); psd[0] = psdArray.join(''); setPassword(psdArray); } else { var psdArray = psd[1].split(''); psdArray.shift(); psd[1] = psdArray.join(''); setPassword(psdArray); } }); function setPassword(values) { for (var i = 0; i < 6; i++) { inputs[i].value = values[i] || ''; } } function validate() { if (psd[0] != psd[1]) { psd[0] = psd[1] = ''; setPassword([]); first.removeClass('his-hide'); last.addClass('his-hide'); lyb.error('两次输入的密码不一致!'); } else { lyb.ajax(ctx + 'member/info/addPassword', { type: 'post', dataType: 'json', data: { password: psd[0], cardId: params.cardId }, success: function (result) { if (result.success) { lyb.toast('支付密码设置成功!', function () { if (sessionStorage.getItem('callbackUrl')) { window.location.href = sessionStorage.getItem('callbackUrl'); sessionStorage.removeItem('callbackUrl'); } else { window.location.href = ctx + 'html/personal/index.html'; } }); } else { lyb.error(result.msg); setPassword([]); first.removeClass('his-hide'); last.addClass('his-hide'); } } }); } }
import { isDefined } from '../../core/utils/type'; import tagHelper from './excel.tag_helper'; var numberFormatHelper = { ID_PROPERTY_NAME: 'id', tryCreateTag: function tryCreateTag(sourceObj) { var result = null; if (typeof sourceObj === 'string') { result = { formatCode: sourceObj }; if (numberFormatHelper.isEmpty(result)) { result = null; } } return result; }, areEqual: function areEqual(leftTag, rightTag) { return numberFormatHelper.isEmpty(leftTag) && numberFormatHelper.isEmpty(rightTag) || isDefined(leftTag) && isDefined(rightTag) && leftTag.formatCode === rightTag.formatCode; }, isEmpty: function isEmpty(tag) { return !isDefined(tag) || !isDefined(tag.formatCode) || tag.formatCode === ''; }, toXml: function toXml(tag) { // §18.8.30 numFmt (Number Format) return tagHelper.toXml('numFmt', { 'numFmtId': tag[numberFormatHelper.ID_PROPERTY_NAME], formatCode: tag.formatCode // §21.2.2.71 formatCode (Format Code), §18.8.31 numFmts (Number Formats) }); } }; export default numberFormatHelper;
class KanyaWestTweet { firstName = ''; lastName = ''; content = ''; constructor(firstName, lastName, content) { this.firstName = firstName; this.lastName = lastName; this.content = content; this.getNewTweet(); } getNewTweet() { let button = document.querySelector(".get-quote"); button.addEventListener("click", function() { let ajax = new XMLHttpRequest(); let self = this; ajax.onreadystatechange = function() { if (this.readyState == 1) { target.innerHTML = "Loading..."; } else if (this.readyState == 4 && this.status == 200) { let text = JSON.parse(this.responseText); target.innerHTML = text.quote; } }; ajax.open("GET", "https://cors-anywhere.herokuapp.com/https://api.kanye.rest", true); ajax.send(); }); button.click(); } } let target = document.querySelector(".quote"); let quote = new KanyaWestTweet( "Kanye", "West", "" ); console.log(quote);
import React, { Component } from "react"; import { Link } from "react-router-dom"; import { connect } from "react-redux"; import { getCurrentProfile, postFavorites, removeFavorites, fetchItinerariesID } from "./../../actions/profileActions"; import { fetchItineraries, fetchItinerariesByCity } from "./../../actions/itinerariesActions"; import { fetchActivityByKey } from "./../../actions/activitiesActions"; import { fetchAxiosComments } from "./../../actions/commentActions"; import Activity from "./../Activity"; import Comments from "./../Comments"; import StarRatingComponent from "react-star-rating-component"; import CardContent from "@material-ui/core/CardContent"; import Grid from "@material-ui/core/Grid"; import Card from "@material-ui/core/Card"; import Icon from "@material-ui/core/Icon"; import Fab from "@material-ui/core/Fab"; import Button from "@material-ui/core/Button"; import Dialog from "@material-ui/core/Dialog"; import DialogActions from "@material-ui/core/DialogActions"; import DialogContent from "@material-ui/core/DialogContent"; import DialogContentText from "@material-ui/core/DialogContentText"; import DialogTitle from "@material-ui/core/DialogTitle"; import Snackbar from "@material-ui/core/Snackbar"; import Fade from "@material-ui/core/Fade"; class ItinCard extends Component { constructor(props) { super(props); this.state = { open: false, isBtn: false, eventId: "", activities: [], itineraries: [], comments: [], errors: {} }; this.addToFav = this.addToFav.bind(this); this.confirmButton = this.confirmButton.bind(this); this.expandOpen = this.expandOpen.bind(this); this.expandClose = this.expandClose.bind(this); } // CLOSE DIALOG dialogClose = () => { this.setState({ open: false }); }; // CLOSE SNACKBAR snackbarClose = () => { this.setState({ snackbar: false }); }; // SAVE TO FAVORITES BUTTON addToFav = async event => { this.setState({ open: true }); let eventTargetId = event; let favData = { favorites: eventTargetId }; let userID = this.props.auth.user.id; await setTimeout(() => { this.props.postFavorites(userID, favData); }, 1500); }; // REMOVE FAV AND CLOSE SNACKBAR handleOpen = event => { this.setState({ open: true, snackbar: false }); let eventTargetId = event; let favData = { favorites: eventTargetId }; this.setState({ favdataid: favData.favorites }); }; // REMOVE FAV - CONFIRM BUTTON confirmButton = async () => { let userID = this.props.auth.user.id; let favData = { favorites: this.state.favdataid }; await setTimeout(() => { this.setState({ open: false, confirm: true, snackbar: true }); }, 1000); if (this.state.confirm === true) { await this.props.removeFavorites(userID, favData.favorites); } }; // OPEN (FETCH) ACTIVITY AND COMMENTS expandOpen(event) { let eventTargetId = event.target.id; this.props.fetchActivityByKey(eventTargetId); this.props.fetchAxiosComments(eventTargetId); this.setState(() => ({ eventId: eventTargetId, isBtn: eventTargetId })); } //CLOSE ACTIVITY AND COMMENTS expandClose() { this.setState(() => ({ eventId: null, isBtn: null })); } render() { const { isAuthenticated } = this.props.auth; const addFavDialog = ( <React.Fragment> <Dialog open={this.state.open} onClose={this.dialogClose} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <DialogTitle id="alert-dialog-title"> {"MYtinerary added to your Favorites"} </DialogTitle> <DialogContent> <DialogContentText id="alert-dialog-description"> This itinerary has been added to your favorites. Go to Favorites page to view and manage your Itineraries. </DialogContentText> </DialogContent> <DialogActions> <Link to="/dashboard" className="gotoFav"> <Fab className="confirmFabButton" variant="extended" size="small" color="primary" onClick={this.dialogClose} > Go To Favorites </Fab> </Link> <Button onClick={this.dialogClose} color="inherit" autoFocus> Close </Button> </DialogActions> </Dialog> </React.Fragment> ); const removeFavDialog = ( <React.Fragment> <Dialog open={this.state.open} onClose={this.dialogClose} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <DialogTitle id="alert-dialog-title"> {"Are you sure you want to delete MYtinerary from your Favorites?"} </DialogTitle> <DialogContent> <DialogContentText id="alert-dialog-description"> Please confirm you want to delete this MYtinerary from your Favorites. </DialogContentText> </DialogContent> <DialogActions> <Fab className="confirmFabButton" variant="extended" size="small" color="primary" onClick={this.confirmButton.bind(this)} > Confirm </Fab> <Button onClick={this.dialogClose} color="inherit" autoFocus> Close </Button> </DialogActions> </Dialog> </React.Fragment> ); const unauthedIcons = ( <React.Fragment> <div className="itinIconpanel"> <Fab variant="round" disabled> <Icon fontSize="large">add_location</Icon> </Fab> </div> </React.Fragment> ); const authedIcons = ( <React.Fragment> <div className="itinIconpanel"> {/* TERNARY CONDITION*/} {this.props.profile.favid.includes(this.props._id) ? ( <React.Fragment> {/* DASHBOARD CONDITION*/} {this.props.history === "/dashboard" ? ( <React.Fragment> {/* DASHBOARD PAGE CONDITION - FAV REMOVE*/} <Fab variant="round"> <Icon value={this.props.title} variant="outlined" fontSize="large" onClick={this.handleOpen.bind(this, this.props._id)} > favorite_border </Icon> {removeFavDialog} </Fab> </React.Fragment> ) : ( <React.Fragment> {/* DASHBOARD PAGE CONDITION - FAV SAVED*/} <Fab variant="round" disabled> <Icon value={this.props.title} fontSize="large"> favorite </Icon> </Fab> </React.Fragment> )} </React.Fragment> ) : ( <React.Fragment> {/* ITIN PAGE CONDITION - ADD TO FAV*/} <Fab variant="round"> <Icon value={this.props.title} fontSize="large" onClick={this.addToFav.bind(this, this.props._id)} > add_location </Icon> {addFavDialog} </Fab> </React.Fragment> )} </div> </React.Fragment> ); return ( <React.Fragment> <div className="itineraryCard"> <Card raised> {/* CARD HEADER */} <Grid container spacing={0}> <Grid item xs={9} sm={6}> <div className="itinCardDiv"> <h2 className="itinCardTitleText">{this.props.title}</h2> <div className="itinCardTitleBy">By: {this.props.author}</div> </div> </Grid> {/* CARD ICONS => TERNARY : AUTHED : UNAUTHED */} <Grid item xs={3} sm={6}> {isAuthenticated ? authedIcons : unauthedIcons} </Grid> </Grid> {/* CARD CONTENT */} <CardContent> <Grid container spacing={0}> <Grid item xs={5} sm={6}> <div className="dashboardImgDiv"> <img alt="profile" src={this.props.authorimage} className="dashboardImg" /> </div> </Grid> <Grid item xs={7} sm={6}> {/* TIME */} <Grid item xs={10}> <div>• Time: {this.props.duration} Hours</div> </Grid> {/* COST */} <Grid item xs={10}> <div>• Cost: {this.props.price}</div> </Grid> {/* LIKES */} <Grid item xs={10}> <div>• Likes: {this.props.likes} </div> </Grid> {/* RATINGS */} <Grid item xs={10}> <div className="starRatingComponentDiv"> • Rating: <StarRatingComponent className="starRatingComponent" name="Rating" starCount={5} value={this.props.ratings} editing={false} /> </div> </Grid> {/* HASHTAGS */} <Grid item xs={12}> <div> • Hashtags:{" "} {this.props.hashtag.map(item => { return ( <React.Fragment key={item + item}> {" "} <Link to={{ pathname: "/hashtag/" + item.toLowerCase().replace("#", ""), state: { hashtag: { item } } }} > <span className="hashtagTags">{item}</span> </Link>{" "} </React.Fragment> ); })} </div> </Grid> </Grid> </Grid> </CardContent> {/* {BUTTON} */} {this.state.eventId === this.props.activitykey ? ( [ <Activity itineraryKey={this.props.activitykey} key={this.props.title} />, <Comments activityKey={this.props.activitykey} key={this.props._id} />, <button className="closeActivityBtn" id={this.props.activitykey} onClick={this.expandClose} key={this.props.title + this.props._id} > Close </button> ] ) : ( <button className="viewActivityBtn " id={this.props.activitykey} onClick={this.expandOpen} key={this.props.title + this.props._id} > Expand </button> )} {/* END OF CARD */} </Card> </div> <Snackbar open={this.state.snackbar} onClose={this.snackbarClose} autoHideDuration={2500} variant="success" TransitionComponent={Fade} ContentProps={{ "aria-describedby": "message-id" }} message={<div className="snackbartext">Favorite Removed!</div>} /> </React.Fragment> ); } } const mapStateToProps = state => { return { itineraries: state.itineraries, profile: state.profile, auth: state.auth, favid: state.favid, activities: state.activities, comments: state.comments, errors: state.errors }; }; export default connect( mapStateToProps, { fetchItineraries, postFavorites, getCurrentProfile, removeFavorites, fetchActivityByKey, fetchAxiosComments, fetchItinerariesID, fetchItinerariesByCity } )(ItinCard);