text
stringlengths
7
3.69M
import React from "react"; import { Redirect, Route, Switch } from "react-router-dom"; import SignIn from "../pages/SignIn/SignIn"; import SignUp from "../pages/SignUp/SignUp"; function UnauthorizedRoutes() { return ( <Switch> <Route exact path="/sign-in" component={SignIn} /> <Route exact path="/sign-up" component={SignUp} /> <Redirect to="/sign-in" /> </Switch> ); } export default UnauthorizedRoutes;
import React, { Component } from 'react'; import Footer from '../../components/Footer'; import Header from '../../components/Header'; import Axios from 'axios'; import { withRouter } from "react-router-dom"; class ProductSetting extends Component { constructor(props) { super(props); this.state = { products: null }; } componentDidMount() { Axios.get("http://localhost:3002/products").then(res => { console.log(res.data); this.setState({ products: res.data }) }) } delProduct(product) { Axios.delete("http://localhost:3002/products/" + product.id).then(res => { Axios.get("http://localhost:3002/products").then(res => { this.setState({ products: res.data }) }) }) } edit(product){ this.props.history.push('/productSetting/edit/'+ product.id) } showProduct() { return this.state.products && this.state.products.map(product => { return ( <div key={product.id} className="col-md-2"> <img className="img-fluid img-thumbnail mb-1" src={require(`../../components/Car.jpg`)} /> {product.productName} <ul> <li> <small> {product.unitPrice + " THB"} </small> </li> </ul> <button className="btn btn-info btn-sm btn-block" onClick={()=> this.edit(product)} >Edit</button> <button className="btn btn-danger btn-sm btn-block" onClick={() => this.delProduct(product)}>Delete</button> </div> ) }) } render() { return ( <div> <Header /> <div className="container-fluid"> <div className="row"> <div className="col-md-4"> <h1>Setting</h1> </div> <div className="col-md-8 text-right"> <button className="btn btn-primary btn-sm mt-3" onClick={()=> this.props.history.push('productSetting/add')}>+Product</button> </div> </div> <hr /> <div className="row"> {this.showProduct()} </div> </div> <Footer /> </div> ); }; } export default withRouter(ProductSetting);
$(document).ready(function() { //refs var container = $('.cds-container'); //container var albumApi = 'https://flynn.boolean.careers/exercises/api/array/music'; //api $.ajax({ url: albumApi, method: 'GET', success: function(data) { var album = data.response; console.log(album); // init handlebar var source = $('#album-template').html(); //refs template var template = Handlebars.compile(source); for (var i = 0; i < album.length; i++) { var copertina = album[i].poster; var titolo = album[i].title; var autore = album[i].author; var anno = album[i].year; var genere = album[i].genre; //object var albumContent = { poster: copertina, title: titolo, author: autore, year: anno, genre: genere } //create template var content = template(albumContent); //push in html container.append(content); } }, error: function(){ console.log('errore'); } }) }); // <-- End Doc Ready
import axios, { ERROR_CODES } from '../../api/config'; //Make GET request for vendors export const REQUEST_VENDORS = 'REQUEST_VENDORS'; //Receive requested vendors export const RECEIVE_VENDORS = 'RECEIVE_VENDORS'; //Notify UI that request has failed export const NOTIFY_VENDOR_REQUEST_FAILURE = 'NOTIFY_VENDOR_REQUEST_FAILURE'; //Dismiss the error message export const DISMISS_VENDORS_REQUEST_ERROR = 'DISMISS_VENDORS_REQUEST_ERROR'; export function requestVendors(){ return { type: REQUEST_VENDORS }; } export function dismissRequestError(){ return { type: DISMISS_VENDORS_REQUEST_ERROR }; } export function receiveVendors(data){ return { type: RECEIVE_VENDORS, data }; } export function notifyVendorsRequestFailure(errorMessage){ return { type: NOTIFY_VENDOR_REQUEST_FAILURE, error: errorMessage }; } export function getVendors(){ return (dispatch, getState) => { dispatch(requestVendors); const authToken = getState().session.userDetails.token; console.log("authToken" + authToken); axios.get('/api/vendors',{ headers: { "Authorization": authToken } }) .then(response => { return dispatch(receiveVendors(response.data)); }) .catch(function(error){ return dispatch(notifyVendorsRequestFailure("Failed to fetch data")); }); } }
var Peepub = require('pe-epub'); var fs = require('fs'); var outputFilename = './book.json'; fs.writeFile(outputFilename, JSON.stringify(book, null, 4), function(err) { if(err) console.log(err); console.log("JSON saved to " + outputFilename); }); var epubJson = require('./book.json'); // see examples/example.json for the specs var myPeepub = new Peepub(epubJson); myPeepub.create('./test.epub') .then(function(filePath){ console.log(filePath); // the same path to your epub file! });
import WordpressFeedPage from './WordpressFeedPage'; export default WordpressFeedPage;
import React from 'react'; import { useSelector } from 'react-redux'; import { Loader, CardGroup } from 'semantic-ui-react'; import { ErrMsg, EventLink } from '../../components'; import { BACKEND } from '../../config'; import { useAPI } from '../../hooks'; const ParticipatedEvent = () => { const { token } = useSelector(state => state.user); const [connection, connect] = useAPI("json"); if (connection.isInit()) { connect( BACKEND + `/event`, "GET", null, { 'authorization': token, 'content-type': "application/json" } ); } if (connection.error) { return <ErrMsg />; } else if (connection.success) { if(connection.response.length === 0) { return <span>You have not participated in any event yet.</span>; } return ( <CardGroup stackable style={{marginTop: "1em"}}> {connection.response.map(({name, _id, begin, reward}) => ( <EventLink key={_id} name={name} id={_id} time={begin} reward={reward} /> ))} </CardGroup> ); } else { return <Loader active={true} />; } } export default ParticipatedEvent;
'use strict'; var gulp = require('gulp'); var connect = require( 'gulp-connect' ); var rjs = require('gulp-requirejs'); var files = [ "./app/scripts/modules/**/**/**/*.js", "./app/scripts/modules/**/**/**/*.html", "./app/scripts/**/**/**/*.js", "./app/scripts/**/**/**/*.html", "./app/scripts/**/**/*.js", "./app/scripts/**/**/*.html", "./app/scripts/**/*.js", "./app/scripts/**/*.html", "./app/scripts/*.js" ]; gulp.task( 'files', function() { gulp.src( files ).pipe( connect.reload() ); }); gulp.task( 'watch', function() { gulp.watch( files, [ 'files' ]); }); gulp.task( 'connect', function() { connect.server({ root: ['app', 'tmp'], port: 9000, livereload: true }); }); gulp.task('requirejsBuild', function() { rjs({ baseUrl: './app/scripts/', out: 'teste.js', paths: { angular: '../bower_components/angular/angular', ocLazyLoad: '../bower_components/oclazyload/dist/ocLazyLoad', lodash: '../bower_components/lodash/dist/lodash', angularUiRoute: '../bower_components/angular-ui-router/release/angular-ui-router', angularAria: '../bower_components/angular-aria/angular-aria', angularAnimate: '../bower_components/angular-animate/angular-animate', angularMaterial: '../bower_components/angular-material/angular-material' }, name: 'config', shim: { angular: { exports: 'angular' }, lodash: { exports: 'lodash' }, ocLazyLoad : { exports : 'ocLazyLoad', deps: ['angular', 'angularUiRoute'] }, angularUiRoute: { exports: 'angularUiRoute', deps: ['angular'] }, angularAria: { exports: 'angularAria', deps: ['angular'] }, angularAnimate : { exports: 'angularAnimate', deps: ['angular'] }, angularMaterial: { exports: 'angularMaterial', deps: ['angular', 'angularAria', 'angularAnimate'] } } }) .pipe(gulp.dest('./dist/')); // pipe it to the output DIR }); gulp.task( 'default', [ 'connect', 'watch']);
import React, { Component } from 'react' import MonacoEditor from 'react-monaco-editor' import './App.css' const prefix = 'json-' const defaultCode = `return json` const flagNames = ['slow', 'simple'] class App extends Component { constructor() { super() this.state = { ...this.load(), result: '' } } load() { const name = window.location.hash.substr(1) || 'default' const fromLocalStorage = JSON.parse(window.localStorage.getItem(prefix + name)) || {} const names = [...window.localStorage] .map((_, i) => localStorage.key(i)) .filter(n => n.startsWith(prefix)) .map(n => n.substr(prefix.length)) const data = { code: fromLocalStorage.code || defaultCode, json: fromLocalStorage.json || '[]', flags: fromLocalStorage.flags || flagNames.reduce((p, c) => ({ ...p, [c]: false }), {}), name, names } if (!data.slow) { data.result = this.run(data) } return data } run({ code, json }) { try { // eslint-disable-next-line var transform = new Function('json', code) return transform(JSON.parse(json)) } catch (e) { return e.toString() } } async runSlow() { //try { const result = await this.run(this.state) this.setState({ result }) //} catch (e) { // this.setState({ result: e.toString() }); //} } componentDidMount() { window.addEventListener('hashchange', e => { console.log('hashchange') this.setState(this.load()) }) } delete(name) { window.localStorage.removeItem(prefix + name) this.setState(this.load()) } render() { const { name, names, code, json, flags, result } = this.state const onMonacoChange = section => newValue => { const data = { code, json, flags } data[section] = newValue window.localStorage.setItem(prefix + name, JSON.stringify(data)) this.setState(this.load()) } const onChange = section => e => { const data = { code, json, flags } data[section] = e.target.value window.localStorage.setItem(prefix + name, JSON.stringify(data)) this.setState(this.load()) } const onCheckedFlag = flagName => e => { console.log('e.target.checked, section:', e.target.checked, flagName) const data = { code, json, flags } data['flags'][flagName] = e.target.checked window.localStorage.setItem(prefix + name, JSON.stringify(data)) this.setState(this.load()) } const options = { selectOnLineNumbers: true, roundedSelection: false, readOnly: false, cursorStyle: 'line', automaticLayout: false } return ( <div className="App"> <main> <header> {names.map(n => ( <span key={n}> [<a href={`#${n}`}>{n}</a>{' '} <button onClick={() => this.delete(n)}> <span role="img" aria-label={`delete ${name}`}> ❌ </span> </button> ]{' '} </span> ))} </header> <h1>{name}</h1> <div className="leftBar"> {flagNames.map(name => ( <span> <label> {name} <input type="checkbox" checked={flags[name]} onChange={onCheckedFlag(name)} /> </label>{' '} </span> ))} </div> <div className="rightBar"> {flags.slow && <button onClick={() => this.runSlow()}>Run</button>} </div> <div className="code"> <fieldset> <legend>Code</legend> {flags.simple ? ( <textarea value={code} onChange={onChange('code')} /> ) : ( <MonacoEditor height="200" language="javascript" value={code} options={options} onChange={onMonacoChange('code')} /> )} </fieldset> </div> <div> <fieldset> <legend>JSON</legend> {flags.simple ? ( <textarea value={json} onChange={onChange('json')} /> ) : ( <MonacoEditor height="500" language="json" value={json} options={options} onChange={onMonacoChange('json')} /> )} </fieldset> </div> <div> <fieldset> <legend>Result</legend> <pre className="Preview"> {flags.simple ? ( JSON.stringify(result, null, ' ') ) : ( <MonacoEditor height="500" language="json" value={JSON.stringify(result, null, ' ')} options={{ ...options, readOnly: true }} /> )} </pre> </fieldset> </div> </main> </div> ) } } export default App
/* flow */ export const IDLESTATUS_AWAY = 'AWAY' export const IDLESTATUS_INACTIVE = 'INACTIVE' export const IDLESTATUS_EXPIRED = 'EXPIRED' export const IDLE_STATUSES = [IDLESTATUS_AWAY, IDLESTATUS_INACTIVE, IDLESTATUS_EXPIRED]
import React, { useState } from "react"; import Filter from "./Filter"; import QuoteMobile from "./QuoteMobile"; import backIcon from "./icons/back.svg"; import plusIcon from "./icons/plus.svg"; const ContentMobile = (props) => { const [contentMobileActivated, setContentMobileActivated] = useState(false); const [nbrAuthorFiltersOn, setNbrAuthorFiltersOn] = useState( props.authorFilters.length ); const [nbrSourceFiltersOn, setNbrSourceFiltersOn] = useState( props.sourceFilters.length ); const nbrFiltersSelected = nbrAuthorFiltersOn + nbrSourceFiltersOn; return ( <div> {!contentMobileActivated && ( <div className="filtersLabelMobile"> <b>{props.language === "fr" ? "Filtres" : "Filters"}</b> <img className="toggleFiltersMobile" title="search" alt="search" type="image" src={plusIcon} width="100%" height="100%" onClick={() => setContentMobileActivated(true)} /> <b> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {props.language === "fr" ? `(${nbrFiltersSelected} selected)` : `(${nbrFiltersSelected} sélectionné${ nbrFiltersSelected > 1 ? "s" : "" })`} </b> </div> )} <div className="contentMobile"> <div className="filtersMobile"> {contentMobileActivated && ( <input className="desactivateFiltersMobile" title="search" alt="search" type="image" src={backIcon} width="100%" height="100%" onClick={() => setContentMobileActivated(false)} /> )} <div style={{ visibility: contentMobileActivated ? "visible" : "hidden", display: contentMobileActivated ? "block" : "none", }} > <Filter display={props.language === "fr" ? "Auteur" : "Author"} values={props.authorFilters} language={props.language} onFilterChange={(authorFilters) => { props.updateAuthorFilters(authorFilters); setNbrAuthorFiltersOn(authorFilters.length); }} /> <Filter display="Book" values={props.sourceFilters} language={props.language} selectedValues={props.sourceFiltersSelected} onFilterChange={(sourceFilters) => { props.updateSourceFilters(sourceFilters); setNbrSourceFiltersOn(sourceFilters.length); }} /> </div> </div> <div className="quotes"> {props.quotes.map((quote, index) => ( <QuoteMobile quote={quote.quote} author={quote.author} source={quote.source} language={quote.language} chapter={quote.chapter} number={quote.number} key={index} /> ))} {props.quotes.length > 0 && !props.isRandomSearch && ( <button type="button" className="moreQuoteButton" onClick={() => props.showMoreQuotes()} disabled={props.allQuotesFetched} > {props.language === "fr" ? "Afficher plus" : "Show more"} </button> )} </div> </div> </div> ); }; export default ContentMobile;
'use strict'; const express = require('express'); const uuid = require('uuid/v4'); const logger = require('./logger'); const BookmarksService = require('./bookmarks-service'); const bookmarkRouter = express.Router(); const bodyParser = express.json(); bookmarkRouter .route('/bookmark') .get((req, res, next) => { const knexInstance = req.app.get('db'); BookmarksService.getAllBookmarks(knexInstance) .then(bookmarks => { res.json(bookmarks); }) .catch(next); }) .post(bodyParser, (req, res) => { const { title, url, description, rating } = req.body; if (!title) { logger.error('Need valid input'); return res.status(400).send('Invalid data'); } const bookmark = { id: uuid(), title, url, description, rating }; bookmarks.push(bookmark); logger.info(`Bookmark with id ${bookmark.id} created`); res .status(201) .location(`http://localhost:8000/bookmark/${bookmark.id}`) .json(bookmark); }); bookmarkRouter .route('/bookmark/:id') .get((req, res, next) => { const knexInstance = req.app.get('db'); BookmarksService.getById(knexInstance, req.params.id) .then(bookmark => { if (!bookmark) { return res.status(404).json({ error: { message: 'Bookmark doesn\'t exist' } }); } res.json(bookmark); }) .catch(next); }) .delete((req, res) => { const id = req.params.id; let index = bookmarks.findIndex(bookmark => bookmark.id === id); bookmarks.splice(index, 1); logger.info(`Bookmark with id ${id} deleted`); res.status(204).end(); }); module.exports = bookmarkRouter;
module.exports = { 1 : { mails: { emailConfirmationSubject: 'Confirmación de correo', emailConfirmationMessage: 'Para confirmar su corre, de clic en el siguiente link:', passwordRecoverSubject: 'Recuperación de contraseña', passwordRecoverMessage: 'Para reestablecer su contraseña, utilice el siguiente codígo:', newDeviceSubject: 'Nuevo dispositivo', newDeviceMessage: 'Para confirmar un nuevo dispositivo, utilice el siguiente codígo:', } }, 2 : { mails: { emailConfirmationSubject: 'Email confirmation', emailConfirmationMessage: 'To confirm the email, click on the next url:', passwordRecoverSubject: 'Password recover', passwordRecoverMessage: 'To set a new password provide the next token:', newDeviceSubject: 'New device', newDeviceMessage: 'To confirm a new device provide the next token:', } } };
// Creates the addCtrl Module and Controller. Note that it depends on the 'geolocation' module and service. var addCtrl = angular.module('addCtrl', ['geolocation', 'gservice', 'Message']); addCtrl.controller('addCtrl', function($scope, $http, $rootScope, geolocation, gservice, Message) { $scope.authData = $rootScope.authData; $scope.messages = Message.all; // $scope.messageText = ''; $scope.currentUser = $rootScope.userData; $scope.currentUserName = $scope.currentUser.username; $rootScope.toggle = function() { $scope.visible = !$scope.visible; } //sets selectedUsersName from gmaps click handler, as clicked markers name // $scope.selectedUsersName = $rootScope.selectedUsersName; //gets all users and sets them to $scope.users $scope.users = $http.get('/users').success(function(result) { $scope.users = result; }); $scope.messagePost = function(message) { Message.create(message); $scope.messageText = ''; }; var coords = {}; var lat = 0; var long = 0; //angularJs-Geolocation in action. html5 verified // Set initial coordinates geolocation.getLocation().then(function(data) { // Set the latitude and longitude equal to the HTML5 coordinates coords = { lat: $scope.currentUser.location[1], long: $scope.currentUser.location[0] }; // console.log(coords); //call refresh to reset map with new coords gservice.refresh(coords.lat, coords.long); }); // Functions // ---------------------------------------------------------------------------- //use $rootscope to $broadcast data back and forth to controller // Get coordinates based on mouse click. When a click event is detected.... $rootScope.$on("clicked", function() { // Run the gservice functions associated with identifying coordinates $scope.$apply(function() { $scope.formData.latitude = parseFloat(gservice.clickLat).toFixed(3); $scope.formData.longitude = parseFloat(gservice.clickLong).toFixed(3); $scope.formData.htmlverified = "No"; }); }); });
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var constants_1 = require("./constants"); var utils_1 = require("./utils"); var BufferBase = /** @class */ (function () { function BufferBase(args, bufferType) { if (args === void 0) { args = { dataOrLength: null, attributes: [], dataType: constants_1.FLOAT, usage: constants_1.STATIC_DRAW }; } this._glContext = null; this._glProgram = null; this._glBuffer = null; this._dataOrLength = ('dataOrLength' in args) ? args.dataOrLength : null; this._attributes = ('attributes' in args) ? args.attributes : []; this._enabledAttributes = this._attributes; this._attributeToLocation = new Map(); this._dataType = ('dataType' in args) ? args.dataType : constants_1.FLOAT; this._usage = ('usage' in args) ? args.usage : constants_1.STATIC_DRAW; this._bufferType = bufferType; this._isInitialized = false; this._flushData = function (context, buffer) { }; this._totalAttributesSize = this._attributes.reduce(function (prev, attr) { return prev + attr.size; }, 0); this._data = null; if (this._dataOrLength !== null) { this.bufferData(this._dataOrLength); } } /** * Send data to the buffer. * @param {TypedArrayLike | number} dataOrLength */ BufferBase.prototype.bufferData = function (dataOrLength) { var _this = this; this._flushData = function (context, buffer) { _this._dataOrLength = dataOrLength; context.bindBuffer(_this._bufferType, buffer); if (typeof dataOrLength === 'number') { var bytes = dataOrLength * utils_1.getBytesPerElementByGlType(_this._dataType); context.bufferData(_this._bufferType, bytes, _this._usage); } else { context.bufferData(_this._bufferType, dataOrLength, _this._usage); _this._data = dataOrLength; } context.bindBuffer(_this._bufferType, null); }; this._flush(); }; BufferBase.prototype.activate = function () { this._enableAttributes(); }; BufferBase.prototype.deactivate = function () { this._disableAttributes(); }; BufferBase.prototype._flush = function () { if (this._glContext !== null && this._glBuffer !== null) { this._flushData(this._glContext, this._glBuffer); } }; /** * Initializes attributes. * Do not call this method manually. * @param {WebGL2RenderingContext} context * @param {WebGLProgram | null} program * @param {Attribute[] | null} attributes * @private */ BufferBase.prototype._initAttributes = function (context, program, attributes) { var _this = this; if (attributes === void 0) { attributes = null; } this._enabledAttributes = this._attributes; if (attributes !== null) { this._enabledAttributes = attributes; } this._attributes.forEach(function (attr) { var location = context.getAttribLocation(program, attr.name); _this._attributeToLocation.set(attr, location); }); var bytesPerElement = utils_1.getBytesPerElementByGlType(this._dataType); var strideBytes = bytesPerElement * this._totalAttributesSize; var offsetBytes = 0; var _loop_1 = function (i) { var attr = this_1._attributes[i]; var location_1 = this_1._attributeToLocation.get(attr); if (this_1._enabledAttributes.find(function (e) { return e.equals(attr); })) { context.enableVertexAttribArray(location_1); context.vertexAttribPointer(location_1, attr.size, this_1._dataType, false, strideBytes, offsetBytes); } offsetBytes += attr.size * bytesPerElement; }; var this_1 = this; for (var i = 0; i < this._attributes.length; i++) { _loop_1(i); } }; BufferBase.prototype._enableAttributes = function () { if (this._glContext !== null) { var context = this._glContext; var program = this._glProgram; context.bindBuffer(this.bufferType, this._glBuffer); this._initAttributes(context, program, this._enabledAttributes); context.bindBuffer(this.bufferType, null); } }; BufferBase.prototype._disableAttributes = function () { var _this = this; if (this._glContext !== null) { var context_1 = this._glContext; this._enabledAttributes.forEach(function (attr) { var location = _this._attributeToLocation.get(attr); context_1.disableVertexAttribArray(location); }); } }; /** * Initializes the buffer. * Do not call this method manually. * @param {WebGL2RenderingContext} context * @param {WebGLProgram | null} program * @param {Attribute[] | null} attributes * @private */ BufferBase.prototype._init = function (context, program, attributes) { if (program === void 0) { program = null; } if (attributes === void 0) { attributes = null; } var buffer = context.createBuffer(); context.bindBuffer(this._bufferType, buffer); if (program !== null) { this._initAttributes(context, program, attributes); } this._glContext = context; this._glProgram = program; this._glBuffer = buffer; this._flush(); // unbind context.bindBuffer(this._bufferType, null); this._isInitialized = true; }; /** * Initializes the buffer. * Do not call this method manually. * @param {WebGL2RenderingContext} context * @param {WebGLProgram | null} program * @param {Attribute[] | null} attributes * @private */ BufferBase.prototype._initOnce = function (context, program, attributes) { if (program === void 0) { program = null; } if (attributes === void 0) { attributes = null; } if (!this.isInitialized) { this._init(context, program, attributes); } }; /** * Creates and return `WebGLVertexArrayObject`. * You don't have to call this method manually. * @param {WebGL2RenderingContext} context * @param {WebGLProgram | null} program * @param {Attribute[] | null} attributes * @returns {WebGLVertexArrayObject} * @private */ BufferBase.prototype._createWebGLVertexArrayObject = function (context, program, attributes) { if (program === void 0) { program = null; } if (attributes === void 0) { attributes = null; } var buffer = this._glBuffer; var vao = context.createVertexArray(); context.bindVertexArray(vao); context.bindBuffer(this._bufferType, buffer); if (program !== null) { this._initAttributes(context, program, attributes); } if (this._dataOrLength !== null && typeof this._dataOrLength === 'number') { context.bufferData(this._bufferType, this._dataOrLength, this._usage); } else if (this._dataOrLength !== null) { context.bufferData(this._bufferType, this._dataOrLength, this._usage); } context.bindBuffer(this._bufferType, null); context.bindVertexArray(null); return vao; }; Object.defineProperty(BufferBase.prototype, "data", { /** * Returns data of the buffer. * @returns {TypedArrayLike | null} */ get: function () { return this._data; }, enumerable: true, configurable: true }); Object.defineProperty(BufferBase.prototype, "dataType", { /** * Returns data type of the buffer. * @returns {number} */ get: function () { return this._dataType; }, enumerable: true, configurable: true }); Object.defineProperty(BufferBase.prototype, "dataCount", { /** * Returns how many data set stored in the buffer. * @returns {number} */ get: function () { if (this.data !== null) { return this.data.length / this._totalAttributesSize; } else { return 0; } }, enumerable: true, configurable: true }); Object.defineProperty(BufferBase.prototype, "usage", { /** * Returns usage of the buffer. * @returns {number} */ get: function () { return this._usage; }, enumerable: true, configurable: true }); Object.defineProperty(BufferBase.prototype, "isInitialized", { /** * Returns if the buffer is initialized. * @returns {boolean} */ get: function () { return this._isInitialized; }, enumerable: true, configurable: true }); Object.defineProperty(BufferBase.prototype, "totalAttributesSize", { /** * Returns total size of attributes. * @returns {number} */ get: function () { return this._totalAttributesSize; }, enumerable: true, configurable: true }); Object.defineProperty(BufferBase.prototype, "bufferType", { /** * Returns type of the buffer. * It can be `XenoGL..ARRAY_BUFFER` or `XenoGL..ELEMENT_ARRAY_BUFFER`. * @returns {number} */ get: function () { return this._bufferType; }, enumerable: true, configurable: true }); Object.defineProperty(BufferBase.prototype, "glBuffer", { /** * Returns `WebGLBuffer` if the buffer is initialized. * Otherwise, throws an error. * @returns {WebGLBuffer} */ get: function () { if (this.isInitialized) { return this._glBuffer; } else { throw new Error('This buffer is not initialized yet.'); } }, enumerable: true, configurable: true }); return BufferBase; }()); exports.BufferBase = BufferBase; /** * ArrayBuffer. */ var ArrayBuffer = /** @class */ (function (_super) { __extends(ArrayBuffer, _super); function ArrayBuffer(args) { if (args === void 0) { args = { dataOrLength: null, attributes: [], dataType: constants_1.FLOAT, usage: constants_1.STATIC_DRAW }; } return _super.call(this, args, constants_1.ARRAY_BUFFER) || this; } return ArrayBuffer; }(BufferBase)); exports.ArrayBuffer = ArrayBuffer; /** * ElementArrayBuffer. */ var ElementArrayBuffer = /** @class */ (function (_super) { __extends(ElementArrayBuffer, _super); function ElementArrayBuffer(args) { if (args === void 0) { args = { dataOrLength: null, attributes: [], dataType: constants_1.UNSIGNED_SHORT, usage: constants_1.STATIC_DRAW }; } return _super.call(this, args, constants_1.ELEMENT_ARRAY_BUFFER) || this; } return ElementArrayBuffer; }(BufferBase)); exports.ElementArrayBuffer = ElementArrayBuffer; /** * UniformBuffer. */ var UniformBuffer = /** @class */ (function (_super) { __extends(UniformBuffer, _super); function UniformBuffer(args) { if (args === void 0) { args = { dataOrLength: null, dataType: constants_1.UNSIGNED_SHORT, usage: constants_1.STATIC_DRAW }; } return _super.call(this, args, constants_1.UNIFORM_BUFFER) || this; } return UniformBuffer; }(BufferBase)); exports.UniformBuffer = UniformBuffer;
/** * @name: 队列queue * @description: 实现数据结构——队列 * @problem: 通过数组实现队列是有问题的,原因在于dequeue这个操作的时间复杂度是O(n) * getSize: 获取栈的元素个数 * isEmpty: 查看栈是否为空 * enqueue: 插入元素 * dequeue: 取出元素 * getFront: 获取队首元素 */ class Queue { constructor () { this.data = [] } getSize () { return this.data.length } isEmpty () { return this.data.length === 0 } enqueue (e) { this.data.push(e) } dequeue () { return this.data.shift() } getFront () { return this.data[0] } }
import styled from 'styled-components'; export const Transition = styled.div` opacity: ${props => props.in ? 1 : 0}; visibility: ${props => props.in ? 'visible' : 'hidden'}; -webkit-transition: all 0.15s ease-in; transition: all 0.15s ease-in; `;
var camelcase = require('camelcase') module.exports = [ { type: 'input', name: 'name', message: 'What is the name of the component?', filter: answer => camelcase(answer, {pascalCase: true}) }, { type: 'list', name: 'type', message: 'What type of component should I create?', choices: ['functional', 'stateful', 'pure'] } ]
/** * Represents the container area for the main page * * @ngdoc module * @name ff.dashboardModule */ angular.module('ff.dashboardModule', []) .config(require('./ff.dashboard.routes.js')) .controller('ffDashboardController', require('./ff.dashboard.controller.js'))
var oTab = document.getElementById("tab"); var tHead = oTab.tHead; var oThs = tHead.rows[0].cells; var tBody = oTab.tBodies[0]; var oRows = tBody.rows; function bindData() { var frg = document.createDocumentFragment(); for (var i = 0; i < data.length; i++) { var cur = data[i]; cur.name = cur.name || "--"; cur.age = cur.age || "25"; cur.score = cur.score || "0"; cur.sex = cur.sex === 0 ? "男" : "女"; var oTr = document.createElement("tr"); for (var key in cur) { var oTd = document.createElement("td"); oTd.innerHTML = cur[key]; oTr.appendChild(oTd); } frg.appendChild(oTr); } tBody.appendChild(frg); frg = null; } bindData();
import React, { useState, useEffect } from 'react'; import { FlatList } from 'react-native'; import Styled from 'styled-components/native'; import BigCatalog from '~Components/BigCatalog'; const Container = Styled.View` height: 300px; margin-bottom: 8px; `; const BigCatalogList = ({ url, onPress }) => { const [ data, setData ] = useState([]); useEffect(() => { fetch(url) .then(response => response.json()) .then(json => { console.log(json); setData(json.data.movies); }) .catch(error => { console.log(error); }); }, []); return ( <Container> <FlatList horizontal={true} pagingEnabled={true} data={data} keyExtractor={( item, index ) => { return `bigScreen-${index}`; }} renderItem={({ item, index }) => ( <BigCatalog id={item.id} image={item.large_cover_image} year={item.year} title={item.title} genres={item.genres} onPress={onPress} /> )} /> </Container> ); }; export default BigCatalogList;
import React, { Component } from "react"; import PropTypes from "prop-types"; import TextField from "@material-ui/core/TextField"; class Location extends Component { render() { return <TextField id="standard-basic" label={this.props.label} />; } } export default Location;
import React, { Component } from 'react' import AvatarEditor from 'react-avatar-editor' import Select from 'react-select' import Dropzone from 'react-dropzone' import 'react-select/dist/react-select.css' import ProfileView from './ProfileView' import { createProfile, uploadPicture, profileToPayload } from './api' import { clinicalSpecialtyOptions, additionalInterestOptions, hospitalOptions } from './options' import AppScreen from './AppScreen' function scaleCanvas(canvas) { const scaled = document.createElement('canvas') const size = 200 scaled.width = size scaled.height = size const context = scaled.getContext('2d') context.drawImage(canvas, 0, 0, size, size) return scaled } export default class EditProfile extends Component { state = { position: { x: 0.5, y: 0.5 }, scale: 1, rotate: 0, width: 200, height: 200, name: '', email: '', image: null, imageUrl: null, imageSuccess: false, uploadingImage: false, affiliations: [], clinicalSpecialties: [], additionalInterests: [], additionalInformation: '', willingShadowing: false, willingNetworking: false, willingGoalSetting: false, willingDiscussPersonal: false, willingResidencyApplication: false, cadence: 'monthly', otherCadence: null, preview: false } handleSelectClinicalSpecialties = specialties => { this.setState({ clinicalSpecialties: specialties.map(specialty => specialty.value) }) } handleSelectAffiliations = affiliations => { this.setState({ affiliations: affiliations.map(affiliation => affiliation.value) }) } handleSelectAdditionalInterests = interests => { this.setState({ additionalInterests: interests.map(interest => interest.value) }) } update = field => ({ target }) => { this.setState({ [field]: target.value }) } updateBoolean = field => ({ target }) => { this.setState({ [field]: target.checked }) } submit = () => { let promise if (!this.state.imageSuccess && this.state.image !== null) { promise = this.saveImage() } else { promise = Promise.resolve(true) } return promise.then(() => { createProfile(this.state) .then(profile => { this.props.authenticate(1) // TODO proper server-given token this.props.history.push(`/profiles/${profile.id}`) }) .catch(error => { console.error(error) }) }) } handleDrop = acceptedFiles => { this.setState({ image: acceptedFiles[0] }) } handleNewImage = e => { this.setState({ image: e.target.files[0] }) } handleScale = e => { const scale = parseFloat(e.target.value) this.setState({ scale }) } saveImage = () => { this.setState({ uploadingImage: true }) const canvas = this.editor.getImage() const scaled = scaleCanvas(canvas) return new Promise(resolve => { scaled.toBlob(blob => uploadPicture(blob).then(response => { this.setState({ imageUrl: response.image_url, imageSuccess: true, uploadingImage: false }) resolve(response) }) ) }) } setEditorRef = editor => { this.editor = editor } rotateRight = () => { const rotation = (90 + this.state.rotate) % 360 this.setState({ rotate: rotation }) } render() { if (this.state.preview) { return ( <div> <ProfileView data={profileToPayload(this.state)} /> <div style={{width: '700px', margin: 'auto'}}> <button style={{marginRight: '1em'}} className="button" onClick={() => { this.setState({ preview: false }) }} > Edit </button> <button className="button" onClick={this.submit}>Publish profile</button> </div> </div> ) } return ( <AppScreen className="edit-profile"> <div className="columns"> <div className="column contact"> <Dropzone onDrop={this.handleDrop} disableClick multiple={false} style={{ width: '200px', height: '200px', marginBottom: '55px' }} > <AvatarEditor ref={this.setEditorRef} borderRadius={100} image={this.state.image} scale={parseFloat(this.state.scale)} width={180} height={180} rotate={this.state.rotate} /> </Dropzone> <div> <input name="newImage" type="file" onChange={this.handleNewImage} /> <input name="scale" type="range" onChange={this.handleScale} min={this.state.allowZoomOut ? '0.1' : '1'} max="2" step="0.01" defaultValue="1" /> <button onClick={this.rotateRight}>Rotate</button> <input value={ this.state.uploadingImage ? 'Uploading...' : 'Save image' } disabled={!this.state.image} type="submit" onClick={this.saveImage} /> {this.state.imageSuccess ? 'Image uploaded' : null} </div> </div> <div className="about" style={{ width: '450px', paddingLeft: '50px' }} > <p>Name</p> <input type="text" name="name" autoComplete="off" className="fullWidth" onChange={this.update('name')} /> <p>Preferred contact email</p> <input name="email" type="email" className="fullWidth" onChange={this.update('email')} /> <p>Hospital Affiliations</p> <Select className="column" multi options={hospitalOptions} value={this.state.affiliations} onChange={this.handleSelectAffiliations} /> <p>Clinical Interests</p> <Select className="column" multi options={clinicalSpecialtyOptions} value={this.state.clinicalSpecialties} onChange={this.handleSelectClinicalSpecialties} /> <p>Additional Interests</p> <Select className="column" multi options={additionalInterestOptions} value={this.state.additionalInterests} onChange={this.handleSelectAdditionalInterests} /> <p>Additional Information</p> <textarea onChange={this.update('additionalInformation')} maxLength={500} style={{ width: '100%', height: '3em', fontSize: '18px' }} /> </div> </div> <div> <div className="expectations"> <h3>Optional expectations</h3> <div className="expectation"> <label> <input type="checkbox" checked={this.state.willingShadowing} onChange={this.updateBoolean('willingShadowing')} /> Will allow shadowing opportunities for mentee(s). </label> </div> <div className="expectation"> <label> <input type="checkbox" checked={this.state.willingNetworking} onChange={this.updateBoolean('willingNetworking')} /> Will help mentee(s) with networking as deemed appropriate. </label> </div> <div className="expectation"> <label> <input type="checkbox" checked={this.state.willingGoalSetting} onChange={this.updateBoolean('willingGoalSetting')} /> Will help mentee(s) with goal setting. </label> </div> <div className="expectation"> <label> <input type="checkbox" checked={this.state.willingDiscussPersonal} onChange={this.updateBoolean('willingDiscussPersonal')} /> Willing to discuss personal as well as professional life. </label> </div> <div className="expectation"> <label> <input type="checkbox" checked={this.state.willingResidencyApplication} onChange={this.updateBoolean('willingResidencyApplication')} /> Willing to advise for residency application. </label> </div> </div> <div className="cadence"> <h3>Meeting Cadence</h3> <label> <input onChange={this.update('cadence')} name="cadence" type="radio" value="biweekly" /> Every 2 weeks </label> <label> <input defaultChecked onChange={this.update('cadence')} name="cadence" type="radio" value="monthly" /> Monthly </label> <label> <input onChange={this.update('cadence')} name="cadence" type="radio" value="quarterly" /> Quarterly </label> <label> <input onChange={this.update('cadence')} name="cadence" type="radio" value="other" ref={el => { this.otherCadenceInput = el }} /> Other <input type="text" onFocus={() => { this.setState({ cadence: 'other' }) this.otherCadenceInput.checked = true }} onChange={this.update('otherCadence')} /> </label> </div> <button className="button" onClick={() => { if (this.state.image !== null && this.state.imageUrl === null) { this.saveImage().then(() => { this.setState({ preview: true }) }) } else { this.setState({ preview: true }) } }} > Preview profile </button> </div> </AppScreen> ) } }
/** * 文件上传服务 * @author heroic */ /** * Module dependencies */ var path = require('path'), Uploader = require('../plugins/uploader'), uploader = new Uploader(), LocalStrategy = require('../plugins/local_uploader'), QiniuStrategy = require('../plugins/qiniu_uploader'), config = require('../config'); /** 加载 LocalStrategy 插件 */ uploader.use(new LocalStrategy({ uploadPath: path.join(process.cwd(), config.media.cwd, config.media.uploadPath) })); /** 加载 QiniuStrategy 插件 */ uploader.use(new QiniuStrategy({ uploadPath: path.join(config.media.cwd, config.media.uploadPath), accessKey: config.uploader.options.accessKey, secretKey: config.uploader.options.secretKey, bucket: config.uploader.options.bucket, domain: config.uploader.options.domain })); /** * 包装一个快捷调用的方法并暴露出去 */ exports.upload = function(files, callback) { uploader.upload(config.uploader.strategy, files, callback); };
/** * 业务工具方法 */ import { getAlbum, getMvDetail } from '@/api' import { isDef, notify } from './common' import router from '@/router' export const createSong = (song) => { const { id, name, img, artists, duration, albumId, albumName, mvId, ...rest } = song return { id, name, img, artists, duration, albumName, url: genSongPlayUrl(song.id), artistsText: genArtistisText(artists), durationSecond: duration / 1000, // 专辑 如果需要额外请求封面的话必须加上 albumId, // mv的id 如果有的话 会在songTable组件中加上mv链接。 mvId, ...rest } } export const genArtistisText = (artists) => { return (artists || []).map(({ name }) => name).join('/') } function genSongPlayUrl (id) { return `https://music.163.com/song/media/outer/url?id=${id}.mp3` } export async function getSongImg (id, albumId) { if (!isDef(albumId)) { throw new Error('need albumId') } const { songs } = await getAlbum(albumId) const { al: { picUrl } } = songs.find(({ id: songId }) => songId === id) || {} return picUrl } // 有时候虽然有mvId 但是请求确实404 所以跳转之前先请求一次 export async function goMvWithCheck (id) { try { console.log('aaaaaaa') await getMvDetail(id) goMv(id) } catch (error) { notify('mv获取失败') } } export function goMv (id) { router.push(`/mv/${id}`) }
/* --------------------------- INTUIT CONFIDENTIAL --------------------------- categorySummary.js Written by Date Jason Harris 08/12/09 Revised by Date Summary of changes Lane Roathe 09-08-10 [S715] TopOnly now expands topLevel sections to show collapsed subs Lane Roathe 09/17/10 [DE1703] get show me state from report filters on init so returning to view doesn't reset to loaded state Lane Roathe 01/24/11 [S876] handling hiding/showing of memo/notes column w/adjustment of account/payee column widths Lane Roathe 01/28/11 [DE2089] updating collapsed states from header so entire section isn't a clickable area Added checks for available function callbacks to prevent exceptions closing open files Copyright 2009-2011 Intuit, Inc All rights reserved. Unauthorized reproduction is a violation of applicable law. This material contains certain confidential and proprietary information and trade secrets of Intuit, Inc. RESTRICTED RIGHTS LEGEND Use, duplication, or disclosure by the Government is subject to restrictions as set forth in subdivision (b) (3) (ii) of the Rights in Technical Data and Computer Software clause at 52.227-7013. Intuit, Inc P.O. Box 7850 Mountain View, CA 94039-7850 ----------------------------- INTUIT CONFIDENTIAL ------------------------- */ // [DE1827] - Lane Roathe - can't use rows.animate because the animation // which hides/shows the rows happens after printing function _ShowHideElements(elements, show, saveStates) { elements.each(function () { this.style.display = show ? '' : 'none'; }); } function _ShowElements(elements, saveStates) { _ShowHideElements(elements, true, saveStates); } function _HideElements(elements, saveStates) { _ShowHideElements(elements, false, saveStates); } function _TransactionEntryElements(tags) { var transactionEntryElements = tags.children(".collapsible").children(".transactionEntry"); return transactionEntryElements; } function _OpenTag(tag, saveStates, transactionEntriesIncluded) { var childElements = tag.children('.collapsible'); if (transactionEntriesIncluded) childElements = childElements.add(_TransactionEntryElements(tag)); _ShowElements(childElements, saveStates); childElements.parent(".tagHeader").each(function() { var element = $(this); if (element.hasClass("closed")) { element.toggleClass("closed").toggleClass("opened"); if( saveStates && window.viewController && window.viewController.SetTableState ) window.viewController.SetTableState(element.attr('quickenid'), "opened"); } }); var tagHeader = tag.children('.tagHeader'); tagHeader.css('-webkit-border-bottom-left-radius', '0px'); tagHeader.css('-webkit-border-bottom-right-radius', '0px'); } function _CloseTag(tag, saveStates) { var childElements = tag.children('.collapsible'); childElements.add(_TransactionEntryElements(tag)); _HideElements(childElements, saveStates); childElements.parent(".tagHeader").each(function() { var element = $(this); if (element.hasClass("opened")) { element.toggleClass("opened").toggleClass("closed"); if( saveStates && window.viewController && window.viewController.SetTableState ) window.viewController.SetTableState(element.attr('quickenid'), "closed"); } }); var tagHeader = tag.children('.tagHeader'); tagHeader.css('-webkit-border-bottom-left-radius', '8px'); tagHeader.css('-webkit-border-bottom-right-radius', '8px'); } function _CloseTransactionEntries(tag, saveStates) { var childElements = _TransactionEntryElements(tag); _HideElements(childElements, saveStates); if (0 == tag.children('.treeCollection').length) { var tagHeader = tag.children('.tagHeader'); tagHeader.css('-webkit-border-bottom-left-radius', '8px'); tagHeader.css('-webkit-border-bottom-right-radius', '8px'); } if (0 == tag.find(".collapsible .collapsible").length) { _CloseTag(tag, saveStates); return; } } function _OpenTags(tags, saveStates, childrenIncluded) { if (0 == tags.length) return; tags.each(function() { _OpenTag($(this), saveStates, true); }); if (childrenIncluded) _OpenTags(tags.find('.tagHeader'), saveStates, childrenIncluded); } function _CloseTags(tags, saveStates, childrenIncluded) { if (0 == tags.length) return; tags.each(function() { _CloseTag($(this), saveStates); }); if (childrenIncluded) _CloseTags(tags.find('.tagHeader'), saveStates, childrenIncluded); } function InitDisclosures() { var tagHeaders = $(".tagHeaderRow"); tagHeaders.each(function() { var tagHeader = $(this).parent(); if( window.viewController && window.viewController.TableState ) { var state = window.viewController.TableState(tagHeader.attr('quickenid'),"opened"); if( state == "opened" ) _OpenTags(tagHeader, false, true); else _CloseTags(tagHeader, false, true); } $(this).click(function(e) { var tagHeader = $(this).parent(); var childrenIncluded = e.altKey; if (tagHeader.hasClass("closed")) _OpenTags(tagHeader, true, childrenIncluded); else if (tagHeader.hasClass("opened")) _CloseTags(tagHeader, true, childrenIncluded); if( window.viewController && window.viewController.SetAttribute ) window.viewController.SetAttribute("showMeMode", "custom"); updateFilterDescription("custom"); return false; }); }); } function DisplaySummary(saveStates) { $('.tagHeader').each(function() { var thisTag = $(this); if (0 == thisTag.parent('.tagHeader').length) { _OpenTag(thisTag, saveStates, false); _CloseTransactionEntries(thisTag, saveStates); } else _CloseTag(thisTag, saveStates); }); } function ShowAll(saveStates) { $('.tagHeader').each(function() { var thisTag = $(this); _OpenTag(thisTag, saveStates, true); }); } function TopOnly(saveStates) { $('.tagHeader').each(function() { var thisTag = $(this); _CloseTag(thisTag, saveStates); if (thisTag.hasClass("topLevel")) _OpenTag(thisTag, saveStates, false); }); } function updateFilterDescription(newValue) { var newState; if (newValue == "summary") newState = "Summary for all categories"; else if (newValue == "showAll") newState = "Details for all categories"; else if (newValue == "topOnly") newState = "Top-level categories only"; else newState = "Custom"; var showMeElement = $('#showMeMode').find('li')[0]; showMeElement.textContent = newState; } function updateShowMeFilter(newValue) { updateFilterDescription(newValue); var selectElement = $("#showMeSelector"); if (selectElement && selectElement.length) { var optionElement = selectElement.find("option[value='" + newValue + "']"); optionElement.attr('selected', 'NO'); optionElement = selectElement.find("option[value='showMe']"); optionElement.attr('selected', 'YES'); } } function UpdateNotesVisibility(showNotes) { $('input[name=showNotes]').attr('checked', showNotes); var notes = $(".note"); if( notes.length ) { var accounts = $(".account"); if( accounts.length ) var accountWidth = accounts[0].offsetWidth; var payees = $(".payee"); if( payees.length ) var payeeWidth = payees[0].offsetWidth; var transAccounts = $(".transAccounts"); if( transAccounts.length ) var transAccountWidth = transAccounts[0].offsetWidth; var transPayees = $(".transPayee"); if( transPayees.length ) var transPayeeWidth = transPayees[0].offsetWidth; if( showNotes ) { notes.show(); accounts.css({ width: 120 }); payees.css({ width: 210 }); transAccounts.css({ width: 160 }); transPayees.css({ width: 170 }); } else { accounts.css({ width: 120 + 60 }); payees.css({ width: 210 + 100 }); transAccounts.css({ width: 160 + 60 }); transPayees.css({ width: 170 + 100 }); notes.hide(); } } } function ShowNotesDidChange(selectElement) { var newValue = selectElement.checked; if( window.viewController && window.viewController.ShowNotesDidChange ) window.viewController.ShowNotesDidChange(newValue); UpdateNotesVisibility(newValue); } function ViewAsDidChange(selectElement, saveStates) { var newValue = selectElement.value; if (newValue == "summary") DisplaySummary(saveStates); else if (newValue == "showAll") ShowAll(saveStates); else if (newValue == "topOnly") TopOnly(saveStates); else return; updateShowMeFilter(newValue); if( window.viewController && window.viewController.ShowMeModeDidChange ) window.viewController.ShowMeModeDidChange(newValue); } function ShowMeSetup() { var showNotes = (window.viewController ? window.viewController.ShowNotesState() : "true"); if( showNotes == "false" ) UpdateNotesVisibility(false); var newValue = (window.viewController ? window.viewController.GetAttribute("showMeMode") : "showAll"); updateShowMeFilter(newValue); }
// ===================== // provider list // ===================== // +function($){ // // provider.list = { // ====================================================================== // Emoji // emoji: { selector: 'emoji', callback: 'initEmojione', css: '', js: 'emojione/emojione.min.js', }, iconMaterial: { selector: '$ .material-icons', css: 'material-icons/css/material-icons.css', }, animate: { selector: '$ .animated', css: 'animate/animate.min.css', }, vuejs: { selector: 'vuejs', js: 'vuejs/vue.min.js', }, sweetalert: { selector: 'sweetalert', callback: 'initSweetalert2', css: 'sweetalert2/sweetalert2.min.css', js: 'sweetalert2/sweetalert2.min.js', }, } }(jQuery);
import Link from '@/components/mdx/Link' const PostNavigation = ({ next, prev }) => { return ( <div className="divide-gray-200 text-sm font-medium leading-5 dark:divide-gray-700"> {(next || prev) && ( <div className="flex justify-between py-4"> {prev && ( <div> <h2 className="text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400"> Previous Article </h2> <div className="text-primary-500 hover:text-primary-600 dark:hover:text-primary-400"> <Link href={`/blog/${prev.slug}`}>{prev.title}</Link> </div> </div> )} {next && ( <div> <h2 className="text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400"> Next Article </h2> <div className="text-primary-500 hover:text-primary-600 dark:hover:text-primary-400"> <Link href={`/blog/${next.slug}`}>{next.title}</Link> </div> </div> )} </div> )} </div> ) } export default PostNavigation
/** * @name JSON Editor * @description JSON Schema Based Editor * Deprecation notice * This repo is no longer maintained (see also https://github.com/jdorn/json-editor/issues/800) * Development is continued at https://github.com/json-editor/json-editor * For details please visit https://github.com/json-editor/json-editor/issues/5 * @version {{ VERSION }} * @author Jeremy Dorn * @see https://github.com/jdorn/json-editor/ * @see https://github.com/json-editor/json-editor * @license MIT * @example see README.md and docs/ for requirements, examples and usage info */ (function() {
const chromium = require('chrome-aws-lambda'); const { eagateLogin, eagateLogout } = require('./module/eagate'); const { doJanken } = require('./module/janken'); const doEvent = async (event) => { const browser = await chromium.puppeteer.launch({ args: chromium.args, defaultViewport: chromium.defaultViewport, executablePath: await chromium.executablePath, headless: false, // default is true }); await eagateLogin(browser); await doJanken(browser); await eagateLogout(browser); await browser.close(); return { statusCode: 200, body: JSON.stringify( { message: 'Go Serverless v1.0! Your function executed successfully!', input: event, }, null, 2, ), }; // Use this code if you don't use the http event with the LAMBDA-PROXY integration // return { message: 'Go Serverless v1.0! Your function executed successfully!', event }; }; module.exports.doEvent = doEvent;
import axios from 'axios'; import { FETCH_POSTS, CREATE_POST, GET_POST, DELETE_POST } from './types'; const ROOT_URL = 'http://reduxblog.herokuapp.com/api'; const API_KEY = '?key=fdgfh3tf36'; export const fetchPosts = () => { const request = axios.get(`${ROOT_URL}/posts${API_KEY}`); return { type: FETCH_POSTS, payload: request }; }; export const createPost = (values, callback) => { const request = axios .post(`${ROOT_URL}/posts${API_KEY}`, values) .then(() => callback()); //adding a callback so that we can redirect to home once the user click on submit - this.props.history.push('/'); in PostsNew.js return { type: CREATE_POST, payload: request }; }; export const getPost = id => { const request = axios.get(`${ROOT_URL}/posts/${id}${API_KEY}`); return { type: GET_POST, payload: request }; }; export const deletePost = (id, callback) => { const request = axios .delete(`${ROOT_URL}/posts/${id}${API_KEY}`) .then(() => callback()); return { type: DELETE_POST, payload: id }; };
const router = require("express").Router(); const { response } = require("express"); const userController = require("../../controllers/userController"); const User = require("../../models/user.js"); //login route router.post("/",async (req,res) => { console.log(req.body); console.log("you're in api user / to create a post"); try { const userData = await User.create({ email: req.body.email, firstName: req.body.firstName, lastName: req.body.lastName, password: req.body.password, }); req.session.save(() => { console.log(userData); req.session.user_id = userData._id; req.session.loggedIn = true; console.log("req.session.user_id" + req.session.user_id); res.status(200).json(userData); console.log("You made it through the sign-in user route"); }); } catch (err) { console.log(err); res.status(400).json(err); } }); //route to find 1 user router.route("/get-user").get(userController.find); //route to update and add a new project in progress router.route("/new-project").put(userController.update); //route to update & add a completed project router.route("/completed-project").put(userController.updateCompletedProject); //route to remove project in progress // router.route("/remove").post(userController.destroyProjectInProgress); module.exports = router; // router.post("/", async (req, res) => { // console.log(req.body); // console.log("you're in api user / to create a post"); // try { // const userData = await User.create({ // email: req.body.email, // firstName: req.body.firstName, // lastName: req.body.lastName, // password: req.body.password, // }); // req.session.save(() => { // req.session.user_id = userData.user_id; // req.session.loggedIn = true; // res.status(200).json(userData); // console.log("You made it through the sign-in user route"); // }); // } catch (err) { // console.log(err); // res.status(400).json(err); // } // }); // .post("/login", ({body}, res) => { // const user = new User(body); // user.setFullName(); // user.lastUpdatedDate(); // User.create(user) // .then(dbUser => { // res.json(dbUser); // }) // .catch(err => { // res.json(err); // }); // }); // router // .route("/") // .get(userController.findAll); // router.post("/submit", ({body}, res) => { // const user = new User(body); // user.setFullName(); // user.lastUpdatedDate(); // User.create(user) // .then(dbUser => { // res.json(dbUser); // }) // .catch(err => { // res.json(err); // }); // });
module.exports = { templates: { path: __dirname + '/html/' }, mime_type: { js: 'text/javascript', css: 'text/css' } };
$(window).on( 'load', function() { var uname = null; var pass = null; var dab = null; var mt = null; $(document).on( 'click', '#butt', function() { uname = $('#uname').val(); pass = $('#pass').val(); if (uname, pass != "") { } else { alert("Enter the value"); } var url = "/Mysql/Mysql?operation=getdb&uname=" + uname + "&pass=" + pass; $.ajax(url).done(function(result) { var rs = JSON.parse(result); if ($(".first").length > 0) { $(".first").remove(); } var div1 = document.createElement("div"); document.body.appendChild(div1); div1.setAttribute("class", "first"); var table = document.createElement("table"); var th = document.createElement("th"); th.setAttribute("class", "row header blue"); table.appendChild(th); $(th).append("Databases") $(div1).append(table); for (var i = 0; i < rs.length; i++) { var tr = document.createElement("tr"); table.appendChild(tr); tr.setAttribute("id", "db"); tr.setAttribute("class", "row") $(tr).append(rs[i]); } }).fail(function(result) {}) }); $(document).on( 'click', '#db', function() { uname = $('#uname').val(); pass = $('#pass').val(); dab = $($(this)[0]).text(); var url = "/Mysql/Mysql?operation=gettable&uname=" + uname + "&pass=" + pass + "&dab=" + dab; $.ajax(url).done(function(result) { var rs = JSON.parse(result); if ($(".second").length > 0) { $(".second").remove(); } var div2 = document.createElement("div"); document.body.appendChild(div2); div2.setAttribute("class", "second"); var table = document.createElement("table"); var th = document.createElement("th"); table.appendChild(th); th.setAttribute("class", "row header blue"); $(th).append("Tables in " + dab) div2.appendChild(table); for (var i = 0; i < rs.length; i++) { var tr = document.createElement("tr"); table.appendChild(tr); tr.setAttribute("id", "tableName"); tr.setAttribute("class", "row"); $(tr).append(rs[i]); } }).fail(function(result) {}) }); $(document).on( 'click', '#tableName', function() { uname = $('#uname').val(); pass = $('#pass').val(); tableName = $($(this)[0]).text(); var url = "/Mysql/Mysql?operation=ssft&uname=" + uname + "&pass=" + pass + "&dab=" + dab + "&tableName=" + tableName; $.ajax(url).done(function(result) { var response = JSON.parse(result); var columns = response.columnName; if ($(".third").length > 0) { $(".third").remove(); } var table = "<div class=third><h3>" + tableName + " </h3><table>"; for (var i = 0; i < columns.length; i++) { table += "<th class=\"green\">" + columns[i] + "</th>" } table += "</div>" var rowCount = response.keys.length; for (var i = 0; i < rowCount; i++) { var row = response['r' + i]; table += "<tr class=row>" for (var j = 0; j < columns.length; j++) { table += "<td class=td>" + row[j] + "</td>" } table += "</tr>"; } $("#table").append(table); }).fail(function(result) { }) }); });
var hbs = require('express-hbs'); var express = require('express'); var fs = require('fs'); var recursion = require('./recursion.js'); var app = express(); app.set('view engine', 'hbs'); app.set('views', __dirname + '/views'); app.engine('hbs', hbs.express3({ partialsDir: __dirname + '/views/partials' })); var colors = {}; hbs.registerHelper('color', function() { return 'the ' + this + ' is ' + colors[this]; }); app.get('/', function(req, res){ colors = { turtle : 'green', giraffe : 'yellow', flamingo: 'pink' }; var content = recursion.listFiles("/Somnath/nodejs-ws/helloworld.js"); console.log("returned contents" + content); var data = {animals:['flamingo','turtle','giraffe']} console.log("Hello "+data) res.render('index', data); }); app.get('/listDir', function(req, res){ colors = { turtle : 'green', giraffe : 'yellow', flamingo: 'pink' }; res.render('files', { animals: ['flamingo', 'turtle'] }); }); module.exports = app;
exports.install = function (Vue, options) { Vue.prototype.$success = function (msg) { this.$notify({ title: '成功', message: msg, type: 'success', duration: 2000 }) } Vue.prototype.$error = function (msg) { this.$notify({ title: '失败', message: msg, type: 'error', duration: 2000 }) } }
const express = require("express"); const MessageController = require("../controllers/MessageController"); const ProductController = require("../controllers/ProductController"); const BasketController = require("../controllers/BasketController"); const OrderController = require("../controllers/OrderController"); const router = express.Router(); router.post("/message/sendMessage", MessageController.sendMessage); router.get("/message/getAllMessages", MessageController.getAllMessages); router.get("/product/:category/:productID", ProductController.getSingleProduct); router.get("/product/getAllCategories", ProductController.getAllCategories); router.get("/product/:category", ProductController.getAllOfSingleCategory); router.post("/basket/addProduct", BasketController.addProductToBasket); router.get("/basket/getBasket", BasketController.getBasket); router.post("/order/sendOrder", OrderController.sendOrder); module.exports = router;
const express = require('express') const router = express.Router(); //FutsalCourts model const Ground = require('../../../models/groundModel'); //Get Futsal Courts from api/futsalCourts router.get('/',(req,res)=>{ Ground.find() .then(Ground=> res.json(Ground)) }) //Post Futsal Courts to api/futsalcourts router.post('/',(req,res)=>{ const newFutsalCourts = new FutsalCourts({ Name: req.body.Name, Address: req.body.Address, ContactNo: req.body.ContactNo, Email: req.body.Email, }); newFutsalCourts.save() .then(FutsalCourts =>res.json(FutsalCourts)); }) module.exports = router;
'use strict'; /* JavaScript will go here */ console.log("Hello world!"); //System.out.println var message = "Hello World!"; message = "haha"; console.log(message); //Make a new string variable for the value "The iSchool is my school" var school = "The iSchool is my school"; //Log out the string console.log(school); //Convert the string to upper case, replacing the previous string //Log out the changed variable school = school.toUpperCase(); console.log(school); //Use the substring method to extract chars 2 through 10 (inclusive) //into a new variable, and log that variable var sub = school.substring(2, 11); console.log(sub); //Use the indexOf method to see if the word "cool" is in your string var index = school.indexOf("cool"); console.log(index >= 0); //Declare a new variable `rect` that represents a rectangle //This should be an Object with properties: // x-coordinate of 30, y-coordinate of 50 // width of 100, height of 50 var rect = { x:30, y:50, width:100, height:50 }; //Log out the rectangle's starting position (as "30, 50") console.log(rect.x + ", " + rect.y); //Log out the rectangle's area console.log(rect.width * rect.height); //"Move" the rectangle to the right by 20 and up by 10 //by changing its properties rect.x = rect.x + 20; rect.y = rect.y - 10; //Log out the rectangle's new position console.log(rect.x + ", " + rect.y); console.log(rect); //Declare a variable `circle` that represents a circle //This should be an Object with properties: // center-x-coord of 50, center-y-coord of 50 // radius of 35 var circle = {centerX:50, centerY:50, r:35}; //Declare a variable `shapes` that represents a list of shapes //The list should contain the rectangle and the circle var shapes = [rect, circle]; console.log(shapes); //Implement a function `getArea()` that takes as a //parameter an object representing a circle (like //from the last exercise) and returns the area of //that circle. // Area calculated as is π*(radius^2) function getArea(cir) { return cir.r * cir.r * Math.PI }; console.log(getArea(circle)); //HINTS: // 1. Pi is defined in the Math class // 2. ^ is not an exponential operator! //The area of your circle should be 3848.451 var numbers = [2,0,6,6,8,5,1,6,2,2]; //Use a forEach loop to sum up the numbers //in the array. Log out this sum. var sum = 0; var sumUp = function(nums) { sum += nums; } numbers.forEach(sumUp); console.log(sum); //Use a forEach loop to find the biggest //number in the array. Log out this number. var big = numbers[0]; var biggest = function(nums) { if (big < nums) { big = nums; } } numbers.forEach(biggest); console.log(big); var max = numbers[0]; numbers.forEach( function(nums) { if (nums > max) { max = nums; } } ); console.log(max);
import * as serve from './server' class PotluckRecipeApi { static createPotluckRecipes(recipeIds) { //take an array of recipe IDs and a potluckid const request = new Request(`${serve.PRODUCTION_SERVER}/potluck_recipes`, { method: 'POST', headers: new Headers({ 'Content-Type': 'application/json', 'Authorization': `Bearer ${sessionStorage.jwt}`, }), body: JSON.stringify({potluck_recipes: {recipe_ids: recipeIds.selectedIds, potluck_id: recipeIds.potluck_id}}) }); return fetch(request).then(response => { return response.json(); }).catch(error => { return error; }); } } export default PotluckRecipeApi
module.exports = angular .module('cpApp', ['ui.router']) .run(function($state) { }); require('./index.html'); require('../../node_modules/daterangepicker/daterangepicker.css'); require('./style.sass'); require('./main/main.controller'); require('./routing.config');
'use strict'; var assert = require("chai").assert , linearRegression = require("../lib/everpolate.js").linearRegression describe('Linear regression function', function () { var xValues = [0, 1, 2, 3, 4, 5] , yValues = [2, 3, 4, 5, 6, 7] , regression = linearRegression(xValues, yValues) it('Returns an object with slope, intercept and rSquared properties', function(){ assert.strictEqual(regression.slope, 1) assert.strictEqual(regression.intercept, 2) assert.strictEqual(regression.rSquared, 1) }) it('Returns a function which computes regression at a given x-value', function () { assert.deepEqual(regression.evaluate(2), [4]) }) it('Returns a function which computes regression at a set of x-values', function () { assert.deepEqual(regression.evaluate([2, 3.5]), [4, 5.5]) }) })
/* Noble characteristic notifcation example This example uses Sandeep Mistry's noble library for node.js to subscribe to a characteristic that has its notify property set. The startScanning function call filters for the specific service you want, in order to ignore other devices and services. For a peripheral example that works with this see the Arduino BLEAnalogNotify example in this repository created 2 Mar 2015 modified 5 Mar 2015 by Tom Igoe with much advice from Sandeep Mistry and Don Coleman */ var noble = require('noble'); //noble library var targetService = 'fff0'; // the service you want // The scanning function function scan(state){ if (state === 'poweredOn') { // if the radio's on, scan for this service noble.startScanning([targetService], false); console.log("Started scanning"); } else { // if the radio's off, let the user know: noble.stopScanning(); console.log("Is Bluetooth on?"); } } // the main discovery function function findMe (peripheral) { console.log('discovered ' + peripheral.advertisement.localName); peripheral.connect(); // start connection attempts // called only when the peripheral has the service you're looking for: peripheral.on('connect', connectMe); // the connect function. This is local to the discovery function // because it needs the peripheral to discover services: function connectMe() { noble.stopScanning(); console.log('Checking for services on ' + peripheral.advertisement.localName); // start discovering services: peripheral.discoverSomeServicesAndCharacteristics(['fff0'],['fff1'], exploreMe); } // when a peripheral disconnects, run disconnectMe: peripheral.on('disconnect', disconnectMe); } // the service/characteristic exploration function: function exploreMe(error, services, characteristics) { console.log('services: ' + services); console.log('characteristics: ' + characteristics); for (c in characteristics) { characteristics[c].notify(true); // turn on notifications // whenever a notify event happens, get the result. // this handles repeated notifications: characteristics[c].on('read', listenToMe); } } // the notification read function: function listenToMe (data, notification) { if (notification) { // if you got a notification var value = data.readIntLE(0); // read the incoming buffer as a float console.log('value: ' + value); // print it } } function disconnectMe() { console.log('peripheral disconnected'); // exit the script: process.exit(0); } /* ---------------------------------------------------- The actual commands that start the program are below: */ noble.on('stateChange', scan); // when the BT radio turns on, start scanning noble.on('discover', findMe); // when you discover a peripheral, run findMe()
var db = require('../../models/DB_InitTest.js'); var testModel = require('../../models/TestModel.js'); var isTesting = false; module.exports.isTesting = function(){ return isTesting; }; module.exports.initTestDB = function(callback){ isTesting = true; db.createMsgInfoTableForTest(function(result){ if(!result.status){ callback({statusCode: 500, desc: result.desc}); return; }else{ callback({statusCode: 200, desc: "create database for testing successed."}); } }); }; module.exports.putPublicMessage = function(msg, callback){ testModel.savePublicMessage(msg.content, msg.author, msg.messageType, msg.target, msg.postedAt, function(result){ if(!result.status){ callback({statusCode: 500, desc: result.desc}); return; }else{ callback({statusCode: 200, desc: 'save public message successed.'}); return; } }); }; module.exports.getPublicMessages = function(callback){ testModel.getPublicMessages(function(result){ if(!result.status){ callback({statusCode: 500, msglist: null, desc: result.desc}); return; }else{ callback({statusCode: 200, msglist: result.msgs, desc: 'get public message successed.'}); return; } }); }; module.exports.finishTest = function(callback){ isTesting = false; db.destoryTable(function(result){ if(!result.status){ callback({statusCode: 500, desc: result.desc}); return; }else{ callback({statusCode: 200, desc: 'destory table successed.'}); return; } }); };
$(function() { $.cookie('test_cookie'); var cookie = $.cookie('test_cookie'); if(cookie == 1) { //cookieが保存されていたらアラートを表示 alert('cookieがあります'); } else { //cookieが保存されていなかったらモーダルを表示 $.magnificPopup.open({ items: {src: '#modal'}, type: 'inline', closeOnBgClick:true }) } //追加ボタンでcookieを保存 $('.add').on('click',function() { $.cookie('test_cookie',1,{expires: 183,}); }) //削除ボタンでcookieを削除 $('.remove').on('click',function() { $.removeCookie('test_cookie'); }) //閉じるボタンでモーダルを閉じる $('.closeBtn').on('click',function() { $('#modal').magnificPopup('close'); }) });
var SELECTOR_ADD_OBJECT_BTN = '.top-section-home .btn.btn-primary'; var SELECTOR_ADD_OBJECT_FORM_TITLE = '.modal-content .title input[name=title]'; var SELECTOR_MODAL_SUBMIT_BTN = '.modal-footer .btn.btn-primary'; module.exports = { load: function() { var client = this.client; return this.client .url(function(currentUrl) { if (currentUrl.value !== client.globals.urls.HOME_URL) { return client .cLog('HomePage.load()') .url(client.globals.urls.HOME_URL) .waitForElementNotPresent('.spinner'); } else { client.cLog('HomePage already at home page') } }) ; }, createObject: function(objectName) { return this.client .cLog('HomePage.createObject(' + objectName + ')') .moveToElement(SELECTOR_ADD_OBJECT_BTN, 10, 10) .click(SELECTOR_ADD_OBJECT_BTN) .assert.elementPresent('.modal-title', 'Should show modal') .assert.containsText('.modal-title', 'Add Object', 'Modal title shoul be "Add object"') .click(SELECTOR_ADD_OBJECT_FORM_TITLE) .setValue(SELECTOR_ADD_OBJECT_FORM_TITLE, objectName) .moveToElement(SELECTOR_MODAL_SUBMIT_BTN, 10, 10) .click(SELECTOR_MODAL_SUBMIT_BTN) .waitForElementNotPresent('.spinner') .waitForElementPresent('.info-block-text h2 i') .assert.urlMatch(/objects\/object\/\d+\/description/, "Should be redirected into object page") .assert.elementPresent('.info-block-text h2 i') .assert.containsText('.info-block-text h2 i', objectName, 'Element for object "' + objectName + '" was found') ; }, searchObject: function(objectName) { var enter = ['\uE006']; return this.client .cLog('HomePage.searchObject(' + objectName + ')') .moveToElement('#sidebar input.search', 10, 10) .setValue('#sidebar input.search', objectName + '\n') .pause(500) .keys(enter) .pause(500) .waitForElementNotPresent('.spinner') ; }, createSection: function(sectionName) { return this.client .cLog('HomePage.createSection(' + sectionName + ')') .click('.top-section-home .pull-right .btn:first-of-type') .assert.elementPresent('.modal-content', "Should open modal") .click('.modal-body input[name=name]') .setValue('.modal-body input[name=name]', sectionName) .click('.modal-footer .btn-primary') .waitForElementNotPresent('.spinner') .assert.jqueryExists('h2:contains("' + sectionName + '"):visible') ; }, createGroup: function(groupName, groupDescription) { groupDescription = groupDescription || ''; return this.client .cLog('HomePage.createGroup(' + groupName + ')') .click('.top-section-home .pull-right .btn:nth-child(2)') .assert.elementPresent('.modal-content', "Should open modal") .click('.modal-body input[name=name]') .setValue('.modal-body input[name=name]', groupName) .click('.modal-body input[name=description]') .setValue('.modal-body input[name=description]', groupDescription) .click('.modal-footer .btn-primary') .waitForElementNotPresent('.spinner') .assert.jqueryExists('h4:contains("' + groupName + '"):visible') ; }, removeSection: function(sectionName) { var jqSelector = 'h2:contains("' + sectionName + '") + .btn-wrap .btn:contains("Delete Section")'; var client = this.client; return this.client .cLog('HomePage.removeSection(' + sectionName + ')') .execute(function() { // patch for phaantomjs // todo: create compatibility file window.confirm = function() { return true; }; window.alert = function() { return true; }; }) .pause(500) .jqueryClick(jqSelector) .pause(500) .acceptAlert() .assert.jqueryExists('!' + jqSelector) ; }, removeGroup: function(groupName) { var jqSelector = 'a[href^="/group"] h4:contains("' + groupName + '")'; var client = this.client; return this.client .cLog('HomePage.removeGroup(' + groupName + ')') .jqueryClick(jqSelector) .waitForElementNotPresent('.spinner') .waitForElementPresent('.top-section .btn') .execute(function() { // patch for phantomjs // todo: create compatibility file window.confirm = function() { return true; }; window.alert = function() { return true; }; }) .pause(500) // todo: add waitForToggleElement - to wait while element will be present and then while it be removed .jqueryClick('.top-section .btn:contains("Delete Group")') .pause(500) .acceptAlert() .waitForElementNotPresent('.spinner') .url(function(currentUrl) { this.assert.equal(currentUrl.value, client.globals.urls.HOME_URL, 'After removing group should be redirected into home page'); }) .jqueryElement(jqSelector, function(el) { this.assert.equal(el, null, 'Element for group "' + groupName + '" was not found at page'); }) ; }, getSectionsList: function(callback) { var self; return this.client .cLog('HomePage.getSectionsList') .execute(function() { var ret = [], section; $('.subtitle').each(function(sectionNum, sectionEl) { $se = $(sectionEl); ret.push(section = { title: $se.find('h2').text(), groups: [] }); $se.next('.row').find('article').each(function(groupNumber, groupEl) { $ge = $(groupEl); section.groups.push({ title: $.trim($ge.find('h4').text()), objectsNumber: parseInt($.trim($ge.find('.meta b').text())), id: ($ge.find('a[href^="/group"]').attr('href') || '').replace('/group/', '') }); }); }); return ret; }, [], function(result) { callback.call(self, result.value); }); } }
db.tareas.insert({ title : 'establecer requisitos', description: 'requisitos del proyecto definidos y consensuados con cliente', status : 'done', tags : ['desarrollo','diseño','marketing','finanzas'] }); db.tareas.insert({ title : 'presupuestar', description: 'presupuesto acordado y cerrado', status : 'done', tags : ['desarrollo','diseño','marketing','finanzas'] }); db.tareas.insert({ title : 'comprar dominio', description: 'estudio de dominio y compra', status : 'done', tags : ['desarrollo','finanzas'] }); db.tareas.insert({ title : 'desarrollo front', description: 'html5/css3/angular', status : 'review', tags : ['desarrollo','diseño','marketing'] }); db.tareas.insert({ title : 'desarrollo back', description: 'desarrollo en node', status : 'doing', tags : ['desarrollo'] }); db.tareas.insert({ title : 'implementación', description: 'juntar todas las piezas', status : 'doing', tags : ['desarrollo','diseño'] }); db.tareas.insert({ title : 'test', description: 'funciona?', status : 'doing', tags : ['desarrollo','diseño','marketing'] }); db.tareas.insert({ title : 'revision SEO', description: 'Sin SEO y viralización no somos nadie', status : 'todo', tags : ['desarrollo','diseño','marketing'] }); db.tareas.insert({ title : 'vacaciones pre lanzamiento', description: 'si llegamos a la fecha, vacaciones', status : 'todo', tags : ['desarrollo'] }); db.tareas.insert({ title : 'lanzamiento', description: 'party hard.', status : 'todo', tags : ['desarrollo','diseño','marketing','finanzas'] }); db.tareas.insert({ title : 'mantenimiento', description: 'no caer y crecer', status : 'todo', tags : ['desarrollo','diseño','marketing','finanzas'] });
import React from 'react'; import PropTypes from 'prop-types'; import LinearGradient from 'react-native-linear-gradient'; const GradientBackground = ({ children, style, error }) => ( <LinearGradient style={{ flex: 1, ...style }} colors={error === true ? ['#F90000', '#FF4000'] : ['#0090FF', '#60DFDE']} > {children} </LinearGradient> ); GradientBackground.propTypes = { children: PropTypes.any, error: PropTypes.bool, }; GradientBackground.defaultProps = { error: false, }; export default GradientBackground;
define(['apps/system3/demo/demo.controller'], function (app) { app.controller("demo.controller.typography", function ($scope) { $scope.$watch("$viewContentLoaded", function () { }) }); });
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import WidgetList from 'components/dashboard/button/widgetList'; import ButtonList from 'containers/dashboard/button/buttonList'; import FontAwesome from 'react-fontawesome'; import { fetchWidgets } from 'actions/dashboard/widgetActions'; import { getAllWidgets, getWidgetButtons } from 'reducers/dashboard/widgetReducer'; import style from '../../../../assets/stylesheets/dashboard/button.scss'; import spinner from '../../../../assets/img/gears.gif'; class ButtonBoard extends Component { constructor(props) { super(props); this.state = { widgetMode: true, widgetId: null } } componentDidMount(){ // this has to check first if we exec before the fetchWidgets this.props.fetchWidgets(); } showWidgetList() { this.setState({ widgetMode: true, widgetId: null }); } widgetSelected(widgetId) { this.setState({ widgetId, widgetMode: false }) } renderSpinner() { let important = { backgroundImage: `url("${spinner}")`, width: '160px', height: '160px', marginTop: '150px', marginLeft: '200px' }; return <div className="row col-lg-12" style={ important }></div>; } renderWidgetList() { if(this.props.isFetching) { return this.renderSpinner(); } else { if(this.state.widgetMode) { return <WidgetList widgets={ this.props.widgets } widgetSelected={ (widgetId) => this.widgetSelected(widgetId) }/>; } else { return <ButtonList widgetId={ this.state.widgetId } buttonList={ this.props.buttons }/>; } } } render() { return ( <div className="button-board"> <div className="row"> <div className="col-lg-12 headline"> <h5> Choose the widget and set the tag in the button </h5> </div> <div className="col-lg-1"> { !this.state.widgetMode && <FontAwesome name="chevron-circle-left" size="2x" onClick={ () => this.showWidgetList() } className="back-button"/> } </div> <div className="col-lg-10"> { this.renderWidgetList() } </div> </div> </div> ); } } ButtonBoard.PropTypes = { fetchWidgets: React.PropTypes.func.isRequired, widgets: React.PropTypes.func.isRequired, isFetching: React.PropTypes.bool.isRequired }; function mapDispatchToProps(dispatch) { return bindActionCreators({ fetchWidgets }, dispatch); } function mapStateToProps(state) { return { isFetching: state.dashboard.widgets.isFetching, widgets: getAllWidgets(state.dashboard.widgets) } } export default connect(mapStateToProps, mapDispatchToProps)(ButtonBoard);
'use strict'; angular.module('beerMeApp') .controller('QuestionnaireCtrl', function ($scope, $routeParams, likeButton, Questionnaire, $location) { Questionnaire.counter = 0; console.log('counter = ', Questionnaire.counter) $scope.beername = Questionnaire.initialBeers[0].name; $scope.imgUrl = Questionnaire.initialBeers[0].imgUrl; $scope.beernameInDB = Questionnaire.initialBeers[0].beernameInDB; $scope.rate = 0; // loads the next beer in the predetermined survey list $scope.nextbeer = function(){ if($scope.rate != 0){ // Update the like relationship when user clicked nextbeer button. likeButton.like($scope.beernameInDB, $scope.rate); } var response = Questionnaire.changeBeer(); $scope.rate = 0; $scope.beername = response.beername; $scope.imgUrl = response.imgUrl; $scope.beernameInDB = response.beernameInDB; if (response.message != null) { $scope.message = response.message; } }; $scope.goToRecommendations = function(){ $location.path('/'+ localStorage.userName + '/recommendations'); } //makes initial beer list available for ng-repeat in html this.questionnaire = Questionnaire })
import React from 'react'; import PixelGrid from './PixelGrid'; export default class GridWrapper extends React.Component { shouldComponentUpdate(newProps) { const { cells } = this.props; return newProps.cells !== cells; } render() { const { props } = this; return ( <PixelGrid cells={props.cells} drawHandlers={props.drawHandlers} classes={props.classes} /> ); } }
 let locationInput = document.querySelector("#Trip_Location"); locationInput.addEventListener("keyup", (e) => { let locationText = e.target.value; let googleQuery = "https://www.google.com/search?q=things+to+do+in+"; let newQuery = googleQuery + locationText.split(" ").join("+"); document.querySelector("#search-activity-btn").setAttribute("href", newQuery); }) //set incrementers for the food places and visit places let foodI = 1 let visitI = 1 //add event listener to the visit locations container document.querySelector(".activities-container").addEventListener("click", (e) => { //perform actions when add food/add visit buttons are clicked if (e.target.id === "add-food-btn" || e.target.id === "add-visit-btn") { //prevent overall form submission e.preventDefault(); //grab type (food or visit) from button ids let type = e.target.id.split("-")[1]; //create capitalized version for interpolation purposes let Type = type.charAt(0).toUpperCase() + type.slice(1); //instantiate an indexer let i = 0; //set indexer to equal foodI or visitI depending on type if (type === "food") { i = foodI } else { i = visitI } //grab container for food or visit let container = document.querySelector(`.${type}-container`); //create new card for new visit location and set attributes let newParent = document.createElement("div"); if (type === "food") { newParent.setAttribute("class", "card p-2 bg-light mb-2 mr-3 ml-3 inset-shadow-orange"); } else { newParent.setAttribute("class", "card p-2 bg-light mb-2 mr-3 ml-3 inset-shadow-green"); } newParent.setAttribute("id", `${type}-location-${i + 1}`); //create innerdiv to mirror what is on page currently let innerDiv = document.createElement("div"); //create form-group divs to house the inputs let formGroup1 = document.createElement("div"); formGroup1.setAttribute("class", "form-group"); let formGroup2 = document.createElement("div"); formGroup2.setAttribute("class", "form-group"); //build out name area, including a label, input, and span for validation let nameLabel = document.createElement("label"); nameLabel.setAttribute("for", `${Type}-name-${i + 1}`); nameLabel.setAttribute("class", "control-label"); nameLabel.textContent = "Name"; let nameInput = document.createElement("input"); nameInput.setAttribute("type", "text"); nameInput.setAttribute("class", "form-control"); nameInput.setAttribute("id", `${Type}-name-${i + 1}`); nameInput.setAttribute("data-val", true); nameInput.setAttribute("data-val-required", "A Name is required"); nameInput.setAttribute("name", `EnteredTrip${Type}Locations[${i}].Name`); let nameValidator = document.createElement("span"); nameValidator.setAttribute("class", "text-danger field-validation-valid"); nameValidator.setAttribute("data-valmsg-for", `EnteredTrip${Type}Locations[${i}].Name`); nameValidator.setAttribute("data-valmsg-replace", true); //build out description area with label and textarea let descLabel = document.createElement("label"); descLabel.setAttribute("for", `${Type}-desc-${i + 1}`); descLabel.setAttribute("class", "control-label"); descLabel.textContent = "Description"; let descTextarea = document.createElement("textarea"); descTextarea.setAttribute("type", "text"); descTextarea.setAttribute("class", "form-control"); descTextarea.setAttribute("id", `${Type}-desc-${i + 1}`); descTextarea.setAttribute("name", `EnteredTrip${Type}Locations[${i}].Description`); //place name items in first form group and description items in second form group formGroup1.appendChild(nameLabel); formGroup1.appendChild(nameInput); formGroup1.appendChild(nameValidator); formGroup2.appendChild(descLabel); formGroup2.appendChild(descTextarea); //place form groups into innerdiv innerDiv.appendChild(formGroup1); innerDiv.appendChild(formGroup2); //put innerdiv into the new card newParent.appendChild(innerDiv); //insert new card onto DOM in appropriate container container.appendChild(newParent); //return updated incrementer for future adds accuracy. if (type === "food") { return foodI++ } else { return visitI++ } } })
let IStore = require('./IStore.js'); var fs = window.require('fs'); var path = window.require('path'); class NWStore extends IStore { constructor(){ super(); this.root = nw.App.dataPath + path.sep; this.fs = fs; } } module.exports = NWStore;
const Telegraf = require('telegraf') const app = new Telegraf(339280148:AAG2sB7Jjh6CQcWsj4ffGo2EllkwLLf0i2Q) app.command('start', (ctx) => { console.log('start', ctx.from) ctx.reply('Welcome!') }) app.hears('hi', (ctx) => ctx.reply('Hey there!')) app.on('sticker', (ctx) => ctx.reply('👍')) app.startPolling()
import React from 'react'; import styled from "styled-components"; import {AiOutlineArrowRight} from "react-icons/ai" import img from "./Assets/board.png" import img1 from "./Assets/costo.png" import img2 from "./Assets/google.png" import img3 from "./Assets/fender.png" import img4 from "./Assets/space.jpg" export const SecondComponent = () => { return ( <Container> <Wrapper> <Content> <Title>It’s more than work. It’s a way of working together. </Title> <Desc>Start with a Trello board, lists, and cards. Customize and expand with more features as your teamwork grows. Manage projects, organize tasks, and build team spirit—all in one place.</Desc> <Button>Start doing<span><AiOutlineArrowRight/></span></Button> </Content> <Image src={img}/> <Sub> <Info>Join over 1,000,000 teams worldwide that are using Trello to get more done. </Info> <Logos> <Logo src={img2}/> <Logo src={img3}/> <Logo src={img4}/> <Logo src={img1}/> </Logos> </Sub> </Wrapper> </Container> ) } const Sub=styled.div` width:100%; display:flex; flex-direction:column; align-items:center; justify-content:center; `; const Logos=styled.div` display:flex; `; const Logo=styled.img` width:150px; height:60px; object-fit:contain; margin:0 5px; `; const Info=styled.div` font-size:20px; margin-bottom:10px; `; const Image=styled.img` width:83%; object-fit:contain; `; const Content=styled.div` width:70%; text-align:center; `; const Title=styled.div` font-size:30px; color:#091e42; font-weight:600; line-height:48px; font-family:Charlie Display, sans-serif; margin-bottom:20px; `; const Desc=styled.div` font-size:20px; font-family:Charlie Text, sans-serif; line-height:29px; letter-spacing:1px; margin-bottom:20px; `; const Button=styled.button` border:0; outline:none; width:150px; height:40px; border-radius:4px; color:#0065FF; border:1px solid #0065FF; font-size:20px; background-color:transparent; transition:all 400ms; margin-bottom:30px; span{ margin-left:8px; font-size:15px; } :hover{ cursor:pointer; background-color:#0065FF; color:white; } `; const Container=styled.div` width:100%; min-height:100vh; height:100%; background-color:#FAFBFC `; const Wrapper=styled.div` width:100%; display:flex; justify-content:center; flex-direction:column; align-items:center; margin:40px 0; `;
import React, {Component} from 'react'; import {View, Text, ImageBackground, Image, TouchableOpacity, Alert, TextInput, Dimensions}from 'react-native'; import { Notifications } from 'expo'; import Constants from 'expo-constants'; import * as Location from 'expo-location'; import * as Permissions from 'expo-permissions'; import mainStyle from '../../src/styles/mainStyle'; import {saveStorage} from '../../src/api/storage'; import {submitLogin} from '../../src/api/apiMember'; export default class Login extends Component{ constructor(props) { super(props); this.state = { version: 'guest', username: '', password: '', buttonText: 'ĐĂNG NHẬP', token: '', longitude: 105.850525, latitude: 21.032711, errorMessage: '', error: 0 } } async componentDidMount() { const version = this.props.navigation.state.params.version; this.setState({version}); try { if (!Constants.isDevice) { var token = ''; }else{ var token = await Notifications.getExpoPushTokenAsync(); } this.setState({token}); } catch (e) { console.log('Error', e); } try { let { status } = await Permissions.askAsync(Permissions.LOCATION); if (status !== 'granted') { console.log('Error', 'Permission to access location was denied'); this.setState({ errorMessage: 'Permission to access location was denied', }); } let location = await Location.getCurrentPositionAsync({}); this.setState({ longitude: location.coords.longitude, latitude: location.coords.latitude }); console.log('location', location); console.log('state', this.state); } catch (e) { console.log('Error', e); } } changeVersion(){ var {version} = this.state; if(version == 'guest') version = 'technical'; else version = 'guest'; this.setState({version}); } gotoForgot(){ this.props.navigation.navigate('ForgotPasswordScreen', {version: this.state.version}); } onSubmit(){ var {username, password, token, version, latitude, longitude, error } = this.state; if(username == ''){ Alert.alert('Thông báo', 'Bạn vui lòng nhập email.'); return; } if(password == ''){ Alert.alert('Thông báo', 'Bạn vui lòng nhập mật khẩu.'); return; } this.setState({ buttonText: 'Đang xử lý...'}); submitLogin(username, password, token, version, latitude, longitude ) .then((responseJson) => { if(responseJson.error == '0'){ saveStorage('user', JSON.stringify(responseJson.user)); this.props.navigation.navigate('MemberScreen'); }else{ error++; this.setState({error, buttonText: 'ĐĂNG NHẬP'}); if(error > 3) Alert.alert('Thông báo', responseJson.message+'. Liên hệ 0936.310.222, để được hỗ trợ'); else Alert.alert('Thông báo', responseJson.message); } }).done(); } render() { return ( <ImageBackground source = {require('../../assets/backgroundImage.png')} style = {mainStyle.container}> <View style = {mainStyle.content_1_LoginClient}> <View style = {mainStyle.content_1a}> <Image source = {require('../../assets/logo.png')} style = {{width:100 * standarWidth/ width , height:100 * standarHeight / height, resizeMode:'contain'}}></Image> </View> <View style = {mainStyle.content_1b}> <Text style = {mainStyle.textContent_1b}>Đăng nhập </Text> <Text style = {mainStyle.textContent_1b}>{this.state.version=='guest'?'tài khoản khách hàng':'tài khoản kỹ thuật'}</Text> </View> <View style = {mainStyle.content_1c_login}> <View style = {mainStyle.inputTaiKhoan}> <Image source={require('../../assets/iconLogin1.png')} style = {mainStyle.imageTextInput}/> <TextInput style={mainStyle.textInputLoginClient} placeholder="Email/Số điện thoại" returnKeyType="next" onSubmitEditing={() =>this.logPassword.focus()} onChangeText={(username) => this.setState({username})} /> </View> <View style = {mainStyle.inputMatKhau}> <Image source={require('../../assets/iconLogin2.png')} style = {mainStyle.imageTextInput}/> <TextInput style={mainStyle.textInputLoginClient} secureTextEntry = {true} placeholder="Mật Khẩu" returnKeyType="done" ref={(input) => { this.logPassword = input; }} onChangeText={(password) => this.setState({password})} onSubmitEditing={() =>this.onSubmit()}/> </View> </View> </View> <View style = {mainStyle.content_2_LoginClient}> <View style = {mainStyle.content_2a_LoginClient}> <TouchableOpacity style = {mainStyle.buttonDangNhap} onPress={() => this.onSubmit()}> <Text style = {{color:'#f42535',fontWeight:'bold'}}>{this.state.buttonText}</Text> </TouchableOpacity> </View> <View style = {mainStyle.content_2b_LoginClient}> <TouchableOpacity onPress={()=>this.props.navigation.navigate('RegisterScreen', {version: this.state.version})}> <Text style ={{color:'#ffffff'}}>Tạo tài khoản Danh Kiệt</Text> </TouchableOpacity> </View> <View style = {mainStyle.content_2c_LoginClient}> <TouchableOpacity style={mainStyle.banLakhachHang_LoginClient} onPress={()=>this.changeVersion()}> <Text style ={{color:'#ffffff'}}>{this.state.version=='guest'?'Bạn là Kỹ thuật':'Bạn là Khách Hàng'}</Text> </TouchableOpacity> </View> <View style = {mainStyle.content_2c}> <TouchableOpacity onPress={()=>this.gotoForgot()}> <Text style ={{color:'#ffffff'}}>Quên mật khẩu?</Text> </TouchableOpacity> </View> </View> </ImageBackground> ); } } const {height, width} = Dimensions.get('window'); const standarWidth = 360; const standarHeight = 592; const text12 = 12/standarWidth * width; const text14 = 14/standarWidth * width; const text17 = 17/standarWidth * width; const buttonWidth = 150/standarWidth * width; const buttonHeight = 10/standarHeight * height; const marginBottom = 10/standarHeight * height; const padding = 10/standarWidth * width; const margin = 20/standarWidth * width;
//app.js const api = require("utils/request.js") App({ navigateToLogin: false, onLaunch: function() { wx.hideShareMenu(); let that = this; /** * 初次加载判断网络情况 * 无网络状态下根据实际情况进行调整 */ wx.getNetworkType({ success(res) { const networkType = res.networkType if (networkType === 'none') { that.globalData.isConnected = false wx.showToast({ title: '当前无网络', icon: 'loading', duration: 2000 }) } } }); /** * 监听网络状态变化 * 可根据业务需求进行调整 */ wx.onNetworkStatusChange(function(res) { if (!res.isConnected) { that.globalData.isConnected = false wx.showToast({ title: '网络已断开', icon: 'loading', duration: 2000, complete: function() { that.goStartIndexPage() } }) } else { that.globalData.isConnected = true wx.hideToast() } }); if (wx.canIUse('getUpdateManager')) { const updateManager = wx.getUpdateManager() updateManager.onCheckForUpdate(function (res) { if (res.hasUpdate) { updateManager.onUpdateReady(function () { wx.showModal({ title: '更新提示', content: '新版本已经准备好,请重启应用', showCancel: false, success: function (res) { if (res.confirm) { updateManager.applyUpdate() } } }) }) updateManager.onUpdateFailed(function () { wx.showModal({ title: '已经有新版本了哟~', content: '新版本已经上线啦~,请您删除当前小程序,重新搜索打开哟~' }) }) } }) } else { wx.showModal({ title: '提示', content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。' }) } }, globalData: { userInfo: null, type: '', isConnected: true } })
import {createReducer} from '../../action-reducer/reducer'; import {mapReducer} from '../../action-reducer/combine'; const create = (key) => { const prefix = ['basic', key]; const edit = createReducer(prefix.concat('edit')); const toEdit = ({activeKey}, {payload={}}) => { const key = payload.currentKey || activeKey; return key !== 'index' ? {keys: [key], reducer: edit} : {}; }; return createReducer(prefix, mapReducer(toEdit)); }; const reducer = create('excelConfigLib'); export default reducer;
// !Scheduled Classes Grid StudentCentre.grid.AttendanceScheduledClasses = function(config) { config = config || {}; Ext.applyIf(config,{ id: 'studentcentre-grid-attendance-scheduled-classes' ,url: StudentCentre.config.connectorUrl ,baseParams: { action: 'mgr/attendance/scScheduledClassGetList'/* , scheduled_class_id: 11 */ } ,fields: ['id', 'class_id', 'location_id', 'class_name', 'location_name', 'duration', 'description', 'start_date', 'end_date', 'active'] ,paging: true ,pageSize: 30 ,remoteSort: true ,anchor: '97%' ,autoExpandColumn: 'class_name' ,sortBy: 'class_id' ,grouping: true ,groupBy: 'class_name' ,pluralText: 'Classes' ,singleText: 'Class' ,save_action: 'mgr/attendance/scScheduledClassUpdateFromGrid' ,autosave: true ,columns: [{ header: 'id' ,hidden: true ,dataIndex: 'id' ,sortable: true ,name: 'id' },{ header: 'class_id' ,hidden: true ,dataIndex: 'class_id' ,name: 'class_id' },{ header: 'location_id' ,hidden: true ,dataIndex: 'location_id' ,name: 'location_id' },{ header: _('studentcentre.class') ,dataIndex: 'class_name' ,name: 'class_name' ,sortable: true ,width: 100 },{ header: _('studentcentre.location') ,dataIndex: 'location_name' ,name: 'location_name' ,sortable: true ,width: 100 },{ header: _('studentcentre.description') ,dataIndex: 'description' ,name: 'description' ,sortable: false ,width: 100 ,editor: { xtype: 'textfield' } },{ header: _('studentcentre.duration') ,dataIndex: 'duration' ,name: 'duration' ,sortable: false ,width: 100 ,editor: { xtype: 'numberfield' } },{ header: _('studentcentre.first_class') ,dataIndex: 'start_date' ,name: 'start_date' ,sortable: false ,width: 100 },{ header: _('studentcentre.last_class') ,dataIndex: 'end_date' ,name: 'end_date' ,sortable: false ,width: 100 },{ header: _('studentcentre.active') ,dataIndex: 'active' ,sortable: true ,width: 50 ,editor: { xtype: 'attendance-combo-active-status', renderer: true} }] ,tbar:[{ xtype: 'button' ,id: 'attendance-create-scheduled-class-button' ,text: _('studentcentre.schedule_class') ,handler: { xtype: 'studentcentre-window-scheduled-class-create', blankValues: true } },{ xtype: 'button' ,id: 'attendance-update-scheduled-class-button' ,text: _('studentcentre.update') ,listeners: { 'click': {fn: this.updateScheduledClass, scope: this} } },{ xtype: 'button' ,id: 'attendance-scheduled-class-active-toggle-button' ,text: _('studentcentre.toggle_active_status') ,handler: function(btn,e) { this.toggleActive(btn,e); } ,scope: this },'->',{ // This defines the toolbar for the search xtype: 'textfield' // Here we're defining the search field for the toolbar ,id: 'scheduled-class-search-filter' ,emptyText: _('studentcentre.search...') ,listeners: { 'change': {fn:this.search,scope:this} ,'render': {fn: function(cmp) { new Ext.KeyMap(cmp.getEl(), { key: Ext.EventObject.ENTER ,fn: function() { this.fireEvent('change',this); this.blur(); return true; } ,scope: cmp }); },scope:this} } },{ xtype: 'button' ,id: 'clear-scheduled-class-search' ,text: _('studentcentre.clear_search') ,listeners: { 'click': {fn: this.clearSearch, scope: this} } }] }); StudentCentre.grid.AttendanceScheduledClasses.superclass.constructor.call(this,config) }; Ext.extend(StudentCentre.grid.AttendanceScheduledClasses,MODx.grid.Grid,{ search: function(tf,nv,ov) { var s = this.getStore(); s.baseParams.query = tf.getValue(); this.getBottomToolbar().changePage(1); this.refresh(); } ,clearSearch: function() { this.getStore().baseParams = { action: 'mgr/attendance/scScheduledClassGetList' }; Ext.getCmp('scheduled-class-search-filter').reset(); this.getBottomToolbar().changePage(1); this.refresh(); } ,getMenu: function() { // MODX looks for getMenu when someone right-clicks on the grid return [{ text: _('studentcentre.update') ,handler: this.updateScheduledClass },'-',{ text: _('studentcentre.toggle_active_status') ,handler: this.toggleActive }]; } ,updateScheduledClass: function(btn,e) { var selRow = this.getSelectionModel().getSelected(); if (selRow.length <= 0) return false; if (!this.updateScheduledClassWindow) { this.updateScheduledClassWindow = MODx.load({ xtype: 'sc-window-scheduled-class-update' ,record: selRow.data ,listeners: { 'success': { fn:function(r){ this.refresh(); this.getSelectionModel().clearSelections(true); },scope:this } } }); } this.updateScheduledClassWindow.setValues(selRow.data); this.updateScheduledClassWindow.show(e.target); } ,toggleActive: function(btn,e) { var selRow = this.getSelectionModel().getSelected(); if (selRow.length <= 0) return false; MODx.Ajax.request({ url: this.config.url ,params: { action: 'mgr/attendance/scScheduledClassUpdate' ,id: selRow.data.id ,toggleActive: 1 } ,listeners: { 'success': {fn:function(r) { this.refresh(); Ext.getCmp('studentcentre-grid-attendance-scheduled-classes').refresh(); this._updateScheduledClassComboBoxes(); },scope:this} } }); return true; } // used to reload the Scheduled Class comboboxes in other grids ,_updateScheduledClassComboBoxes: function() { var cbScheduledClass = new Array(); cbScheduledClass[0] = Ext.getCmp('attendance-create-class-enrollment-scheduled-class-combo'); for (var i=0; i<cbScheduledClass.length; i++) { if (cbScheduledClass[i]) { cbScheduledClass[i].setDisabled(false); var s = cbScheduledClass[i].store; s.removeAll(); s.load(); cbScheduledClass[i].clearValue(); } } } }); Ext.reg('studentcentre-grid-attendance-scheduled-classes',StudentCentre.grid.AttendanceScheduledClasses); // !Class Combobox StudentCentre.combo.ScheduledClassGridClassName = function(config) { config = config || {}; Ext.applyIf(config, { fieldLabel: _('studentcentre.class') ,width: 300 ,hiddenName: 'class_id' ,hiddenValue: '' ,emptyText: 'Select class...' ,typeAhead: true ,valueField: 'id' ,displayField: 'name' ,fields: ['id', 'name'] ,pageSize: 20 ,url: StudentCentre.config.connectorUrl ,baseParams: { action: 'mgr/attendance/scClassGetList' } }); StudentCentre.combo.ScheduledClassGridClassName.superclass.constructor.call(this, config); }; Ext.extend(StudentCentre.combo.ScheduledClassGridClassName, MODx.combo.ComboBox); Ext.reg('attendance-class-name-combo', StudentCentre.combo.ScheduledClassGridClassName); // !Location Combobox /* StudentCentre.combo.ScheduledClassGridLocationName = function(config) { config = config || {}; Ext.applyIf(config, { fieldLabel: _('studentcentre.location') ,width: 300 ,hiddenName: 'location_id' ,hiddenValue: '' ,emptyText: 'Select location...' ,typeAhead: true ,valueField: 'id' ,displayField: 'name' ,fields: ['id', 'name'] ,pageSize: 20 ,url: StudentCentre.config.connectorUrl ,baseParams: { action: 'mgr/attendance/scLocationGetList' } }); StudentCentre.combo.ScheduledClassGridLocationName.superclass.constructor.call(this, config); }; Ext.extend(StudentCentre.combo.ScheduledClassGridLocationName, MODx.combo.ComboBox); Ext.reg('attendance-location-name-combo', StudentCentre.combo.ScheduledClassGridLocationName); */ // !Weekday Combobox StudentCentre.combo.Weekday = function(config) { config = config || {}; Ext.applyIf(config, { store: new Ext.data.ArrayStore({ id: 'attendance-combo-weekday' ,fields: ['value','display'] ,data: [ ['Monday','Monday'] ,['Tuesday','Tuesday'] ,['Wednesday','Wednesday'] ,['Thursday','Thursday'] ,['Friday','Friday'] ,['Saturday','Saturday'] ,['Sunday','Sunday'] ] }) ,mode: 'local' ,displayField: 'display' ,valueField: 'value' }); StudentCentre.combo.Weekday.superclass.constructor.call(this, config); }; Ext.extend(StudentCentre.combo.Weekday, MODx.combo.ComboBox); Ext.reg('attendance-combo-weekday', StudentCentre.combo.Weekday); // !Create Window StudentCentre.window.CreateScheduledClass = function(config) { config = config || {}; var dateToday = new Date(); Ext.applyIf(config,{ title: _('studentcentre.schedule_class') ,width: '400' ,url: StudentCentre.config.connectorUrl ,labelAlign: 'left' ,baseParams: { action: 'mgr/attendance/scScheduledClassCreate' } ,fields: [{ xtype: 'attendance-class-name-combo' ,id: 'attendance-create-scheduled-class-class-combo' ,name: 'class_id' ,hiddenName: 'class_id' ,anchor: '100%' ,baseParams: { action: 'mgr/attendance/scClassGetList' ,activeOnly: 1 } },{ xtype: 'attendance-combo-location' ,id: 'attendance-create-scheduled-class-location-combo' ,name: 'location_id' ,hiddenName: 'location_id' ,anchor: '100%' ,baseParams: { action: 'mgr/attendance/scLocationGetList' ,activeOnly: 1 } },{ xtype: 'textfield' ,name: 'description' ,allowBlank: true ,maxLength: 20 ,fieldLabel: _('studentcentre.description') },{ xtype: 'numberfield' ,fieldLabel: _('studentcentre.duration_hours') ,name: 'duration' ,anchor: '100%' },{ xtype: 'datefield' ,name: 'start_date' ,fieldLabel: _('studentcentre.first_class') ,format: 'd/m/Y' },{ xtype: 'datefield' ,name: 'end_date' ,fieldLabel: _('studentcentre.last_class') ,format: 'd/m/Y' }] }); StudentCentre.window.CreateScheduledClass.superclass.constructor.call(this,config); }; Ext.extend(StudentCentre.window.CreateScheduledClass,MODx.Window); Ext.reg('studentcentre-window-scheduled-class-create',StudentCentre.window.CreateScheduledClass); // !Update Window StudentCentre.window.UpdateScheduledClass = function(config) { config = config || {}; Ext.applyIf(config,{ title: _('studentcentre.update') ,width: '400' ,url: StudentCentre.config.connectorUrl ,labelAlign: 'left' ,baseParams: { action: 'mgr/attendance/scScheduledClassUpdate' } ,fields: [{ xtype: 'hidden' ,name: 'id' },{ xtype: 'attendance-class-name-combo' ,id: 'attendance-update-scheduled-class-class-combo' ,name: 'class_id' ,hiddenName: 'class_id' ,anchor: '100%' ,baseParams: { action: 'mgr/attendance/scClassGetList' } },{ xtype: 'attendance-combo-location' ,id: 'attendance-update-scheduled-class-location-combo' ,name: 'location_id' ,hiddenName: 'location_id' ,anchor: '100%' ,baseParams: { action: 'mgr/attendance/scLocationGetList' } },{ xtype: 'textfield' ,name: 'description' ,allowBlank: true ,maxLength: 20 ,fieldLabel: _('studentcentre.description') },{ xtype: 'numberfield' ,fieldLabel: _('studentcentre.duration_hours') ,name: 'duration' ,anchor: '100%' },{ xtype: 'datefield' ,name: 'start_date' ,allowBlank: true ,fieldLabel: _('studentcentre.first_class') ,format: 'd/m/Y' },{ xtype: 'datefield' ,name: 'end_date' ,allowBlank: true ,fieldLabel: _('studentcentre.last_class') ,format: 'd/m/Y' },{ xtype: 'attendance-combo-active-status' ,fieldLabel: _('studentcentre.active') ,name: 'active' ,hiddenName: 'active' ,anchor: '100%' }] }); StudentCentre.window.UpdateScheduledClass.superclass.constructor.call(this,config); }; Ext.extend(StudentCentre.window.UpdateScheduledClass,MODx.Window); Ext.reg('sc-window-scheduled-class-update',StudentCentre.window.UpdateScheduledClass);
$(function(){ $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $(".autocomplete").select2({ width: "100%", maximumSelectionLength : 1 }); $(".tag").select2(); $(".autocomplete-cases").select2({ width: "100%", showSearchBox: true, ajax: { url: "/api/cases", dataType: 'json', delay: 250, data: function (term, page) { return { q: term, // search term }; }, results: function (data, params) { params.page = params.page || 1; data.map(function(d){ d.text = d.title; }) return { results: data }; } } }); $(".autocomplete-templates").select2({ width: "100%", showSearchBox: true, ajax: { url: "/api/messageTemplates", dataType: 'json', delay: 250, data: function (term, page) { return { q: term, // search term }; }, results: function (data, params) { params.page = params.page || 1; data.map(function(d){ d.id = d.text; }) return { results: data }; } } }); $("#category-form-ajax").on('submit',function(e){ $.ajaxSetup({ header:$('meta[name="_token"]').attr('content') }) e.preventDefault(); $.ajax({ type:"POST", url:'/api/categories', data:$(this).serialize(), dataType: 'json', success: function(data){ if(data == true){ getCategories(function (data) { var $reportCategories = $(".report-categories"); $reportCategories.find('option').remove(); $.each(data, function(index, category) { $reportCategories.append('<option value="' + category.id + '">' + category.title + '</option>'); }); }); } }, error: function(data){ } }); }); }); function getCases(callback){ $.get("/api/cases", function(data){ callback(data); }); } function getUsers(callback){ $.get("/api/users/", function(data){ callback(data); }); } function getRoles(callback){ $.get("/api/roles/", function(data){ callback(data); }); } function getCategoriesData(callback){ $.get("/api/categories?editable=true", function(data){ callback(data); }); } function getCategories(callback){ $.get("/api/categories", function(data){ callback(data); }); } function dubitoConfirm(callback){ var confirmCancel = $('.confirm-cancel'); var confirmDelete = $('.confirm-delete'); $('.confirm-delete-modal').modal({ show: true}); $(confirmCancel).on('click',function(){ //console.log('cancel'); $('.confirm-delete-modal').modal('hide'); callback(false); }); $(confirmDelete).on('click',function(){ //console.log('delete'); $('.confirm-delete-modal').modal('hide'); callback(true); }); }
// JavaScript Document var channel_account_add_btn_ststus=1; $(function(){ //loginHeight(); //显示当前列表td未显示的内容 $(".tablelist_tbody td").mouseover(function(){ //当前对象宽度 //var objwidth = $(this).width(); var status = true; var text = $.trim($(this).html()); //text = text.replace("/^\s*|\s*$/g", ""); var arr = new Array("buttom","span","label"); for(var item in arr) { if(text.indexOf(arr[item])>-1){ status = false; } } if(status){ $(this).attr("title",text); } }); //二级菜单伸缩 $(".navone").click(function(){ var $navone=$(this).parent("dd").siblings().find(".navone"); $(this).toggleClass("active").next(".navonecon").slideToggle(); $navone.removeClass("active").next(".navonecon").slideUp(); }) //三级菜单伸缩 $(".navtwo").click(function(){ var $navtwo=$(".navtwo").not(this); $(this).toggleClass("active"); if($(this).next().is(".navtwocon")){ $(this).next(".navtwocon").slideToggle(); }else{ $(this).addClass("active"); } $navtwo.removeClass("active").next(".navtwocon").slideUp(); }) //三级菜单选中效果 $(".navtwocon li").click(function(){ $(".navtwocon li").not(this).removeClass("active"); $(this).addClass("active"); }) //菜单伸缩 $("#menuslide").click(function(){ var $logo=$(".header .logo"); var $navbox=$(".navbox"); var $mainbox=$(".main_box"); var $left=$navbox.css("left"); if(parseInt($left)==0){ $logo.stop(true,true).animate({width:"0px"},300); $navbox.stop(true,true).animate({left:"-216px"},300); $mainbox.stop(true,true).animate({left:"0px"},300); }else{ $logo.stop(true,true).animate({width:"216px"},300); $navbox.stop(true,true).animate({left:"0px"},300); $mainbox.stop(true,true).animate({left:"216px"},300); } }); //地区选择 $(".saleset_add").click(function(event){ setUpSites(this.jsonClassName); event.stopPropagation(); var $contentW=$(this).parents(".saleset_con").width(); var $left=$(this).offset().left; var $top=$(this).offset().top; $(".saleset_add").siblings("dl").hide(); if(parseInt($contentW)-parseInt($left)<472){ $(this).siblings("dl").css({left:parseInt($contentW)-parseInt($left)-472}) } $(this).siblings("dl").show(); }) $(document).click(function(){ $(".saleset_nav").find("dl").hide(); }); //提醒 $("#tips,#announce").click(function(event){ event.stopPropagation(); $(this).siblings("dd").find(".tipcon").hide(); $(".admin_con").removeClass("open"); $(this).children(".tipcon").show(); }) $(document).click(function(){ $("#tips,#announce",top.document).children(".tipcon").hide(); $(".admin_con", top.document).removeClass("open"); //清空输入框联想内容 if ($("#user_type_ids",top.document).val()=="" || $("#user_type_ids",top.document).val()==undefined){ $("#inputusername",top.document).val(""); } //清空通道名称内容 if ($("#channel_ids",top.document).val()=="" || $("#channel_ids",top.document).val()==undefined){ $("#inputchannel",top.document).val(""); } //清空网关名称内容 if ($("#server_ids",top.document).val()=="" || $("#server_ids",top.document).val()==undefined){ $("#inputserver",top.document).val(""); } $(".inputusernameall").each(function(){ if($(this,top.document).val()=="" || $(this,top.document).val()==undefined){ var $objthis = $(this).attr("data-id-name"); $("#"+$objthis,top.document).val(""); } }); $("#inputusernamelist").hide(); }); $(".admin_toggle").click(function(){ $(this).parents("dd").siblings().find(".tipcon").hide(); }) //省份选择 $(".region_down").click(function(event){ event.stopPropagation(); $(this).next(".region_box").show(); }) $(document).click(function(){ $(".region_box").hide(); }) $(".region_con li").click(function(event){ var $text=$(this).text(); $(this).parents(".region_box").prev(".region_down").find("span").text($text); }) $(".navbox .home_pannel").click(function(){ $(this).find("a").removeClass("collapsed"); $(".panel_con .panel_tit").find("a").addClass("collapsed"); }) $(".panel_con .panel_tit").click(function(){ $(".home_pannel").find("a").addClass("collapsed"); }) //二级菜单点击 $(".panel_body li").click(function(){ $(".home_pannel").find("a").addClass("collapsed"); $(".panel_body li").removeClass("current"); $(this).addClass("current").parents(".panel_body").siblings(".panel_tit").find("a").removeClass("collapsed"); }) //首页单点击 $(".home_pannel").click(function(){ $(this).find("a").removeClass("collapsed"); $(".panel_tit").find("a").addClass("collapsed"); $(".panel_body li").removeClass("current"); }) //登录输入框获得焦点 $(".logintext .text").focus(function(){ $(this).parents(".logintext").addClass("focus"); }) //登录输入框失去焦点 $(".logintext .text").blur(function(){ $(this).parents(".logintext").removeClass("focus"); }) $(document).on("click",".checkbox", function(){ if(!$(this).hasClass('disabled')){ $(this).toggleClass("checked"); } }) $(document).on('click',".radio",function(){ if(!$(this).hasClass('disabled')){ var val = $(this).attr('value'); $(this).addClass("checked").siblings().removeClass("checked").siblings("input[type='hidden']").val(val); } }) //时间控件 $(".start_datetime").datetimepicker({ //开始时间 minView: "month", //选择日期后,不会再跳转去选择时分秒 format: "yyyy-mm-dd", //选择日期后,文本框显示的日期格式 language: 'zh-TW', //汉化 autoclose:true //选择日期后自动关闭 }).on("click",function(ev){ $(".start_datetime").datetimepicker("setEndDate", $(".end_datetime").val()); }); $(".end_datetime").datetimepicker({ //结束时间 minView: "month", //选择日期后,不会再跳转去选择时分秒 format: "yyyy-mm-dd", //选择日期后,文本框显示的日期格式 language: 'zh-TW', //汉化 autoclose:true //选择日期后自动关闭 }).on("click", function (ev) { $(".end_datetime").datetimepicker("setStartDate", $(".start_datetime").val()); }); $(".create_date").datetimepicker({ //付款时间 minView: "month", //选择日期后,不会再跳转去选择时分秒 format: "yyyy-mm-dd", //选择日期后,文本框显示的日期格式 language: 'zh-TW', //汉化 autoclose:true //选择日期后自动关闭 }); // 下拉列表控件触发 //$(".select").select2(); tablelistboxHeight(); tableSize(); $(window).resize(function(){ //loginHeight(); tablelistboxHeight(); tableSize(); }); //横向滚动条 //$(".mCustomScrollbar_x").mCustomScrollbar({ // axis:"x", // autoHideScrollbar:true, // theme:"3d-thick", // scrollInertia:0, // }); //纵向滚动条 $(".mCustomScrollbar_y").mCustomScrollbar({ axis:"y", // horizontal scrollbar scrollbarPosition:"outside", autoHideScrollbar:true, scrollInertia:0, }); //$(".mCustomScrollbar_xy").mCustomScrollbar({ // axis:"yx", // horizontal scrollbar // scrollbarPosition:"outside", // autoHideScrollbar:true, // scrollInertia:0, // }); //$(".tablelist_con").mCustomScrollbar({ // axis:"yx", // horizontal scrollbar // scrollInertia:0, // autoHideScrollbar:true, // callbacks:{ // whileScrolling: function(){ // if(this.mcs.direction == "y"){ // var $h=-parseInt(this.mcs.top); // $(".tablelist_thead").css({top:$h}) // } // } , // onUpdate: function(){ // setTimeout(function(){ // var $top=$("#mCSB_1_container").css("top"); // var $headtop =- parseInt($top); // $(".tablelist_thead").css("top",$headtop); // },50); // } // }, // }); //表格滚动条 $(".tablelist_tbody").scroll(function(){ $(".tablelist_thead").scrollLeft($(this).scrollLeft()); }) //提示小工具 $('[data-toggle="tooltip"]').tooltip({ trigger:'hover', }); //首页图表下拉列表点击效果 $(".chart_tit .dropmenu li").click(function(){ var $text = $(this).text(); $(this).addClass("current").siblings().removeClass("current"); $(this).parent(".dropmenu").siblings(".droptit").find(".text").text($text); //讲字符串转为调用方法 var f_name = eval("("+$(this).attr('data-function')+")"); //调用方法转参数 f_name(); }); /*重置按钮*/ $(".reset_button").click(function(){ var $form=$(this).parents("form"); $form.find(".inputtext").val(''); $form.find("select").each(function(){ var $hiddenval=$(this).next(":hidden").val(); $(this).val($hiddenval); }); }); //代理商与企业名称联想返回信息 $("div").delegate("#inputusername","keyup",function(){ objs = this; var width = $(this).outerWidth(); var top = $(this).offset().top+$(this).outerHeight()+1; var left = $(this).offset().left; var usertype = $(this).attr("data-usertype"); if(usertype=="user_types"){ var usertype_id = $(".usertype_id").val(); if(usertype_id==2){ usertype = "enterprise"; }else{ usertype = "proxy"; } } var name = $(this).val(); var nameall = $(this).attr("data-nameall"); if(name!=""){ $.post("/index.php/Admin/Index/ajax_username",{usertype:usertype,name:name,nameall:nameall},function(data){ $("#user_type_ids",top.document).attr("value",""); //此代码无法运行 if(data.info){ var html=""; html+="<ul>"; for(var i=0; i < data.info.length;i++) { html += '<li onclick="user_type_all(' + data.info[i].id + ',\'' + data.info[i].name + '\',' + data.info[i].code + ')">(' + data.info[i].code + ')' + data.info[i].name + '</li>'; } html+="</ul>"; $("#inputusernamelist").show().css("width",width+"px").css("top",top+"px").css('left',left+"px").html(html); }else{ $("#inputusernamelist").hide().html(""); } },"json"); }else{ $("#inputusernamelist").hide().html(""); } }); //代理商与企业名称联想返回信息(同页面多个查询方法) $("div").delegate(".inputusernameall","keyup",function(){ objthis = this; var width = $(this).outerWidth(); var top = $(this).offset().top+$(this).outerHeight()+1; var left = $(this).offset().left; var usertype = $(this).attr("data-usertype"); if(usertype=="user_types"){ var usertype_id = $(".usertype_id").val(); if(usertype_id==2){ usertype = "enterprise"; }else{ usertype = "proxy"; } } var name = $(this).val(); var nameall = $(this).attr("data-nameall"); if(name!=""){ $.post("/index.php/Admin/Index/ajax_username",{usertype:usertype,name:name,nameall:nameall},function(data){ $("#"+$(this).attr("data-id-name"),top.document).attr("value",""); //此代码无法运行 if(data.info){ var html=""; html+="<ul>"; for(var i=0; i < data.info.length;i++) { html += '<li onclick="user_type_all2(' + data.info[i].id + ',\'' + data.info[i].name + '\',' + data.info[i].code + ')">(' + data.info[i].code + ')' + data.info[i].name + '</li>'; } html+="</ul>"; $("#inputusernamelist").show().css("width",width+"px").css("top",top+"px").css('left',left+"px").html(html); }else{ $("#inputusernamelist").hide().html(""); //执行调用方法 datafunctionname(); } },"json"); }else{ $("#inputusernamelist").hide().html(""); //执行调用方法 datafunctionname(); } }); //通道(名称编码)联想返回信息 $("div").delegate("#inputchannel","keyup",function(){ objs = this; var width = $(this).outerWidth(); var top = $(this).offset().top+$(this).outerHeight()+1; var left = $(this).offset().left; var name = $(this).val(); var have_discount = $(this).attr("have-discount"); var is_filter = $(this).attr("is-filter"); var type = $(this).data("type");//显示样式 onlyname(不显示编号) var ctype=$(this).data("ctype");//显示状态 java(表示只显示java通道) if(have_discount != 1){ have_discount = 0; } if(name!=""){ $.post("/index.php/Admin/Index/ajax_channel",{name:name,have_discount:have_discount,is_filter:is_filter,ctype:ctype},function(data){ $("#channel_ids",top.document).attr("value",""); //此代码无法运行 if(data.info){ var html=""; html+="<ul>"; if(type=="onlyname"){ for(var i=0; i < data.info.length;i++){ html+='<li onclick="channel_all('+data.info[i].id+',\''+data.info[i].name+'\','+'\''+data.info[i].code+'\','+'\''+data.info[i].attribute+'\','+'\''+type+'\')">'+data.info[i].name+'</li>'; } }else{ for(var i=0; i < data.info.length;i++){ html+='<li onclick="channel_all('+data.info[i].id+',\''+data.info[i].name+'\','+'\''+data.info[i].code+'\','+'\''+data.info[i].attribute+'\','+'\''+type+'\')">('+data.info[i].code+')'+data.info[i].name+'</li>'; } } html+="</ul>"; $("#inputusernamelist").show().css("width",width+"px").css("top",top+"px").css('left',left+"px").html(html); }else{ $("#inputusernamelist").hide().html(""); } },"json"); }else{ $("#inputusernamellist").hide().html(""); } }); //网关联想返回信息 $("div").delegate("#inputserver","keyup",function(){ objs = this; var width = $(this).outerWidth(); var top = $(this).offset().top+$(this).outerHeight()+1; var left = $(this).offset().left; var name = $(this).val(); if(name!=""){ $.post("/index.php/Admin/Index/ajax_server",{name:name},function(data){ $("#server_ids",top.document).attr("value",""); //此代码无法运行 if(data.info){ var html=""; html+="<ul>"; for(var i=0; i < data.info.length;i++){ html+='<li onclick="server_all('+data.info[i].id+',\''+data.info[i].name+'\','+'\''+data.info[i].code+'\')">'+data.info[i].name+'</li>'; } html+="</ul>"; $("#inputusernamelist").show().css("width",width+"px").css("top",top+"px").css('left',left+"px").html(html); }else{ $("#inputusernamelist").hide().html(""); } },"json"); }else{ $("#inputusernamellist").hide().html(""); } }); $(".tab_hd h3").click(function(){ var $index=$(this).index(); $(this).addClass("active").siblings().removeClass("active"); $(this).parent().next(".tab_bd").children().eq($index).show().siblings().hide(); }) //查找当前页面日期选择框如果出现+号的直接替换 $(".inputdateall").each(function(){ var dates = $(this).val(); if(dates!=""){ if(dates.indexOf("+")>-1){ var datea = dates.replace("+"," "); $(this).val(datea); } } }); //将当前位置的图片和导行标题换成当前分类图标和导行标题(每页头部导行图标和导行标题) if($('.currenttit').children('i').length > 0){ //导行图标 var icons = $("#"+newaction,top.document).attr("data-icon"); $('.currenttit').children('i').addClass("midicon "+icons); //导行标题 if($("#"+newaction,top.document).attr("data-title")!=null){ var title = $("#"+newaction,top.document).attr("data-title").split("|"); var ht = ''; for (i=0;i<title.length ;i++ ){ var ii = i+1; ht+="<em>"+title[i]+"</em>"; if(title[ii])ht+=">"; } $('.currenttit').children('span').html(ht); } } //如页面未读到显示数据信息则将提示句中TD合并的个数调设为标题的总个数 var colspan_int = $(".tablelist_tbody table tr td").attr("colspan"); if(colspan_int==20){ var thlength = $(".tablelist_thead table tr th").length; $(".tablelist_tbody table tr td").attr("colspan",thlength); } //页面加载完成后格式化列表中的金额 if ($(".tablelist_tbody").length > 0 ) { $(".tablelist_tbody table tr td").each(function(){ if($(this).html().indexOf('.') > -1 && !isNaN($(this).html())){ $(this).html(toThousands($(this).html())); } }); } //页面加载完成后格式化页面中公共的金额 if($('.prepaidtip').length > 0){ $('.prepaidtip').html(js_toThousands2($('.prepaidtip').html(),'</span>元')); } }); //获取代理商和企业选择出来名称并赋值 var objs = ""; function user_type_all(id,name,code){ var text = "("+code+")"+name; $(objs).val(text); $("#user_type_ids").val(id); } //------------ var objthis = ""; function user_type_all2(id,name,code){ var text = "("+code+")"+name; $(objthis).val(text); $("#"+$(objthis).attr("data-id-name")).val(id); //执行调用方法 datafunctionname(); } //公共代理商和企业名称查询所调用其他方法 function datafunctionname(){ //获取是否有需要执行的方法 var f_name = $(objthis).attr("data-functionname"); if(f_name && f_name!="undefined"){ var extra = $(objthis).attr("data-functionextra"); if(typeof(f_name) == "string")f_name = eval("("+f_name+")"); if(extra){ f_name(extra); }else{ f_name(); } } } //--------------- //获取通道选择出来名称并赋值 function channel_all(id,name,code,attribute,type) { var text = ""; if (type == "onlyname") { text = name; $("#channel_ids").val(name); } else { text = "(" + code + ")" + name; $("#channel_ids").val(id); } if (attribute == 1) {//通道属性,2流量池通道 $(".discount").hide(); $(".discount_hid").show(); $("#discount_1").val(""); $("#discount_2").val("10"); $("#channel_type").val("1"); } else { $(".discount_hid").hide(); $("#discount_2").val(""); $(".discount").show(); $("#channel_type").val("2"); } $(objs).val(text); } //获取网关选择出来名称并赋值 function server_all(id,name,code){ var text = name; $(objs).val(text); $("#server_ids").val(id); } //重新加载下拉和滚动条 function mCustomScrollbar(){ //$(".select",parent.document).select2(); //纵向滚动条 $(".mCustomScrollbar_y").mCustomScrollbar({ axis:"y", // horizontal scrollbar scrollbarPosition:"outside", autoHideScrollbar:true, scrollInertia:0, }); $("input[vtype='tel'],input[vtype='mobile'],input[vtype='money'],input[vtype='icense'],input[vtype='identity']",top.document).keypress(function(event){ var type = $(this).attr('vtype'); var eventObj = event || e; var keyCode = eventObj.keyCode || eventObj.which; //alert('keyCode '+keyCode); switch(type){ //48-57:数字 45:- 8:后退 116:F5 13:回车 9:table制表键 123:F12 46:删除键 case 'tel': if ((keyCode >= 48 && keyCode <= 57) || (keyCode == 45) || (keyCode == 67) || (keyCode == 86) || (keyCode == 118) || (keyCode == 99) || (keyCode == 8) || (keyCode == 13) || (keyCode == 123) || (keyCode == 46) || (keyCode == 37) || (keyCode == 39) || (keyCode == 116) || (keyCode == 9)) return true; else return false; break; case 'mobile': if ((keyCode >= 48 && keyCode <= 57) || (keyCode == 8) || (keyCode == 67) || (keyCode == 86) || (keyCode == 118) || (keyCode == 99) || (keyCode == 13) || (keyCode == 123) || (keyCode == 46) || (keyCode == 37) || (keyCode == 39) || (keyCode == 116) || (keyCode == 9)) return true; else return false; break; case 'money': if ((keyCode >= 48 && keyCode <= 57) || (keyCode == 46) || (keyCode == 8) || (keyCode == 13) || (keyCode == 123) || (keyCode == 46) || (keyCode == 37) || (keyCode == 39) || (keyCode == 116) || (keyCode == 9)) return true; else return false; break; case 'icense': if ((keyCode >= 48 && keyCode <= 57) || (keyCode == 8) || (keyCode == 13) || (keyCode == 123) || (keyCode == 46) || (keyCode == 37) || (keyCode == 39) || (keyCode == 116) || (keyCode == 9)) return true; else return false; break; case 'identity': if ((keyCode >= 48 && keyCode <= 57) || (keyCode == 120) || (keyCode == 8) || (keyCode == 13) || (keyCode == 123) || (keyCode == 46) || (keyCode == 37) || (keyCode == 39) || (keyCode == 116) || (keyCode == 9)) return true; else return false; break; } }) $('input,select',top.document).focus(function(){ $(this).parents(".add_value").nextAll("div[class='error']").remove(); }) /* var val = $(this).val(); var type = $(this).attr('vtype'); switch(type){ case 'tel': vreg = /^[0-9-]$/; break; case 'mobile': vreg = /^[0-9]$/; break; case 'money': vreg = /^[0-9\.]?$/; break; } for (var i = 0; i < val.length; i++) { if(!vreg.test(val[i])){ } }; */ } //表单区域高度计算函数 function tablelistboxHeight(){ var $searchboxH=$(".search_box").outerHeight(); var $totalH=parseInt($searchboxH)+42+52; $(".tablelistboxH").css("height","calc(100% - "+$totalH+"px)"); } // 通用列表宽度计算 function tableSize() { var $thead=$(".tablelist_thead"); var $theadTh=$(".tablelist_thead th"); var $tbody=$(".tablelist_tbody"); var $tbodyTr=$(".tablelist_tbody tr"); var $firstTd=$(".tablelist_tbody tr:first td"); var tablelistW=$(".tablelist_tbody table").innerWidth(); var $w=parseInt(tablelistW)-20-2; var $totalWidth=0; var $changeW=0; var $unchangeW=0; var $theadW=0; $theadTh.each(function(i) { var $thWidth=parseInt($(this).attr("width")); $totalWidth=$totalWidth+$thWidth; if($(this).is(".change")){ $(this).css("width",$thWidth); $firstTd.eq(i).css("width",$thWidth); $changeW=$changeW+$thWidth; } else{ $(this).css("width",$thWidth); $firstTd.eq(i).css("width",$thWidth); $unchangeW=$unchangeW+$thWidth; } }); //$theadW=$totalWidth; if($w>$totalWidth) { var $surplusW=$w-$unchangeW; $theadTh.each(function(i) { var $thWidth=parseInt($(this).attr("width")); if($(this).is(".change")) { var $thW=($thWidth/$changeW)*$surplusW; $(this).css("width",$thW); $firstTd.eq(i).css("width",$thW); } else { $(this).css("width",$thWidth); $firstTd.eq(i).css("width",$thW); } }) } if($tbodyTr.length==1 && $firstTd.length==1){ if($w>$totalWidth){ $firstTd.css("width",$w); }else{ $firstTd.css("width",$totalWidth); } } var $tablebodyw=$tbody.outerWidth(); $theadW=$tablebodyw; if($tbody.get(0)){ var $innerW=$tbody.get(0).clientWidth; var $outerW=$tbody.get(0).offsetWidth; var $sw=parseInt($outerW)-parseInt($innerW); if($sw>0){ $thead.width($theadW-$sw); }else{ $thead.width("100%"); } } } /*function loginHeight(){ var $winh=$(window).height(); if($winh<=600){ return; }else{ var $marginTop=($winh-600)/2-20; $("body.white").css("padding-top",$marginTop) } }*/ /** * 提示成功和失败信息 * @data 数组型式包括状态和提示内容 * @time 时间,默认为3秒 */ function alertbox(data){ if(data.status == 0){ var msg = data.info; }else{ var msg = data.msg; } var type = data.status == "success"? "success" : "failed"; var html='<div class="alert alert_'+type+'" role="alert">'; html+='<span>'+msg+'</span>'; html+='<button type="button" class="close" data-dismiss="alert" aria-label="Close"></button>'; html+='</div>'; setTimeout("closebox()",4000); $("#prompt_msg",parent.parent.document).html(html); } /** * 关闭提示弹框 */ function closebox(){ $("#prompt_msg",parent.parent.document).html(''); } /** * 刷新子页面后如果有弹框信息则关闭弹框信息 */ $(function(){ if($("#prompt_msg",parent.document).html() != ''){ setTimeout("closebox()",1500); } }) //切换顶级菜单信息 function top_menu_show(id){ var id = id > 0 ? id : 1; $("#top_menu_id").val("0"); $(".systypeall").hide(); $(".systype"+id).show(); } //切换用户通道的代理商和企业 function list_show(){ var user_type = $("#user_type").val(); if(user_type==1){ $(".proxy_list").show(); $(".enterprise_list").hide(); }else{ $(".proxy_list").hide(); $(".enterprise_list").show(); } $("#ids").val(''); } /** * 关闭公告 */ function close_notice(){ $(".announce_con").css("display","none"); } function inputFocus(formname){ $("form[name='"+formname+"']",top.document).find("input[type='text']").first().focus(); } /** * 弹出地区选择的框 */ var ns = 0; function showprovince(obj,n) { ns = n; var e = arguments.callee.caller.arguments[0] || window.event; window.event?e.returnValue = false:e.preventDefault(); window.event?e.cancelBubble:e.stopPropagation(); e.stopPropagation(); var $top = parseInt($(obj).offset().top)+30; var $left = $(obj).offset().left; $("#discount_province_box").css({position:"fixed",top:$top,left:$left,zIndex:2000}).show(); return false; } //选择省份 function chooseprovince(province_id, province_name) { var fc = 1; var childlis = $("#dc_add_plist"+ns).children(); $.each(childlis, function(i, n) { if($(n).hasClass("vlic"+ns+province_id)) { fc = 0; return false; } }); if(fc) { var vli = '<li id="vli'+ns+province_id+'" class="vlic'+ns+province_id+'"><label class="label">'+province_name+'</label>'; vli += '<input type="text" class="inputtext" name="discount_number'+ns+province_id+'" value="" />'; vli += '<span onclick="delprovince('+ns+province_id+')"><i class="minicon delete_icon"></i></span></li>'; $("#dc_add_plist"+ns).append(vli); } } //删除省份 function delprovince(oid) { $("#vli"+oid).remove(); } function open_menu(id,msg,url){ openMenu(id,msg,url); } //充值提示信息的更改 function payment_name(){ var paymentname = $("#source").val(); var text=new Array("打款户名","支付订单号","交易号","打款户名"); if(paymentname!=""){ $("#source_name").html(text[paymentname-1]); $("#source_input").attr("field",text[paymentname-1]); }else{ $("#source_name").html(text[0]); $("#source_input").attr("field",text[0]); } } function payment_name_channel(){ var paymentname = $("#source").val(); var text=new Array("打款户名","支付订单号","交易号","授信","打款户名"); if(paymentname!=""){ if(paymentname==4){ $("#channel_soruce").hide(); $("#channel_time").hide(); $("#source_input").val("-1"); $("#payment_date").val("-1"); }else{ if($("#source_input").val()=="-1"){ $("#source_input").val(""); $("#payment_date").val(""); $("#channel_soruce").show(); $("#channel_time").show(); } $("#source_name").html(text[paymentname-1]); $("#source_input").attr("field",text[paymentname-1]); } }else{ $("#source_name").html(text[0]); $("#source_input").attr("field",text[0]); } } //充值类型切换 function content_hide(){ var recharge_type = $("#recharge_type").val(); if(recharge_type==1){ $(".recharge_type_div").show(); }else{ $(".recharge_type_div").hide(); } } //自定义回复切换 function customreply_type(){ var replyname = $("#reply_type").val(); $("#dtphf").hide(); $("#mtphf").hide(); $('#hdhf').hide(); $("#wzhf").hide(); if(replyname==1){ $("#wzhf").show(); } if(replyname==2){ $('#dtphf').show(); } if(replyname==3){ $("#mtphf").show(); } if(replyname==4){ $("#hdhf").show(); } } //处理弹框中的金额将金额格式化并返回 function page_toThousands(){ $("#layerdivid span , #layerdivid td").each(function(){ $(this).html(js_toThousands($(this).html())); }); } // 将 confirm 对话框中的数字格式化(传入字符串) function js_toThousands(text){ var s=text,num,chr; //提取数字 num=s.match(/\d+(\.\d+)?/g); for (x in num) { var nums = num[x]+'元'; if(s.indexOf(nums) > -1){ s = s.replace(num[x],toThousands(num[x])); } } return s; //提取非数字字符 //chr=s.match(/[^\d\.]/g) //alert(chr) } // 将方法传入的数字格式化(传入字符串和判断条件) function js_toThousands2(text,content){ var s=text,num,chr; //提取数字 num=s.match(/\d+(\.\d+)?/g); for (x in num) { var nums = num[x]+content; if(s.indexOf(nums) > -1){ s = s.replace(num[x],toThousands(num[x])); } } return s; } /** * 将传入金额格式化并返回格式化后的数据 * @param num 金额 * @returns {string} */ function toThousands(numi){ //直接返回当前格式(如不需要格式化的时候打开直接返回的代码) return numi; //等于 0 直接返回 numi = $.trim(numi); var numj = numi; if(numi==0)return numi; //小于 0 去掉减号 if(numj.indexOf('-') > -1){ var int = numi.split('-'); numi = int[1]; } //定义变量并将金额转成字符串加入数组中 var num = (numi || 0).toString(), result = '',nums = [ ]; if(num.indexOf('.') > -1){ nums = num.split('.'); nums[1] = '.'+nums[1]; }else{ nums.push(num); nums.push('.000'); } nums[0] = nums[0].replace(',',''); //将金额格式化 while (nums[0].length > 3) { result = ',' + nums[0].slice(-3) + result; nums[0] = nums[0].slice(0, nums[0].length - 3); } if (nums[0]) { result = nums[0] + result; } //还原格式化后的金额 if(numj.indexOf('-') > -1){ return '-'+result+nums[1]; }else{ return result+nums[1]; } } /* * 表示显示过滤通道 * id用来标示是不是选择全国时出现所以市 */ function get_is_filter(id){ var province_id=$("#province_id").val(); if(id==1&&province_id==""){ province_id=1; } if(province_id==1&&id!=1 || province_id==""){ $("#filter_type").hide(); //$("#filter_city").hide(); $("#is_filter").val(0); $(".filter_radio1").addClass("checked"); $(".filter_radio2").removeClass("checked"); var html='<option value="" >请选择</option>'; $("#city_id").html(html); }else{ $("#filter_type").show(); $.post("/index.php/Admin/Index/ajax_city",{province_id:province_id},function(data){ if(data.info){ var html='<option value="" >请选择</option>'; for(var i=0; i < data.info.length;i++){ html+='<option value="'+data.info[i]["city_id"]+'" >'+data.info[i]["city_name"]+'</option>'; } $("#city_id").html(html); }else{ $("#city_id").hide().html(""); } $("#filter_city").show(); },"json"); } }
_.max = function(collections,arg){ var maxItem; var maxValue; var currentValue; for(var i in collections){ if(!maxItem) { maxItem = collections[i]; continue; } maxValue = Base.getValue(maxItem,arg); currentValue = Base.getValue(collections[i],arg); if(currentValue > maxValue){ maxItem = collections[i]; } } return maxItem; }
'use strict'; import * as React from 'react'; import ReactCSSTransitionGroup from 'react-addons-css-transition-group'; import * as EventManager from 'modules/events'; import * as settings from 'modules/settings'; import './style'; class Errors extends React.Component { state = { isHide: true, upworkError: false, proxyError: false, networkError: false }; clearState = () => { this.setState({ isHide: true, upworkError: false, proxyError: false, networkError: false }); }; handlerRetry = () => { this.clearState(); EventManager.trigger('updatedAfterError'); }; handlerChangeServer = () => { var sData = settings.get(); sData.useProxy.value = !sData.useProxy.value; settings.set(sData); this.handlerRetry(); }; componentDidMount() { EventManager.on('inboxError', () => { var state = { isHide: false }; if (navigator.onLine) { state.upworkError = true; } else { state.networkError = true; } this.setState(state); }); EventManager.on('settingsInit', () => { this.clearState(); }); }; render() { var state = this.state; return ( <ReactCSSTransitionGroup transitionName="errtooltip" component="div" transitionEnterTimeout={300} transitionLeaveTimeout={300}> {!state.isHide ? <div id="serverError"> {state.upworkError ? <div> Upwork.com server internal error <br /> <button className="btn_blue" onClick={this.handlerRetry}>Retry</button> </div> : null } {state.networkError ? <div> Check your network connection, then press "Retry" <br /> <button onClick={this.handlerRetry}>Retry</button> </div> : null } </div> : null } </ReactCSSTransitionGroup> ); } } export default Errors;
;(function() { let detectBitness = function() { // Detect is OS is 64 bit const indicators64Bit = [ "x86_64", "x86-64", "Win64", "x64;", // Mind the semicolon! Without it you will have false-positives. "amd64", "AMD64", "WOW64", "x64_64", ]; for (let needle in indicators64Bit) { if (window.navigator.appVersion.indexOf(needle) !== -1) { return "64"; } } return "32"; } let detectOS = function () { if (window.navigator.userAgent.indexOf("Windows") !== -1) { return "windows" + detectBitness(); } //if (window.navigator.userAgent.indexOf("Ubuntu") !== -1) { // return "ubuntu" + detectBitness(); //} if (window.navigator.userAgent.indexOf("Mac") !== -1) { return "osxintel"; } return "unknown"; } let osName = detectOS(); if (osName === "unknown") { return; } document.addEventListener("DOMContentLoaded", function() { let button = document.querySelector("#download .download-button") if (!button) { return; } let description = document.querySelector("#download .download-button-description") if (!description) { return; } let link = document.querySelector("#stable .download-" + osName) if (!link || !link.href || !link.dataset.os) { return; } button.href = link.href; if (link.onclick) { button.setAttribute("onclick", link.onclick.toString()); } description.innerHTML = link.dataset.os; }); }());
var db=require('./db.js') var utils=require('./utils.js'); exports.otherRegister = otherRegister; exports.getCode=getCode; exports.register=register; exports.login=login; exports.changePassword=changePassword; exports.userinfo=userinfo; //第三方用户的注册\登录 async function otherRegister(params,callBack){ if(null!=params.openid){ //将数据表中的OPENID设置为唯一索引,直接插入数据,强制性的有就覆盖,没有就新插入一列 let regResult=await db.asyncQuery("REPLACE INTO userinfo (uid,openid,nickname,city,face,add_time,login_type,sex) VALUES ('"+params.uid+"','"+params.openid+"','"+params.nickname+"','"+params.city+"','"+params.face+"','"+new Date().toLocaleString()+"','"+params.login_type+"','"+params.sex+"')"); if(0==regResult){ console.log("连接数据库表失败") typeof callBack=='function' &&callBack(utils.returnTrueJsonData(null,'注册失败')); }else{ let userData= await db.asyncQuery("SELECT * FROM userinfo WHERE openid='"+params.openid+"'"); if(0==userData){ typeof callBack=='function' &&callBack(utils.returnTrueJsonData(null,'注册账号失败,内部发生了错误!')); }else{ console.log("注册成功") typeof callBack=='function' &&callBack(utils.returnTrueJsonData(userData[0],'注册成功')); } } }else{ typeof callBack=='function' &&callBack(utils.returnTrueJsonData(null,"缺少必要参数")); } } //账号密码的用户注册 function register(params,callBack){ if(null!=params&&null!=params.account&&null!=params.password&&null!=params.code){ //查询用户手机号码下面的是否存在已注册的用户 db.query("SELECT * FROM userinfo WHERE account='"+params.account+"'",function(err,rows){ if(err){ typeof callBack=='function' &&callBack(utils.returnTrueJsonData(null,"连接数据库失败")); }else{ if(null!=rows&&rows.length>0){ typeof callBack=='function' &&callBack(utils.returnTrueJsonData(null,'该用户已存在!请直接登录')); }else{ db.query("insert into userinfo (uid,openid,nickname,account,phonenumber,password,add_time,login_type,sex) values ('"+params.uid+"','"+params.account+"','用户"+params.account+"','"+params.account+"','"+params.account+"','"+params.password+"','"+new Date().toLocaleString()+"','"+params.login_type+"','"+params.sex+"')",function(err,rows){ if(err){ console.log("注册账号失败,数据库发生了错误!") typeof callBack=='function' &&callBack(utils.returnTrueJsonData(null,'注册账号失败,数据库发生了错误!')); }else{ db.query("SELECT * FROM userinfo WHERE account='"+params.account+"'",function(err,rows){ if(err){ console.log("数据库查询失败"+err) typeof callBack=='function' &&callBack(utils.returnTrueJsonData(null,'数据库查询失败')); }else{ console.log("注册成功") typeof callBack=='function' &&callBack(utils.returnTrueJsonData(rows[0],'注册成功')); } }) } }); } } }); }else{ typeof callBack=='function' &&callBack(utils.returnTrueJsonData(null,"注册失败,参数不正确")); } } //用户登录 function login(params,callBack){ if(null!=params&&null!=params.account&&null!=params.password){ //查询账号是否存在 db.query("SELECT * FROM userinfo WHERE account='"+params.account+"'",function(err,rows){ if(err){ typeof callBack=='function' &&callBack(utils.returnTrueJsonData(null,"连接数据库失败")); }else{ if(null!=rows&&rows.length>0){ console.log(rows) //比对登录密码 console.log(rows[0].password) if(params.password==rows[0].password){ console.log("密码匹配相等") typeof callBack=='function' &&callBack(utils.returnTrueJsonData(rows[0],'登录成功!')); }else{ console.log("密码错误!") typeof callBack=='function' &&callBack(utils.returnTrueJsonData(null,'密码错误!')); } }else{ console.log("该账号不存在,请先注册!") typeof callBack=='function' &&callBack(utils.returnTrueJsonData(null,'该账号不存在,请先注册!')); } } }); }else{ typeof callBack=='function' &&callBack(utils.returnTrueJsonData(null,"注册失败,参数不正确")); } } //修改密码,先校验用户手机号码 function changePassword(params,callBack){ if(null!=params&&null!=params.account&&null!=params.code){ //查询账号是否存在 db.query("SELECT * FROM userinfo WHERE account='"+params.account+"'",function(err,rows){ if(err){ typeof callBack=='function' &&callBack(utils.returnTrueJsonData(null,"连接数据库失败")); }else{ if(null!=rows&&rows.length>0){ console.log(rows) db.query("UPDATE userinfo SET password='"+params.password+"'WHERE account='"+params.account+"'",function(err,rows){ if(err){ console.log("修改密码失败!连接数据库错误:"+err) typeof callBack=='function' &&callBack(utils.returnTrueJsonData(null,"修改密码失败!连接数据库错误")); }else{ console.log("修改密码成功") typeof callBack=='function' &&callBack(utils.returnTrueJsonData({"acount":params.account,"password":params.password},"修改密码成功")); } }); }else{ console.log("该账号不存在,请先注册!") typeof callBack=='function' &&callBack(utils.returnTrueJsonData(null,'该账号不存在,请先注册!')); } } }); }else{ typeof callBack=='function' &&callBack(utils.returnTrueJsonData(null,"修改密码失败,参数不正确")); } } //获取用户的额基本信息 async function userinfo(params,callBack){ try{ //查询用户信息 let rows=await db.asyncQuery("SELECT * FROM userinfo WHERE id='"+params.user_id+"'"); if(0==rows){ console.log("连接数据库失败") typeof callBack=='function' &&callBack(utils.returnTrueJsonData(null,"获取用户信息失败")); }else{ if(null!=rows&&rows.length>0){ let collectCount= await db.queryUserCollectCount(rows[0].id); let trackCount= await db.queryUserTrackCount(rows[0].id); console.log("用户收藏个数:"+collectCount+",用户浏览个数:"+trackCount) rows[0].collect_count=collectCount; rows[0].track_count=trackCount; typeof callBack=='function' &&callBack(utils.returnTrueJsonData(rows[0],'获取用户信息成功')); }else{ typeof callBack=='function' &&callBack(utils.returnTrueJsonData(null,'该用户不存在')); } } }catch(err){ console.log(err) typeof callBack=='function' &&callBack(utils.returnTrueJsonData(null,"获取用户信息失败")); } } //获取验证码 function getCode(params,callBack){ if(null!=params&&null!=params.phone){ typeof callBack=='function' &&callBack(utils.returnTrueJsonData("手机号码:"+params.phone+"的验证码已成功下发")); }else{ typeof callBack=='function' &&callBack(utils.returnTrueJsonData(null,"获取验证码失败!参数不正确")); } }
/* *description:经销网络 *author:fanwei *date:2014/04/25 */ define(function(require, exports, module){ var global = require('../global/global'); //var fenye = require('../../../../global/js/widget/dom/fenye'); var scrollLoad = require('../../../../global/js/widget/dom/scrollLoad'); function Sale() { } Sale.prototype = { init: function() { this.scroller(); }, showPage: function() { var oTplSale, oSale, getDataUrl; oTplSale = require('../../tpl/build/sale_net/list'); oSale = $('[sc = sale_net]'); getDataUrl = reqBase + 'vshop/getlist' fenye(oSale, getDataUrl , oTplSale, '10', wparam, function(data){}); }, scroller: function() { var oTplNew,oNew; var oScroll = new scrollLoad(); var oTip = $('[sc = monsary-tip]'); oTplNew = require('../../tpl/build/sale_net/list'); oNew = $('[sc = sale_net]'); oScroll.requestUrl = reqBase + 'vshop/getlist'; oScroll.oTpl = oTplNew; oScroll.param = wparam; oScroll.param.num = 10; oScroll.oDataWrap = oNew; oScroll.oTip = oTip; oScroll.init(); } } var oSale = new Sale(); oSale.init(); });
import { combineReducers } from 'redux' import { isBusy, hasErrored, listUsers, setUser, editUser } from './admin' import { loginIsPending, loginHasErrored, userIsAdmin, sessionChange } from './session' import { forecast } from './weather' // This is what controls the state object shape export default combineReducers({ isBusy: isBusy, hasErrored: hasErrored, users: listUsers, //user: [setUser,editUser], user: setUser, editUser: editUser, session: sessionChange, loginHasErrored: loginHasErrored, loginIsPending: loginIsPending, userIsAdmin: userIsAdmin, forecast: forecast });
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; // import Shoe from './shoe'; import axios from 'axios'; class ShoesList extends Component { constructor(props) { super(props); this.state = { allShoes: [] } } // method to retrieve the info in the database componentDidMount = () => { axios.get('https://shoes2match-be.herokuapp.com/') .then(response => { console.log(response) this.setState({allShoes: response.data}) }) .catch(function (error){ console.log(error); }) } render() { return( <div className="shoe-list"> <h2>Hello My Pretties...</h2> <div className="all-shoes-container"> <div className="all-shoes"> { this.state.allShoes.map((pair, i) => { return ( <Link to={{ pathname: "/:id", state: { pair: pair, } }} key={i} > <img className="list-images" src={pair.image} alt={pair.style} /> </Link> ) })} </div> </div> </div> ) } } export default ShoesList; // <a href=<Shoe pair={pair} key={i} /> className="shoe-pics"><img src="{pair.image}" alt={pair.style} /></a> // <Link to={"/"+pair._id} pair={pair} key={i}><img src="{pair.image}" alt={pair.style} /></Link>
var attributeArray = []; var total = 0; var numbers = []; var dieCount = 0; function attributeGen() { return 1 + Math.floor(Math.random() * 6); } while ( dieCount < 4 ) { numbers.push(attributeGen()); dieCount += 1; } numbers.sort(); numbers.shift(); numbers.forEach(function(number) { total += number; }); alert(total); console.log(total); attributeArray.push(total); console.log(attributeArray); // do { // // } while (attributeArray.length < 6 ); // console.log(attributeArray);
import createToken from './createToken'; import addToken from './addToken'; // import validateToken from './validateToken'; // import createTokenRecord from './createTokenRecord'; export default { createToken, addToken, // validateToken, // createTokenRecord, };
require('dotenv').config(); const bodyParser = require('body-parser'), express = require('express'), bcrypt = require('./lib/bCrypt.js'), db = require('./db/db.js'); var app = express(); /** bodyParser.urlencoded(options) * Parses the text as URL encoded data (which is how browsers tend to send form data from regular forms set to POST) * and exposes the resulting object (containing the keys and values) on req.body */ app.use(bodyParser.urlencoded({ extended: true })); /**bodyParser.json(options) * Parses the text as JSON and exposes the resulting object on req.body. */ app.use(bodyParser.json()); app.get('/', function (req, res) { res.send('Hello World!'); }); app.listen(process.env.PORT || 5000); console.log('Server running in port ' + (process.env.PORT || 5000)); /////////////////////////////////// ///////// CUSTOMERS ///////// /////////////////////////////////// //customer registration // receives: app.post('/register', function(req, res) { //TODO if(!req.body.user){ res.status(404).send('No user info received!'); return; } var user = req.body.user; console.log(req.body); if(!user.name || !user.roll || !user.contact || !user.password || !user.gender || !user.branch || !user.year) res.status(404).send("Missing parameters!"); else{ db.insertUser(user, function(result){ if(result == null){ res.send({"error" : "Invalid parameters, or already existing email address!"}); } else{ console.log(result); res.send(result); } }); } }); //customer login // receives // { "user" : { email: "xxx", pin : xxxx}} app.post('/login', function(req, res) { if(!req.body.user){ res.status(404).send('No user info received!'); return; } var user = req.body.user; console.log(user); if(!user.roll || !user.pass) res.status(404).send("Missing parameters!"); else{ db.checkLoginByRoll(user, function(result){ if(result == null){ res.send({"error" : "Invalid Roll or password!"}); } else{ console.log(result); res.send(result); } }); } }); app.post('/feedback', function(req, res) { if(!req.body.user){ res.status(404).send('No user info received!'); return; } var user = req.body.user; console.log(user); if(!user.type || !user.fb) res.status(404).send("Missing parameters!"); else{ res.send({"response" : "Success"}); } }); app.post('/record', function(req, res) { if(!req.body.order){ res.status(404).send('No user info received'); return; } var user = req.body.order; console.log(user); if(!user.roll || !user.purp) res.status(404).send("Missing parameters!"); else{ db.insertRecord(user,function(result){ if(result == null){ res.send({"error" : "Error recording"}); } else{ console.log(result); res.send({"response" : result}); } }); } }); app.post('/event', function(req, res){ if(!req.body.user){ res.status(404).send('No user info received!'); return; } var user = req.body.user; console.log(user); if(!user.roll) res.status(404).send("Missing parameters!"); else { db.getEvent(function(result){ if(result == null){ res.send({"error" : "Invalid Roll or password!"}); } else{ console.log(result); res.send({"event" : result}); } }); } });
const BasePage = require ('./base_page/basePage'); const Helper = require('../helpers/helper'); const logger = require('../../config/logger.config'); const EC = protractor.ExpectedConditions; class NewDataEntryPage extends BasePage { constructor () { super(); this.helper = new Helper(); this.dockNumField = element(by.xpath("//*[contains(@name,'PAM$DOCKETNUMBER')]//input")); this.countryClearIcon = element(by.xpath("//*[contains(@name,'PAM$COUNTRY')]//*[contains(@class,'k-clear-value')]")); this.countryField = element(by.xpath("//*[contains(@name,'PAM$COUNTRY')]//input")); this.caseTypeClearIcon = element(by.xpath("//*[contains(@name,'PAM$CASETYPE')]//*[contains(@class,'k-clear-value')]")); this.caseTypeField = element(by.xpath("//*[contains(@name,'PAM$CASETYPE')]//input")); this.relationTypeClearIcon = element(by.xpath("//*[contains(@name,'PAM$RELATIONTYPE')]//*[contains(@class,'k-clear-value')]")); this.relationTypeField = element(by.xpath("//*[contains(@name,'PAM$RELATIONTYPE')]//input")); this.filingTypeClearIcon = element(by.xpath("//*[contains(@name,'PAM$FILINGTYPE')]//*[contains(@class,'k-clear-value')]")); this.filingTypeLookupBtn = element(by.xpath("//*[contains(@name,'PAM$FILINGTYPE')]//*[contains(@class,'ca-hierarchy__actions')]")); this.searchField = element(by.xpath("//*[contains(@class,'ca-hierarchy-modal__search')]//*[contains(@class,'ca-textbox__input')]")); this.searchBtn = element(by.xpath("//*[contains(@class,'ca-hierarchy-modal__search')]//*[contains(@class,'ca-search__search-button')]")); this.searchResult = element(by.xpath("//div[contains(@class,'ca-tree-view__item')]")); this.addBtn = element(by.buttonText('Add')); this.filingTypeField = element(by.xpath("//*[contains(@name,'PAM$FILINGTYPE')]//input")) this.saveBtn = element(by.buttonText('Save')); this.toastMessage = element(by.xpath("//*[contains(@class,'ca-notification-message--success')]")); this.toastMessageCloseIcon = element(by.xpath("//*[contains(@class,'ca-notification-message--success')]//button")); this.recordID = element(by.xpath("//*[contains(@class,'data-entry-form__id')]")); } async fillRequiredFields(obj) { await this.fillSingleLineField("Docket Number", this.dockNumField, obj.docketNumber); await this.fillComboBoxField("Country", this.countryClearIcon, this.countryField , obj.country); await this.fillComboBoxField("Case Type", this.caseTypeClearIcon, this.caseTypeField, obj.caseType); await this.fillComboBoxField("Relation Type", this.relationTypeClearIcon, this.relationTypeField, obj.relationType); await this.fillComboBoxField("Filing Type", this.filingTypeClearIcon, this.filingTypeField, obj.filingType); return logger.info(`Required fields are successfully filled.`); } async fillSingleLineField(elementName, fieldElement, value) { await fieldElement.sendKeys(value); const actualValue = await fieldElement.getAttribute('value') logger.debug(`[${elementName}] value entered: "${value}", actual value: "${actualValue}".`); return logger.info(`[${elementName}] is filled with "${value}" value.`); } async fillComboBoxField(elementName, clearIconElement, fieldElement, value) { await clearIconElement.click(); await fieldElement.sendKeys(value); await this.helper.waitForBusyIndicatorHidden(); await fieldElement.sendKeys(protractor.Key.ARROW_DOWN); await fieldElement.sendKeys(protractor.Key.ENTER); const actualValue = await fieldElement.getAttribute('value') logger.debug(`[${elementName}] value entered: "${value}", actual value: "${actualValue}".`); return logger.info(`[${elementName}] is filled with "${value}" value.`); } // implementation of click action via executeScript async save() { await browser.wait(EC.elementToBeClickable(this.saveBtn), 5000); await browser.executeScript("arguments[0].style.backgroundColor = '" + "pink" + "'", this.saveBtn); await browser.executeScript("arguments[0].click()", this.saveBtn); logger.info(`Save button is clicked.`); await this.helper.waitForSpinnerHidden(); return browser.executeScript("arguments[0].style.backgroundColor = '" + "white" + "'", this.saveBtn); } async toastMessageIsDisplayed() { let isDisplayed = await browser.wait(EC.visibilityOf(this.toastMessage), 3000); logger.info(`Toast message is displayed.`); return isDisplayed; } async closeToastMessage() { await browser.wait(EC.elementToBeClickable(this.toastMessageCloseIcon), 3000); await this.toastMessageCloseIcon.click(); await browser.wait(EC.invisibilityOf(this.toastMessage), 3000); return logger.info(`Toast message is closed.`); } async getRecordID() { let recordIDText = await this.recordID.getText(); logger.debug(`Record ID is: ${recordIDText}`); return recordIDText; } }; module.exports = NewDataEntryPage;
import { cloudBusinessApiUrl } from "../../utilities/constants"; import { SET_SUPPLIES_LIST, CREATE_SUPPLY, UPDATE_SUPPLY } from "../actionTypes"; import { SET_ALERT, REMOVE_ALERT } from "../actionTypes"; /*************get supplies list************/ export const getSuppliesList = idToken => async dispatch => { const options = { headers: { "Content-Type": "application/json", Authorization: idToken } }; const res = await fetch(`${cloudBusinessApiUrl}/supplies/list`, options); const supplies = await res.json(); if (res.status >= 200 && res.status <= 299) { dispatch({ type: SET_SUPPLIES_LIST, payload: { suppliesList: supplies } }); } else { dispatch({ type: SET_SUPPLIES_LIST, payload: { suppliesList: [] } }); dispatch({ type: SET_ALERT, payload: { type: "error", triggeredBy: "getSuppliesList", message: JSON.stringify(supplies) } }); } }; /*************create supply************/ export const createSupply = (supplyData, idToken) => async dispatch => { dispatch({ type: REMOVE_ALERT, payload: { triggeredBy: "createSupply" } }); const options = { method: "POST", headers: { "Content-Type": "application/json", Authorization: idToken }, body: JSON.stringify({ active: supplyData.active, barCode: supplyData.barCode, description: supplyData.description, family: supplyData.family, size: supplyData.size, units: supplyData.units, factor: supplyData.factor, cost: supplyData.cost }) }; const res = await fetch(`${cloudBusinessApiUrl}/supplies/create`, options); const newSupply = await res.json(); if (res.status >= 200 && res.status <= 299) { dispatch({ type: CREATE_SUPPLY, payload: { newSupply } }); dispatch({ type: SET_ALERT, payload: { type: "success", triggeredBy: "createSupply", message: `El producto "${newSupply.description}" fue creado correctamente` } }); } else { dispatch({ type: SET_ALERT, payload: { type: "error", triggeredBy: "createSupply", message: JSON.stringify(newSupply) } }); } }; /***************update supply**************/ export const updateSupply = (supplyData, idToken) => async dispatch => { dispatch({ type: REMOVE_ALERT, payload: { triggeredBy: "updateSupply" } }); const options = { method: "PUT", headers: { "Content-Type": "application/json", Authorization: idToken }, body: JSON.stringify({ _id: supplyData.selectedSupplyId, active: supplyData.active, barCode: supplyData.barCode, description: supplyData.description, family: supplyData.family, size: supplyData.size, units: supplyData.units, factor: supplyData.factor, cost: supplyData.cost }) }; const res = await fetch(`${cloudBusinessApiUrl}/supplies/update`, options); const updatedSupply = await res.json() if (res.status >= 200 && res.status <= 299) { dispatch({ type: UPDATE_SUPPLY, payload: { updatedSupply } }); dispatch({ type: SET_ALERT, payload: { type: "success", triggeredBy: "updateSupply", message: `El producto "${updatedSupply.description}" fue modificado correctamente` } }); } else { dispatch({ type: SET_ALERT, payload: { type: "error", triggeredBy: "updateSupply", message: JSON.stringify(updatedSupply) } }); } };
class Player{ constructor(){ this.index=null; this.distance=0; this.name=null; this.rank=null; } //Updating the player count in other player's device getPlayerCount(){ var playerCountRef=database.ref('playerCount') playerCountRef.on("value",(data)=>{ playerCount= data.val(); }) } //Updating the player count in the database updatePlayerCount(count){ database.ref('/').update({ playerCount:count }) } // Update the the name, distance of the player in the database update(){ var playerIndex='players/player'+this.index; database.ref(playerIndex).set({ name:this.name, distance:this.distance } ) } // static used to call the function only once // We are storing the player's data in a variable called playerInfo static playerInfo(){ database.ref('players').on("value",(data)=>{ playerInfo=data.val(); }) } // Updating the input given by the user regarding the number of players updatePlayerNumber(){ database.ref('/').update({ playerNumber:this.playerInput }) } getPlayerNumber(){ var playerNumberInfo=database.ref('playerNumber'); playerNumberInfo.on("value",(data)=>{ playerNumber=data.val(); }) } }
import React from 'react'; import { Title, TextBlock, InvasivePotential, Resources, Resource, Summary, SexualReproduction, AsexualReproduction, EcologicalNiche, PopulationDensity, EnvironmentImpact, ManagementMethod, ManagementApplication, OriginalArea, SecondaryArea, Introduction, Breeding, CaseImage, } from '../components'; import image from '../../../assets/caseDetails/netykavka-zlaznata.jpg'; const NetykavkaZlaznata = (props) => ( <div> <Title name="Netýkavka žláznatá" nameSynonyms="Netýkavka Royleova" latinName="Impatiens glandulifera" latinNameSynonyms="Impatiens roylei" /> <Summary> <OriginalArea text="oblast západního Himaláje" /> <SecondaryArea text="Evropa, Severní Amerika, Jižní Amerika, Mikronésie, Asie, Nový Zéland" /> <Introduction text="Pěstování jako okrasná, užitková a medonosná rostlina" /> <Breeding text="Ano" /> </Summary> <CaseImage source={image} copyright="Foto: Petra Kubíková" /> <TextBlock> <p> Netýkavka žláznatá je jednoletá statná bylina dorůstající až 3 m výšky. Lodyha je lysá, dutá, v dolní části až 5 cm široká. Lodyžní listy jsou vstřícné, nebo v trojčetných přeslenech v horní části lodyhy, v dolní pak střídavé, kopinaté, ostře pilovité, lesklé. Na bázi listu se nacházejí výrazné žlázky. Květy uspořádané v hroznu jsou oproti ostatním netýkavkám velké (až 4 cm), ve všech odstínech nachové, někdy bílé, vonící těžkou sladkou vůní. Semena jsou po 5 až 10 ve tobolkách až 30 mm dlouhých. Vyzrálé tobolky pukají, a vystřelují tak semena na vzdálenost až 5m od mateřské rostliny. </p> <h5>Ekologie a způsob šíření</h5> <p> Jde o polostinný druh, rostoucí zejména na vlhkých stanovištích na živinami bohatých půdách – podél vodních toků, v nivách řek, lužních lesích, v polních mokřadech a okrajích polí. Někdy se též vyskytuje na rumištích a opuštěných antropogenních plochách. Jde o druh konkurenčně velmi silný, šířící se na rozsáhlá území. Zejména vodní toky působí jako silný vektor šíření plovavých semen. Semena klíčí většinou následující sezónu a nejsou přeléhavá. Z hlediska vlivu invaze na invadované biotopy nebyl zaznamenán výrazný negativní dopad kromě vysoké kompetice a zástinu ostatních druhů. Druh je často předmětem ochranářského managementu, jehož dopad je ovšem vzhledem k rozsahu invaze v ČR sporný.{' '} </p> </TextBlock> <InvasivePotential> <SexualReproduction score={3} /> <AsexualReproduction score={1} /> <EcologicalNiche score={3} /> <PopulationDensity score={3} /> <EnvironmentImpact score={1} /> <ManagementMethod text="Aplikace herbicidu, kosení, vytrhávání" /> <ManagementApplication text="Lokálně v ZCHÚ, sporné výsledky" /> </InvasivePotential> <Resources> <Resource> MLÍKOVSKÝ J., STÝBLO P. (eds). 2006. Nepůvodní druhy fauny a flóry České republiky. Praha, ČSOP, 495 s. </Resource> <Resource> PERGL, J.; PERGLOVÁ, I.; VÍTKOVÁ, M.; POCOVÁ, L.; JANATA, T.; ŠÍMA, J. 2014. SPPK D02 007 LIKVIDACE VYBRANÝCH INVAZNÍCH DRUHŮ ROSTLIN. Standard péče o přírodu a krajinu. Péče o vybrané terestrické ekosystémy. Řada D. AOPK ČR (pracovní verze) </Resource> <Resource> SLAVÍK, B. (editor); ŠTĚPÁNKOVÁ, J. (editor). Květena České republiky 7. Praha: Academia, 2004.{' '} </Resource> <Resource> STALMACHOVÁ, B. a kol. (2019). Strategie řešení invazních druhů rostlin v obcích česko-polského pohraničí. IMAGE STUDIO s.r.o., Slezská Ostrava. </Resource> <Resource> PLADIAS. dostupné z:{' '} <a href="https://pladias.cz/" target="_blank"> https://pladias.cz/ </a> ; cit. 21.10.2019 </Resource> </Resources> </div> ); export default NetykavkaZlaznata;
"use strict"; var normalize = require('normalize-path'); module.exports = { create: function (req, res) { let titulo1 = req.param('titulo1'), titulo2 = req.param('titulo2'), titulo3 = req.param('titulo3'), titulo4 = req.param('titulo4'), titulo5 = req.param('titulo5'), titulo6 = req.param('titulo6'), updates = req.param('updates'); let images = []; var path = require('path') req.file('archivos').upload({ dirname: require('path').resolve(sails.config.appPath, 'assets/images/projects') }, function (err, uploadedFiles) { if (err) return res.negotiate(err); let imgs = []; res.setTimeout(0); uploadedFiles.forEach(function(file) { file.fd = normalize(file.fd); imgs.push('/images/projects/' + file.fd.split('/').reverse()[0]); }); let index = 0 for (var i = 0; i < updates.length; i++) { if (updates[i] == 'YES') { images.push(imgs[index]) index+=1 } else { images.push('') } } makeRequest() .then(result => res.ok(result)) .catch(err => res.serverError(err)); }); //create async method makeRequest const makeRequest = async () =>{ try { const projects = await Projects.find(); let news = true; if (projects.length > 0) { news = false } if (news) { //create new Projects await Projects.create({ descripcion: titulo1, images: [ images[0], images[1], images[2], images[3], images[4] ] }); console.log(images); await Projects.create({ descripcion: titulo2, images: [ images[5], images[6], images[7], images[8], images[9] ] }); await Projects.create({ descripcion: titulo3, images: [ images[10], images[11], images[12], images[13], images[14] ] }); await Projects.create({ descripcion: titulo4, images: [ images[15], images[16], images[17], images[18], images[19] ] }); await Projects.create({ descripcion: titulo5, images: [ images[20], images[21], images[22], images[23], images[24] ] }); await Projects.create({ descripcion: titulo6, images: [ images[25], images[26], images[27], images[28], images[29] ] }); return 'OK'; } else { let up = 0 await Projects.update(projects[up].id, { descripcion: titulo1.trim() != "" ? titulo1 : projects[up].descripcion, images: [ images[0+up*5].trim() != "" ? images[0+up*5] : projects[up].images[0], images[1+up*5].trim() != "" ? images[1+up*5] : projects[up].images[1], images[2+up*5].trim() != "" ? images[2+up*5] : projects[up].images[2], images[3+up*5].trim() != "" ? images[3+up*5] : projects[up].images[3], images[4+up*5].trim() != "" ? images[4+up*5] : projects[up].images[4] ] }); up+=1 await Projects.update(projects[up].id, { descripcion: titulo2.trim() != "" ? titulo2 : projects[up].descripcion, images: [ images[0+up*5].trim() != "" ? images[0+up*5] : projects[up].images[0], images[1+up*5].trim() != "" ? images[1+up*5] : projects[up].images[1], images[2+up*5].trim() != "" ? images[2+up*5] : projects[up].images[2], images[3+up*5].trim() != "" ? images[3+up*5] : projects[up].images[3], images[4+up*5].trim() != "" ? images[4+up*5] : projects[up].images[4] ] }); up+=1 await Projects.update(projects[up].id, { descripcion: titulo3.trim() != "" ? titulo3 : projects[up].descripcion, images: [ images[0+up*5].trim() != "" ? images[0+up*5] : projects[up].images[0], images[1+up*5].trim() != "" ? images[1+up*5] : projects[up].images[1], images[2+up*5].trim() != "" ? images[2+up*5] : projects[up].images[2], images[3+up*5].trim() != "" ? images[3+up*5] : projects[up].images[3], images[4+up*5].trim() != "" ? images[4+up*5] : projects[up].images[4] ] }); up+=1 await Projects.update(projects[up].id, { descripcion: titulo4.trim() != "" ? titulo4 : projects[up].descripcion, images: [ images[0+up*5].trim() != "" ? images[0+up*5] : projects[up].images[0], images[1+up*5].trim() != "" ? images[1+up*5] : projects[up].images[1], images[2+up*5].trim() != "" ? images[2+up*5] : projects[up].images[2], images[3+up*5].trim() != "" ? images[3+up*5] : projects[up].images[3], images[4+up*5].trim() != "" ? images[4+up*5] : projects[up].images[4] ] }); up+=1 await Projects.update(projects[up].id, { descripcion: titulo5.trim() != "" ? titulo5 : projects[up].descripcion, images: [ images[0+up*5].trim() != "" ? images[0+up*5] : projects[up].images[0], images[1+up*5].trim() != "" ? images[1+up*5] : projects[up].images[1], images[2+up*5].trim() != "" ? images[2+up*5] : projects[up].images[2], images[3+up*5].trim() != "" ? images[3+up*5] : projects[up].images[3], images[4+up*5].trim() != "" ? images[4+up*5] : projects[up].images[4] ] }); up+=1 await Projects.update(projects[up].id, { descripcion: titulo6.trim() != "" ? titulo6 : projects[up].descripcion, images: [ images[0+up*5].trim() != "" ? images[0+up*5] : projects[up].images[0], images[1+up*5].trim() != "" ? images[1+up*5] : projects[up].images[1], images[2+up*5].trim() != "" ? images[2+up*5] : projects[up].images[2], images[3+up*5].trim() != "" ? images[3+up*5] : projects[up].images[3], images[4+up*5].trim() != "" ? images[4+up*5] : projects[up].images[4] ] }); return 'OK'; } //return slider and category return { slider }; } catch (err){ throw err; } }; }, findAll: function (req, res) { Slider.find() .then(anuncios => { if(!anuncios || anuncios.length ===0){ throw new Error('No post found'); } return res.ok(anuncios); }) .catch(err => res.notFound(err)); }, findOne : function (req,res) { Projects.find() .then( projects => { if(projects.length == 0){ return []; } return projects[0]; }) .catch(err => res.notFound(err)); }, findFirst : function (req,res) { Projects.find() .then( projects => { if(projects.length == 0){ return []; } return res.ok(projects[0]); }) .catch(err => res.notFound(err)); }, findOthers : function (req,res) { Projects.find() .then( projects => { if(projects.length == 0){ return []; } return res.ok([ projects[1], projects[2], projects[3], projects[4], projects[5], ]); }) .catch(err => res.notFound(err)); } };
QUnit.module( "modules with async hooks", hooks => { hooks.before( async assert => { assert.step( "before" ); } ); hooks.beforeEach( async assert => { assert.step( "beforeEach" ); } ); hooks.afterEach( async assert => { assert.step( "afterEach" ); } ); hooks.after( assert => { assert.verifySteps( [ "before", "beforeEach", "afterEach" ] ); } ); QUnit.test( "all hooks", assert => { assert.expect( 4 ); } ); } ); QUnit.module( "before/beforeEach/afterEach/after", { before: async assert => { assert.step( "before" ); }, beforeEach: async assert => { assert.step( "beforeEach" ); }, afterEach: async assert => { assert.step( "afterEach" ); }, after: async assert => { assert.verifySteps( [ "before", "beforeEach", "afterEach" ] ); } } ); QUnit.test( "async hooks order", assert => { assert.expect( 4 ); } );
'use strict' const JollofCommand = require('../util/JollofCommand'); const jollof = require('jollof'); const log = jollof.log; const appPaths = require('../../appPaths') class DataCommand extends JollofCommand { /** * @description this is the description of your script * @method description * @return {String} * @public */ * help() { log.info(` Contains actions for handling batch databases actions. Actions: help: Shows this message migrate: runs all pending data migrations. `) console.log(m) process.exit() } /** * @description Migrate * @method handle * @param {Object} options * @param {Object} flags * @return {void} * @public */ * migrate() { log.info("Running DATA migrations (order : name) ..."); try { var migrations = require(appPaths.appRoot+'/migrations'); var embassy = jollof.services.migration; var ignored = 0 var ran = 0 var nothingnew = true; for (var i in migrations) { var m = migrations[i]; if (yield embassy.exists(m.path) ) { //already ran } else { //set the insertion order regardless of exclusions m.order = i; //Should we exclude this from current environment? var exclude = false if (m.excludeFrom) { if (Array.isArray(m.excludeFrom)) { if (m.excludeFrom.indexOf(jollof.config.env) > -1) exclude = true } else { if (m.excludeFrom === jollof.config.env) exclude = true } } //if not exluding, run this migration if (!exclude) { log.debug("Running "+m.path+"...") var content = require(appPaths.appRoot+'/migrations/' + m.path) m.reason = content.reason; yield content.migrate_up(); yield embassy.create(m); ran++ } else { log.trace("[Migration] " + m.path + ": ignored. Excluded from " + jollof.config.env + " environment."); ignored++ } } } if (ran == 0) log.info(`No migrations ran. Database already up-to-date. Ignored ${ignored}`); else log.info(`Databases updated. Ran: ${ran} , Ignored:${ignored}`) } catch (e) { log.error(e.stack) } process.exit() } } module.exports = new DataCommand()
var Modeler = require("../Modeler.js"); var className = 'Typedemographicsaccount'; var Typedemographicsaccount = function(json, parentObj) { parentObj = parentObj || this; // Class property definitions here: Modeler.extend(className, { sortcode: { type: "string", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "sortcode", "s:annotation": { "s:documentation": "Bank sort code of main banking relationship" }, "s:simpleType": { "s:restriction": { base: "s:string", "s:maxLength": { value: 6 }, "s:minLength": { value: 1 } } }, type: "s:string" }, mask: Modeler.GET | Modeler.SET, required: false }, accountnumber: { type: "string", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "accountnumber", "s:annotation": { "s:documentation": "Account number of main banking relationship" }, "s:simpleType": { "s:restriction": { base: "s:string", "s:maxLength": { value: 20 }, "s:minLength": { value: 1 } } }, type: "s:string" }, mask: Modeler.GET | Modeler.SET, required: false }, timeatbank: { type: "Typeduration", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "timeatbank", type: "s:duration" }, mask: Modeler.GET | Modeler.SET, required: false }, paymentmethod: { type: "Typedemographicspaymentmethod", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "paymentmethod", type: "tns:demographicspaymentmethod", "s:annotation": { "s:documentation": "Account&apos;s Payment Method Code" } }, mask: Modeler.GET | Modeler.SET, required: false }, financetype: { type: "Typedemographicsfinancetype", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "financetype", type: "tns:demographicsfinancetype", "s:annotation": { "s:documentation": "Finance/Non Finance Type Code" } }, mask: Modeler.GET | Modeler.SET, required: false } }, parentObj, json); }; module.exports = Typedemographicsaccount; Modeler.register(Typedemographicsaccount, "Typedemographicsaccount");
import React, { useEffect, useState } from 'react' import PropTypes from 'prop-types' import { getComicStories } from '../../../services/comics.service' import StoryCard from '../../stories/story-card' import Spinner from '../../spinner' import NoContent from '../../no-content' function ComicStories(props) { const { comicId } = props const [stories, setStories] = useState([]) const [loading, setLoading] = useState(true) useEffect(() => { const getData = async () => { setLoading(true) const { data } = await getComicStories(comicId) setStories(data?.data.results) setLoading(false) } getData() }, [comicId]) const renderStoryCards = () => stories.map((story, index) => ( <StoryCard key={'comic-story-' + index} id={story.id} name={story.title} /> )) const renderSpinner = () => (loading ? <Spinner /> : null) const renderNoContent = () => !loading && !stories?.length ? <NoContent /> : null return ( <div className="ContentRow"> {renderSpinner()} {renderStoryCards()} {renderNoContent()} </div> ) } ComicStories.propTypes = { comicId: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), } export default ComicStories
global.api.File.board_add_file = function( doc ){ global.api.REQUIRES.MongoDB.MongoClient.connect(global.DB.CONFIG.driver_connect_url , function(err, db) { global.CSJLog.log("Connected correctly to server"); //ToDo function 으로 분리하기; var Long = require('mongodb').Long; var d = new Date(); var r = [ Long( d.getFullYear() ).toInt(), Long( d.getMonth() + 1 ).toInt(), Long( d.getDate() ).toInt(), Long( d.getHours() ).toInt(), Long( d.getMinutes() ).toInt(), Long( d.getSeconds() ).toInt() ]; var _to = { _id : -1 , _d : Long( 1 ).toInt() , member : { _id : -1 , mid : doc.member.mid , nm : doc.member.nm , image : doc.member.image } , cd : "" , cd$project : doc.cd$project , cd$notebook : doc.cd$notebook , cd$doc : doc.cd$doc , filePath : doc.filePath , fileNm : doc.fileNm , fileExtend : doc.fileExtend , regist_date : r , delete_date : null } var db0 = db.db('file'); var db1 = db.db('member'); db0.collection("board").find({}).sort({_id : -1}).limit(1).toArray(function(err,result){ if( result.length == 0 ) var idx = 0 else var idx = result[ 0 ]._id + 1 _to._id = idx; db0.collection("board").count({ cd$doc : doc.cd$doc },function(err,result){ var doc_idx = result; _to.cd = doc.cd$doc + "-FILE" + doc_idx; db0.collection("board").insert(_to,function(d){ console.log("file add OK!") db.close(); }); }) }); }); };
/************************************************************************** \ | Subitup Schedule View | | Author: Robert Arango | | Date: 10/17/2012 | | File: GenerateSchedule.js | | Info: This script reads all the shifts that are pulled from subitup | | through RetrieveShifts.php and then generates the schedule | | depending on which view is selected. | \***************************************************************************/ /***************************************************\ | Declare All Globally Available Variable | \***************************************************/ var current_time = new Date(); var column_Counter = 0; var fri_date,sat_date,sun_date,mon_date,tue_date,wed_date,thu_date; var week_dates = new Array(); /**************************************************\ | Create Date Objects for all JSON Dates | \**************************************************/ function ConvertDateTimes() { for (i=0; i < Departments.length; i++){ for (j=0;j<Shifts[i].Table.length;j++) { Shifts[i].Table[j].S_DateTimeIn = Date.parse(Shifts[i].Table[j].S_DateTimeIn); Shifts[i].Table[j].S_DateTimeOut = Date.parse(Shifts[i].Table[j].S_DateTimeOut); } } } /**************************************************\ | Calculate Week Dates if Neccessary | \**************************************************/ function CalculateWeekDates(){ fri_date = new Date(php_start_date.add({days:1})); sat_date = new Date(php_start_date.add({days:1})); sun_date = new Date(php_start_date.add({days:1})); mon_date = new Date(php_start_date.add({days:1})); tue_date = new Date(php_start_date.add({days:1})); wed_date = new Date(php_start_date.add({days:1})); thu_date = new Date(php_start_date.add({days:1})); week_dates[0] = fri_date; week_dates[1] = sat_date; week_dates[2] = sun_date; week_dates[3] = mon_date; week_dates[4] = tue_date; week_dates[5] = wed_date; week_dates[6] = thu_date; } /**************************************************\ | Countdown Timer & Clock | \**************************************************/ function CountdownTimer() { var startSeconds = 900; var miuntesLeft; var secondsLeft; setInterval(function(){ if(startSeconds == 5){ document.location.reload(true); } startSeconds = startSeconds - 1; minutesLeft = Math.floor(startSeconds/60); secondsLeft = Math.floor(startSeconds - (minutesLeft*60)); document.getElementById('min_left').innerHTML = minutesLeft; document.getElementById('sec_left').innerHTML = secondsLeft; }, 1000); } function Clock(){ var time_now = new Date(); document.getElementById('clock').innerHTML = time_now.toString("ddd MMM dd, yyyy | h:mmtt"); setInterval(function(){ time_now = new Date(); document.getElementById('clock').innerHTML = time_now.toString("ddd MMM dd, yyyy | h:mmtt"); }, 15000); } /**************************************************\ | Create Week View | \**************************************************/ function GenerateWeekView(){ for(i=0; i < Departments.length; i++){ document.write("<table>"); document.write("<tr><th class='department' colspan='7'>" + Departments[i] + "</th></tr>"); document.write("<tr>"); document.write("<th>Friday<br />" + fri_date.toString("MM/dd") + "</th><th>Saturday<br />" + sat_date.toString("MM/dd") + "</th><th>Sunday<br />" + sun_date.toString("MM/dd") + "</th><th>Monday<br />" + mon_date.toString("MM/dd") + "</th><th>Tuesday<br />" + tue_date.toString("MM/dd") + "</th><th>Wednesday<br />" + wed_date.toString("MM/dd") + "</th><th>Thursday<br />" + thu_date.toString("MM/dd") + "</th>"); document.write("</tr>"); document.write("<tr>"); var arr = []; var obj = { start_time: Shifts[i].Table[0].S_DateTimeIn, end_time: Shifts[i].Table[0].S_DateTimeOut }; arr.push(obj); for (var j = 1; j < Shifts[i].Table.length; j++) { var duplicate = 0; for (var k = 0; k < arr.length; k++){ if(Date.equals(Shifts[i].Table[j].S_DateTimeIn,arr[k].start_time) && Date.equals(Shifts[i].Table[j].S_DateTimeOut,arr[k].end_time)){ duplicate = 1; } } if (duplicate == 0) { var obj = { start_time: Shifts[i].Table[j].S_DateTimeIn, end_time: Shifts[i].Table[j].S_DateTimeOut }; arr.push(obj); } } for(w=0; w<week_dates.length; w++){ document.write("<td>"); if(arr.length > 0){ var no_shifts = true; for (var k = 0; k < arr.length; k++){ if(arr[k].start_time.same().day(week_dates[w])){ if(current_time.between(arr[k].start_time,arr[k].end_time)){ document.write('<pre class="onShift">'); } else { document.write('<pre>'); } document.write('<span class="time"><b>'+arr[k].start_time.toString("hh:mmtt")+'-'+ arr[k].end_time.toString("hh:mmtt")+'</b></span><br />'); for (var j = 0; j < Shifts[i].Table.length; j++) { if (Date.equals(Shifts[i].Table[j].S_DateTimeIn,arr[k].start_time) && Date.equals(Shifts[i].Table[j].S_DateTimeOut,arr[k].end_time)){ if(Shifts[i].Table[j].status == "add"){ document.write("<span style='color:red';><b>"+Shifts[i].Table[j].firstname+' '+ Shifts[i].Table[j].lastname+'</b></span><br />'); } if(Shifts[i].Table[j].status == "set"){ document.write(Shifts[i].Table[j].firstname+' '+Shifts[i].Table[j].lastname+'<br />'); } no_shifts = false; } } document.write('</pre>'); } } if(no_shifts == true){ document.write('<pre class="NoShift">'); document.write('There are no Shifts<br />scheduled today.'); document.write('</pre>'); } } document.write("</td>"); } document.write("</tr>"); document.write("</table>"); } } /**************************************************\ | Create Today View | \**************************************************/ function GenerateTodayView(){ document.write("<div class='row-fluid'>"); for(i=0; i<Departments.length; i++){ var arr = []; var obj = { start_time: Shifts[i].Table[0].S_DateTimeIn, end_time: Shifts[i].Table[0].S_DateTimeOut }; arr.push(obj); for (var j = 1; j < Shifts[i].Table.length; j++) { var duplicate = 0; for (var k = 0; k < arr.length; k++){ if(Date.equals(Shifts[i].Table[j].S_DateTimeIn,arr[k].start_time) && Date.equals(Shifts[i].Table[j].S_DateTimeOut,arr[k].end_time)){ duplicate = 1; } } if (duplicate == 0) { var obj = { start_time: Shifts[i].Table[j].S_DateTimeIn, end_time: Shifts[i].Table[j].S_DateTimeOut }; arr.push(obj); } } if(arr.length > 0){ var no_shifts = true; document.write("<div class='span4'>"); document.write("<table>"); document.write("<tr><th class='department' colspan='1'>" + Departments[i] + "</th></tr>"); document.write("<tr>"); document.write("<td>"); for (var k = 0; k < arr.length; k++){ if(current_time.between(arr[k].start_time,arr[k].end_time)){ document.write('<pre class="onShift">'); } else { document.write('<pre>'); } document.write('<span class="time"><b>'+arr[k].start_time.toString("hh:mmtt")+'-'+ arr[k].end_time.toString("hh:mmtt")+'</b></span><br />'); for (var j = 0; j < Shifts[i].Table.length; j++) { if (Date.equals(Shifts[i].Table[j].S_DateTimeIn,arr[k].start_time) && Date.equals(Shifts[i].Table[j].S_DateTimeOut,arr[k].end_time)){ if(Shifts[i].Table[j].status == "add"){ document.write("<span style='color:red';><b>"+Shifts[i].Table[j].firstname+' '+ Shifts[i].Table[j].lastname+'</b></span><br />'); } if(Shifts[i].Table[j].status == "set"){ document.write(Shifts[i].Table[j].firstname+' '+Shifts[i].Table[j].lastname+'<br />'); } no_shifts = false; } } document.write('</pre>'); } if(no_shifts == true){ document.write('<pre class="NoShift">'); document.write('There are no Shifts scheduled today.'); document.write('</pre>'); } document.write("</td>"); document.write("</tr>"); document.write("</table>"); document.write("</div>"); } column_Counter++; if(column_Counter == 3){ document.write("</div>"); document.write("<div class='row-fluid'>"); column_Counter = 0; } } document.write("</div>"); } /**************************************************\ | Create Who's On Now View | \**************************************************/ function GenerateWhosOnNowView() { document.write("<div class='row-fluid'>"); for(i=0; i<Departments.length; i++){ var arr = []; var obj = { start_time: Shifts[i].Table[0].S_DateTimeIn, end_time: Shifts[i].Table[0].S_DateTimeOut }; arr.push(obj); for (var j = 1; j < Shifts[i].Table.length; j++) { var duplicate = 0; for (var k = 0; k < arr.length; k++){ if(Date.equals(Shifts[i].Table[j].S_DateTimeIn,arr[k].start_time) && Date.equals(Shifts[i].Table[j].S_DateTimeOut,arr[k].end_time)){ duplicate = 1; } } if (duplicate == 0) { var obj = { start_time: Shifts[i].Table[j].S_DateTimeIn, end_time: Shifts[i].Table[j].S_DateTimeOut }; arr.push(obj); } } if(arr.length > 0){ var no_shifts = true; document.write("<div class='span4'>"); document.write("<table>"); document.write("<tr><th class='department' colspan='1'>" + Departments[i] + "</th></tr>"); document.write("<tr>"); document.write("<td>"); for (var k = 0; k < arr.length; k++){ if(current_time.between(arr[k].start_time,arr[k].end_time)){ document.write('<pre class="onShift">'); document.write('<span class="time"><b>'+arr[k].start_time.toString("hh:mmtt")+'-'+ arr[k].end_time.toString("hh:mmtt")+'</b></span><br />'); for (var j = 0; j < Shifts[i].Table.length; j++) { if (Date.equals(Shifts[i].Table[j].S_DateTimeIn,arr[k].start_time) && Date.equals(Shifts[i].Table[j].S_DateTimeOut,arr[k].end_time)){ if(Shifts[i].Table[j].status == "add"){ document.write("<span style='color:red';><b>"+Shifts[i].Table[j].firstname+' '+ Shifts[i].Table[j].lastname+'</b></span><br />'); } if(Shifts[i].Table[j].status == "set"){ document.write(Shifts[i].Table[j].firstname+' '+Shifts[i].Table[j].lastname+'<br />'); } no_shifts = false; } } document.write('</pre>'); } } if(no_shifts == true){ document.write('<pre class="NoShift">'); document.write('There are no Shifts scheduled now.'); document.write('</pre>'); } document.write("</td>"); document.write("</tr>"); document.write("</table>"); document.write("</div>"); } column_Counter++; if(column_Counter == 3){ document.write("</div>"); document.write("<div class='row-fluid'>"); column_Counter = 0; } } document.write("</div>"); }
const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({ template: './index.html', filename: 'index.html', inject: 'body' }); module.exports = { context: path.resolve(__dirname, 'client'), entry: [ 'react-hot-loader/patch', // activate HMR for React 'webpack-dev-server/client?http://localhost:8080', // bundle the client for webpack-dev-server // and connect to the provided endpoint 'webpack/hot/only-dev-server', // bundle the client for hot reloading // only- means to only hot reload for successful updates './index.js' ], output: { path: path.resolve('dist'), filename: 'bundle.js', publicPath: '/' }, devtool: 'inline-source-map', devServer: { hot: true, contentBase: path.resolve(__dirname, 'dist'), publicPath: '/' }, module: { loaders: [ {test:/\.js$/, loader: 'babel-loader', exclude:/node_modules/} ] }, plugins: [ new webpack.HotModuleReplacementPlugin(), HtmlWebpackPluginConfig ] };
import styled from 'styled-components'; const Wrapper = styled.div` display: flex; min-height: 100vh; flex-direction: column; overflow: hidden; position: relative; background: #fffff3; `; const Layout = ({ children }) => { return <Wrapper>{children}</Wrapper>; }; export default Layout;
import React, { Component } from 'react'; import { FoldingCube } from 'better-react-spinkit' class SpinnerComponent extends Component { render() { return ( <div className="spinner-container"> <FoldingCube size={100} color='#26B4FF'/> </div> ); } } export default SpinnerComponent;
export const getPlayers = playerInfo => dispatch => { const players = []; playerInfo.find({ fileName: 'gameAnalysis' }, (err, docs) => { docs.map(d => { const player = { title: d.TeamvsTeam, _id: d._id }; players.push(player); }); players.sort((a,b) => (a.title > b.title) ? 1 : ((b.title > a.title) ? -1 : 0)) dispatch({ type: 'GA_TEAMS', players }); }); }; export const getRecords = playerInfo => dispatch => { const records = []; playerInfo.find({ fileName: 'gameAnalysis' }, (err, docs) => { dispatch({ type: 'GA_RECORDS', records: docs }); }); };
// console.log('working?'); var favRecipe = { title: 'Guacamole', servings: 3, ingredients: ['avacado','lemon','salt','onion'] }; //cmd-shift-L multiline shortcut console.log(favRecipe.title); console.log("Serves", + favRecipe.servings); console.log("Ingredients: "); for (var i = 0; i < favRecipe.ingredients.length; i++){ console.log((i+ 1) + " " + favRecipe.ingredients[i]); } console.log(favRecipe.ingredients.join('\n')); var books = [ { title:'The Sun also Rises', author:'Ernest Hemingway', alreadyRead: true, }, { title:'Homegoing', author:'Yaa Gyasi', alreadyRead: true, }, { title:'Americanah', author:'Chimamanda Ngozi Adichie', alreadyRead: true, }, { title:'A Gentleman in Moscow', author:'Amor Towles', alreadyRead: false, } ] for (var i = 0; i < books.length; i++){ console.log(books[i].title + ' by ' + books[i].author); } for (var i = 0; i < books.length; i ++){ if (books[i].alreadyRead === true){ console.log ("You have already read " + books[i].title + "."); } else { console.log("You still need to read " + books[i].title + "."); } } var movies = { title:'Goodwill Hunting', duration:126, stars: ['Matt Damon','Ben Affleck','Robin Williams'] }; console.log(movies.title + " lasts for " + movies.duration + " minutes. Stars " + movies.stars[0] + ", " + movies.stars[1]+ " and " + movies.stars[2] + ".") var movieInfo = function(movies){ return movies.title + " lasts for " + movies.duration + " minutes. Stars " + movies.stars + "." } console.log( movieInfo(movies) );
import React, { useState } from 'react'; import { withStyles, ThemeProvider } from '@material-ui/core/styles'; import Button from '@material-ui/core/Button'; import Grid from '@material-ui/core/Grid'; import AddFromExistingForm from 'components/AddFromExistingForm'; import ActionItemForm from 'components/ActionItemForm'; import PropTypes from 'prop-types'; import theme from 'utils/theme'; import styles from './styles'; const Setting = { SCRATCH: 0, TEMPLATE: 1, }; function ActionItemCreationContainer({ classes, templates, selectedActionItemIds, title, setTitle, description, setDescription, categorySelected, setCategory, dueDate, setDueDate, selectActionItemTemplate, removeSelectedActionItem, createActionItem, deleteTemplate, setFile, handleOpenModal, categories, }) { const [creationSetting, setCreationSetting] = useState(Setting.TEMPLATE); const [addToTemplates, setAddToTemplates] = useState(false); const renderButtonRow = () => { const isTemplateSetting = creationSetting === Setting.TEMPLATE; return ( <Grid container item justify="flex-start" className={classes.containerStyle} > <Grid item> <Button disableElevation variant={isTemplateSetting ? 'contained' : 'outlined'} size="small" className={ isTemplateSetting ? classes.selectedButton : classes.unselectedButton } onClick={() => setCreationSetting(Setting.TEMPLATE)} > SEE COMMON ASSIGNMENTS </Button> </Grid> <Grid item> <Button disableElevation variant={!isTemplateSetting ? 'contained' : 'outlined'} size="small" className={ !isTemplateSetting ? classes.selectedButton : classes.unselectedButton } onClick={() => setCreationSetting(Setting.SCRATCH)} > CREATE FROM SCRATCH </Button> </Grid> </Grid> ); }; return ( <ThemeProvider theme={theme}> <Grid container direction="column" alignItems="center" justify="center" className={classes.containerStyle} > {renderButtonRow()} <Grid item container> {creationSetting === Setting.SCRATCH ? ( <ActionItemForm title={title} setTitle={setTitle} description={description} setDescription={setDescription} categorySelected={categorySelected} setCategory={setCategory} dueDate={dueDate} setDueDate={setDueDate} addToTemplates={addToTemplates} setAddToTemplates={setAddToTemplates} createActionItem={createActionItem} setFile={setFile} categories={categories} /> ) : ( <AddFromExistingForm templates={templates} selectedActionItemIds={selectedActionItemIds} selectActionItemTemplate={selectActionItemTemplate} removeSelectedActionItem={removeSelectedActionItem} deleteTemplate={deleteTemplate} handleOpenModal={handleOpenModal} categories={categories} /> )} </Grid> </Grid> </ThemeProvider> ); } ActionItemCreationContainer.propTypes = { classes: PropTypes.object.isRequired, templates: PropTypes.array.isRequired, selectedActionItemIds: PropTypes.instanceOf(Set).isRequired, title: PropTypes.string.isRequired, description: PropTypes.string.isRequired, dueDate: PropTypes.string.isRequired, categorySelected: PropTypes.string, setTitle: PropTypes.func.isRequired, setDescription: PropTypes.func.isRequired, createActionItem: PropTypes.func.isRequired, selectActionItemTemplate: PropTypes.func.isRequired, removeSelectedActionItem: PropTypes.func.isRequired, setDueDate: PropTypes.func.isRequired, setCategory: PropTypes.func.isRequired, deleteTemplate: PropTypes.func.isRequired, handleOpenModal: PropTypes.func.isRequired, categories: PropTypes.array.isRequired, setFile: PropTypes.func.isRequired, }; export default withStyles(styles)(ActionItemCreationContainer);
import React from 'react' import PropTypes from 'prop-types' import { withStyles } from '@material-ui/core/styles' class Toolbar extends React.PureComponent { render() { const { classes, children, show } = this.props if (!show) { return null } return ( <div className={classes.root}> {children} </div> ) } } const styles = (theme) => ({ root: { display: 'flex', alignItems: 'center', margin: 2 * theme.spacing.unit, height: 48 } }) export default withStyles(styles)(Toolbar)
import { renderString } from '../../src/index'; describe(`Return a random item from the sequence.`, () => { it(`The example below is a standard blog loop that returns a single random post.`, () => { const html = renderString(`{% set contents = ['cats'] %} {% for content in contents|random %} <div class="post-item">Post item markup</div>{% endfor %}`); expect(html).toContain('Post item'); }); });
import ProfProfileForm from './ProfProfileForm'; export default ProfProfileForm;
/** * Created by yishan on 17/4/9. */ /** * 由于 支持 Object.defineProperty()的访问属性的方法 完全支持需要IE9以上 IE8不完全实现 * 所以一般创建访问器属性 使用下面的这种方法 * @type {{_name: string}} */ var person = { _name:'lc' }; person.__defineGetter__('name', function () { return this._name; }); person.__defineSetter__('name', function (val) { this._name = val+'好好学习'; }); person.name = 'glc'; console.log(person.name);
/** * Created by xiaojiu on 2016/11/19. */ define(['../../../app','../../../services/platform/settle-accounts/examineBlaOutInService'], function (app) { var app = angular.module('app'); app.controller('examineBlaOutInCtrl', ['$rootScope', '$scope', '$stateParams','$state', '$sce', '$filter', 'HOST', '$window','examineBlaOutIn', function ($rootScope, $scope,$stateParams, $state, $sce, $filter, HOST, $window,examineBlaOutIn) { // query moudle setting $scope.querySeting = { items: [ { type: 'text', model: 'taskId', title: '申请编号' },{ type: 'date', model: ['startTime', 'endTime'], title: '申请时间' }, { type: 'select', model: 'chruType', selectedModel: 'chruTypeSelect', title: '特殊出入库类型' }], btns: [{ text: $sce.trustAsHtml('查询'), click: 'searchClick' }] }; //table头 $scope.thHeader = examineBlaOutIn.getThead(); $scope.lookModelThHeader = examineBlaOutIn.getLookModelThHeader(); //分页下拉框 $scope.pagingSelect = [ {value: 5, text: 5}, {value: 10, text: 10, selected: true}, {value: 20, text: 20}, {value: 30, text: 30}, {value: 50, text: 50} ]; //分页对象 $scope.paging = { totalPage: 1, currentPage: 1, showRows: 30, }; var pmsSearch = examineBlaOutIn.getSearch(); pmsSearch.then(function (data) { $scope.searchModel = data.query; //设置当前作用域的查询对象 $scope.searchModel.chruTypeSelect = "-1"; $scope.storageRDC = data.query.rdcId; $scope.storageCDC = data.query.cdcId; $scope.storageSelectedRDC = '-1'; //获取table数据 get(); }, function (error) { console.log(error) }); //查询 $scope.searchClick = function () { $scope.paging = { totalPage: 1, currentPage: 1, showRows: $scope.paging.showRows }; get(); } function get() { //获取选中 设置对象参数 var opts = angular.extend({}, $scope.searchModel, {}); //克隆出新的对象,防止影响scope中的对象 opts.rdcId = $scope.storageSelectedRDC;//获取仓储选择第一个下拉框 opts.cdcId = $scope.storageSelectedCDC;//获取仓储选择第二个下拉框 opts.chruType = $scope.searchModel.chruTypeSelect; opts.pageNo = $scope.paging.currentPage; opts.pageSize = $scope.paging.showRows; var promise = examineBlaOutIn.getDataTable( '/examine/getBalOutInCkOrderOrderList', { param: { query: opts } } ); promise.then(function (data) { $scope.result = data.grid; $scope.paging = { totalPage: data.total, currentPage: $scope.paging.currentPage, showRows: $scope.paging.showRows, }; // $scope.paging.totalPage = data.total; }, function (error) { console.log(error); }); } //分页跳转回调 $scope.goToPage = function () { get(); } //查看bannerModel $scope.lookBannerModel={ "ckName": "", "taskId": "", "examineUserName": "", "type": "", "createUserName": "", "totalMoney": "", } //查看 $scope.lookCus=function(index,item){ var promise = examineBlaOutIn.getDataTable('/examine/getBalOutInCkOrderDetailList', { param: { query: { taskId: item.taskId } } } ); promise.then(function(data){ $rootScope.taskId= data.banner.taskId; $scope.lookBannerModel = data.banner; $scope.lookModelResult=data.grid; }) } //确认财务信息 $scope.update= function () { var promise = examineBlaOutIn.getDataTable('/examine/updateBalOutInCkOrder', { param: { query: { taskId: $rootScope.taskId } } } ); promise.then(function(data){ $("#settleModal").modal("hide"); alert(data.status.msg); get() }) } //打印 $scope.print= function () { $window.open("/print/examineBlaOutInPrint.html?tokenId="+$rootScope.userInfo.token+"&sessionid="+$rootScope.userInfo.sessionId+"&taskId="+$rootScope.taskId); $('#lookModal').modal('hide'); } }]) });
let url = "https://jsonplaceholder.typicode.com/users/1"; const fetchPromise = fetch(url); console.log(fetchPromise); // fetchPromise // .then(res => { // console.log(res); // }); // function callback1(res) { // console.log(res); // }; // fetchPromise // .then(callback1); fetchPromise .then((res) => { return res.json(); }) .then((data) => { console.log("data: ", data); return data.name }) .then((name) => { console.log("name: ", name); });
import muster, { applyTransforms, arrayList, count, eq, filter, get, head, length, location, ref, variable, } from '@dws/muster-react'; import 'todomvc-app-css/index.css'; import loadItems from '../utils/load-items'; export default function createGraph() { return muster({ itemCount: ref('itemList', length()), itemList: arrayList( loadItems().map((item) => ({ id: item.id, label: variable(item.label), completed: variable(item.completed), editing: variable(false), temp: variable(''), })), ), remainingCount: head( applyTransforms(ref('itemList'), [ filter((item) => eq(get(item, 'completed'), false)), count(), ]), ), nav: location({ hash: 'slash' }), }); }
/* * fil: js.js * purpose: introdction to jQuery */ console.log('file: js/js.js loaded'); // A $( document ).ready() block. // ... codeing from here ... /* THE DOCUMENTATION MAY CONFUSE YOU A BIT, SO HERE'S A HOWTO DON'T please, don't use this sample: https://samples.openweathermap.org/data/2.5/weather?q=Aarhus,DK&appid=YOURTOKENHERE DO Use the api as below: https://api.openweathermap.org/data/2.5/weather?q=Aarhus,DK&appid=YOURTOKENHERE PS: Probably your token will not activate right away. Have some patience here. */ const token = "201d090c9cceacfc8931df89310ebfbb"; // save your token in this variable const aarhus = "https://api.openweathermap.org/data/2.5/weather?q=Aarhus,DK&appid=" + token + "&units=metric"; $(document).ready(function () { // get the weather data fetch(aarhus).then(response => { return response.json(); }).then(data => { // Work with JSON data here console.log(data); // show what's in the json $('#result').append( '<div class="weatherInfo">' + data.weather[0].main + ' in ' + data.name + '<figure><img src="http://openweathermap.org/img/w/' + data.weather[0].icon + '.png" alt="The weather : ' + data.weather[0].main + '"></figure>' + '</div>'); // here are the icons: https://openweathermap.org/weather-conditions }).catch(err => { // Do something for an error here console.log('There was an error ...'); }); }); // document ready end mapboxgl.accessToken = 'pk.eyJ1IjoiamVubnltYWUiLCJhIjoiY2tmcWtlbGNtMGJ0NTJ3bzB2ODM2NWl3biJ9.OoNBfHTXEtINPw6pee5DVg'; var map = new mapboxgl.Map({ container: 'map', // container id style: 'mapbox://styles/jennymae/ckfxt6os90k6p19qipk7uwlyf', // style URL center: [10.551, 56.424], // starting position [lng, lat] zoom: 15 // starting zoom });
const mongoose = require("mongoose"); let productoSchema = new mongoose.Schema({ idArticulo: String, nombre: String, descripcion: String, precio: Number, modelo: String }); module.exports = mongoose.model("producto", productoSchema);
../../../../shared/src/generic/reducers.js
// JavaScript - Node v8.1.3 Test.assertEquals(f(100), 5050);