text
stringlengths
7
3.69M
// Formats the time (mm:ss) export function convertToTime(float) { let rounded = Math.floor(float); let minutes = Math.floor(rounded / 60); let seconds = rounded % 60; let string = ''; string = `${minutes}:`; return seconds < 10 ? string + `0${seconds}` : string + `${seconds}`; }
import React from 'react'; import ReactDOM from 'react-dom'; import FlightSegment from '../FlightSegment/FlightSegment'; class FlightSegments extends React.Component { constructor(props) { super(props); } render() { return ( <div> {this.props.data.map((datum,index) => { return ( <FlightSegment key={index} data={datum} /> ) })} </div> ); } } export default FlightSegments;
function autocomplete(input, latInput, lngInput) { // Wes explains how to do this in Video 16 but I skipped it because of the google maps billing } export default autocomplete;
exports.Game = require('./game'); exports.Deck = require('./deck'); exports.Board = require('./board'); exports.Player = require('./player'); exports.modes = require('./modes');
const FiltersData = { "ALL_MOVIES": { CAPTION: `All movies`, HAS_COUNTER: false, LINK: `#all`, IS_ACTIVE: true, ACTION: (films) => films, }, "WATCHLIST": { CAPTION: `Watchlist`, HAS_COUNTER: true, LINK: `#watchlist`, IS_ACTIVE: false, ACTION: (films) => films.reduce((total, it) => it.isWatchlisted ? ++total : total, 0), }, "HISTORY": { CAPTION: `History`, HAS_COUNTER: true, LINK: `#history`, IS_ACTIVE: false, ACTION: (films) => films.reduce((total, it) => it.isWatched ? ++total : total, 0), }, "FAVORITES": { CAPTION: `Favorites`, HAS_COUNTER: true, LINK: `#favorites`, IS_ACTIVE: false, ACTION: (films) => films.reduce((total, it) => it.isFavorite ? ++total : total, 0), }, }; const generateFilter = (filter) => { return { caption: filter.CAPTION, hasCounter: filter.HAS_COUNTER, link: filter.LINK, isActive: filter.IS_ACTIVE, action: filter.ACTION, }; }; const generateFilters = () => { const targetFilters = []; for (const filterKey in FiltersData) { if (FiltersData.hasOwnProperty(filterKey)) { targetFilters.push(generateFilter(FiltersData[filterKey])); } } return targetFilters; }; export {generateFilters};
import React, { useState } from 'react' import { Card, Container, Image, Title, Select, CardHeader, Subtitle } from './styles.js'; import Signo from '../../components/Signo'; import aquario from "../../assets/images/signos/aquario.png" import libra from "../../assets/images/signos/libra.png" import gemeos from "../../assets/images/signos/gemeos.png" import cancer from "../../assets/images/signos/cancer.png" import touro from "../../assets/images/signos/touro.png" import leao from "../../assets/images/signos/leao.png" import virgem from "../../assets/images/signos/virgem.png" import peixes from "../../assets/images/signos/peixes.png" import aries from "../../assets/images/signos/aries.png" import capricornio from "../../assets/images/signos/capricornio.png" import sargitario from "../../assets/images/signos/sargitario.png" import escorpiao from "../../assets/images/signos/escorpiao.png" export default function Index() { const signos = [ { name: "Aquario", value: "aquario", img: aquario }, { name: "Peixes", value: "peixes", img: peixes }, { name: "Aries", value: "aries", img: aries }, { name: "Touro", value: "touro", img: touro }, { name: "Gêmeos", value: "gemeos", img: gemeos }, { name: "Cancer", value: "cancer", img: cancer }, { name: "Leão", value: "leao", img: leao }, { name: "Virgem", value: "virgem", img: virgem }, { name: "Libra", value: "libra", img: libra }, { name: "Escorpião", value: "escorpiao", img: escorpiao }, { name: "Sargitário", value: "sargitario", img: sargitario }, { name: "Capricórnio", value: "capricornio", img: capricornio }, ] const [signo, setSigno] = useState("") const changeSigno = (event) => { const filterSigno = signos.find(opt => opt.value === event) setSigno(filterSigno) } return ( <Container> <div> <Card> <CardHeader> <Title>Selecione o Signo</Title> <Subtitle>Confira o que os astros tem a dizer para o seu signo hoje</Subtitle> </CardHeader> <Select name="signos" onChange={e => changeSigno(e.currentTarget.value)}> <option value="">Selecione seu signo</option> {signos.map(signo => ( <option key={signo.value} value={signo.value}>{signo.name}</option> ))} </Select> <Image src={signo.img} /> </Card> </div> <Signo signo={signo} /> </Container> ) }
var babel = require('babel'); var bowerFiles = require('main-bower-files'); module.exports = function (wallaby) { var files = bowerFiles() .map(function (fileName) { return {pattern: fileName, instrument: false}; }); var otherFiles =[ {pattern: 'node_modules/babel/node_modules/babel-core/browser-polyfill.js', instrument: false}, {pattern: 'node_modules/babel-core/browser-polyfill.js', instrument: false}, {pattern: 'bower_components/angular-mocks/angular-mocks.js', instrument: false}, 'src/app/app.js', 'src/**/*.js', '!src/**/*spec.js' ]; return { files: files.concat(otherFiles), tests: [ 'src/**/*spec.js' ], compilers: { '**/*.js': wallaby.compilers.babel({ babel: babel, // NOTE: If you're using Babel 6, it should be `presets: ['es2015']` instead of `stage: 0`. // You will also need to // npm install babel-core (and require it instead of babel) // and // npm install babel-preset-es2015 // See http://babeljs.io/docs/plugins/preset-es2015/ stage: 0 }) } }; };
import React from "react"; import { render } from "react-dom"; import Photos from "./Photos"; import { store } from "./store"; import { Provider } from "react-redux"; import './index.css'; const App = () => ( <Provider store={store}> <Photos /> </Provider> ); render(<App />, document.getElementById("root"));
import React from "react"; import PropTypes from "prop-types"; import styled from "styled-components"; const Container = styled.div` margin-bottom: 10px; `; const List = styled.ul` margin-top: 5px; `; const Item = styled.li` font-weight: bolder; `; const Pay = styled.li` font-weight: bold; `; const CoinExchange = ({ name, fiats }) => ( <Container> <List> <Item>{name}</Item> <Pay>Pay On USD {fiats.map(fiat => `${fiat.symbol}\t`)}</Pay> </List> </Container> ); CoinExchange.propTypes = { name: PropTypes.string.isRequired, fiats: PropTypes.array.isRequired }; export default CoinExchange;
var aesjs = require('aes-js'); // An example 128-bit passwordBytes (16 bytes * 8 bits/byte = 128 bits) var passwordBytes = aesjs.utils.utf8.toBytes("145678"); // Convert seed to bytes var seed = 'dignity cradle very post bulb credit super close forget twelve guess lawn'; var seedBytes = aesjs.utils.utf8.toBytes(seed); // The counter is optional, and if omitted will begin at 1 var aesCtr = new aesjs.ModeOfOperation.ctr(passwordBytes, new aesjs.Counter(5)); var encryptedBytes = aesCtr.encrypt(seedBytes); // To print or store the binary data, you may convert it to hex var encryptedHex = aesjs.utils.hex.fromBytes(encryptedBytes); console.log(encryptedHex); // "a338eda3874ed884b6199150d36f49988c90f5c47fe7792b0cf8c7f77eeffd87 // ea145b73e82aefcf2076f881c88879e4e25b1d7b24ba2788" // When ready to decrypt the hex string, convert it back to bytes var encryptedBytes = aesjs.utils.hex.toBytes(encryptedHex); // The counter mode of operation maintains internal state, so to // decrypt a new instance must be instantiated. var aesCtr = new aesjs.ModeOfOperation.ctr(passwordBytes, new aesjs.Counter(5)); var decryptedBytes = aesCtr.decrypt(encryptedBytes); // Convert our bytes back into seed var decryptedText = aesjs.utils.utf8.fromBytes(decryptedBytes); console.log(decryptedText); // "Text may be any length you wish, no padding is required."
module.exports = { up: queryInterface => { return queryInterface.removeColumn('meetup', 'org_id'); }, down: queryInterface => { return queryInterface.addColumn('meetup', 'org_id'); }, };
import './sass/main.scss'; import menuTemplate from './menu.json' import menuList from './tamplates/list.hbs' // refs const menuRef = document.querySelector('.js-menu') const checkboxRef = document.querySelector('#theme-switch-toggle'); const bodyRef = document.querySelector('body'); // Theme const Theme = { LIGHT: 'light-theme', DARK: 'dark-theme', }; // addition markup const markup = menuTemplate.map(menuList).join('') menuRef.insertAdjacentHTML('beforeend', markup) // theme picker if (localStorage.theme === Theme.DARK) { checkboxRef.checked = true; bodyRef.classList.add(Theme.DARK); } checkboxRef.addEventListener('change', onChangeAction); // console.log(localStorage.getItem('userSettings', JSON.stringify(Theme))) function onChangeAction() { if (checkboxRef.checked === true) { bodyRef.classList.add(Theme.DARK); bodyRef.classList.remove(Theme.LIGHT); localStorage.setItem('theme', Theme.DARK); } else { bodyRef.classList.add(Theme.LIGHT); bodyRef.classList.remove(Theme.DARK); localStorage.setItem('theme', Theme.LIGHT); } }
// 过滤falsy false null 0 "" undefined NaN const compact = arr => arr.filter(Boolean)
export const SET_ARTBOARD = 'SET_ARTBOARD' const initialState = 1 export default function reducer(state = initialState, action) { switch (action.type) { case SET_ARTBOARD: return action.payload default: return state } } export function setArtboard(id) { return { type: SET_ARTBOARD, payload: id } }
import React, { Component } from 'react' import { connect } from 'react-redux' import { changeView } from '../appState/view' import { setCurrentDoc } from '../appState/edit' import DataField from './DataField' class DataRow extends Component { constructor(props){ super() this.props = props this.state = {} this.showDocument = (e) => { props.setCurrentDoc({maskInd: props.maskIndex, ...props.obj}) props.changeView('Detail') } } render () { const obj = this.props.obj return ( <div className="data-row"> <div className="row-tip"> <button className="show-detail-btn" onClick={this.showDocument}> Open </button> </div> {Object.keys(obj) .map((o,i,arr)=> (i > 2 ? <DataField key={i} fieldName={o} fieldData={obj[o]} className={'field-data-cell'} /> :null) )} </div> ) } } const mapStateToProps = ({thisDoc}) => { return { thisDoc : thisDoc } } export default connect(mapStateToProps, {changeView, setCurrentDoc})(DataRow)
/** * EmbedSheet data store * @author Chase Cathcart <https://github.com/ChaseOnTheWeb> * * Reads the contents of a fetched URL into a Loki in-memory database. */ import XLSX from 'xlsx'; import loki from 'lokijs'; // We don't want all the codepages from cpexcel.js because it makes the script // huge. However, we may need some of the file encoding utility functions. window.cptable = {}; require('codepage/cputils'); export default function EmbedSheetData(data, options) { this.db = new loki(); this.items = this.db.addCollection('item'); this.headers = {}; this.options = options; var workbook = XLSX.read(data, { type: 'array', cellFormula: false, cellHTML: false, cellText: false }); var sheet = workbook.Sheets[this.options.sheet ? this.options.sheet : workbook.SheetNames[0]]; var range = XLSX.utils.decode_range(sheet['!ref']); var filters = {}; if (this.options.columns) { // If we are only displaying certain columns, we will only load those into // memory for performance purposes. However, we also need to include // columns used for sorting, filtering, row processors, and custom queries. var columns = this.options.columns .concat( this.options.sortby.map(function (v) { return Array.isArray(v) ? v[0] : v; }), this.options.filters.map(function (v) { return v.col; }), Object.keys(this.options.query), Object.values(this.options.row_processors).reduce(function (acc, cur) { return acc.concat(Array.isArray(cur) ? cur : []) }, []) ) .sort() .filter(function (v, i, a) { return v != a[i - 1]; }); } else { var columns = new Array(range.e.c - range.s.c); for (var i = range.s.c; i <= range.e.c; ++i) { output.push(XLSX.utils.encode_col(i)); } } for (var i = 0; i < this.options.filters.length; ++i) { var col = 'col' + this.options.filters[i].col; filters[col] = this.db.addCollection(col, { unique: ['value'] }); this.items.ensureIndex(this.options.filters[i].col); } columns.map(function (col) { this.headers[col] = this.options.column_labels[col] ? this.options.column_labels[col] : sheet[col + "1"].v; }, this); for (var i = 2; i <= range.e.r + 1; ++i) { var row = {}; columns.map(function (col) { row[col] = sheet[col + i] ? sheet[col + i].v : null; }) for (var j = 0; j < this.options.filters.length; ++j) { var col = this.options.filters[j].col; row[col] && (filters['col' + col].by('value', row[col]) || filters['col' + col].insert({ value: row[col] })); } this.items.insert(row); } return this; } EmbedSheetData.prototype.pagedQuery = function (conditions, page) { var rows_per_page = this.options.rows_per_page; var data = this.items.chain().find(conditions).compoundsort(this.options.sortby); var total_rows = data.count(); var max_pages = rows_per_page ? Math.floor(total_rows / rows_per_page) : 0; page = parseInt(max_pages < page ? max_pages : page); if (rows_per_page) { data = data.offset(page * rows_per_page).limit(rows_per_page); } return { total: total_rows, page: page, max_pages: max_pages, data: data.data() }; } /** * Returns object of information needed to build filters: * label: Column name * choices: All column values for select list */ EmbedSheetData.prototype.getFilter = function (col) { return { label: this.headers[col], choices: this.db.getCollection('col' + col) }; } /** * Fetches the given URL and initializes the data store. * url: URL to fetch * options: object of options to pass to EmbedSheetData * complete: callback function to be invoked on success. It is passed an * instance of EmbedSheetData. */ EmbedSheetData.fromURL = function (url, options, complete) { if (typeof FileReader === 'undefined') return; var reader = new FileReader(); reader.onload = function (e) { var data = new Uint8Array(e.target.result); var datastore = new EmbedSheetData(data, options); complete(datastore); }; fetch(url) .then(function (response) { return response.blob(); }) .then(function (file) { reader.readAsArrayBuffer(file); }) .catch(function (err) { console.log(err); }); }
exports.exit = async (msg, client) => { if (msg.channel.type === 'dm') return const game = await client.gamestore.findGame(msg.channel) if (game === null) { return msg.say( client.util.embedSmallError( "There's no game to quit!", `You can create one with **${client.commandPrefix}uno create**!` ) ) } if (msg.author.id !== game.gameOwner.id) { return msg.say( client.util.embedSmallError( "Can't remove game, you're not the game owner!", `You can leave it with **${client.commandPrefix}uno leave**!` ) ) } clearTimeout(game.timer) await client.gamestore.removeGame(msg.author) msg.say(client.util.embedSmallSuccess('Game Removed!', 'Thanks for playing!')) }
function chat(name, msg, align){ var tmp = '<p>'+msg+'</p>'; document.write(tmp) }
const User = require('../models/User'); const constants = require('../utils/constants'); const phoneService = require('./../services/PhoneService'); const forgotPassword = async function (req, res) { if (!req.params.phoneNumber) { ReS(res, { message: 'Bad request' }, 400); } else { let objUser = await User.findOne({ phoneNumber: req.params.phoneNumber }); if (objUser) { const newPassword = 'Ph@' + Math.floor(10000 + 89999 * Math.random()); objUser.set({ password: newPassword }); let objUserReturn = await objUser.save(); if (objUserReturn) { let [errors, _] = await to(phoneService.sendSMSPassword(req.params.phoneNumber, newPassword)); if (errors) { return ReEM2(res, 'Có lỗi khi gửi message!', 400); } else { return ReS(res, { status: true, message: 'Mật khẩu mới đã được gửi tới số điện thoại của bạn!', }, 200); } } } else { return ReEM2(res, 'Số điện thoại không đúng.', 404); } } }; module.exports.forgotPassword = forgotPassword; const getUserById = async function (req, res, _) { const userId = req.params.userId; if (!userId) { ReE(res, { status: false, message: 'Vui lòng nhập userId', }, 400); } User.find({ _id: userId, deletionFlag: false, }, (err, results) => { if (err) { return ReE(res, err, 500); } if (results && results.length === 0) { return ReE(res, 'Người dùng không tồn tại', 404); } let user = results[0]; if (user && user.role === constants.ROLE_LOCATION_MANAGER) { ReS(res, { status: true, user: user.toWeb(), locationDetail: null, }, 200); } else { ReS(res, { status: true, user: user.toWeb(), }, 200); } }); }; module.exports.getUserById = getUserById; const getAllUsers = async function (_, res, _) { User.find({}).where('role').equals(constants.ROLE_USER) .exec((err, results) => { if (err) { return ReE(res, err, 500); } return ReS(res, { status: true, users: results }, 200); }); }; module.exports.getAllUsers = getAllUsers; const banUserById = async function (req, res, _) { User.findByIdAndUpdate(req.body.id, { $set: { deletionFlag: req.body.deletionFlag }}, { new: true }, (err, _) => { if (err) { return ReE(res, err, 500); } return ReS(res, { message: 'Thay doi thanh cong' }, 200); }); }; module.exports.banUserById = banUserById; const getStatusUserById = async (req,res) =>{ User.findById(req.params.id).select('deletionFlag').exec((err, results) => { if (err) { return ReE(res, err, 500); } return ReS(res, { message: 'Thay doi thanh cong', deletionFlag: results.deletionFlag }, 200); }); } module.exports.getStatusUserById =getStatusUserById;
const express = require('express'); const bodyParser = require('body-parser'); const morgan = require('morgan'); const mongoose = require('mongoose'); const { Note, Asset } = require('./mongo'); const { getNoteById, getAssetById, getAssets, patchNoteById, postNoteByAssetId, postAsset, deleteAssetById, purgeAssetById } = require('./rest'); var app = express(); const expressPort = 8080; // Tell express to log all http requests to console. app.use(morgan('dev')); // For handling POST, PUT, PATCH correctly // Parses the body of the request app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); var router = express.Router(); // For every request this function will be run router.use((req,res,next) => { // Good location to put logging console.log("Received request."); next(); }); // Supply a generic message when someone hits the root url router.get('/', (req,res) => { res.json({ message: 'Nothing here.'}); }); // http://hostname:port/api/asset/ // Methods: // POST: Creates an asset // Input: // { uri: string, // name: string } // Returns: // { message: string } router.route('/asset') .post((req,res) => postAsset(req,res)) // http://hostname:port/api/assets/ // Methods: // GET: Returns a list of all assets // Input: None // Returns: // { assets: // [ // { _id: ID, // notes: [ ID ], // deleted: boolean, // uri: string, // name: string // } // ] // } router.route('/assets') .get((req,res) => getAssets(req,res)) // http://hostname:port/api/asset/id // Methods: // GET: Returns a singular asset by its id // Input: NONE // Returns: // { asset: // { _id: ID, // notes: [ ID ], // deleted: boolean, // uri: string, // name: string // } // } // // DELETE: Marks an asset and its notes for deletion // Input: NONE // Returns: { message: string } // // PURGE: Immediately removes an asset and its notes from the database // Input: NONE // Returns: { message: string } router.route('/asset/:_id') .get((req,res) => getAssetById(req,res)) .delete((req,res) => deleteAssetById(req,res)) .purge((req,res) => purgeAssetById(req,res)) // http://hostname:port/api/asset/id/note // Methods: // POST: Creates a new note associated with the asset // Input: { note: string } // Returns: { message: string } router.route('/asset/:_id/note') .post((req,res) => postNoteByAssetId(req,res)) // http://hostname:port/api/asset/id/note/id // Methods: // PATCH: Updates a note // Input: { note: string } // Returns: { message: string } router.route('/asset/:_id/note/:note_id') .patch((req,res) => patchNoteById(req,res)) // http://hostname:port/api/note/id // Methods: // GET: Returns a singular note, with it's associated asset populated // Input: NONE // Returns: // { note: // { deleted: boolean, // _id: ID, // asset: { ...Asset Object... } // note: string // } // } // // PATCH: Updates a note by it's ID // Input: { note: string } // Returns: { message: string } router.route('/note/:_id') .get((req,res) => getNoteById(req,res)) .patch((req,res) => patchNoteById(req,res)) // Attach all the rest routes to /api app.use('/api', router); // Start the HTTP server app.listen(expressPort, () => { console.log(`Server running on port ${expressPort}`); });
var fs; if (typeof(require) !== "undefined") { fs = require('fs'); } function Kernel(class_method, name) { this.class_method = class_method; this.class_name = name; } Kernel._extend = function(self, object, clone) { var o; if (!(object instanceof Array)) { object = [object]; } for (var i=0 ; i < object.length ; i++) { clone = clone === undefined ? true : clone; o = object[i]; if (typeof o == "string") { if (Class.__class_config[o]) { o = Class.__class_config[o].methods; } else { return self; } } if (clone) o = CanvasEngine.clone(o); for (var key in o) { self[key] = o[key]; } } return self; } Kernel.prototype = { New: function() { return this["new"].apply(this, arguments) }, "new": function() { this._class = new Class(); Class.__class[this.class_name] = this._class; this._construct(); return this._class; }, _construct: function() { this._class.extend(this.class_method); }, _attr_accessor: function(attrs, reader, writer) { var self = this; for (var i=0 ; i < attrs.length ; i++) { this.class_method["_" + attrs[i]] = null; this.class_method[attrs[i]] = {}; if (reader) { this.class_method[attrs[i]].set = function(value) { self.class_method["_" + attrs[i]] = value; }; } if (writer) { this.class_method[attrs[i]].get = function() { return self.class_method["_" + attrs[i]]; }; } } return this; }, /** @doc class/ @method attr_accessor Defines the properties that can be read and modified @params {Array} Properties names in an array @example Class.create("Foo", { mymethod: function() { this.bar.set(5); console.log(this.bar.get()); // Value of property "bar" is 5 console.log(this._bar); // ditto } }).attr_accessor(["bar"]); <jsfiddle>WebCreative5/HzCSm/1</jsfiddle> @return {Object} */ attr_accessor: function(attrs) { return this._attr_accessor(attrs, true, true); }, /** @doc class/ @method attr_reader Defines the properties that can be only read @params {Array} Properties names in an array @example Class.create("Foo", { mymethod: function() { console.log(this.bar.get()); } }).attr_reader(["bar"]); @return {Object} */ attr_reader: function(attrs) { return this._attr_accessor(attrs, true, false); }, /** @doc class/ @method attr_writer Defines the properties that can be only modified @params {Array} Properties names in an array @example Class.create("Foo", { mymethod: function() { this.bar.set(5); console.log(this._bar); } }).attr_writer(["bar"]); @return {Object} */ attr_writer: function(attrs) { return this._attr_accessor(attrs, false, true); }, /** @doc class/ @method extend add object in this class @params {Object|String} object or name of existing class @params {Boolean} clone (optional) Makes a clone of the object (false by default) @example Example 1 : Class.create("Foo", { mymethod: function() { } }).extend({ othermethod: function() { } }); Example 2 : Class.create("Bar", { initialize: function() { } }); Class.create("Foo", { mymethod: function() { } }).extend("Bar"); @return {Object} */ extend: function(object, clone) { Kernel._extend(this.class_method, object, clone); return this; }, // TODO addIn: function(name) { if (!Class.__class[name]) { return this; } Class.__class[name][this.name] = this; return this; } } function Class() { this.name = null; } Class.__class = {}; Class.__class_config = {}; /** @doc class/ @method get By retrieve the class name @static @params {String} name Class name @return {Kernel} Core class */ Class.get = function(name) { return Class.__class[name]; }; /** @doc class/ @method create Creating a class. the constructor is the method "initialize" @static @params {String} name Class name @params {Object} methods Methods and properties of the class @example Class.create("Foo", { bar: null, initialize: function(bar) { this.bar = bar; } }); var foo = Class.new("Foo", ["Hello World"]); <jsfiddle>WebCreative5/cbtFk</jsfiddle> @return {Kernel} Core class */ Class.create = function(name, methods, _static) { var p, _class, _tmp_class; /*if (typeof(window) === 'undefined') { var window = {}; }*/ Class.__class_config[name] = {}; Class.__class[name] = {}; /* Class.__class[name] = function(params) { // this.__parent = Class; // this.__parent(); if (this.initialize) { this.initialize.apply(this, params); } };*/ if (_static) { p = window[name]; tmp_class = new Class(); for (var key in tmp_class) { p[key] = tmp_class[key]; } for (var key in methods) { p[key] = methods[key]; } _class = p; } else { //p = Class.__class[name].prototype = methods; Class.__class_config[name].methods = methods; var kernel = Class.__class_config[name].kernel = new Kernel(Class.__class_config[name].methods, name); //p.extend(methods); } return kernel; } /** @doc class/ @method new new class. @static @params {String} name Class name @params {Array} params (optional) Parameters for the constructor @params {Boolean} initialize (optional) Calls the constructor "initialize" (true by default) @return {Class} */ Class.New = function() { return Class["new"].apply(this, arguments) }; Class["new"] = function(name, params, initialize) { var _class; if (typeof params == "boolean") { initialize = params; params = []; } if (initialize == undefined) { initialize = true; } params = params || []; if (!Class.__class_config[name]) { throw name + " class does not exist. Use method \"create\" for build the structure of this class"; } _class = Class.__class_config[name].kernel["new"](); if (initialize && _class.initialize) { _class.initialize.apply(_class, params); } _class.__name__ = name; return _class; } Class.prototype = { /** @method extend add object in this class @params {Object} object @parmas {Boolean} clone (optional) Makes a clone of the object (false by default) @example Class.create("Foo", { mymethod: function() { } }); Class.new("Foo").extend({ othermethod: function() { } }); @return {Object} */ extend: function(object, clone) { return Kernel._extend(this, object, clone); } } var CanvasEngine = {}; /** @doc utilities/ @method uniqid Generating a unique identifier by date @static @return {String} */ CanvasEngine.uniqid = function() { // return new Date().getTime(); return (Math.random()+"").replace(/^0./g, ""); }; /** @doc utilities/ @method arraySplice Removes an element in an array by value @static @params {Object} val @params {Array} array */ CanvasEngine.arraySplice = function(val, array) { var i; for (i=0 ; i < array.length ; ++i) { if (val == array[i]) { array.splice(i, 1); return; } } }; /** @doc ajax/ @method ajax Perform an asynchronous HTTP (Ajax) request. System uses wire on Node.js @static @params {Object} options * url {String} File Path * type {String} (optional) "GET" (default) or "POST" * data {Object} (optional) Data key/value * dataType {String} (optional) "text" (default), "json" or "xml" * success {Function} (optional) Callback if the request was successful */ CanvasEngine.ajax = function(options) { options = CanvasEngine.extend({ url: "./", type: "GET", statusCode: {} }, options); options.data = options.data ? JSON.stringify(options.data) : null; if (fs) { fs.readFile('./' + options.url, 'ascii', function (err, ret) { if (err) throw err; ret = ret.toString('ascii'); if (options.dataType == 'json') { ret = CanvasEngine.parseJSON(ret); } options.success(ret); }); return; } var xhr; try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) { try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e2) { try { xhr = new XMLHttpRequest(); } catch (e3) { xhr = false; } } } function onSuccess() { var ret; if (options.success) { ret = xhr.responseText; if (options.dataType == 'json') { ret = CanvasEngine.parseJSON(ret); } else if (options.dataType == 'xml') { ret = xhr.responseXML; } options.success(ret); } } xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (options.statusCode && options.statusCode[xhr.status]) options.statusCode[xhr.status](); if (xhr.status == 200) { onSuccess(); } else { if (options.error) options.error(xhr); } } }; xhr.open(options.type, options.url, true); if (options.mimeType) { xhr.overrideMimeType(options.mimeType); } xhr.send(options.data); } /** @doc ajax/ @method getJSON Load JSON-encoded data from the server using a GET HTTP request. @static @params {String} url File Path @params {String} (optional) data Data key/value @params {Function} (optional) callback Callback if the request was successful */ CanvasEngine.getJSON = function(url, data, callback) { if (typeof data == "function") { callback = data; data = null; } CanvasEngine.ajax({ url: url, dataType: 'json', data: data, success: callback }); } /** @doc utilities/ @method parseJSON Takes a well-formed JSON string and returns the resulting JavaScript object. @static @params {String} json JSON format @return {Object} */ CanvasEngine.parseJSON = function(json) { return JSON.parse(json); } /** @doc utilities/ @method each The array is read and sent to a callback function @static @params {Array|Object|Integer} array If the value is an integer, it returns to perform a number of loop iteration @params {Function} callback two parameters : * index * value @example var foo = ["bar", "test"]; CE.each(foo, function(i, val) { console.log(val); }); var foo = ["bar", "test"]; CE.each(2, function(i) { console.log(foo[i]); }); var foo = {bar: "bar", test: "test"}; CE.each(foo, function(i, val) { console.log(val); }); */ CanvasEngine.each = function(array, callback) { var i, l; if (!(array instanceof Array) && !(typeof array == "number")) { for (i in array) { callback.call(array, i, array[i]); } return; } if (array instanceof Array) { l = array.length; } else if (typeof array == "number") { l = array; array = []; } for (i=0 ; i < l ; ++i) { callback.call(array, i, array[i]); } } /** @doc utilities/ @method inArray The CE.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, CE.inArray() returns 0. Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), if we're checking for the presence of value within array, we need to check if it's not equal to (or greater than) -1. @static @params {String} val The value to search for. @params {Array} array An array through which to search. @return {Integer} */ CanvasEngine.inArray = function(val, array) { var i; for (i=0 ; i < array.length ; ++i) { if (val == array[i]) { return i; } } return -1; }; /** @doc engine/ @method clone Clone an object @static @params {Object} instance @return {Object} */ CanvasEngine.clone = function(srcInstance) { var i; if(typeof(srcInstance) != 'object' || srcInstance == null) { return srcInstance; } var newInstance = srcInstance.constructor(); if (newInstance === undefined) { return srcInstance; } for(i in srcInstance){ newInstance[i] = CanvasEngine.clone(srcInstance[i]); } return newInstance; }; /** @doc utilities/ @method hexaToRGB Converts the hexadecimal value of a color in RGB. Returns an array with 3 colors : [r, g, b] @static @params {String} hexa Hexadecimal with or without # @return {Array} */ CanvasEngine.hexaToRGB = function(hexa) { var r, g, b; function cutHex(h) { return (h.charAt(0) == "#") ? h.substring(1,7) : h; } r = parseInt((cutHex(hexa)).substring(0,2),16); g = parseInt((cutHex(hexa)).substring(2,4),16); b = parseInt((cutHex(hexa)).substring(4,6),16); return [r, g, b]; }; /** @doc utilities/ @method rgbToHex Converts the RGB value of a color in Hexadecimal. @static @params {String} r Red value (0-255) @params {String} g Green value (0-255) @params {String} b Blue value (0-255) @return {String} */ CanvasEngine.rgbToHex = function(r, g, b) { return ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); }; // Private CanvasEngine._getRandomColorKey = function() { var r = Math.round(Math.random() * 255), g = Math.round(Math.random() * 255), b = Math.round(Math.random() * 255); return CanvasEngine.rgbToHex(r, g, b); }; /** @doc utilities/ @method random Random value between `min` and `max` @static @params {Integer} min @params {Integer} max @return {Integer} */ CanvasEngine.random = function(min, max) { return Math.floor((Math.random() * max) + min); }; /** @doc utilities/ @method mobileUserAgent Returns the name of the user agent used @static @return {String|Boolean} name of the agent user ("iphone", "ipod", "ipad", "blackberry", "android" or "windows phone") or false if it is not a mobile @example if (CE.mobileUserAgent()) { // It's a mobile } if (CE.mobileUserAgent() == "android") { // It's a Android mobile } */ CanvasEngine.mobileUserAgent = function() { var ua = navigator.userAgent; if (ua.match(/(iPhone)/)) return "iphone"; else if (ua.match(/(iPod)/)) return "ipod"; else if (ua.match(/(iPad)/)) return "ipad"; else if (ua.match(/(BlackBerry)/)) return "blackberry"; else if (ua.match(/(Android)/)) return "android"; else if (ua.match(/(Windows Phone)/)) return "windows phone"; else return false; }; CanvasEngine._benchmark = {}; CanvasEngine._interval_benchmark = 60; CanvasEngine._freq_benchmark = {}; CanvasEngine.microtime = function() { var now = new Date().getTime() / 1000; var s = parseInt(now, 10); return now * 1000; }; CanvasEngine.benchmark = function(id) { var m = this.microtime(); if (this._benchmark[id]) { console.log("Performance " + id + " : " + (m - this._benchmark[id]) + "ms"); } this._benchmark[id] = m; }; CanvasEngine.objectSize = function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; }; /** @doc utilities/ @method extend `(>= 1.2.7)` Merging two objects @static @params {Object} target An object that will receive the new properties if additional objects are passed in. @params {Object} obj An object containing additional properties to merge in. @examples CE.extend({a: 1}, {b: 2}); // =>{a: 1, b: 2} @return {Object} */ // TODO : clone CanvasEngine.extend = function(obj1, obj2, clone) { if (!obj1) obj1 = {}; if (!obj2) obj2 = {}; return Kernel._extend(obj1, obj2, clone); } /*CanvasEngine.browser = function() { var ua = navigator.userAgent.toLowerCase(); var browser = {}; function testNavigator(name) { var patt = new RegExp (name); browser[name] = {}; browser[name] = patt.test(ua) && (name == "mozilla" ? !/webkit/.test(ua) : true); if (browser[name] } browser.webkit = /webkit/.test(ua); browser.opera = /opera/.test(ua); browser.msie = /msie/.test(ua); /msie\/([^ ]+)/.exec(); return browser; }*/ /** @doc utilities/ @static @property browser `(>= 1.2.8)` Retrieves the methods and properties related to browser. It contains flags for each of the four most prevalent browser classes (Internet Explorer, Mozilla, Webkit, and Opera) as well as version information. * `mozilla` : Tests if the browser is Mozilla * `webkit` : Tests if the browser is Webkit (Chrome, Safari) * `opera` : Tests if the browser is Opera * `msie` : Tests if the browser is Internet Explorer Example if (CE.browser.msie) { // if browser is Internet Explorer } Knowing the browser version : * `version` Example if (CE.browser.msie && parseInt(CE.browser.version) == 9) { // crop value // if browser is Internet Explorer 9 } Knowing the browser used by the user : * `which()`. Returns the object: `{ua: , version: }` Example CE.browser.which(); // returns {ua: "mozilla", version: "22.0"} @type Object */ if (typeof exports == "undefined") { var _ua = navigator.userAgent.toLowerCase(), _version = /(chrome|firefox|msie|version)(\/| )([0-9.]+)/.exec(_ua); CanvasEngine.browser = { mozilla: /mozilla/.test(_ua) && !/webkit/.test(_ua), webkit: /webkit/.test(_ua), opera: /opera/.test(_ua), msie: /msie/.test(_ua), version: _version ? _version[3] : null, which: function() { var is; CanvasEngine.each(["mozilla", "webkit", "opera", "msie"], function(i, ua) { if (CanvasEngine.browser[ua]) { is = ua; } }) return { ua: is, version: CanvasEngine.browser.version }; } }; } /** @doc utilities/ @method moveArray Move one index to another location of an array @static @params {&Array} array Array to handle @params {Integer} pos1 Index of the element to move @params {Integer} pos2 Destination index @return {Array} */ // http://jsperf.com/array-prototype-move // by Richard Scarrott (http://www.richardscarrott.co.uk) CanvasEngine.moveArray = function(array, pos1, pos2) { // local variables var i, tmp; // cast input parameters to integers pos1 = parseInt(pos1, 10); pos2 = parseInt(pos2, 10); // if positions are different and inside array if (pos1 !== pos2 && 0 <= pos1 && pos1 <= array.length && 0 <= pos2 && pos2 <= array.length) { // save element from position 1 tmp = array[pos1]; // move element down and shift other elements up if (pos1 < pos2) { for (i = pos1; i < pos2; i++) { array[i] = array[i + 1]; } } // move element up and shift other elements down else { for (i = pos1; i > pos2; i--) { array[i] = array[i - 1]; } } // put element from position 1 to destination array[pos2] = tmp; } return array; } /** @doc utilities/ @method toTimer `(>= 1.3.0)` Converts seconds into a format {hour: "", min: "", sec: ""} @static @params {Integer} total_sec Secondes @return {Array} @examples CE.toTimer(136); // => {hour: "00", min: "02", sec: "16"} */ CanvasEngine.toTimer = function(total_sec) { var hour = "" + Math.floor(total_sec / 60 / 60), min = "" + Math.floor(total_sec / 60 % 60), sec = "" + Math.floor(total_sec % 60); if (hour.length == 1) hour = "0" + hour; if (min.length == 1) min = "0" + min; if (sec.length == 1) sec = "0" + sec; return { hour: hour, min: min, sec: sec }; } CanvasEngine.algo = { pascalTriangle: function(max) { max = max || 10; var enchain = [[1,1], [1,2,1]], nb_max_move = max - enchain.length; for (var i=enchain.length ; i <= nb_max_move ; i++) { enchain[i] = [1] for (var j=1 ; j <= i ; j++) { enchain[i][j] = enchain[i-1][j] + enchain[i-1][j-1]; } enchain[i][i+1] = 1; } return enchain; }, } /** @doc utilities/ @method toMatrix `(>= 1.3.0)` Transforms a one-dimensional array to a table with two Diemension @static @params {Array} array The one-dimensional array to convert @params {Integer} width Width of the matrix created @params {Integer} height Height of the matrix created @return {Array} @examples CE.toMatrix([1, 2, 3, 4], 2, 2); // => [[1, 2], [3, 4]] */ CanvasEngine.toMatrix = function(array, width, height) { var matrix = [], k = 0; for (var j=0 ; j < height ; j++) { for (var i=0 ; i < width ; i++) { if (!matrix[i]) matrix[i] = []; matrix[i][j] = array[k]; k++; } } return matrix; } /** @doc utilities/ @method rotateMatrix `(>= 1.3.0)` Change the positions of the array elements, the rotation matrix @static @params {Array} array The matrix in question @params {String} rotation (optional) Rotation in degree : `90` or `-90`, `180` (`90` by default) @return {Array} @examples var matrix = [ [1, 0], [1, 1], [1, 0] ]; CE.rotateMatrix(matrix); // => [ [1, 1, 1], [0, 1, 0] ] CE.rotateMatrix(matrix, "-90"); // => [ [0, 1, 0], [1, 1, 1] ] CE.rotateMatrix(matrix, "180"); // => [ [0, 1], [1, 1], [0, 1] ] */ CanvasEngine.rotateMatrix = function(array, rotation) { var matrix = [], matrix2 = []; rotation = rotation || "90"; if (rotation == "90" || rotation == "-90") { for (var j=0 ; j < array[0].length ; j++) { matrix[j] = []; for (var i=0 ; i < array.length ; i++) { matrix[j][i] = array[i][j]; } } } if (rotation == "-90") { var j=0; for (var i=matrix.length-1 ; i >= 0 ; i--) { matrix2[j] = matrix[i]; j++; } return matrix2; } if (rotation == "180") { for (var i=0 ; i < array.length ; i++) { matrix[i] = array[i].reverse(); } } return matrix; } var _CanvasEngine = CanvasEngine; if (typeof(exports) !== "undefined") { exports.Class = Class; exports.CanvasEngine = CanvasEngine; }
import React from 'react' function Answers(props) { return ( props.answers.map((answer, index) => ( <input key={index} type='hidden' name="line_itemable[answers][]" value={JSON.stringify(answer)} /> )) ); } export default Answers
18 gid=1329781531 17 uid=183816338 20 ctime=1441138964 20 atime=1441138971 23 SCHILY.dev=16777221 23 SCHILY.ino=32546095 18 SCHILY.nlink=1
import React from 'react'; import { ScrollView, View, ImageBackground, Dimensions, StyleSheet, RefreshControl, } from 'react-native'; import PropTypes from 'prop-types'; import appStyle from '../../const/appStyles'; const styles = StyleSheet.create({ scrollStyle: { flex: 1, }, container: { justifyContent: 'flex-start', alignItems: 'center', }, imageStyle: { ...appStyle.backgroundAbsoluteStyle, }, }); const BackgroundImageScroll = (props) => { const { children, containerStyle, onRefresh, isLoading, scrollRef, } = props; const { width } = Dimensions.get('window'); return ( <ScrollView style={styles.scrollStyle} contentContainerStyle={[styles.container, containerStyle]} refreshControl={onRefresh && <RefreshControl refreshing={isLoading} onRefresh={onRefresh} />} ref={scrollRef} > <View style={{ width: '100%', height: '100%' }}> <ImageBackground style={styles.container} imageStyle={[styles.imageStyle, { width, height: 1116 }]} source={require('../../assets/images/background-field-dim.png')} > {children} </ImageBackground> </View> </ScrollView> ); }; BackgroundImageScroll.propTypes = { containerStyle: PropTypes.object, onRefresh: PropTypes.func, isLoading: PropTypes.bool, scrollRef: PropTypes.func, }; BackgroundImageScroll.defaultProps = { containerStyle: {}, onRefresh: null, isLoading: false, scrollRef: null, }; export default BackgroundImageScroll;
// 03-colors/01-change-bcg-one/script.js - 3.1: Bcg one (1) (() => { // your code here document.getElementById('red').onclick = colorRed; function colorRed() { document.body.style.background ='red'; } document.getElementById('green').onclick = colorGreen; function colorGreen() { document.body.style.background ='green'; } document.getElementById('yellow').onclick = colorYellow; function colorYellow() { document.body.style.background ='yellow'; } document.getElementById('blue').onclick = colorBlue; function colorBlue() { document.body.style.background ='blue'; } })();
import React, {Component} from 'react'; import './css/home-nav.css'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faSadCry, faPlus } from '@fortawesome/free-solid-svg-icons'; class AllNotifications extends Component { render() { let noNotificationIcon; if(this.props.allNotif.length === 0) { noNotificationIcon = <div className="no-notifications"> <FontAwesomeIcon icon={faSadCry} size="5x" /> <br /> <br /> <h1>No new notifications</h1> </div> } return ( <div className="notifications-container"> <div className="all-notifications"> {noNotificationIcon} {this.props.allNotif.map((notif, index) => <div key={index} className="notification"> <FontAwesomeIcon icon={faPlus} /> <strong>A new order has been placed with order number #{notif}</strong> </div> )} {/* {this.props.allNotif.recievedNotification} */} </div> </div> ) } } export default AllNotifications;
import React from 'react' import { View, Text } from 'react-native' import Sta from '../components/Staking' export default function Staking() { return ( <> <Sta /> </> ) }
//If anyone is looking at this and wondering why I'm not just doing //seperate pages: I just really wanted an excuse to use Javascript. const navButtons = document.getElementsByClassName('navbtn'); const infoBoxes = document.getElementsByClassName('infobox'); const boxNames = { ABOUT: 0, RESUME: 1, PROJECTS: 2, SHOUTOUTS: 3, }; //defines the currently visible box let visibleBox = infoBoxes[boxNames.ABOUT]; //switches the visible infoBox function switchBoxes(boxNum) { visibleBox.style.display = "none"; visibleBox = infoBoxes[boxNum]; visibleBox.style.display = "block"; return `Switched infoBox to ${boxNum}`; } // bit over-engineered, but it saves me from having to add the attribute manually for(i = 0; i < navButtons.length; i++) { navButtons[i].setAttribute("onclick", `switchBoxes(${i})`); console.log("Added click attribute"); }
// A jQuery plugin to capture DOM events and send data regarding the event to // Google Analytics as a tracked event. // // Usage // // Include this javascript file in your build. // Initialize the event handler on your page. // // Caveats // // Only pushes GA event if JSON.stringify is available. Sorry old browsers. // // Example // // form.ga-track.onSubmit => // { // "location":{ // "hostname":"www.lib.umn.edu", // "pathname":"/" // }, // "name":"mncat-discovery", // "inputs":{ // "submit":"", // "phrase":"beer" // }, // "media":"large", // "date":1409081954817 // } // // a.onClick => // { // "location":{ // "hostname":"drupal.dev", // "pathname":"/" // }, // "media":"large", // "href":"researchsupport", // "text":"Researcher", // "parents":"main|featured-items|researcher-support", // "date":1409082445329 // } var GaEventTrack = (function() { var _events = ['forms', 'links', 'scrolldepth']; var FormSubmit = {}; var LinkClick = {}; var ScrollDepth = {}; return { _events: _events, FormSubmit: FormSubmit, LinkClick: LinkClick, ScrollDepth: ScrollDepth }; }(GaEventTrack));
/** * This file is part of the Spryker Demoshop. * For full license information, please view the LICENSE file that was distributed with this source code. */ 'use strict'; // add your custom common js here // and/or change the existing one var aside = require('js/base/components/aside'); var viewer = require('js/base/components/viewer'); aside.init(); viewer.init();
// Built-in const path = require("path"); // App-specific const express = require("express"); const cookieParser = require("cookie-parser"); const bodyParser = require("body-parser"); const helmet = require("helmet"); const hbs = require("hbs"); // Env-specific const logger = require("morgan"); const routes = require("./src/routes"); const registerHelpers = require("./src/helpers/handlebars"); const app = express(); registerHelpers(hbs); app.set("views", path.join(__dirname, "target/views")); app.set("view engine", "hbs"); if ( app.get("env") === "development" ) { app.use(logger("dev")); } app.use(helmet()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false})); app.use(cookieParser()); app.use(express.static(path.join(__dirname, "target/assets"))); app.use("/", routes); // catch 404 and forward to error handler app.use(function(req, res, next) { let err = new Error('Not Found'); err.status = 404; next(err); }); // 404 错误处理 app.use(function( err, req, res, next ) { if ( err.status === 404 ) { res.render("sessions/404", {meta: {title: "找不到该页面"}}); } else { next(err); } }); // 其他错误处理 app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get("env") === "development" ? err : {}; // render the error page res.status(err.status || 500); res.render("sessions/error", {meta: {title: "系统错误"}}); }); module.exports = app;
import React, { Component } from 'react' import styled from 'styled-components' import { Button } from '../../mia-ui/buttons' import { Label } from '../../mia-ui/forms' import { Modal } from '../../mia-ui/modals' import MediaManager from '../MediaManager' import router from 'next/router' import { Flex, Box } from 'grid-styled' import { Icon } from '../../mia-ui/icons' export default class MultiMedia extends Component { state = { modal: false } render() { const { handleModalOpen, handleModalClose, props: { additionalMedias, label, onRemove, organization }, handleAdd, state: { modal } } = this return ( <Flex flexWrap={'wrap'}> <Box w={1}> <Label>{label}</Label> </Box> <Flex w={1}> {additionalMedias.map(media => ( <Flex key={media.id} flexDirection={'column'} mr={1}> <MediaContainer justifyContent={'center'} alignItems={'center'}> <Icon icon={media.format === 'mp4' ? 'local_movies' : 'volume_up'} size={'70px'} /> <TitleOverlay>{media.title}</TitleOverlay> </MediaContainer> <Button color={'red'} onClick={() => onRemove(media.id)}> Remove </Button> </Flex> ))} </Flex> <Box w={1}> <Button onClick={handleModalOpen}>Add</Button> </Box> <Modal open={modal} onClose={handleModalClose} header={`Edit Image`} width={'60%'} > {modal ? <MediaManager onMediaSave={handleAdd} /> : null} </Modal> </Flex> ) } handleModalOpen = () => { this.setState({ modal: true }) } handleModalClose = () => { this.setState({ modal: false }) } handleAdd = mediaId => { const { onAdd } = this.props onAdd(mediaId) this.setState({ modal: false }) } } const MediaContainer = styled(Flex)` height: 150px; width: 150px; border: 1px solid black; position: relative; ` const TitleOverlay = styled(Box)` background-color: ${({ theme }) => theme.color.gray60}; color: white; position: absolute; bottom: 0; height: 40%; font-size: 20px; `
'use strict'; import React from 'react'; import {_} from 'underscore'; import $ from 'jquery'; var dropdownStyle = { display: 'inline-block', marginRight: '10px' }; var dropdownButtonStyle = { backgroundImage: 'none' }; var clickableStyle = { cursor: 'pointer' }; var drillDownControlStyle = { cursor: 'pointer', width: '20px' }; function camelCaseToTitleCase(camelCase) { var result = camelCase.replace( /([A-Z])/g, " $1" ); return result.charAt(0).toUpperCase() + result.slice(1); } function getDataFromUrl(url) { return new Promise((resolve, reject) => { $.ajax({ url: url, dataType: 'json', success: (data => resolve(data)), error: ((xhr, status, error) => reject(xhr, status, error)) }); }); } function pivotData(data, groupBys, summaries, sortColumn, sortAscending) { function groupToRow(group, key) { return _.extend( {rawData: group, key: key}, _.extend( _.object(groupBys, groupBys.map(gb => group[0][gb])), _.object(summaries, summaries.map(s => _.reduce(_.pluck(group, s), (a, b) => a + b))))); } var groups = _.values(_.groupBy(data, d => _.map(groupBys, gb => d[gb] ))); var key = 0; var sortedResults = _.sortBy(groups.map(g => groupToRow(g, key++)), r => r[sortColumn]); return sortAscending ? sortedResults : sortedResults.reverse(); } var HeaderRow = React.createClass({ propTypes: { groupBys: React.PropTypes.arrayOf(React.PropTypes.string).isRequired, summaries: React.PropTypes.arrayOf(React.PropTypes.string).isRequired, sortColumn: React.PropTypes.string.isRequired, sortAscending: React.PropTypes.bool.isRequired, onChange: React.PropTypes.func }, updateSort: function(sortColumn) { var newSortAscending = this.props.sortColumn == sortColumn ? !this.props.sortAscending : true; this.props.onChange(sortColumn, newSortAscending); }, render: function() { var sortClass = this.props.sortAscending ? 'glyphicon glyphicon-arrow-up' : 'glyphicon glyphicon-arrow-down'; var groupByHeaders = this.props.groupBys.map(gb => <th key={gb} style={clickableStyle} onClick={() => this.updateSort(gb)}> {camelCaseToTitleCase(gb)} {this.props.sortColumn == gb ? <span className={sortClass}></span> : <span></span>} </th>); var summaryHeaders = this.props.summaries.map(s => <th key={s} style={clickableStyle} onClick={() => this.updateSort(s)}> {camelCaseToTitleCase(s)} {this.props.sortColumn == s ? <span className={sortClass}></span> : <span></span>} </th>); return (<thead><tr><th style={{width: '20px'}}></th>{groupByHeaders}{summaryHeaders}</tr></thead>) } }); var GroupRow = React.createClass({ propTypes: { selectedGroupBys: React.PropTypes.arrayOf(React.PropTypes.string).isRequired, selectedSummaries: React.PropTypes.arrayOf(React.PropTypes.string).isRequired, groupBys: React.PropTypes.arrayOf(React.PropTypes.string).isRequired, summaries: React.PropTypes.arrayOf(React.PropTypes.string).isRequired, row: React.PropTypes.object.isRequired }, getInitialState: function() { return { showDrillDown: false } }, toggleDrillDown: function() { var showDrillDown = ! this.state.showDrillDown; this.setState({showDrillDown: showDrillDown}); }, render: function() { var cellKey = 0; var groupValues = this.props.selectedGroupBys.map(gb => <td key={cellKey++}>{this.props.row[gb]}</td>); var summaryValues = this.props.selectedSummaries.map(s => <td key={cellKey++}>{this.props.row[s]}</td>); var drillDownClassName = this.state.showDrillDown ? 'glyphicon glyphicon-minus' : 'glyphicon glyphicon-plus'; var drillDownControl = this.props.row.rawData.length > 1 ? <td style={drillDownControlStyle} onClick={this.toggleDrillDown}><span className={drillDownClassName}></span></td> : <td></td>; var drillDownColSpan = this.props.groupBys.length + this.props.summaries.length + 1; var drillDownRow = ( <tr> <td colSpan={drillDownColSpan}> <PivotTable groupBys={this.props.groupBys} summaries={this.props.summaries} data={this.props.row.rawData} hideControls={true}/> </td> </tr> ); return ( <tbody> <tr>{drillDownControl}{groupValues}{summaryValues}</tr> {this.state.showDrillDown ? drillDownRow : null} </tbody>); } }); var DropdownSelection = React.createClass({ propTypes: { title: React.PropTypes.string.isRequired, options: React.PropTypes.arrayOf(React.PropTypes.string).isRequired, onChange: React.PropTypes.func }, getInitialState: function() { return { selectedOptions: this.props.options.slice() } }, toggleOption: function(option) { var selectedOptions = this.state.selectedOptions.slice(); if (selectedOptions.indexOf(option) > -1) { selectedOptions.splice(selectedOptions.indexOf(option), 1) } else { selectedOptions.push(option); } this.setState({selectedOptions: selectedOptions}); this.props.onChange(selectedOptions); }, render: function() { var optionElements = this.props.options.map(option => { var isSelected = this.state.selectedOptions.indexOf(option) > -1; return (<li key={option}> <a href="javascript:void(0)" onClick={() => this.toggleOption(option)}> {isSelected ? <span className="glyphicon glyphicon-ok"></span>: <span>&nbsp;&nbsp;&nbsp;</span>} &nbsp;&nbsp;{camelCaseToTitleCase(option)} </a> </li>)}); return (<div className="dropdown" style={dropdownStyle}> <button className="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" style={dropdownButtonStyle}> {this.props.title}&nbsp; <span className="caret"></span> </button> <ul className="dropdown-menu"> {optionElements} </ul> </div>); } }); var PivotTable = React.createClass({ propTypes: { groupBys: React.PropTypes.arrayOf(React.PropTypes.string).isRequired, summaries: React.PropTypes.arrayOf(React.PropTypes.string).isRequired, dataUrl: React.PropTypes.string, data: React.PropTypes.arrayOf(React.PropTypes.object), hideControls: React.PropTypes.bool }, getInitialState: function() { return { selectedGroupBys: this.props.groupBys.slice(), selectedSummaries: this.props.summaries.slice(), sortColumn: this.props.groupBys[0] ? this.props.groupBys[0] : this.props.summaries[0] ? this.props.summaries[0] : undefined, sortAscending: true, data: this.props.data || [] }; }, componentWillReceiveProps: function(nextProps) { this.setState({ sortColumn: nextProps.groupBys[0] ? nextProps.groupBys[0] : nextProps.summaries[0] ? nextProps.summaries[0] : undefined }); }, componentDidMount: function() { if (this.props.dataUrl) { getDataFromUrl(this.props.dataUrl) .then(data => this.setState({data: data})) .catch((xhr, status, error) => { console.error('Failed to retrieve pivot table data from ' + this.props.dataUrl, status, error.toString()) }); } }, groupBysUpdated: function(selectedGroupBys) { this.setState({selectedGroupBys: selectedGroupBys}); }, summariesUpdated: function(selectedSummaries) { this.setState({selectedSummaries: selectedSummaries}); }, headerRowUpdated: function(sortColumn, sortAscending) { this.setState({sortColumn: sortColumn, sortAscending: sortAscending}); }, render: function() { var pivotRows = pivotData(this.state.data, this.state.selectedGroupBys, this.state.selectedSummaries, this.state.sortColumn, this.state.sortAscending); var groupRows = pivotRows.map(pr => <GroupRow selectedGroupBys={this.state.selectedGroupBys} selectedSummaries={this.state.selectedSummaries} groupBys={this.props.groupBys} summaries={this.props.summaries} row={pr} key={pr.key}/>); var controls = ( <div className="row"> <div className="col-md-12"> <DropdownSelection title="Group By" options={this.props.groupBys} onChange={this.groupBysUpdated}/> <DropdownSelection title="Summaries" options={this.props.summaries} onChange={this.summariesUpdated}/> <hr style={{marginTop: '15px', marginBottom: '10px'}}/> </div> </div> ); return ( <div> {this.props.hideControls ? <span></span> : controls} <div className="row"> <div className="col-md-12"> <table className="table small"> <HeaderRow groupBys={this.state.selectedGroupBys} summaries={this.state.selectedSummaries} sortColumn={this.state.sortColumn} sortAscending={this.state.sortAscending} onChange={this.headerRowUpdated}/> {groupRows} </table> </div> </div> </div> ) } }); export default PivotTable;
import Ember from 'ember'; export default Ember.Component.extend({ classNames: ['info-box'], average: function() { var values = this.get('values'); if (values) { var component = this; var sum = 0, count = 0; values.forEach(function(value) { var gpa = value.get(component.get('value')); if (!isNaN(parseFloat(gpa)) && isFinite(gpa)) { sum += parseFloat(gpa) count += 1; } }) if (count > 0) { return (sum/count).toFixed(2); } else { return '—'; } } }.property('values') });
const request = require('request'); const chart = require('chartist'); const remote = require('electron').remote; var stockList = ["goog", "aapl", "amzn", "ibm", "tsla", "fb"]; var stockNames = ["Alphabet Inc.", "Apple Inc.", "Amazon Inc.", "IBM Inc.", "Tesla Inc.", "Facebook Inc."]; var oldDivs = document.getElementsByClassName("stocks"); var wrapper = document.getElementById("wrapper"); document.getElementById("minimize").addEventListener("click", (e) => { var window = remote.getCurrentWindow(); window.minimize(); }); document.getElementById("maximize").addEventListener("click", (e) => { var window = remote.getCurrentWindow(); if (!window.isMaximized()) { window.maximize(); } else { window.unmaximize(); } }); document.getElementById("close").addEventListener("click", (e) => { var window = remote.getCurrentWindow(); window.close(); }); document.getElementById("searchbutton").addEventListener("click", () => { var search = document.getElementById("searchinput").value; setupSearchGraph(); getMonthlyStockData("monthly", search, 1); searchStockNamer(search); }); function getStockNumbers(stock) { var url = "https://www.google.com/finance/info?client=ig&q=" + stock; //console.log(url); request(url, function(error, response, body) { //console.log('error:', error); // Print the error if one occurred //console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received if (!error && response.statusCode === 200) { body = body.slice(3); body = JSON.parse(body); //console.log(body); drawTable(body, stock); } }); } function getMonthlyStockData(timeInterval, stock, value) { if (timeInterval == "weekly") { var url = "http://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY&symbol=" + stock + "&apikey=EL0R"; } else if (timeInterval == "monthly") { var url = "http://www.alphavantage.co/query?function=TIME_SERIES_MONTHLY&symbol=" + stock + "&apikey=EL0R"; } else if (timeInterval == "daily") { var url = "http://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=" + stock + "&apikey=EL0R"; } else { console.log("IlligalArgumentException"); } request(url, function(error, response, body) { //console.log('error:', error); // Print the error if one occurred //console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received if (!error && response.statusCode === 200) { body = JSON.parse(body); //console.log(body);' if(value == 0){ drawGraph(body, stock); } else if(value == 1){ drawSearchGraph(body, stock); } } }); } function setupSearchGraph(){ //console.log("oldDivs.length is " + oldDivs.length); while(oldDivs.length > 0){ wrapper.removeChild(oldDivs[oldDivs.length - 1]); //console.log("oldDivs.length is " + oldDivs.length); } console.log(document.getElementsByClassName("searchStock").length == 0); if(document.getElementsByClassName("searchStock").length == 0){ var searchStock = document.createElement("div"); var head = document.createElement("div"); var graph = document.createElement("div"); searchStock.className = "searchStock"; head.className = "head"; graph.className = "graphs"; wrapper.appendChild(searchStock); searchStock.appendChild(head); searchStock.appendChild(graph); } } function drawTable(array, stock) { var infoNames = ["Ticker", "Listing Price", "Exchange", "Growth"]; var info = [array[0]["t"], array[0]["l"], array[0]["e"], array[0]["c"]]; var text = document.createTextNode(stock.toUpperCase()); var stockDiv = document.getElementsByClassName("stocks")[stockList.indexOf(stock)]; var table = stockDiv.getElementsByTagName("table")[0]; //console.log("Table " + table); //Creates all table rows and appends them to table for (var x = 0; x < info.length; x++) { var tr = document.createElement("tr"); table.insertBefore(tr, table.children[i]); } //Creats all table data and appends them to table rows for (var i = 0; i < info.length; i++) { var tr = table.children[i]; var td0 = document.createElement("td"); var text0 = document.createTextNode(infoNames[i]); var td1 = document.createElement("td"); var text1 = document.createTextNode(info[i]); td0.appendChild(text0); tr.appendChild(td0); td1.appendChild(text1); tr.appendChild(td1); } var td = table.children[3].lastChild; td.style.fontWeight = "bolder"; //console.log(td.innerHTML); if (td.innerHTML.charAt(0) === "+") { td.style.color = "#00FF00"; } else { td.style.color = "#FF0000"; } } function drawGraph(obj, stock) { var even = true; var graphDivs = document.getElementsByClassName("graphs"); var keys = Object.keys(obj["Monthly Time Series"]); var data = { labels: [], series: [{ name: 'series1', data: [] }] }; var options = { width: 400, height: 200, showPoint: false, lineSmooth: false, onlyInteger: true, series: { 'series1': { showArea: true } }, axisY: { labelInterpolationFnc: function(value) { return '$' + value; }, type: chart.AutoScaleAxis, showGrid: false, }, axisX: { showGrid: false } }; for (var i = 0; i < 8; i++) { var info = obj["Monthly Time Series"][Object.keys(obj["Monthly Time Series"])[i]]["4. close"]; var key = keys[i]; if (even) { data.labels.unshift(key.slice(8,10) + "."+ key.slice(5,7)); } else { data.labels.unshift(""); } data.series[0]['data'].unshift(parseInt(info)); even ? even = false : even = true; //switch value of even } //console.log(data); new chart.Line(graphDivs[stockList.indexOf(stock)], data, options); } function drawSearchGraph(obj, stock){ var graphDiv = document.getElementsByClassName("graphs"); var keys = Object.keys(obj["Monthly Time Series"]); var data = { labels: [], series: [{ name: 'series1', data: [] }] }; var options = { width: '1200px', height: '650px', showPoint: false, lineSmooth: false, onlyInteger: true, series: { 'series1': { showArea: false } }, axisY: { labelInterpolationFnc: function(value) { return '$' + value; }, type: chart.AutoScaleAxis, showGrid: false, }, axisX: { showGrid: true } }; for (var i = 0; i < 8; i++) { var info = obj["Monthly Time Series"][Object.keys(obj["Monthly Time Series"])[i]]["4. close"]; var key = keys[i]; data.labels.unshift(key.slice(8,10) + "."+ key.slice(5,7)); data.series[0]['data'].unshift(parseInt(info)); } //console.log(data); new chart.Line(graphDiv[0], data, options); } function setupClickHandlers() { var stocks = document.getElementsByClassName("stocks"); for (var i = 0; i < stocks.length; i++) { var stock = stocks[i]; var flipper = stock.children[0]; stock.onclick = (function(flipper) { var rotated = false; return function() { if (!rotated) { flipper.style.transform = "rotateY(180deg)"; flipper.style.webkitTransform = "rotateY(180deg)"; rotated = true; } else if (rotated) { flipper.style.transform = "rotateY(0deg)"; flipper.style.webkitTransform = "rotateY(0deg)"; rotated = false; } }; })(flipper); } } function flip() { var rotated = false; if (!rotated) { flipper.style.transform = "rotateY(180deg)"; flipper.style.webkitTransform = "rotateY(180deg)"; rotated = true; } else { flipper.style.transform = "rotateY(0deg)"; flipper.style.webkitTransform = "rotateY(0deg)"; rotated = false; } } //Adds names to all the stocks function stockNamer() { var head = document.getElementsByClassName("head"); for (var y = 0; y < stockNames.length; y++) { if (!head[y].hasChildNodes()) { var node = document.createTextNode(stockNames[y]); var h1 = document.createElement("h1"); h1.appendChild(node); head[y].appendChild(h1); } } } function searchStockNamer(stock){ var head = document.getElementsByClassName("head"); var node = document.createTextNode(stock); var h1 = document.createElement("h1"); h1.id="header"; h1.appendChild(node); if(head[0].hasChildNodes()){ document.getElementById("header").parentNode.removeChild(document.getElementById("header")); } head[0].appendChild(h1); } //Runs the functions for displaying the front page function loadFrontPage(){ for (var i = 0; i < stockList.length; i++) { getStockNumbers(stockList[i]); getMonthlyStockData("monthly", stockList[i], 0); } stockNamer(); setupClickHandlers(); } loadFrontPage();
import component from './pt-BR/component'; import globalHeader from './pt-BR/globalHeader'; import menu from './pt-BR/menu'; import pwa from './pt-BR/pwa'; import settingDrawer from './pt-BR/settingDrawer'; import settings from './pt-BR/settings'; import userLogin from './pt-BR/userLogin'; export default { 'navBar.lang': 'Idiomas', 'layout.user.link.help': 'ajuda', 'layout.user.link.privacy': 'política de privacidade', 'layout.user.link.terms': 'termos de serviços', 'app.preview.down.block': 'Download this page to your local project', ...globalHeader, ...menu, ...settingDrawer, ...settings, ...pwa, ...component, ...userLogin, };
import React,{useState,useRef} from 'react'; import FetchCenters from './FetchCenters'; import DatePicker from 'react-datepicker'; import { GiLoveInjection } from 'react-icons/gi'; import { AiOutlineHome } from 'react-icons/ai'; export default function SearchByDistrict(props) { const states=require('../assets/states.json'); const url1='https://cdn-api.co-vin.in/api/v2/admin/location/districts/'; const url2='https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findByDistrict'; const [state,setState] = useState('') const [districts, setDistricts] = useState([]); const [districtId, setDistrictId] = useState(null); const [items, setItems] = useState(null); const [selectedDate,setSelectedDate] = useState(null) const [stateError,setStateError] = useState('') const [districtError,setDistrictError] = useState('') const [dateError,setDateError] = useState('') const focusRef = useRef() const handleStateChange = (event) => { setState(event.target.value) setStateError('') fetch(url1+`${event.target.value}`) .then(res => res.json()) .then(result => { setDistricts(result.districts); }); } const handleDistrictChoice =(event) => { setDistrictId(event.target.value); setDistrictError('') } const handleDateChange = date => { setSelectedDate(date) setDateError('') } const retrieve = (e) => { e.preventDefault(); if(state && districtId && selectedDate) { const date = selectedDate; const today = `${date.getDate()}-${(date.getMonth()+1).toString().padStart(2,0)}-${date.getUTCFullYear()}` fetch(url2+`?district_id=${districtId}&date=${today}`) .then(res=> res.json()) .then(result => { let res = result.sessions?result.sessions.filter(item => item.available_capacity>0):[]; setItems(res); focusRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' }) }); } if(!state) setStateError('State is not selected') if(!districtId) setDistrictError('District is not selected') if(!selectedDate) setDateError('Date is not selected') } return ( <div> <div className="App"> <form onSubmit={retrieve}> <div className='container'> <p><label>Choose State: </label></p> <select className='input' onChange={handleStateChange}> { states.map(state=> <option key={state.state_id} value={state.state_id}>{state.state_name}</option>) } </select> <p className='error'>{stateError}</p> </div> <div className='container'> <p><label>Choose District: </label></p> <select className='input' onChange={handleDistrictChoice}> { districts.map(district=> <option key={district.district_id} value={district.district_id}>{district.district_name}</option>) } </select> <p className='error'>{districtError}</p> </div> <div className='container'> <p><label>Date:</label></p> <DatePicker className='input' placeholderText="Enter date..." selected={selectedDate} withPortal onChange={date => handleDateChange(date)} dateFormat='dd/MM/yyyy' minDate={new Date()} isClearable showYearDropdown scrollableMonthYearDropdown/> <p className='error'>{dateError}</p> </div> <div style={{marginLeft:'10px'}}> <div><button type='submit' className='button btn2'><span><GiLoveInjection style={{marginBottom: '4px'}}/> Find Slots</span></button></div> <div><button className='button btn2' onClick={() => props.onChange('0')}><span><AiOutlineHome style={{marginBottom: '4px'}}/> Home</span></button></div> </div> </form> </div> <div ref={focusRef}><FetchCenters items={items}/></div> </div> ) }
var dir_7159a0b79bffcc693b8d3696d3c54cc7 = [ [ "ams", "dir_d3f5636e64b5f92308f97ef557b6e0e3.html", "dir_d3f5636e64b5f92308f97ef557b6e0e3" ] ];
const LineClient = require('line-socket/client-node'); const {SocketKit} = require('./index'); SocketKit.LineClient = LineClient; exports.SocketKit = SocketKit; exports.Event = SocketKit.Event;
var casper = require('casper').create(); casper.userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36'); casper.start("http://jra.jp/",function(){ this.clickLabel('出馬表', 'a'); }); casper.then(function(){ var labels = this.evaluate(function() { var tmp1 = document.querySelectorAll('.kaisaiBtn a') return Array.prototype.map.call(tmp1, function(e) { //return e.getAttribute('innerText'); return e.innerText; }); }); var i = 0; this.repeat(labels.length,function(){ if ( labels[i].indexOf( "回" ) != -1 ) { //this.echo(labels[i]); //レース名をクリック this.clickLabel(labels[i],'a'); //500ms待つ this.wait(500,function () { this.capture('google.png', { top: 100, left: 100, width: 500, height: 800 }); this.then(function(){ //レースのリンクを全て取得 var raceList = getRaceList.call(this); //各レース毎の処理 var j=0 this.repeat(raceList.length,function(){ if(raceList[j].indexOf("pw01bmd")!=-1){ var spl = raceList[j].split("'"); //POST this.evaluate(function(cname) { document.getElementById( "cname" ).value = cname; document.getElementById( "commForm01" ).action="/JRADB/accessD.html"; document.getElementById( "commForm01" ).submit(); },spl[3]); //レース詳細画面を取得 casper.then(function(){ this.wait(300,function () { //出走馬リスト var hourseList = getHorseList.call(this); var k=0 this.repeat(hourseList.length,function(){ var spl = hourseList[k].split("'"); this.evaluate(function(cname) { document.getElementById( "cname" ).value = cname; document.getElementById( "commForm01" ).action="/JRADB/accessD.html"; document.getElementById( "commForm01" ).submit(); },spl[3]); casper.then(function(){ this.wait(300,function () { //この中で馬の詳細情報を取得すること var hoge = this.evaluate(function(){ document.write("<meta charset='utf-8'>"); var tmp1 = document.querySelectorAll('strong') return tmp1[0].innerText return Array.prototype.map.call(tmp1, function(e) { //return e.getAttribute('innerText'); return e.innerHTML; }); }) this.echo(hoge) }); }) k+=1; }); }); }) } j+=1; }); }); i+=1 this.evaluate(function() { history.back(); }); }); } }); //this.evaluate(function() { // history.back(); //}); var fs = require('fs'); fs.write("log.txt", labels, 'w'); }); function getRaceList(){ return this.evaluate(function() { var tmp1 = document.querySelectorAll('a') return Array.prototype.map.call(tmp1, function(e) { return e.getAttribute("onclick") }); }); } function getHorseList(){ return this.evaluate(function() { var tmp1 = document.querySelectorAll('.horseName a') return Array.prototype.map.call(tmp1, function(e) { return e.getAttribute("onclick") }); }); } casper.run(); //レース結果取得版 //casper.start("http://jra.jp/",function(){ //this.clickLabel('レース結果', 'a'); //}); //casper.then(function(){ // this.clickLabel('過去レース検索画面はこちらをご覧ください。', 'a'); //}); //casper.then(function(){ // this.evaluate(function() { // setParameter('2013', '03') // }); //}); //casper.then(function(){ // var text = this.evaluate(function(searchTxt) { // return document.querySelector('.kaisaiDay1').innerHTML // }); // this.echo(text); //});
const getStream = require('get-stream').array const csvParse = require('csv-parse') const fs = require('fs') const uuidv4 = require('./uuidv4') async function parse () { const rows = await getStream( fs.createReadStream(process.argv[2]) .pipe(csvParse({skip_lines_with_error: true, columns: true})) ) const normalizedRows = rows.map(r => { const row = {...r} return { id: uuidv4(), name: row.name, description: row.description, dep: row.dep, timetable: row.timetable, address: row.adresse, address2: row.Compl_adresse, city: row.commune, department: row.dep, ownerName: row.direction, ownerEmail: row.dir_mail, ownerPhone: row.dir_tel, contactName: row.Contact, contactEmail: row.Cont_mail, contactPhone: row.Cont_tel, postalCode: row.code_postal, inseeCode: row.code_Insee, domains: parseDomain(row.Domaine), source: 'canope', loc: row.coordonnees_finales && row.coordonnees_finales.split && { type: 'Point', coordinates: row.coordonnees_finales.split(',').map(v => Number(v.trim())) } } }).filter(x => x) console.log(JSON.stringify(normalizedRows)) } function parseDomain (domains) { return domains && domains.length && domains.split(',') .map(a => a.trim()) .map(a => a.replace(/�/, 'é')) .map(a => a.replace(/^[Tt]h..tre$/, 'Théâtre')) .map(a => a.charAt(0).toUpperCase() + a.slice(1)) } parse()
var status_8h = [ [ "menu_status_line", "status_8h.html#a1becc7497d5ffb91852fa1c7ff0fd5bd", null ], [ "C_StatusChars", "status_8h.html#a694600745dcefa041009f756774860ff", null ] ];
// app/routes.js var console = require('console-prefix') var users = require('./models/user'); var fs = require('fs.extra'); var multer = require('multer') var upload = multer({ dest: 'uploads/' }) var Event = require('./models/event'); module.exports = function(app, passport) { // ===================================== // LOGIN =============================== // ===================================== // show the login form app.get('/', function(req, res) { res.render('pages/login.ejs', { message: req.flash('loginMessage') }); }); // process the login form app.post('/login', passport.authenticate('local-login', { successRedirect : '/dashboard', // redirect to the secure profile section failureRedirect : '/', // redirect back to the signup page if there is an error failureFlash : true // allow flash messages })); // ===================================== // SIGNUP ============================== // ===================================== // show the signup form app.get('/signup', function(req, res) { res.render('signup.ejs', { message: req.flash('signupMessage') }); }); // process the signup form app.post('/signup', passport.authenticate('local-signup', { successRedirect : '/dashboard', // redirect to the secure profile section failureRedirect : '/signup', // redirect back to the signup page if there is an error failureFlash : true // allow flash messages })); // ===================================== // PROFILE SECTION ========================= // ===================================== app.get('/dashboard',isLoggedIn, function(req, res) { res.render('pages/dashboard.ejs', { user : req.user // get the user out of session and pass to template }); }); // ===================================== // LOGOUT ============================== // ===================================== app.get('/logout', function(req, res) { req.logout(); res.redirect('/'); }); // ===================================== // USERS EXIST ======================== // ===================================== app.get('/users/:document',function(req,res){ // user exist var documentFinger = req.param("document"); users.findOne({"local.document":documentFinger},function(err, users) { if (err){ return done(err); } // if no user is found, return the message if (!users){ return res.end('{"found": false}') } var usr = JSON.parse(JSON.stringify(users)); var name = usr.local.name; return res.end('{"found": true,"name":"'+name+'"}'); }); }); // ===================================== // DOCUMENT USER POST ================== // ===================================== app.get('/file/get/:document',function (req, res, next) { var documentFinger = req.param("document"); var options = { root: './public/huella/', dotfiles: 'deny', headers: { 'x-timestamp': Date.now(), 'x-sent': true } }; users.find({"local.document" : documentFinger},function(err, users) { if (err == '') { res.end("{'found': false}"); }else{ var fileName = documentFinger + '.tml'; res.sendFile(fileName, options, function (err) { if (err) { res.status(err.status).end(); } else { console.log('Sent:', fileName); } }); } }); }); // ===================================== // lOGIN REMOTE ======================== // ===================================== app.post('/loginFinger', upload.array('template',1),function(req,res){ var documentUser = req.body.documentUser; var password = req.body.password; users.findOne({ 'local.document' : documentUser }, function(err, users) { if (err){ return done(err); } // if no user is found, return the message if (!users){ return res.end('{"login": false}') } // if the user is found but the password is wrong if (!users.validPassword(password)){ return res.end('{"login": false}') } // all is well, return successful user return res.end('{"login": true}') }); }); // ===================================== // ALL USER GET========================= // ===================================== app.get('/users',function(req,res){ // r date = new Date (); users.find({'local.date':'{gte:}'},function(err, users) { if (err) { return res.send(err); } Event.find({},function(err, events) { if (err) { return res.send(err); } console.dir(events); }); res.render('pages/users.ejs',{users: users}) }); }); // ===================================== // SAVE FILE FINGER ==================== // ===================================== app.post('/file', upload.array('template',1),function(req,res){ var main_dir='./public/huella/'; var username = req.body.username; var name = [username + '.tml']; var final_path = main_dir; if (!fs.exists(main_dir)) { fs.mkdir(main_dir); } if(!fs.exists(final_path)){ fs.mkdir(final_path); } for(var x=0;x<req.files.length;x++) { fs.createReadStream('./uploads/'+req.files[x].filename).pipe(fs.createWriteStream(final_path+req.files[x].originalname)); fs.renameSync(final_path+req.files[x].originalname,final_path+name[x]); //borramos el archivo temporal creado fs.unlink('./uploads/'+req.files[x].filename); } res.end("{'success': true}") }); // ===================================== // REGISTER EVENT ====================== // ===================================== app.post('/registerEvent/:document',upload.array('template',1),function(req,res){ var documentUser = req.param("document"); var typeEvent = req.body.typeEvent; users.findOne({ 'local.document' : documentUser }, function(err, users) { if (err){ return done(err); } // if no user is found, return the message if (!users){ return res.end('{"login": false}') } if (typeEvent === 'E' || typeEvent === 'S' ) { // all is well, return successful user var datetime = new Date(); var events = new Event(); events.dateRegister = datetime; events.document = documentUser; events.typeEvent = typeEvent; var hour = datetime.getHours(); var min = datetime.getMinutes() var ss = datetime.getSeconds() var usr = JSON.parse(JSON.stringify(users)); var name = usr.local.name; events.save(); return res.end('{"login": true,"name":"'+name+'","date":"'+hour+":"+min+":"+ss+'"}') }else{ return res.end('{"event": false}') } }) }); }; // ===================================== // TOKEN REQ =========================== // ===================================== // route middleware to make sure function isLoggedIn(req, res, next) { // if user is authenticated in the session, carry on if (req.isAuthenticated()) return next(); // if they aren't redirect them to the home page res.redirect('/'); }
$(function() { function getWidth() { var wHeight = $(window).height(); var H = wHeight - 50; $(".side").height(H); } getWidth(); $(window).on("resize", getWidth); $(".datetime").daterangepicker({ singleDatePicker: true , format: 'MM/DD/YYYY' }, function(start, end, label) { console.log(start.toISOString(), end.toISOString(), label); }); $(document).on("click", ".item-title", function() { var self = $(this); // self.toggleClass("act");\ self.find("span").toggleClass("glyphicon-plus"); self.find("span").toggleClass("glyphicon-minus"); self.parent().next("ul").slideToggle(); }); $(".side").find("ul").each(function() { $(this).on("click", "li", function() { var self = $(this); // alert(self.index()); self.siblings().find("a").removeClass("act"); self.find("a").addClass("act"); }); }); // console.log($(".table thead tr th:first")) // var tab=document.getElementsByClassName("table")[0]; // var selAll=tab.tHead.rows[0].cells[0].getElementsByTagName("input")[0]; // var checks=tab.tBodies[0].getElementsByTagName("input"); // var selectAll=document.querySelector(".select-all .selectAll input"); // //// selAll.onclick=selectAll.onclick=function(){ //// for (var i = 0; i < checks.length; i++) { //// if(this.checked){ //// checks[i].checked=true; //// selectAll.checked=true; //// selAll.checked=true; //// }else{ //// checks[i].checked=false; //// selectAll.checked=false; //// selAll.checked=false; //// } //// } //// } //// for (var i = 0; i < checks.length; i++) { //// checks[i].onclick=function(){ //// check(); //// } //// } //// function check(){ //// for (var i = 0; i < checks.length; i++) { //// if(checks[i].checked == false){ //// selectAll.checked = false; //// selAll.checked=false; //// return; //// } //// } //// selectAll.checked = true; //// selAll.checked=true; //// } // // selAll.onclick=selectAll.onclick=function(){ // selAll.checked=this.checked; // selectAll.checked=this.checked; // Array.from(checks).forEach(function(item){ // item.checked=this.checked; // },this) // } // Array.from(checks).forEach(function (item){ // item.onclick = function (){ // var bl = Array.from(checks).every(function (value){ // return value.checked; // }); // selectAll.checked = bl; // selAll.checked = bl; // }; // }) // // var tableHtml=`<tr> // <td class="align-center"> // <input type="checkbox" id="inlineCheckbox3" value="option3"> // </td> // <td class="align-center">123456</td> // <td> // <p>标题标标题标题标题标题标题标题标题标题</p> // <p class="sub-title"> // <span>原价¥2000</span><span>优惠价¥1000</span><span>课时100</span><span>单课</span><span>2017年</span> // </p> // </td> // <td>一级分类标题-二级分类标题</td> // <td> // 2017-03-16开始<br> // 2017-03-16结束 // </td> // <td class="align-center">100</td> // <td class="align-center"><span class="label label-warning">下架</span></td> // <td class="align-center"> // <a href="" class="table-btn">编辑</a> // <a href="" class="table-btn">设置课件</a> // <a href="" class="table-btn">学习进度</a> // <a href="" class="table-btn">更多</a> // </td> // </tr>`; // $(".pagenum li").on("click",function(){ // $(".page").html("每页"+($(this).index()+1)*5+"条 <span class='caret'></span>"); // console.log() // for (var i = 0; i < ($(this).index()+1)*5; i++) { // tableHtml+=`<tr> // <td class="align-center"> // <input type="checkbox" id="inlineCheckbox3" value="option3"> // </td> // <td class="align-center">123456</td> // <td> // <p>标题标标题标题标题标题标题标题标题标题</p> // <p class="sub-title"> // <span>原价¥2000</span><span>优惠价¥1000</span><span>课时100</span><span>单课</span><span>2017年</span> // </p> // </td> // <td>一级分类标题-二级分类标题</td> // <td> // 2017-03-16开始<br> // 2017-03-16结束 // </td> // <td class="align-center">100</td> // <td class="align-center"><span class="label label-warning">下架</span></td> // <td class="align-center"> // <a href="" class="table-btn">编辑</a> // <a href="" class="table-btn">设置课件</a> // <a href="" class="table-btn">学习进度</a> // <a href="" class="table-btn">更多</a> // </td> // </tr>`; // } // tab.tBodies[0].innerHTML=tableHtml; // tableHtml=""; // }) // for (var i = 0; i < 5; i++) { // Things[i] // } });
import highlighter from "../utils/highlighter" import tableOfContents from "../utils/tableOfContents" /** * Add syntax highlighting to code blocks wrapped in pre tags */ const highlightCode = () => { const codes = document.querySelectorAll("pre > code") highlighter.highlight(codes) } /** * Build a table of contents by passing in targets (the headings you want to link) * and the wrapper (the DOM) whose innerHTML will be altered. */ const buildTableOfContents = () => { // get all headings from #content const target = document .getElementById("content") .querySelectorAll("h2, h3, h4, h5, h6") // get the element we are going to fill with html const wrapper = document .getElementById("table-of-contents") .querySelector("ul") tableOfContents.build(target, wrapper) } export default { highlightCode, buildTableOfContents, }
import React,{Component} from 'react'; import {fetchPaymentData} from './API.js'; import PaymentDetail from './PaymentDetail.js'; class LeasePayment extends Component { constructor(props){ super(props); this.state={ id: "", data: "" } } componentDidMount() { if(this.props.location.search !== ""){ let id = ""; const url = this.props.location.search; //get query string const str = url.substring(1); //get all string after "?" const strs = str.split("="); //split string by "=" id = strs[1]; //let id equal to the vaule of leaseId if(strs[0]==="leaseId" && id!==""){ this.setState({ id:id }) fetchPaymentData(id).then(data=>this.handleFetchData(data)).catch(error=>console.log(error)); } }; } handleFetchData(data){ this.setState({ data:data }) const queryString = `?leaseId=${this.state.id}` this.props.history.push({ pathname: "/leases.html", search: queryString }) } onIdChange(e){ this.setState({ id: e.target.value }) } handleSubmit(e){ e.preventDefault(); fetchPaymentData(this.state.id).then(data=>this.handleFetchData(data)).catch(error=>console.log(error)); } render(){ return ( <div className="payment-container"> <div className="search-payment"> <h3>Please Enter the Lease Id</h3> <form onSubmit={this.handleSubmit.bind(this)}> <input value={this.state.id} placeholder="Lease Id" onChange={this.onIdChange.bind(this)} /> <button type="submit"> Search </button> </form> </div> { this.state.data === ""? <h4>Loading</h4> : <PaymentDetail data={this.state.data}/> } </div> ); } } export default LeasePayment;
import React, { useState } from "react"; import { useDispatch } from "react-redux"; import { Col, Button, Form, FormGroup, Label, Input } from "reactstrap"; import { putBike } from "../../../redux/actions/bikesActions"; const FormUpdate = () => { const dispatch = useDispatch(); const [update, setUpdate] = useState({ id: "", color: "", model: "", lat: "", log: "", }); let id = update.id; const updateBike = (e, id) => { dispatch(putBike(id, update)) .then((res) => { e.target.reset(); e.preventDefault(); }) .catch((err) => console.log(err)); }; const handleChange = (e) => { e.preventDefault(); setUpdate({ ...update, [e.target.name]: e.target.value, }); }; return ( <Form onSubmit={(e) => updateBike(e, id)} className="container"> <FormGroup row> <Label for="Id" sm={2}> Id </Label> <Col sm={10}> <Input type="number" name="id" placeholder="Id-Bike" onChange={handleChange} /> </Col> </FormGroup> <FormGroup row> <Label for="color" sm={2}> Color </Label> <Col sm={10}> <Input type="text" name="color" placeholder="Bike color" onChange={handleChange} /> </Col> </FormGroup> <FormGroup row> <Label for="model" sm={2}> Model </Label> <Col sm={10}> <Input type="text" name="model" placeholder="Bike model" onChange={handleChange} /> </Col> </FormGroup> <FormGroup row> <Label for="location" sm={2}> Latitud </Label> <Col sm={10}> <Input type="number" step="0.0000000001" name="lat" placeholder="Bike location" onChange={handleChange} /> </Col> </FormGroup> <FormGroup row> <Label for="location" sm={2}> Longitud </Label> <Col sm={10}> <Input type="number" step="0.0000000001" name="log" placeholder="Bike location" onChange={handleChange} /> </Col> </FormGroup> <FormGroup check row> <Col sm={{ size: 10, offset: 2 }}> <Button type="submit">Submit</Button> </Col> </FormGroup> </Form> ); }; export default FormUpdate;
module.exports = function check(str, bracketsConfig) { let bracketsMap = new Map(bracketsConfig); let bracketsArr = []; let bracketChar; let separator =""; str.split(separator).forEach( function(bracketChar){ if (bracketChar === bracketsMap.get(bracketsArr[bracketsArr.length - 1])){ bracketsArr.pop(); } else bracketsArr.push(bracketChar) }); return bracketsArr.length === 0; }
import { combineReducers } from 'redux'; import readmeReducers from './readme.reducer'; export default combineReducers({ readmeReducers })
// Publish Meteor.publish("restaurants", function(){ return Restaurants.find({}, {sort: {speedValue: -1}}); }); Meteor.publish("restaurant", function() { return Restaurants.find(); });
import React,{useEffect, useState} from "react"; import "./HomeCategListing.css"; import { NormalPost } from "../postTypes/normalPost/normalPost"; import { GrFormNextLink } from "react-icons/gr"; import { NormalPostV } from "../postTypes/normalPostVertical/NormalPostV"; import { Link } from "react-router-dom"; export const HomeCateglisting = (props) => { // console.log(props.posts) const [posts, setposts] = useState(null) useEffect(()=>{ if(props.posts) setposts(props.posts[0]) },[props.posts]) return (<> {posts? <div> <div className="HomeCateglisting_categName"> <h4>{props.name ? props.name : "category"}</h4> </div> <div className="HomeCateglisting_posts"> <div> {props.posts?props.posts.filter((e,i)=>i<4).map((e,i)=>{ return( <NormalPost key={i} post={e} /> ) }):'' } </div> <div> { posts? <NormalPostV post={posts}/>:'empty'} </div> </div> <div className="HomeCateglisting_contBtn"> <Link to={`/posts/${props.name}/1`} className="HomeCateglisting_nextBtn"> next <GrFormNextLink /> </Link> </div> </div>:''}</> ); };
if (typeof define !== 'function') { var define = function (f) { module.exports = f (require); } } define(function(require) { 'use strict'; var Vec2 = require('./vec2'); function intPower (n,p) { if (p < 1) return 1; if (p === 1) return n; var ret = n; while (--p > 0) ret *= n; return ret; } function fact (n) { if (n < 1) return 1; var ret = n; while (n > 1) ret *= --n; return ret; } function nChooseK (n,k) { return fact(n) / (fact(k) * fact(n-k)); } /** * Given the coordinates of the end points of two line segments, this function returns * their intersection point, or null if they do not intersect. */ var geom = { lineIntersect: function (p00x, p00y, p01x, p01y, p10x, p10y, p11x, p11y) { var dx1x3 = p00x - p10x; var dy1y3 = p00y - p10y; var dx2x1 = p01x - p00x; var dy2y1 = p01y - p00y; var dx4x3 = p11x - p10x; var dy4y3 = p11y - p10y; var denom = dy4y3*dx2x1 - dx4x3*dy2y1; var numa = dx4x3*dy1y3 - dy4y3*dx1x3; var numb = dx2x1*dy1y3 - dy2y1*dx1x3; if (denom === 0) return null; numa /= denom; numb /= denom; if (numa >= 0 && numa <= 1 && numb >= 0 && numb <= 1) { return new Vec2( p00x + dx2x1*numa, p00y + dy2y1*numa ); } return null; }, /** * Returns true if the supplied point (x,y) lies in the space bounded by two * infinite lines which intersect the points defining the provided line segment, and * are perpendicular to the provided line segment. */ pointInLinePerpSpace: function (ax, ay, bx, by, x, y) { // If the slope is greater than 1, transpose the coordinate space to avoid infinity. if (perpSlope > 1) { var oax = ax, obx = bx, ox = x; ax = ay; bx = by;_x = y; ay = oax; by = obx; y = ox; } var perpSlope = (ax-bx)/(by-ay); var yMin, yMax; if (ay > by) { yMin = perpSlope*(x - bx) + by; yMax = perpSlope*(x - ax) + ay; } else { yMin = perpSlope*(x - ax) + ay; yMax = perpSlope*(x - bx) + by; } return y > yMin && y < yMax; }, /** * Given the slope of a line passing through the origin and a point on the plane, * this function returns the intersection point of a line which passes through the * provided point and perpendicularly intersects the first line. */ projectPointOnLine: function (m, x, y) { if (Math.abs (m) < 1e-9) { return new Vec2 (x,0); } else if (Math.abs (m) > 1e9) { return new Vec2 (0,y); } var retY = (y*m+x)*m/(1+m*m); return new Vec2 (retY/m, retY); }, /** * Given an array of control points representing an arbitrary order Bezier curve * along with a value 't' between 0, and 1, this function will return a point * along the curve as a Vec2. */ bezier: function (pts,t) { if (pts.length < 2) return pts[0]; if (t <= 0) return pts[0]; if (t >= 1) return pts[pts.length-1]; var u = 1 - t; var n = pts.length - 1; var ret = new Vec2; for (var i = 0; i <= n; ++i) { var coeff = nChooseK(n,i) * intPower(t,i) * intPower(u,n-i); ret.x += coeff * pts[i].x; ret.y += coeff * pts[i].y; } return ret; }, /** * Estimates the length of a Bezier curve by measuring straight line segments * approximating the curve. 'precision' segments are used. */ bezierLength: function (pts,precision) { var step = 1 / precision; var lastPoint = pts[0]; var vec = new Vec2; var len = 0; for (var t = step; t <= 1; t += step) { var newPoint = geom.bezier(pts,t); len += vec.set(newPoint).sub(lastPoint).magnitude(); lastPoint = newPoint; } return len; } }; return geom; });
const pgp = require('pg-promise')({ capSQL: true, // generate capitalized SQL }); pgp.pg.defaults.poolSize = 20; console.log(pgp.pg.defaults.poolSize); const faker = require('faker'); const db = pgp(/* connection details */{ host: 'localhost', port: 5432, database: 'Zaget', user: 'mrmac', }); // your database object // Creating a reusable/static ColumnSet for generating INSERT queries: const cs = new pgp.helpers.ColumnSet([ 'id', 'name', 'address', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'location', 'url', 'phone', 'lat', 'lng', ], { table: 'zagnar' }); const randomFunction = (makeId) => { const amRandom = faker.random.number({ min: 6, max: 11 }); const pmRandomizer = faker.random.number({ min: 1, max: 12 }); const randomizer = faker.random.number({ min: 1, max: 12 }); const latitude = faker.fake('{{address.latitude}}'); const longitude = faker.fake('{{address.longitude}}'); const obj = { id: makeId, name: faker.fake('{{company.companyName}}'), address: `${faker.fake('{{address.streetAddress}}')}, ${faker.fake('{{address.city}}')}, ${faker.fake('{{address.stateAbbr}}')}, ${faker.fake('{{address.zipCode}}')}, ` + 'USA', monday: `${amRandom}:00 AM - ${pmRandomizer}:00 PM`, tuesday: `${amRandom}:00 AM - ${pmRandomizer}:00 PM`, wednesday: `${amRandom}:00 AM - ${pmRandomizer}:00 PM`, thursday: `${amRandom}:00 AM - ${pmRandomizer}:00 PM`, friday: `${amRandom}:00 AM - ${pmRandomizer}:00 PM`, saturday: `${amRandom}:00 AM - ${randomizer}:00 PM`, sunday: 'Closed', location: `https://www.google.com/maps/@${latitude},${longitude},15z`, url: `http://www.${faker.fake('{{lorem.word}}')}.com`, phone: faker.fake('{{phone.phoneNumber}}'), lat: latitude, lng: longitude, }; return obj; }; // const insert = pgp.helpers.insert(data, cs); const getNextData = (t, pageIndex) => { let data = null; if (pageIndex < 1000) { data = []; for (let i = 0; i < 10000; i += 1) { const idx = pageIndex * 10000 + i; data.push(randomFunction(idx)); } } return Promise.resolve(data); }; db.tx('massive-insert', t => t.sequence(index => getNextData(t, index) .then((data) => { if (data) { const insert = pgp.helpers.insert(data, cs); return t.none(insert); } }))) .then((data) => { // COMMIT has been executed console.log('Total batches:', data.total, ', Duration:', data.duration); }) .catch((error) => { // ROLLBACK has been executed console.log(error); }); exports.randomFunction = randomFunction;
// get length of vector export const length = (v) => Math.sqrt(v[0]*v[0] + v[1]*v[1]) // add to vectors together export const add = (a, b) => [a[0]+b[0], a[1]+b[1]] // subtract to vectors export const sub = (a, b) => [a[0]-b[0], a[1]-b[1]] // multiply vector with scalar export const mul = (v, s) => [v[0]*s, v[1]*s] // divide vector by scalar export const div = (v, s) => [v[0]/s, v[1]/s] export const normalized = (v) => div(v, length(v))
// Below is to stop React 16 spewing warnings to the console // It can be removed after the issue has been fixed global.requestAnimationFrame = setTimeout; const Enzyme = require('enzyme'); const Adapter = require('enzyme-adapter-react-16'); Enzyme.configure({ adapter: new Adapter() });
const { Poem, Status } = require('./database') function updateStatus (doc) { const { _id: currentId } = doc const updatedStatus = new Status({ currentId, poemIdCounter: 2 }) updatedStatus.save((err, doc) => { if (err) return console.error(err) console.log('Initialized status', doc) }) } const now = Date.now() const firstPoem = new Poem({ poemId: 1, lines: ['a single line'], maxLength: 1, finishedAt: now }) firstPoem.save((err, savedPoem) => { if (err) return console.error(err) updateStatus(savedPoem) })
define([ 'jquery', 'underscore', 'backbone', 'collections/user', 'views/user/list', 'views/alert', 'text!templates/navbar/dropdown.html', ], function($, _, Backbone, UserCollection, UserListView, AlertView, dropdownTemplate) { var NavbarView = Backbone.View.extend({ el: ".navbar", dropdownTemplate : _.template(dropdownTemplate), events: { "click #logout" : "logout", "click #userlist" : "userList", "click #postList" : "postList", }, initialize: function(options) { _.bindAll(this, 'render','logout','userList','close'); this.vent = options.vent; this.vent.on('user:navbar', this.render); }, render: function(model) { this.$('.nav').html(this.dropdownTemplate(model.toJSON())); return this; }, logout: function(event) { event.preventDefault(); this.vent.trigger('site:logout'); }, userList: function(event) { event.preventDefault(); this.vent.trigger('user:list'); }, postList: function(event) { event.preventDefault(); this.vent.trigger('post:list'); }, close: function() { this.undelegateEvents(); this.remove(); }, }); return NavbarView; });
function devopsTest($scope, $http) { $scope.messages = {}; $scope.init = function () { $scope.messages.text = 'Front end build passed'; }; };
import React from 'react' import { theme } from '../theme' export const responsiveSpace = [ theme.space.medium, theme.space.medium, theme.space.large, theme.space.xlarge, ] export const HorizontalList = ({ children }) => ( <> <div css={[ { overflow: 'hidden', }, ]} > <ul css={[ { display: 'flex', marginLeft: 0, marginRight: 0, marginTop: 0, paddingLeft: 0, paddingRight: 0, marginBottom: -30, paddingBottom: 30, width: '100%', overflowY: 'hidden', overflowX: 'visible', scrollSnapType: 'x mandatory', WebkitOverflowScrolling: 'touch', '::-webkit-scrollbar': { WebkitAppearance: 'none !important', display: 'none !important', }, }, theme.mq({ scrollPaddingLeft: [0, ...responsiveSpace.slice(1)], 'li:first-of-type': { paddingLeft: responsiveSpace, }, 'li:last-of-type': { paddingRight: responsiveSpace, }, }), ]} > {React.Children.map(children, child => ( <li css={[ { display: 'inline-block', }, theme.mq({ scrollSnapAlign: ['center', 'start', 'start', 'start'], ':not(:last-child)': { marginRight: [theme.space.xsmall, theme.space.medium], }, }), ]} > {child} </li> ))} </ul> </div> </> )
const dateRegex = new RegExp("^\\d\\d\\d\\d-\\d\\d-\\d\\d"); // convert date strings to native JS Date types function jsonDateReviver(key, value) { if (dateRegex.test(value)) { // if the value is a date string return new Date(value); // convert to native JS Date type } return value; } class IssueFilter extends React.Component { render() { return <div>IssueFilter</div>; } } function IssueTable(props) { const issueRows = props.issues.map(issue => ( <IssueRow key={issue.id} issue={issue} /> )); return ( <div> <table className="bordered-table"> <thead> <tr> <th>ID</th> <th>Status</th> <th>Owner</th> <th>Created</th> <th>Effort</th> <th>Due date</th> <th>Title</th> </tr> </thead> <tbody>{issueRows}</tbody> </table> </div> ); } function IssueRow(props) { const { id, status, owner, created, effort, due, title } = props.issue; return ( <tr> <td>{id}</td> <td>{status}</td> <td>{owner}</td> <td>{created.toDateString()}</td> <td>{effort}</td> <td>{due ? due.toDateString() : ""}</td> <td>{title}</td> </tr> ); } class IssueAdd extends React.Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(e) { e.preventDefault(); const form = document.forms.issueAdd; const issue = { owner: form.owner.value, title: form.title.value, // status: "New", // set the due date 10 days from the current date due: new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 10) }; this.props.createIssue(issue); form.owner.value = ""; form.title.value = ""; } render() { return ( <div> <form name="issueAdd" onSubmit={this.handleSubmit}> <input type="text" name="owner" placeholder="Owner" /> <input type="text" name="title" placeholder="Title" /> <button>Add</button> </form> </div> ); } } class IssueList extends React.Component { constructor() { super(); this.state = { issues: [] }; this.createIssue = this.createIssue.bind(this); } componentDidMount() { this.loadData(); } // get a list of issues from the issues DB async loadData() { // construct GraphQL query const query = `query { issueList { id title status owner created effort due } }`; // send the query string as the value for the query property within a JSON // as part of the body to the fetch requst const response = await fetch("/graphql", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ query }) }); // convert the JSON data in the response to a JavaScript object and store as the result const body = await response.text(); // the jsonDateReviver parses date string to native JS Date types const result = JSON.parse(body, jsonDateReviver); // set the state with the result data this.setState({ issues: result.data.issueList }); } // createIssue(issue) { // issue.id = this.state.issues.length + 1; // issue.created = new Date(); // const newIssueList = this.state.issues.slice(); // newIssueList.push(issue); // this.setState({ issues: newIssueList }); // } // Add a new issue to the issues database async createIssue(issue) { // GraphQl query const query = `mutation { issueAdd(issue:{ title: "${issue.title}", owner: "${issue.owner}", due: "${issue.due.toISOString()}" }) { id } }`; // use the query to execute fetch asyncronously const response = await fetch("/graphql", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ query }) }); // refresh the list of issues this.loadData(); } render() { return ( <React.Fragment> <h1>Issue Tracker</h1> <IssueFilter /> <hr /> <IssueTable issues={this.state.issues} /> <hr /> <IssueAdd createIssue={this.createIssue} /> </React.Fragment> ); } } const element = <IssueList />; ReactDOM.render(element, document.getElementById("contents"));
var express = require('express'); var router = express.Router(); var mysql_odbc = require('../../db/db_conn')(); var conn = mysql_odbc.init(); function validate (req, res, next , keys) { let isValidated = true; for(let key of keys) { let val = req.body[key]; if(!val){ isValidated = false; // 없는 경우 res.json({ status : 'fail', mesg : '\''+key+'\'가 존재하지 않습니다' }); break; } else{ if(key === 'title'){ if(val.length >= 100){ isValidated = false; res.json({ status : 'fail', mesg : '\''+key+'\'는 100자가 넘을 수 없습니다' }); break; } else if(val.length <= 0){ isValidated = false; res.json({ status : 'fail', mesg : '\''+key+'\'는 공백일 수 없습니다' }); break; } } else if(key === 'content'){ if(val.length >= 1000){ isValidated = false; res.json({ status : 'fail', mesg : '\''+key+'\'는 1000자가 넘을 수 없습니다' }); break; } else if(val.length <= 0){ isValidated = false; res.json({ status : 'fail', mesg : '\''+key+'\'는 공백일 수 없습니다' }); break; } } else if(key === 'passwd'){ if(val.length >= 10){ isValidated = false; res.json({ status : 'fail', mesg : '\''+key+'\'는 10자가 넘을 수 없습니다' }); break; } else if(val.length <= 0){ isValidated = false; res.json({ status : 'fail', mesg : '\''+key+'\'는 공백일 수 없습니다' }); break; } else if(isNaN(val)){ isValidated = false; res.json({ status : 'fail', mesg : '\''+key+'\'는 숫자여야합니다.' }); break; } } } }; if(isValidated){ next(); } } // router.use(validate); // GET : api/board/ // 전체 목록 가져오기 router.get('/' , (req,res,next)=>{ // 모든 글을 json 형태로 반환 // 글 내용은 보여주지 않음 var page = req.params.page; var sql = "select idx, name, title, date_format(modidate,'%Y-%m-%d %H:%i:%s') modidate, " + "date_format(regdate,'%Y-%m-%d %H:%i:%s') regdate from board"; conn.query(sql, function (err, rows) { if (err) console.error("err : " + err); // res.render('list', {title: '게시판 리스트', rows: rows}); res.json(rows); }); }); // POST : api/board // 글 새로 쓰기 router.post("/" , (req,res,next)=>{ validate(req,res,next,['name' , 'title' , 'content' , 'passwd']); } , (req,res,next)=>{ console.log('validated!'); // 글을 새로 등록 var name = req.body.name; var title = req.body.title; var content = req.body.content; var passwd = req.body.passwd; var datas = [name,title,content,passwd]; var sql = "insert into board(name, title, content, regdate, modidate, passwd,hit) values(?,?,?,now(),now(),?,0)"; conn.query(sql,datas, function (err, result) { // 성공했을 경우 if(result.affectedRows > 0 ){ res.json({ statusCode : result.affectedRows, status : "성공했습니다." }); } else{ res.json({ statusCode : result.affectedRows, status : "실패했습니다." }); } }); }); // GET : api/board/3 // 특정 글만 가져오기 router.get('/:idx', function(req, res, next) { // 특정 글만 검색해서 json으로 반환 var hit = req.body.hit; var idx = req.params.idx; var sql = "select idx, name, title, content, date_format(modidate,'%Y-%m-%d %H:%i:%s') modidate, " + "date_format(regdate,'%Y-%m-%d %H:%i:%s') regdate,hit from board where idx=?"; conn.query(sql,[idx], function(err,row){ if(err) console.error(err); else{ "UPDATE board SET hit = hit + 1 WHERE idx = ?"; res.json(row);} }); }); // PUT : api/board/:id // 이미 있는 글을 수정 router.put("/:page" ,(req,res,next)=>{ validate(req,res,next,['name' , 'title' , 'content' , 'passwd']); } , (req,res,next)=>{ var name = req.body.name; var title = req.body.title; var content = req.body.content; var passwd = req.body.passwd; var datas = [name,title,content,req.params.page,passwd]; var sql = "update board set name=? , title=?,content=?, modidate=now() where idx=? and passwd=?"; // if (passwd != ){ // res.json({ // status : "비밀번호가 틀렸습니다!" // }); // return; // } conn.query(sql,datas,function(err,result){ // 에러가 생긴 경우 if (err){ res.json({ statusCode : -1, status : "fail", err : err }); } // 성공했을 경우 if(result.affectedRows > 0 ){ res.json({ statusCode : result.affectedRows, status : "성공했습니다." }); } else{ res.json({ statusCode : result.affectedRows, status : "실패했습니다." }); } }); }); // DELETE : api/board/:id // 이미 있는 글을 삭제 router.delete("/:page" ,(req,res,next)=>{ validate(req,res,next,['passwd']); } , (req,res,next)=>{ // var idx = req.params.idx; var passwd = req.body.passwd; var page = req.params.page; var datas = [page,passwd]; var sql = "delete from board where idx=? and passwd=?"; conn.query(sql,datas,function(err,result){ // 에러가 생긴 경우 if (err){ res.json({ statusCode : -1, status : "fail", err : err }); } // 성공했을 경우 if(result.affectedRows > 0 ){ res.json({ statusCode : result.affectedRows, status : "성공했습니다." }); } else{ console.log(sql , page , passwd); res.json({ statusCode : result.affectedRows, status : "실패했습니다." }); } }); }); module.exports = router;
import moment from 'moment' console.log(moment().format())
import React from "react"; import "./index.css"; const handleCardResult = ( marginTop, profit, chance, ProfitTitle, ProbabilityTitle ) => { return ( <div styleName="result-container-right" style={{ marginTop }}> <div> <p styleName="text-result">{ProfitTitle}</p> <div styleName="result-right"> <p styleName="text-result">{`${profit}`}</p> </div> </div> <div> <p styleName="text-result">{ProbabilityTitle}</p> <div styleName="result-right"> <p styleName="text-result">{`${chance}`}</p> <p styleName="text-result-percent">%</p> </div> </div> </div> ); }; export default handleCardResult;
console.log('ServerJs');//test comment const mongoose = require('mongoose'); const dotenv = require('dotenv'); process.on("uncaughtException", (err)=>{ //handle uncaught exception placed on top so that any synchronous errors below this line would be caught. console.log(err); console.log("Unhandled Exception!! SHUTTING DOWN"); process.exit(1); }) dotenv.config({ path: `${__dirname}/config.env` }); const DB = process.env.DATABASE.replace( '<PASSWORD>', process.env.DATABASE_PASSWORD ); mongoose //.connect(process.env.DATABASE_LOCAL, { .connect(DB, { useNewUrlParser: true, useCreateIndex: true, useFindAndModify: false, useUnifiedTopology: true, }) .then((conn) => { //console.log(conn.connections); console.log(`Connection Successful`); }); /****************Testing Document creation** const testTour = new Tour({ name: 'The Forest Hiker', rating: 6.7, price: 5000, }); testTour .save() .then((doc) => { console.log(doc); }) .catch((err) => { console.log(err); }); *********************************************************************/ //console.log(process.env.NODE_ENV); const app = require(`./app`); //console.log(app.get('env')); //console.log('just after require app'); const port = process.env.PORT || 1440; const server = app.listen(port, () => { console.log(`Server is listening now on port ${port}`); }); process.on("unhandledRejection", (err)=>{ //handle unhandled rejections in a global place console.log(err); console.log("Unhandled rejection!! SHUTTING DOWN"); server.close(()=>{ process.exit(1); }) }) process.on('SIGTERM',()=>{ console.log("SIGTERM SIGNAL FROM HEROKU RECEIVED. SHUTTING DOWN GRACEFULLY!"); server.close(()=>{ console.log("Process terminated due to SIGTERM"); }) })
const fs = require('fs'); const xcode = require('xcode'); const vibesUtils = require('./vibes-utils'); module.exports = function(context) { console.log('Starting hook to add iOS RichPush notification extension to project'); const cordovaCommon = require('cordova-common'); const appConfig = new cordovaCommon.ConfigParser('config.xml'); const appName = appConfig.name(); const packageName = vibesUtils.cordovaPackageNameForPlatform(appConfig, 'ios'); const iosPath = 'platforms/ios/'; const projPath = `${iosPath}${appName}.xcodeproj/project.pbxproj`; const extName = 'RichPush'; const extFiles = [ 'NotificationService.swift', 'RichPushNotificationParsing.swift', 'vibes_custom.wav', `${extName}-Info.plist`, ]; // The directory where the source extension files are stored const sourceDir = `native/ios/${extName}/`; // Wait a few seconds before parsing the project to let some other // asynchronous project file changes complete. Maybe there is a way to get // a promise? console.log('Waiting a few seconds for other project file changes to finish'); vibesUtils.deleteFolderRecursive('platforms/ios/RichPush'); setTimeout(function () { console.log(`Adding notification extension to ${appName}`); let proj = xcode.project(projPath); proj.parse(function (err) { if (err) { console.log(`Error parsing iOS project: ${err}`); } // Copy in the extension files console.log('Copying in the extension files to the iOS project'); fs.mkdirSync(`${iosPath}${extName}`); extFiles.forEach(function (extFile) { let targetFile = `${iosPath}${extName}/${extFile}`; fs.createReadStream(`${sourceDir}${extFile}`) .pipe(fs.createWriteStream(targetFile)); }); // Create new PBXGroup for the extension console.log('Creating new PBXGroup for the extension'); let extGroup = proj.addPbxGroup(extFiles, extName, extName); // Add the new PBXGroup to the CustomTemplate group. This makes the // files appear in the file explorer in Xcode. console.log('Adding new PBXGroup to CustomTemplate PBXGroup'); let groups = proj.hash.project.objects['PBXGroup']; Object.keys(groups).forEach(function (key) { if (groups[key].name === 'CustomTemplate') { proj.addToPbxGroup(extGroup.uuid, key); } }); // Add a target for the extension console.log('Adding the new target'); let target = proj.addTarget(extName, 'app_extension'); // Add build phases to the new target console.log('Adding build phases to the new target'); proj.addBuildPhase([ 'NotificationService.swift', 'RichPushNotificationParsing.swift'], 'PBXSourcesBuildPhase', 'Sources', target.uuid); proj.addBuildPhase(['vibes_custom.wav'], 'PBXResourcesBuildPhase', 'Resources', target.uuid); proj.addBuildPhase([], 'PBXFrameworksBuildPhase', 'Frameworks', target.uuid); console.log('Write the changes to the iOS project file'); // Iterate through the entire XCBuildConfig for config of the new target PRODUCT_NAME and modify it var config = proj.hash.project.objects['XCBuildConfiguration']; for (var ref in config) { if ( config[ref].buildSettings !== undefined && config[ref].buildSettings.PRODUCT_NAME !== undefined && (config[ref].buildSettings.PRODUCT_NAME.includes(extName) || config[ref].buildSettings.PRODUCT_NAME == extName) ) { console.log(`Entered the setting: ${config[ref].buildSettings.PRODUCT_NAME} of ${ref}`); var INHERITED = '"$(inherited)"'; if ( !config[ref].buildSettings['FRAMEWORK_SEARCH_PATHS'] || config[ref].buildSettings['FRAMEWORK_SEARCH_PATHS'] === INHERITED ) { proj.hash.project.objects['XCBuildConfiguration'][ref].buildSettings['FRAMEWORK_SEARCH_PATHS'] = [ INHERITED ]; } proj.hash.project.objects['XCBuildConfiguration'][ref].buildSettings['IPHONEOS_DEPLOYMENT_TARGET'] = '10.0'; var currentBundleID = proj.hash.project.objects['XCBuildConfiguration'][ref].buildSettings['PRODUCT_BUNDLE_IDENTIFIER']; if ( vibesUtils.isEmptyString(currentBundleID) || !currentBundleID.includes(`${packageName}.${extName}`) ) { console.log('Setting PRODUCT_BUNDLE_IDENTIFIER to ', `${packageName}.${extName}`); proj.hash.project.objects['XCBuildConfiguration'][ref].buildSettings[ 'PRODUCT_BUNDLE_IDENTIFIER' ] = `${packageName}.${extName}`; } // ensure code signing identity is pointed correctly proj.hash.project.objects['XCBuildConfiguration'][ref].buildSettings[ 'CODE_SIGN_STYLE' ] = `"Manual"`; proj.hash.project.objects['XCBuildConfiguration'][ref].buildSettings[ 'DEVELOPMENT_TEAM' ] = `"XXXXX"`; proj.hash.project.objects['XCBuildConfiguration'][ref].buildSettings[ 'CODE_SIGN_IDENTITY' ] = `"iPhone Distribution"`; proj.hash.project.objects['XCBuildConfiguration'][ref].buildSettings['PRODUCT_NAME'] = `${extName}`; } } fs.writeFileSync(projPath, proj.writeSync()); console.log(`Added ${extName} notification extension to project`); }); }, 10000); };
const config = { AMQP_URL: process.env.AMQP_URL || 'amqp://localhost' }; module.exports = config;
import React, { Component } from 'react'; import { Rate } from '../_components/myInput'; import { footerActions } from '../../_actions'; import { connect } from 'react-redux'; class OrderHistory extends Component { componentDidMount(){ const { historyData, showFooter } = this.props; if(historyData.length == 0){ showFooter(); } } componentWillUnmount(){ this.props.hideFooter(); } render() { const { historyData } = this.props; if(historyData.length === 0){ return ( <div style={{textAlign: 'center'}}> <h3>no dress</h3> </div> ) } return ( <div> {historyData.map((elem) => { let rating = elem.productRate == undefined || elem.productRate == '' ? 0 : +elem.productRate; return ( <div className="container"> <div className="row" style={{margin:'0px'}}> <div className="col-xs-12 col-sm-1 col-md-2 col-lg-2"></div> <div className="col-xs-12 col-sm-3 col-md-2 col-lg-2" style={{paddingTop: '2%'}}> <img alt="" src={elem.fileList[0]} className="current_image"/> </div> <div className="col-xs-12 col-sm-6 col-md-6 col-lg-6"> <div className="row" style={{margin:'0px'}}> <div className="col-xs-6 col-sm-4 col-md-4 col-lg-4"> <h1 className="current_dress_name">{elem.productName}</h1> </div> <div className="col-xs-6 col-sm-6 col-md-6 col-lg-6" style={{marginTop:'-3%'}}>&emsp;&emsp; <Rate OH={true} rate={rating == 0 ? '' : rating} initialRating={rating} readonly/> </div> </div> <div className="row" style={{margin:'0px'}}> <div className="col-xs-12 col-sm-8 col-md-6 col-lg-6"> <h4 className="orderHistory_sizes">Size: {elem.sizes.join(", ")}</h4> </div> <div className="col-xs-6 col-sm-4 col-md-6 col-lg-6"></div> </div> <div className="row" style={{margin:'0px'}}> <div className="col-xs-12 col-sm-11 col-md-8 col-lg-8"> <h1 className="order_history_command">&nbsp;&nbsp;&nbsp;Rent Used & Returned Succesfully</h1> </div> <div className="col-xs-12 col-sm-1 col-md-4 col-lg-4"></div> </div> <div className="row" style={{margin:'0px'}}> <div className="col-xs-12 col-sm-8 col-md-6 col-lg-6"> <h4 className="current_total_price">${elem.priceDay} X {+elem.rentDay +1} Days = ${elem.amount}</h4> </div> <div className="col-xs-6 col-sm-4 col-md-6 col-lg-6"></div> </div> </div> <div className="col-xs-12 col-sm-2 col-md-2 col-lg-2"></div> </div> <div className="row" style={{margin:'0px'}}> <div className="col-xs-12 col-sm-2 col-md-2 col-lg-2"></div> <div className="col-xs-12 col-sm-8 col-md-8 col-lg-8"> <hr style={{borderTop:'2px solid rgb(203, 157, 108)'}}/> </div> <div className="col-xs-12 col-sm-2 col-md-2 col-lg-2"></div> </div> </div> ) })} </div> ); } } // export default OrderHistory; function mapDispatchToProps(dispatch) { return { showFooter: () => dispatch({ type: 'SHOW_FOOTER' }), hideFooter: () => dispatch({ type: 'HIDE_FOOTER' }) }; } const connectedOrderHistory = connect(null, mapDispatchToProps)(OrderHistory); export default connectedOrderHistory;
var searchData= [ ['bcache_5flist_5ft',['bcache_list_t',['../bcache_2lib_8h.html#a1cbba854dbad4ca2ef97dfad376a2fa6',1,'lib.h']]] ];
$(function(){ function checked_films(){ var check_list = ''; for(var i=0;i<11;i++){ var flag = $("#cmn-toggle-" + i).prop('checked') ? 1 : 0; check_list += flag; } return check_list; } /*movie_id = data.split(' ')[0]; * data = data.split('Name')[0].slice(5);*/ $("#reset").on("click", function(){ document.location.reload(true); }); $("#proceed").on("click", function(){ flags = checked_films(); indexes = movie_list; $.get( "initialize/" + flags + '/' + indexes, function(data){ create_dialog(data); } ); }); tmp_response = ''; function create_dialog(data){ $("#movie_ask").html("<span class='ui-icon ui-icon-alert' style='float:left; margin:12px; 12px 20px 0;'></span>" + data.split('Name')[0].slice(5)); $( "#dialog-confirm" ).dialog({ resizable: false, height: "auto", width: 400, modal: true, buttons: { "YES": function() { $.get( "initialize/1/" + data.split(' ')[0], function(response){ //alert("response yes"); tmp_response = response; setTimeout( function(){ create_dialog(tmp_response); },100); $(this).dialog("close"); }); }, "NO": function() { $.get( "initialize/-/" + data.split(' ')[0], function(response){ //alert("response no"); tmp_response = response; setTimeout( function(){ create_dialog(tmp_response) }, 100); $(this).dialog("close"); }); } } }); } });
import { setError, setPayload, setPending } from '../../utils/actionHandlers'; import { createReducer } from 'reduxsauce'; import productTypes from './product.types'; const INITIAL_STATE = { products: [], }; const actionHandlers = { [productTypes.GET_PRODUCT_REQUEST]: setPending, [productTypes.GET_PRODUCT_DETAILS]: setPayload('products'), [productTypes.GET_PRODUCT_FAIL]: setError, }; const productReducer = createReducer(INITIAL_STATE, actionHandlers); export default productReducer;
const Koa = require('koa') const app = new Koa() const views = require('koa-views') const json = require('koa-json') const onerror = require('koa-onerror') const bodyparser = require('koa-bodyparser') const morgan = require('koa-morgan') const chalk = require('chalk') const util = require('util') const OAuth2 = require('./lib/oauth2').OAuth2 const config = require('./config') const utils = require('./lib/utils') const fetch = require('./routes/fetch') const service = require('./routes/service') const db = require('./models'); var debug = (process.env.NODE_ENV == 'debug'? 'debug': undefined) morgan.token('date', function(){ return new Date().toLocaleString() }) // error handler onerror(app) // middlewares app.use(bodyparser({ enableTypes:['json', 'form', 'text'] })) app.use(json()) app.use(morgan(':date :method :url :status :res[content-length] - :response-time ms')); app.use(require('koa-static')(__dirname + '/public')) app.use(views(__dirname + '/views', { extension: 'ejs' })) //logger if(debug) { app.use(async (ctx, next) => { const start = new Date(); await next(); const ms = new Date() - start util.log(util.format(chalk.red('%s: %s %s - %sms'), 'REQUEST ', ctx.method, ctx.url, ms)); util.log(util.format(chalk.cyan('%s: %s'), 'BODY ', util.inspect(ctx.request.body))); }); } //init OauthSDK var oauth_client = new OAuth2(config.client_id, config.client_secret, config.account_server, '/oauth2/authorize', '/oauth2/token', config.callbackURL); asyncOauthGet= async(url,accessToken)=>{ let oauthGet = await new Promise(function(resolve,reject){ oauth_client.get(url, accessToken,function(e,response){ if (e) { e.status = e.statusCode; e.message = e.data; reject(e); }else{ resolve(response.toString()); } }); }); return oauthGet; } //init database app.use(async(ctx, next) => { try{ if(debug) console.log('Validating user authorization token' ); var access_token = ctx.request.get('Authorization').split(" ")[1]; var url = config.oauth.account_server + '/user'; if(debug) var startOauth = new Date(); let user = await asyncOauthGet(url, access_token); if(debug) var msOauth = new Date() - startOauth; if(debug) console.log(`Validate AccessToken - ${msOauth}ms`) //console.log(user); if(JSON.parse(user).id != config.biz.oauth.username) ctx.throw(400, {message:utils.buildResponse(-3, 'User\'s role is not seller(admin)')}); } catch (ex){ util.log(util.format(chalk.red('%s %s'),'EXCEPTION',JSON.stringify(ex))); ctx.status = parseInt(ex.status,10); switch (ctx.status) { case 404: ctx.body = utils.buildResponse(-1,'Access Token not found'); break; case 401: ctx.body = utils.buildResponse(-2,'Invalid Access Token'); break; default: { ctx.body = ex.message; } } return; } await next(); }); // routes app.use(service.routes(), service.allowedMethods()) app.use(fetch.routes(), fetch.allowedMethods()) module.exports = app
const path = require('path') const resolve = (dir) => path.resolve(__dirname, dir) const devConf = { pages: { index: { entry: resolve('../examples/main.js'), template: resolve('../public/index.html'), filename: 'index.html' } }, css: { loaderOptions: { sass: { prependData: '@import "@/styles/index.scss";' } } }, configureWebpack: { resolve: { extensions: ['.js', '.vue', '.json'], alias: { '@': resolve('../src') } } }, chainWebpack: config => { config.module .rule('js') .include .add('/packages') .end() .use('babel') .loader('babel-loader') .tap(options => { return options }) }, devServer: { port: 8091, hot: true, open: 'Google Chrome' } } module.exports = devConf
var utilLib = require('/lib/enonic/util'); var portalLib = require('/lib/xp/portal'); var authLib = require('/lib/xp/auth'); var connection = require('connection'); exports.getForms = function getAttachment(params) { var repoConn =connection.newConnection(); repoConn.refresh(); var queryResult = repoConn.query({ start: 0, query: "_parentPath = '" + getCurrentFolderPath(params.folder) + "' and key = '" + params.pageUrl + "'", }); if (queryResult.hits.length > 0) { var ids = queryResult.hits.map(function(n){ return n.id}); var results = utilLib.data.forceArray(repoConn.get(ids)); //log.info("-----inside query putForm----------------------------->" + JSON.stringify(results, null, 4)); var forms = {}; if(results.length > 0) forms = results.map(function(n){ return {id: n._id, form: n.form} }); //log.info("-----inside form query putForm----------------------------->" + JSON.stringify(forms, null, 4)); return forms; } return null; } exports.querySingleHit = function querySingleHit(params) { var repoConn = connection.newConnection(); var queryResult = repoConn.query({ start: 0, count: 1, query: "_parentPath = '" + getCurrentFolderPath(params.folder) + "' and key = '" + params.pageUrl + "'", }); if (queryResult.count > 0) { var id = queryResult.hits[0].id; var node = repoConn.get(id); return node; } //log.info("------------------------------------------------------>" + JSON.stringify(node, null, 4)); return null; } exports.put = function(params){ //log.info("-----inside query putForm----------------------------->" + JSON.stringify(params, null, 4)); var repo = connection.newConnection(); connection.checkUserFolder(params.folder); var result; if(params.form){ //log.info("-----inside query 2----------------------------->" + JSON.stringify(params, null, 4)); result = repo.create({ _parentPath: getCurrentFolderPath(params.folder), _permissions: connection.ROOT_PERMISSIONS, key: params.key, form: params.form, }); } } var getCurrentFolderPath = function (folder) { if(folder != null ) return '/' + folder + "/" + getCurrentUserKey(); return '/' + getCurrentUserKey(); } var getCurrentUserKey = function () { var user = authLib.getUser(); return user ? user.key : null; };
import React, { Component } from 'react'; import { Link } from 'react-router'; export default React.createClass({ render() { return ( <div className='footer'> <a href='https://www.facebook.com/ejersonb/' target='_blank'><img className='social-media facebook' src={require('./images/facebook.png')} /></a> <a href='https://www.linkedin.com/in/ejerson-balabas-209b19122/' target='_blank'><img className='social-media linkedin' src={require('./images/linkedin.png')} /></a> <a href='https://medium.com/@ejersonb' target='_blank'><img className='social-media medium' src={require('./images/medium.png')} /></a> <a href='https://github.com/ejerson' target='_blank'><img className='github' src={require('./images/github.png')} /></a> </div> ); } });
alert("欢迎访问!"); console.info("your are loding")
function doClick(o){ o.className="nav_current"; var j; var id; var e; for(var i=1;i<=4;i++){ //这里3 需要你修改 你多少条分类 就是多少 id ="nav"+i; j = document.getElementById(id); e = document.getElementById("sub"+i); if(id != o.id){ j.className="nav_link"; e.style.display = "none"; }else{ e.style.display = "block"; } } }
import classes from './CategoriesList.module.css'; import { CategoriesArray } from '../../../utils/static-data'; const CategoryItem = (props) => { const isCurrent = props.currentCategory === props.category; console.log(isCurrent, props.category); return ( <span className={`${classes.CategoryItem} ${isCurrent ? classes.Active : ''}`}> {props.category} ({props.categoryItems}) </span> ); }; const CategoriesList = () => { return ( <div className={classes.CategoriesList}> {CategoriesArray.map((category) => ( <CategoryItem category={category.category} categoryItems={category.items} key={category.category} currentCategory="electronics" /> ))} </div> ); }; export default CategoriesList;
import { Schema, string, required, validate } from 'sapin' export const loginSchema = new Schema({ 'username': string(required), 'password': string(required) }) export default (loginForm) => { const errors = validate(loginForm, loginSchema) return errors }
"use strict"; // Gulp dev. var gulp = require('gulp'); var watch = require('gulp-watch'); var config = require('./gulp_tasks/config'); var plugins = require('gulp-load-plugins')(); var runSequence = require('run-sequence'); var exec = require('child_process').exec; function tasks(task, options) { return require('./gulp_tasks/' + task)(gulp, plugins, options); } gulp.task('generate:png', function(done){ console.log('Generate png images for both platforms (android / ios) out of svg files in the resources/private/icons/svg directory. This could take a while. Please be patient.') tasks('png_generator')(done); }); gulp.task('generate:launch.images', function(done){ console.log('Generate launch images and App Icons. This can take a while. please be patient.'); tasks('launch_image_generator')(function(errors){ if(errors){ done(errors); return; } console.log('Generated Launch Images...'); tasks('storyboard_generator')(function(errors){ if(errors){ done(errors); return; } console.log('Generated Launch Story Boards ...'); tasks('launch_icon_generator')(function(errors){ if(errors){ done(errors); return; } console.log('Generated Launch Icons ...'); done(); }); }); }); });
const express = require("express"); const handlebars = require("express-handlebars"); const formidable = require("formidable"); const fs = require("fs"); const credentials = require("./credentials.js"); const app = express(); const dataDir = __dirname +"/data"; const photoDir = dataDir + "/photo"; const mv = require("mv"); const user = require("./models/user.js"); const dburl = credentials.dbconnection; const mongoose = require("mongoose"); const opts = { server: { socketOptions: {keepAlive: 1} } }; mongoose.connect(dburl, opts); if(!fs.existsSync(dataDir)) fs.mkdirSync(dataDir); if(!fs.existsSync(photoDir)) fs.mkdirSync(photoDir); app.set("port", process.env.PORT || 3000); app.engine("handlebars", handlebars({ defaultLayout: "main", helpers: { section: function (name, options) { if (!this._sections) this._sections = {}; this._sections[name] = options.fn(this); return null; }}})); app.set("view engine", "handlebars"); //middleware app.use(express.static(__dirname + "/public")); //home page app.get("/", (req, res) => { const now = new Date(); res.render("home", { year: now.getFullYear(), month: now.getMonth() }); }); //Upload form handling app.post("/upload/:year/:month", (req, res) => { const form = new formidable.IncomingForm(); form.parse(req, (err, fields, files) => { if(err) return res.redirect(303, "/error"); new user({name: fields.name, email: fields.email}).save(); const photo = files.photo; const dir = photoDir + "/" + Date.now(); const path = dir + "/" + "uploadedphoto.jpg"; fs.mkdirSync(dir); mv(photo.path.toString(), path.toString(), (err) =>{ if(err) console.log("Error - moving resource from tmp to data directory"); }); res.redirect(303, "/upload-succeeded"); }); }); app.get("/upload-succeeded", (req, res) => { res.render("upload-succeeded"); }); app.get("/users", (req, res) => { user.find({}, (err, users) => { const context = { users: users.map((user) => { return{name: user.name, email: user.email}; }) }; res.render("users", context); }); }); //error page app.get("/error", (req, res) => { res.render("500"); }); // 404 page app.use((req, res) => { res.status(404); res.render("404"); }); // 500 page app.use((err, req, res, next) => { console.error(err.stack); res.status(500); res.render("500"); }); app.listen(app.get("port"), () => { console.log("Server started on http://localhost:" + app.get("port")); });
var router = require("express").Router(), comment = require("./../business/commentBusiness"); router.post("/", function (req, res, next){ comment.create(req, res); }); module.exports = router;
import React from 'react'; function Person({person}) { return ( <div> <h1>Hi I am {person.name} and I am {person.age} years old.</h1> </div> ); } export default Person;
//Last updated November 2010 by Simon Sarris //www.simonsarris.com //sarris@acm.org //Free to use and distribute at will //So long as you are nice to people, etc //This is a self-executing function that I added only to stop this //new script from interfering with the old one. It's a good idea in general, but not //something I wanted to go over during this tutorial (function(window) { // holds all our boxes var boxes2 = []; // New, holds the 8 tiny boxes that will be our selection handles // the selection handles will be in this order: // 0 1 2 // 3 4 // 5 6 7 var selectionHandles = []; // Hold canvas information var canvas; var ctx; var WIDTH; var HEIGHT; var INTERVAL = 20; // how often, in milliseconds, we check to see if a redraw is needed var isDrag = false; var isResizeDrag = false; var expectResize = -1; // New, will save the # of the selection handle if the mouse is over one. var mx, my; // mouse coordinates // when set to true, the canvas will redraw everything // invalidate() just sets this to false right now // we want to call invalidate() whenever we make a change var canvasValid = false; // The node (if any) being selected. // If in the future we want to select multiple objects, this will get turned into an array var mySel = null; // The selection color and width. Right now we have a red selection with a small width var mySelColor = '#CC0000'; var mySelWidth = 2; var mySelBoxColor = 'darkred'; // New for selection boxes var mySelBoxSize = 6; // we use a fake canvas to draw individual shapes for selection testing var ghostcanvas; var gctx; // fake canvas context // since we can drag from anywhere in a node // instead of just its x/y corner, we need to save // the offset of the mouse when we start dragging. var offsetx, offsety; // Padding and border style widths for mouse offsets var stylePaddingLeft, stylePaddingTop, styleBorderLeft, styleBorderTop; var permissionForm = new function () { var me = this; var mouseX, mouseY; var userNodes, currentlyDraggedNode; me.init = function () { if (EventHelpers.hasPageLoadHappened(arguments)) { return; } userNodes = cssQuery('[draggable=true]'); for (var i=0; i<userNodes.length; i++) { EventHelpers.addEvent(userNodes[i], 'dragstart', userDragStartEvent); EventHelpers.addEvent(userNodes[i], 'dragend', userDragEndEvent); } userListNodes = cssQuery('#userList'); for (var i=0; i<userListNodes.length; i++) { var userListNode = userListNodes[i]; EventHelpers.addEvent(userListNode, 'dragover', userDragOverListEvent); EventHelpers.addEvent(userListNode, 'dragleave', userDragLeaveListEvent); } userListNodes = cssQuery('#restrictedUsers'); for (var i=0; i<userListNodes.length; i++) { var userListNode = userListNodes[i]; EventHelpers.addEvent(userListNode, 'drop', userDropListEvent); } userListNodes = cssQuery('#powerUsers'); for (var i=0; i<userListNodes.length; i++) { var userListNode = userListNodes[i]; EventHelpers.addEvent(userListNode, 'drop', userDustbinEvent); } }; function userDragStartEvent(e) { e.dataTransfer.effectAllowed="copy"; e.dataTransfer.setData('Text', "draggedUser: "+ this.innerHTML); currentlyDraggedNode = this; currentlyDraggedNode.className = 'draggedUser'; } function imageDragStartEvent(e) { e.dataTransfer.setData('Text', "draggedImage: " + this.innerHTML); currentlyDraggedNode = this; currentlyDraggedNode.className = 'draggedImage'; } function userDragEndEvent(e) { currentlyDraggedNode.className = ''; } function userDragLeaveListEvent(e){ //setHelpVisibility(this, false); } function userDropListEvent(e) { /* * To ensure that what we are dropping here is from this page */ e.dataTransfer.dropEffect = "copy"; var data = e.dataTransfer.getData('Text'); //alert(data); if(data.length > 30){ alert ("Google Image cannot be dragged, please download as local file!"); } else{ if (data.indexOf("draggedUser: ") != 0 || currentlyDraggedNode.className != "draggedUser") { //alert("Only users within this page are draggable."); } else{ //currentlyDraggedNode.parentNode.appendChild(currentlyDraggedNode.prototype); // new_node = currentlyDraggedNode.cloneNode(true); // EventHelpers.addEvent(new_node, 'dragstart', imageDragStartEvent); // EventHelpers.addEvent(new_node, 'dragend', userDragEndEvent); // new_node.className = ''; //alert(currentlyDraggedNode.src); // this.appendChild(new_node); var img3 = new Image(); img3.src = currentlyDraggedNode.src; addRect(100, 70, 60, 65,img3); //setHelpVisibility(this, false); userDragEndEvent(e); } } } function userDustbinEvent(e) { /* * To ensure that what we are dropping here is from this page */ var data = e.dataTransfer.getData('Text'); if (data.indexOf("draggedImage: ") != 0) { alert("Only images within this page are draggable."); } else{ currentlyDraggedNode.parentNode.removeChild(currentlyDraggedNode); //setHelpVisibility(this, false); userDragEndEvent(e); } } function userDragOverListEvent(e) { e.dataTransfer.dropEffect = "copy"; //setHelpVisibility(this, true); EventHelpers.preventDefault(e); } function setHelpVisibility(node, isVisible) { var helpNodeId = node.id + "Help"; var helpNode = document.getElementById(helpNodeId); if (isVisible) { helpNode.className = 'showHelp'; } else { helpNode.className = ''; } } } // Box object to hold data function Box2() { this.x = 0; this.y = 0; this.w = 1; // default width and height? this.h = 1; this.fill = '#444444'; this.img; } // New methods on the Box class Box2.prototype = { // we used to have a solo draw function // but now each box is responsible for its own drawing // mainDraw() will call this with the normal canvas // myDown will call this with the ghost canvas with 'black' draw: function(context, optionalColor) { // if (context === gctx) { // context.fillStyle = 'black'; // always want black for the ghost canvas // } else { // context.fillStyle = this.fill; // } context.drawImage(this.img, this.x, this.y, this.w, this.h); // // We can skip the drawing of elements that have moved off the screen: // if (this.x > WIDTH || this.y > HEIGHT) return; // if (this.x + this.w < 0 || this.y + this.h < 0) return; // context.fillRect(this.x,this.y,this.w,this.h); // draw selection // this is a stroke along the box and also 8 new selection handles if (mySel === this) { context.strokeStyle = mySelColor; context.lineWidth = mySelWidth; context.strokeRect(this.x,this.y,this.w,this.h); // draw the boxes var half = mySelBoxSize / 2; // 0 1 2 // 3 4 // 5 6 7 // top left, middle, right selectionHandles[0].x = this.x-half; selectionHandles[0].y = this.y-half; selectionHandles[1].x = this.x+this.w/2-half; selectionHandles[1].y = this.y-half; selectionHandles[2].x = this.x+this.w-half; selectionHandles[2].y = this.y-half; //middle left selectionHandles[3].x = this.x-half; selectionHandles[3].y = this.y+this.h/2-half; //middle right selectionHandles[4].x = this.x+this.w-half; selectionHandles[4].y = this.y+this.h/2-half; //bottom left, middle, right selectionHandles[6].x = this.x+this.w/2-half; selectionHandles[6].y = this.y+this.h-half; selectionHandles[5].x = this.x-half; selectionHandles[5].y = this.y+this.h-half; selectionHandles[7].x = this.x+this.w-half; selectionHandles[7].y = this.y+this.h-half; context.fillStyle = mySelBoxColor; for (var i = 0; i < 8; i ++) { var cur = selectionHandles[i]; context.fillRect(cur.x, cur.y, mySelBoxSize, mySelBoxSize); } } } // end draw } // Initialize a new Box, add it, and invalidate the canvas function addRect(x, y, w, h, img) { var rect = new Box2; rect.x = x; rect.y = y; rect.w = w rect.h = h; rect.img = img; //rect.fill = fill; boxes2.push(rect); invalidate(); } // initialize our canvas, add a ghost canvas, set draw loop // then add everything we want to intially exist on the canvas function init2() { canvas = document.getElementById('restrictedUsers'); HEIGHT = canvas.height; WIDTH = canvas.width; ctx = canvas.getContext('2d'); ctx.fillText("Drop an image onto the canvas", 100, 150); ghostcanvas = document.createElement('canvas'); ghostcanvas.height = HEIGHT; ghostcanvas.width = WIDTH; gctx = ghostcanvas.getContext('2d'); mouseDown = false; brushColor = "rgb(0, 0, 0)"; //fixes a problem where double clicking causes text to get selected on the canvas canvas.onselectstart = function () { return false; } // fixes mouse co-ordinate problems when there's a border or padding // see getMouse for more detail if (document.defaultView && document.defaultView.getComputedStyle) { stylePaddingLeft = parseInt(document.defaultView.getComputedStyle(canvas, null)['paddingLeft'], 10) || 0; stylePaddingTop = parseInt(document.defaultView.getComputedStyle(canvas, null)['paddingTop'], 10) || 0; styleBorderLeft = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderLeftWidth'], 10) || 0; styleBorderTop = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderTopWidth'], 10) || 0; } // make mainDraw() fire every INTERVAL milliseconds setInterval(mainDraw, INTERVAL); // set our events. Up and down are for dragging, // double click is for making new boxes canvas.onmousedown = myDown; canvas.onmouseup = myUp; canvas.ondblclick = myDblClick; canvas.onmousemove = myMove; // To enable drag and drop var img0 = document.createElement("img"); // Image for loading img0.addEventListener("load", function () { //clearCanvas(); newImg = new Image(); newImg.src = img0.src; addRect(0, 0, 60, 65,newImg); }, false); canvas.addEventListener("dragover", function (evt) { evt.preventDefault(); }, false); // Handle dropped image file - only Firefox and Google Chrome canvas.addEventListener("drop", function (evt) { var files = evt.dataTransfer.files; if (files.length > 0) { var file = files[0]; if (typeof FileReader !== "undefined" && file.type.indexOf("image") != -1) { var reader = new FileReader(); // Note: addEventListener doesn't work in Google Chrome for this event reader.onload = function (evt) { img0.src = evt.target.result; }; reader.readAsDataURL(file); } } evt.preventDefault(); }, false); // set up the selection handle boxes for (var i = 0; i < 8; i ++) { var rect = new Box2; selectionHandles.push(rect); } // // add custom initialization here: // img = new Image(); // img.src = "http://localhost:8080/RockTee/images/pink%20skull.png"; // addRect(60, 70, 60, 65,img); DragDropHelpers.fixVisualCues=true; permissionForm.init(); //EventHelpers.addPageLoadEvent('permissionForm.init'); } // wipes the canvas context function clear(c) { c.clearRect(0, 0, WIDTH, HEIGHT); } // Main draw loop. // While draw is called as often as the INTERVAL variable demands, // It only ever does something if the canvas gets invalidated by our code function mainDraw() { if (canvasValid == false) { clear(ctx); // Add stuff you want drawn in the background all the time here // draw all boxes var l = boxes2.length; for (var i = 0; i < l; i++) { boxes2[i].draw(ctx); // we used to call drawshape, but now each box draws itself } // Add stuff you want drawn on top all the time here canvasValid = true; } } // function saveimage(){ //// var cs = new CanvasSaver('http://localhost:8080/RockTee/scripts/saveme.php'); // var cs = new CanvasSaver('http://greenethumb.com/canvas/lib/saveme.php'); // alert("hh"); // cs.generateButton('save an image!', canvas, 'myimage'); // } // Happens when the mouse is moving inside the canvas function myMove(e){ if(document.getElementById('image_mode').checked){ if (isDrag) { getMouse(e); mySel.x = mx - offsetx; mySel.y = my - offsety; // something is changing position so we better invalidate the canvas! invalidate(); } else if (isResizeDrag) { // time ro resize! var oldx = mySel.x; var oldy = mySel.y; // 0 1 2 // 3 4 // 5 6 7 switch (expectResize) { case 0: mySel.x = mx; mySel.y = my; mySel.w += oldx - mx; mySel.h += oldy - my; break; case 1: mySel.y = my; mySel.h += oldy - my; break; case 2: mySel.y = my; mySel.w = mx - oldx; mySel.h += oldy - my; break; case 3: mySel.x = mx; mySel.w += oldx - mx; break; case 4: mySel.w = mx - oldx; break; case 5: mySel.x = mx; mySel.w += oldx - mx; mySel.h = my - oldy; break; case 6: mySel.h = my - oldy; break; case 7: mySel.w = mx - oldx; mySel.h = my - oldy; break; } invalidate(); } getMouse(e); // if there's a selection see if we grabbed one of the selection handles if (mySel !== null && !isResizeDrag) { for (var i = 0; i < 8; i++) { // 0 1 2 // 3 4 // 5 6 7 var cur = selectionHandles[i]; // we dont need to use the ghost context because // selection handles will always be rectangles if (mx >= cur.x && mx <= cur.x + mySelBoxSize && my >= cur.y && my <= cur.y + mySelBoxSize) { // we found one! expectResize = i; invalidate(); switch (i) { case 0: this.style.cursor='nw-resize'; break; case 1: this.style.cursor='n-resize'; break; case 2: this.style.cursor='ne-resize'; break; case 3: this.style.cursor='w-resize'; break; case 4: this.style.cursor='e-resize'; break; case 5: this.style.cursor='sw-resize'; break; case 6: this.style.cursor='s-resize'; break; case 7: this.style.cursor='se-resize'; break; } return; } } // not over a selection box, return to normal isResizeDrag = false; expectResize = -1; this.style.cursor='auto'; } } } // Happens when the mouse is clicked in the canvas function myDown(e){ if(document.getElementById('image_mode').checked){ getMouse(e); //we are over a selection box if (expectResize !== -1) { isResizeDrag = true; return; } //clear(gctx); var l = boxes2.length; for (var i = l-1; i >= 0; i--) { // draw shape onto ghost context boxes2[i].draw(gctx, 'black'); // get image data at the mouse x,y pixel var imageData = gctx.getImageData(mx, my, 1, 1); var index = (mx + my * imageData.width) * 4; // if the mouse pixel exists, select and break if (imageData.data[3] > 0) { //alert(imageData.data[3]); mySel = boxes2[i]; offsetx = mx - mySel.x; offsety = my - mySel.y; mySel.x = mx - offsetx; mySel.y = my - offsety; isDrag = true; invalidate(); //clear(gctx); return; } } // havent returned means we have selected nothing mySel = null; // clear the ghost canvas for next time clear(gctx); // invalidate because we might need the selection border to disappear invalidate(); } } function myUp(){ if(document.getElementById('image_mode').checked){ isDrag = false; isResizeDrag = false; expectResize = -1; } } // removes a node function myDblClick(e) { getMouse(e); //clear(gctx); var l = boxes2.length; for (var i = l-1; i >= 0; i--) { // get image data at the mouse x,y pixel var imageData = gctx.getImageData(mx, my, 1, 1); // if the mouse pixel exists, select and break if (imageData.data[3] > 0) { var mySel = boxes2[i]; if (mx >= mySel.x && mx <= mySel.x + mySel.w && my >= mySel.y && my <= mySel.y + mySel.h) { // alert(i); ctx.clearRect(mySel.x,mySel.y,mySel.w,mySel.h); boxes2.splice(i, 1); invalidate(); clear(gctx); return; } } } // havent returned means we have selected nothing mySel = null; // clear the ghost canvas for next time //clear(gctx); // invalidate because we might need the selection border to disappear invalidate(); // canvasValid = false; } function invalidate() { canvasValid = false; } // Sets mx,my to the mouse position relative to the canvas // unfortunately this can be tricky, we have to worry about padding and borders function getMouse(e) { var element = canvas, offsetX = 0, offsetY = 0; if (element.offsetParent) { do { offsetX += element.offsetLeft; offsetY += element.offsetTop; } while ((element = element.offsetParent)); } // Add padding and border style widths to offset offsetX += stylePaddingLeft; offsetY += stylePaddingTop; offsetX += styleBorderLeft; offsetY += styleBorderTop; mx = e.pageX - offsetX; my = e.pageY - offsetY } // If you dont want to use <body onLoad='init()'> // You could uncomment this init() reference and place the script reference inside the body tag // init(); window.init2 = init2; })(window);
import createSelector from '../create-selector' import Inventory from '../../../models/ecommerse/inventory' import columns from './columns' import formItems from './form-items' const defaultSort = [ { 'ignoreCase': false, 'property': 'ctime', 'type': 'DSC' } ] const defaultCriterias = [ { filterType: 'EQ', property: 'deleted', value: false }, { filterType: 'EQ', property: 'onSale', value: true } ] const selector = createSelector({ loadPage: async(pageNo, pageSize, filter, sort) => { return await Inventory.pageNoAuth(pageNo, pageSize, filter, sort) }, selection: true, domain: Inventory, formItems, defaultCriterias, defaultSort, formProps: { labelWidth: 45, expandRow: 1 }, columns, defaultPageSize: 10, size: 'small' }) export default selector
import { createRouter, createWebHistory } from 'vue-router'; import Welcome from '@/pages/Welcome.vue'; import singUpForm from '@/components/sign/singUpForm.vue'; const routes = [ { path: '/', name: 'HomePage', component: Welcome, }, { path: '/signup', name: 'signUp', component: singUpForm, }, ]; const router = createRouter({ history: createWebHistory(), routes, }); export default router;
import { css } from 'styled-components'; import { COLORS, OTHER, SPACE_SIZE } from '../../utils/styleConstants'; const TooltipStyles = css` position: relative; display: inline-block; width: 19px; height: 19px; background: ${COLORS.CHARTS.PRIMARY}; color: #fff; font: 700 14px/19px var(--ff); border-radius: 100%; text-align: center; &:hover { background: ${COLORS.PRIMARY}; } & > div { z-index: 99999999; position: absolute; display: none; top: 100%; left: 50%; max-width: 400px; margin-top: ${SPACE_SIZE.S}; padding: ${SPACE_SIZE.XS} ${SPACE_SIZE.S}; background: #fff; color: ${COLORS.TEXT.PRIMARY}; font: 13px/15px var(--ff); text-align: left; transform: translate(-50%, 0); ${OTHER.BORDER_RADIUS} ${OTHER.BOX_SHADOW} &:before { content: ''; position: absolute; top: 0; left: 50%; width: 15px; height: 15px; background: #fff; transform: translate(-50%, -50%) rotate(-45deg); } & > div { max-width: 100%; width: max-content; hyphens: true; } } &:hover > div { display: inline-block; } `; export default TooltipStyles;
import connectDb from "../../../../utils/connectDb"; import Post from "../../../../models/Post"; import User from "../../../../models/User"; connectDb(); const handler = async (req, res) => { switch (req.method) { case "PATCH": await handlePatchRequest(req, res); break; default: res.status(405).send(`Method ${req.method} not allowed`); break; } }; // @route PATCH api/posts/hidepost/[id] // @desc toggle hide / show post // @res // @access Protected async function handlePatchRequest(req, res) { const { query: { id }, } = req; const { isInappropriate, isInsensitive, isScam, message } = req.body; const inappropriateInc = isInappropriate ? 1 : 0; const insensitiveInc = isInsensitive ? 1 : 0; const scamInc = isScam ? 1 : 0; try { const post = await Post.findByIdAndUpdate(id, { $inc: { "reportLog.inappropriate": inappropriateInc, "reportLog.insensitive": insensitiveInc, "reportLog.scam": scamInc, }, $push: { "reportLog.messages": message }, }); if (!post) res.status(404).send("Post Not Found"); res.status(200).send("Report Filed"); } catch (err) { res.status(500).send("Server Error"); } } export default handler;
/** * @fileoverview * @author 伯才<xiaoqi.huxq@alibaba-inc.com> * @plugin scrollbar XScroll滚动条插件 **/ ; KISSY.add(function(S, Node, Base, Anim,Util) { var $ = S.all; //最短滚动条高度 var MIN_SCROLLBAR_SIZE = 60; //滚动条被卷去剩下的最小高度 var BAR_MIN_SIZE = 5; //transform var transform = Util.prefixStyle("transform"); var transformStr = Util.vendor ? ["-",Util.vendor,"-transform"].join("") : "transform"; //transition webkitTransition MozTransition OTransition msTtransition var transition = Util.prefixStyle("transition"); var borderRadius = Util.prefixStyle("borderRadius"); var events = [ "scale", "afterContainerHeightChange", "afterContainerWidthChange", "afterWidthChange", "afterHeightChange", "refresh" ]; var ScrollBar = Base.extend({ pluginId:"xscroll/plugin/scrollbar", pluginInitializer:function(xscroll){ var self = this; self.userConfig = S.merge({ type:"y" }, self.userConfig); self.xscroll = xscroll; self.xscroll.on("afterRender", function() { self.set("type",self.userConfig.type); self.isY = self.get("type") == "y" ? true : false; self.set("containerSize",self.isY ? self.xscroll.get("containerHeight"):self.xscroll.get("containerWidth")) self.set("indicateSize", self.isY ? self.xscroll.get("height"):self.xscroll.get("width")); self.set("offset",self.xscroll.getOffset()); self.render(); self._bindEvt(); }) }, pluginDestructor:function(){ var self = this; self.$scrollbar && self.$scrollbar.remove(); self.xscroll.detach("scaleAnimate",self._update,self); self.xscroll.detach("scrollEnd",self._update,self); self.xscroll.detach("scrollAnimate",self._update,self); for(var i in events){ self.xscroll.detach(events[i],self._update,self) } delete self; }, render: function() { var self = this; if (self.__isRender) return; self.__isRender = true; var xscroll = self.xscroll; var tpl_scrollbar = "<div></div>"; var css = self.isY ? { width: "3px", position: "absolute", bottom: "5px", top: "5px", right: "2px", zIndex: 999, overflow: "hidden", "-webkit-border-radius": "2px", "-moz-border-radius": "2px", "-o-border-radius":"2px" }:{ height: "3px", position: "absolute", left: "5px", right: "5px", bottom: "2px", zIndex: 999, overflow: "hidden", "-webkit-border-radius": "2px", "-moz-border-radius": "2px", "-o-border-radius":"2px" }; self.$scrollbar = $(tpl_scrollbar).css(css).prependTo(xscroll.$renderTo); var tpl_indicate = '<div></div>'; var style = self.isY ? {width:"100%"}:{height:"100%"}; self.$indicate = $(tpl_indicate).css({ "position": "absolute", background: "rgba(0,0,0,0.3)", "-webkit-border-radius": "1.5px", "-moz-border-radius": "1.5px", "-o-border-radius":"1.5px" }).prependTo(self.$scrollbar).css(style); self._update(); }, _update: function(offset,duration,easing) { var self = this; var offset = offset || self.xscroll.getOffset(); var barInfo = self.computeScrollBar(offset); self.isY ? self.$indicate.height(barInfo.size):self.$indicate.width(barInfo.size); if(duration && easing){ self.scrollTo(barInfo.offset,duration,easing); }else{ self.moveTo(barInfo.offset); } }, //计算边界碰撞时的弹性 computeScrollBar: function(offset) { var self = this; var type = self.isY ? "y" : "x"; var offset = offset && -offset[type]; self.set("containerSize",self.isY ? self.xscroll.get("containerHeight"):self.xscroll.get("containerWidth")) self.set("indicateSize", self.isY ? self.xscroll.get("height"):self.xscroll.get("width")); //滚动条容器高度 var indicateSize = self.get("indicateSize"); var containerSize = self.get("containerSize"); var ratio = offset / containerSize; var barOffset = indicateSize * ratio; var barSize = indicateSize * indicateSize / containerSize; var _barOffset = barOffset * (indicateSize - MIN_SCROLLBAR_SIZE + barSize) / indicateSize if (barSize < MIN_SCROLLBAR_SIZE) { barSize = MIN_SCROLLBAR_SIZE; barOffset = _barOffset; } //顶部回弹 if (barOffset < 0) { barOffset = Math.abs(offset) * barSize/ MIN_SCROLLBAR_SIZE > barSize - BAR_MIN_SIZE ? BAR_MIN_SIZE - barSize : offset * barSize / MIN_SCROLLBAR_SIZE; } else if (barOffset + barSize > indicateSize) { //底部回弹 var _offset = offset - containerSize + indicateSize; if (_offset * barSize / MIN_SCROLLBAR_SIZE > barSize - BAR_MIN_SIZE) { barOffset = indicateSize - BAR_MIN_SIZE; } else { barOffset = indicateSize - barSize + _offset * barSize / MIN_SCROLLBAR_SIZE; } } self.set("barOffset", barOffset) var result = {size: barSize}; var _offset = {}; _offset[type] = barOffset; result.offset = _offset; return result; }, scrollTo: function(offset, duration, easing) { var self = this; self.isY ? self.$indicate[0].style[transform] = "translateY(" + offset.y + "px) translateZ(0)" : self.$indicate[0].style[transform] = "translateX(" + offset.x + "px) translateZ(0)" self.$indicate[0].style[transition] = ["all ",duration, "s ", easing, " 0"].join(""); }, moveTo: function(offset) { var self = this; self.show(); self.isY ? self.$indicate[0].style[transform] = "translateY(" + offset.y + "px) translateZ(0)" : self.$indicate[0].style[transform] = "translateX(" + offset.x + "px) translateZ(0)" self.$indicate[0].style[transition] = ""; }, _bindEvt: function() { var self = this; if (self.__isEvtBind) return; self.__isEvtBind = true; var type = self.isY ? "y" : "x"; self.xscroll.on("scaleAnimate",function(e){self._update(e.offset);}) self.xscroll.on("pan",function(e){self._update(e.offset);}) self.xscroll.on("scrollEnd",function(e){ if(e.zoomType.indexOf(type) > -1){ self._update(e.offset); } }) self.xscroll.on("scrollAnimate",function(e){ if(e.zoomType != type) return; self._update(e.offset,e.duration,e.easing); }) for(var i in events){ self.xscroll.on(events[i],function(e){self._update();}) } }, reset:function(){ var self = this; self.set("offset",{x:0,y:0}); self._update(); }, hide: function() { var self = this; self.$scrollbar.css({opacity: 0}); self.$scrollbar[0].style[transition] = "opacity 0.3s ease-out" }, show: function() { var self = this; self.$scrollbar.css({opacity:1}); } }, { ATTRS: { "offsetTop": { }, "containerSize": { value: 0 }, "indicateSize": { value: 0 }, "barSize": { value: 0 }, "barOffset": { value: 0 } } }); return ScrollBar; }, { requires: ['node', 'base', 'anim','../util'] })
function randomNumber(min, max) { return Math.random() * (max - min) + min; } function arena(id, x, y, p1, p2) { this.class = 'Object Ability Non Movable' this.isdead = false; this.id = id; this.num = 5 this.radius = 300 this.insradius = 280 this.angleupd = false; this.isbiome = false; this.specType2 = 0 this.is1v1 = false this.specType = 0; this.secondaryType = 68 this.type = 14; //object type (animal. hill bush) this.biome = 0; this.isloaded = false; this.sendhp = false this.spawned = false this.p1bites = 0 this.p2bites = 0 this.state = 0 this.movable = false this.speed = 10 this.killerid = 0 this.isinvisible = false this.timer = 1 //PLAYER CHECK this.p1id = p1.id this.p2id = p2.id //PLAYER CHECK //FIRST SEND. this.p1 = p1 this.p2 = p2 //FIRST SEND. this.winner = 0 this.x = x this.y = y this.hurt = false this.isinquadtree = false this.spawnedtime = Date.now(); var a = setInterval(() => { if (!this.isdead) { if (this.state == 0) { if (this.timer == 0) { this.state = 1 } } if (this.state == 0) { this.timer-- } else if (this.state == 1) { this.timer++ } } else { clearInterval(a) } }, 1000); this.veloX = 0 this.veloY = 0 }; arena.prototype = { }; arena.prototype.customdatawriteoncreate = function (buf, off) { } arena.prototype.customdatawriteonupdate = function (buf, off) { } module.exports = arena;
const cfg = {}; const tools = require('./lib/tools'); cfg.host = 'zafchat.herokuapp.com'; cfg.port = process.env.PORT || 3000; cfg.heroku = true; cfg.mode = 'production'; cfg.morganMode = 'combined'; cfg.defaultLayout = 'main'; cfg.relookupDelay = 1000; cfg.onlineBroadcastDelay = 1000; cfg.messageMaxLen = 4096; cfg.paths = {}; cfg.paths.static = './public'; cfg.paths.sessionStore = './db/sessionStore.db'; cfg.session = {}; cfg.session.secret = tools.randomStringSync(32); cfg.session.resave = true; cfg.session.saveUninitialized = true; cfg.session.cookie = { path: '/', maxAge: 24 * 3600 * 1000, }; cfg.session.unset = 'destroy'; cfg.https = {}; cfg.https.enabled = false; cfg.db = {}; cfg.db.inMemoryOnly = true; cfg.modes = {}; cfg.modes.calm = 'calm'; cfg.modes.talking = 'talking'; cfg.modes.stop = 'stop'; module.exports = cfg;
import Album from "./components/Album"; import Dashboard from "./components/Dashboard"; import PersistentDrawer from "./components/PersistentDrawer/PersistentDrawer"; function App() { return ( <div> {/* <Dashboard/> */} {/* <PersistentDrawer/> */} <Album/> </div> ); } export default App;
var EventUtil = { addHandler:function(element,type,handler){ if(element.addEventListener){ element.addEventListener(type,handler,false); }else if (element.attachEvent){ element.attachEvent("on"+type,handler); }else{ element["on"+type] = handler; } }, removeHandler:function(element,type,handler){ if (element.removeEventListener) { element.removeEventListener(element,handler,false); }else if (element.detachEvent) { element.detachEvent("on"+type,handler); }else{ element["on"+type] = null; } } }; function handleTouchEvent(event){ if (event.touches.type == 1) { var output = document.getElementById("output"); switch(event.type){ case "touchstart": output.innerHTML = "touch start:"+event.touch[0].clientX+event.touch[0].clientY; break; } } } EventUtil.addHandler(document,"touchstart",handleTouchEvent);
export function tailGenerator(style, opts) { switch ( style ) { case '-': case 'STRAIGHT': return straightTail; case '~': case 'CURVED': return curvedTail; case 'MESSAGE': return (d) => messageTail(d, opts); case 'LINE': return lineTail; default: throw `Unknown link style "${style}"`; } } const _180OVER_PI = 180 / Math.PI; function lineTail(d) { const sl = d.source.layout; const tl = d.target.layout d.pathMeta = { start: {x: sl.pos.x, y: sl.pos.y}, end: {x: tl.pos.x, y: tl.pos.y}, dir: 'E', } const start = d.pathMeta.start; const end = d.pathMeta.end; const angle = Math.atan2(end.y - start.y, end.x - start.x)*_180OVER_PI; const length = Math.sqrt((end.x - start.x)*(end.x - start.x) + (end.y - start.y)*(end.y - start.y)); d.pathMeta.length = length; d.pathMeta.transform = `translate(${start.x} ${start.y}) rotate(${angle})`; d.textMeta = { pos: {x: start.x + length/2 , y: start.y}, baseLine: 'text-after-edge', textAnchor: 'start' } return `M${0} ${0}L${length} ${0}`; } function messageTail(d, opts) { let yOffset = opts.yStart+ opts.ySeparation * d.index let sl = d.source.layout; let tl = d.target.layout if (d.source == d.target) { d.pathMeta = { start: {x: sl.pos.x, y: yOffset - opts.ySeparation}, end: {x: sl.pos.x, y: yOffset}, dir: 'W' } let start = d.pathMeta.start; d.textMeta = { pos: {x: start.x + opts.ySeparation*0.8, y: start.y + opts.ySeparation/2}, baseLine: 'text-after-edge', textAnchor: 'start' } return `M${start.x} ${start.y} C ${start.x + opts.ySeparation} ${start.y} ${start.x + opts.ySeparation} ${start.y + opts.ySeparation} ${start.x} ${start.y + opts.ySeparation}` } else { d.pathMeta = { start: {x: sl.pos.x, y: yOffset}, end: {x: tl.pos.x, y: yOffset}, dir: tl.pos.x > sl.pos.x ? 'E': 'W' } d.textMeta = { pos: {x: d.pathMeta.start.x + (d.pathMeta.end.x - d.pathMeta.start.x) / 2, y: yOffset - 5 }, baseLine: 'text-after-edge', textAnchor: 'middle' } return `M${d.source.layout.pos.x} ${yOffset} H ${d.target.layout.pos.x}`; } } function straightTail(d) { const [pathMeta, script] = tail(d, true); d.pathMeta = pathMeta; return script; } function curvedTail(d) { const [pathMeta, script] = tail(d, false); d.pathMeta = pathMeta; return script; } function tail(d, isStraight) { let sl = d.source.layout; let tl = d.target.layout; let dir = d.source.id == d.target.id ? 'SELF' : getApparentDir(sl, tl); let start = {x: 0, y:0}; let end = {x: 0, y:0}; let middle = 0; let script = ''; switch (true) { case ['NNE', 'SSE', 'SSW', 'NNW'].indexOf(dir) >= 0: start.x = sl.pos.x + sl.bbw/2; start.y = sl.pos.y; end.x = tl.pos.x; end.y = tl.pos.y + tl.bbh/2; if (['NNW', 'SSW'].indexOf(dir) >= 0) { start.x = sl.pos.x - sl.bbw/2; } if (['SSE', 'SSW'].indexOf(dir) >= 0) { end.y = tl.pos.y - tl.bbh/2; } if (isStraight) { script = `M${start.x} ${start.y} H${end.x} V${end.y}`; } else { script = `M${start.x} ${start.y} Q${end.x} ${start.y} ${end.x} ${end.y}`; } break; case (['ENE', 'ESE', 'WNW', 'WSW'].indexOf(dir) >= 0): start.x = sl.pos.x; start.y = sl.pos.y - sl.bbh/2; end.x = tl.pos.x - tl.bbw/2; end.y = tl.pos.y; if (['ESE', 'WSW'].indexOf(dir) >= 0) { start.y = sl.pos.y + sl.bbh/2; } if (['WNW', 'WSW'].indexOf(dir) >= 0) { end.x = tl.pos.x + tl.bbw/2; } if (isStraight) { script = `M${start.x} ${start.y}V${end.y}H${end.x}`; } else { script = `M${start.x} ${start.y}Q${start.x} ${end.y} ${end.x} ${end.y}`; } break; case ['E', 'W'].indexOf(dir) >= 0: start.x = sl.pos.x + sl.bbw/2; start.y = sl.pos.y; end.x = tl.pos.x - tl.bbw/2; end.y = tl.pos.y; if (dir == 'W') { start.x = sl.pos.x - sl.bbw/2; end.x = tl.pos.x + tl.bbw/2; } middle = start.x + (end.x - start.x)/2; if (isStraight) { script = `M${start.x} ${start.y}H${middle}V${end.y}H${end.x}`; } else { script = `M${start.x} ${start.y}C${middle} ${start.y} ${middle} ${end.y} ${end.x} ${end.y}`; } break; case ['N', 'S'].indexOf(dir) >= 0: start.x = sl.pos.x; start.y = sl.pos.y - sl.bbh/2; end.x = tl.pos.x; end.y = tl.pos.y + tl.bbh/2; if (dir == 'S') { start.y = sl.pos.y + sl.bbh/2; end.y = tl.pos.y - tl.bbh/2; } middle = start.y + (end.y - start.y)/2; if (isStraight) { script = `M${start.x} ${start.y}V${middle}H${end.x}V${end.y}`; } else { script = `M${start.x} ${start.y}C${start.x} ${middle} ${end.x} ${middle} ${end.x} ${end.y}`; } break; case 'SELF' == dir: start.x = sl.pos.x; start.y = sl.pos.y - sl.bbh/2; end.x = sl.pos.x + sl.bbw/2; end.y = sl.pos.y; let r = Math.sqrt(sl.bbw*sl.bbw + sl.bbh*sl.bbh)/4; if (isStraight) { script = `M${start.x} ${start.y}V${start.y - r}H${end.x + r}V${end.y}H${end.x}`; } else { script = `M${start.x} ${start.y}C ${start.x+r} ${start.y-3*r} ${end.x + 3*r} ${end.y} ${end.x} ${end.y}`; } break; } return [ { start: start, end: end, dir: dir }, script ] return script; } export function simpleRightHead(d) { return simpleHead(d, true); } export function simpleLeftHead(d) { return simpleHead(d, true); } function simpleHead(d, isRight) { if (!d.pathMeta) { return; } const w = 14; const h = 8; const bbw = d.source.layout.bbw; const length = d.pathMeta.length; if (isRight) { return `M${length-bbw/2} 0l${-w} ${-h/2}v${h}Z`; } else { return `M${bbw/2} 0l${w} ${-h/2}v${h}Z`; } } export function leftHead(d) { return head(d, false) } export function rightHead(d) { return head(d, true) } function head(d, isRight) { if (!d.pathMeta) { return; } let end; if (isRight) { end = d.pathMeta.end; } else { end = d.pathMeta.start; } const dir = d.pathMeta.dir; const w = 14; const h = 8; let directions; if (isRight) { directions = { easts: ['ENE', 'E', 'ESE'], wests: ['WNW', 'W', 'WSW', "SELF"], norts: ['NNW', 'N', 'NNE'], souths: ['SSW', 'S', 'SSE'] } } else { directions = { easts: ['NNW', 'W', 'SSW'], wests: ['NNE', 'E', 'SSE'], norts: ['WSW', 'S', 'ESE'], souths: ['WNW', 'N', 'ENE', "SELF"] } } switch (true) { case directions.easts.indexOf(dir) >= 0: return `M${end.x} ${end.y}L${end.x - w} ${end.y - h/2}V${end.y + h/2}Z`; case directions.wests.indexOf(dir) >= 0: return `M${end.x} ${end.y}L${end.x + w} ${end.y - h/2}V${end.y + h/2}Z`; case directions.norts.indexOf(dir) >= 0: return `M${end.x} ${end.y}L${end.x - h/2} ${end.y + w}H${end.x + h/2}Z`; case directions.souths.indexOf(dir) >= 0: return `M${end.x} ${end.y}L${end.x - h/2} ${end.y - w}H${end.x + h/2}Z`; } } function getApparentDir(sl, tl) { let vDir = 'SAME'; let hDir = 'SAME'; let dir = '?'; if (tl.pos.y + tl.bbh/2 < sl.pos.y - sl.bbh/2 ) { vDir = 'TOP'; } else if (tl.pos.y - tl.bbh/2 > sl.pos.y + sl.bbh/2) { vDir = 'BOTTOM'; } if (tl.pos.x + tl.bbw /2 < sl.pos.x - sl.bbw/2) { hDir = 'LEFT' } else if (sl.pos.x + sl.bbw/2 < tl.pos.x - tl.bbw/2) { hDir = 'RIGHT' } switch (true) { case hDir == 'SAME' && vDir == 'TOP': dir = 'N'; break; case hDir == 'SAME' && vDir == 'BOTTOM': dir = 'S'; break; case hDir == 'RIGHT' && vDir == 'SAME': dir = 'E'; break; case hDir == 'LEFT' && vDir == 'SAME': dir = 'W'; break; case hDir == 'RIGHT' && vDir == 'TOP': dir = 'NE'; if (tl.pos.x - tl.bbw/2 - sl.pos.x - sl.bbw/2 > sl.pos.y - sl.bbh/2 - tl.pos.y - tl.bbh/2) { dir = 'ENE' } else { dir = 'NNE' } break; case hDir == 'RIGHT' && vDir == 'BOTTOM': dir = 'SE'; if (tl.pos.x - tl.bbw/2- sl.pos.x - sl.bbw/2 > tl.pos.y - tl.bbh /2 - sl.pos.y - sl.bbh/2) { dir = 'ESE' } else { dir = 'SSE' } break; case hDir == 'LEFT' && vDir == 'TOP': dir = 'NW'; if (sl.pos.x - sl.bbw/2 - tl.pos.x - tl.bbw/2 > sl.pos.y - sl.bbh/2- tl.pos.y - tl.bbh/2) { dir = 'WNW' } else { dir = 'NNW' } break; case hDir == 'LEFT' && vDir == 'BOTTOM': dir = 'SW'; if (sl.pos.x - sl.bbw/2 - tl.pos.x - tl.bbw/2 > tl.pos.y - tl.bbh/2 - sl.pos.y - sl.bbh/2) { dir = 'WSW' } else { dir = 'SSW' } break; } return dir; }
hide_page=false; django.jQuery(document).ready(function(){ //*****RESERVA DE ASIENTO FUNCTIONS*****// if (django.jQuery("#id_pagado").prop('checked')) { django.jQuery("#id_fechareserva").prop('disabled', true); django.jQuery("#id_usuario").prop('disabled', true); django.jQuery("#id_proyeccion").prop('disabled', true); django.jQuery("#id_horario").prop('disabled', true); django.jQuery("#id_cantidad_menor").prop('disabled', true); django.jQuery("#id_cantidad_mayor").prop('disabled', true); django.jQuery("#id_asientos").prop('disabled', true); django.jQuery("#id_fechafuncion").prop('disabled', true); django.jQuery("#id_totalentrada").prop('disabled', true); django.jQuery("#id_combo").prop('disabled', true); django.jQuery("#id_totalcombo").prop('disabled', true); django.jQuery("#id_total").prop('disabled', true); django.jQuery("#id_pagado").prop('disabled', true); //var texto = 'Pelicula: ',; //jAlert(, 'Alert Dialog'); //$('#popup').fadeIn('slow'); //$('.popup-overlay').fadeIn('slow'); //alert() //$('.popup-overlay').height($(window).height()); } //*****ORDEN DE COMPRA FUNCTIONS*****// //estos campos deben estar vacios cada vez que hay una nueva recepcion django.jQuery("#id_fecharecepcion").val(""); django.jQuery("#id_fechaemision").val(""); django.jQuery("#id_cantidadrecibida").val(""); django.jQuery("#id_factura").val(""); django.jQuery("#id_dia").val(""); //cuando una orden de compra se anula, se deshabilitan los campos de esa orden if (django.jQuery("#id_estado").prop('checked')) { //alert('entra') django.jQuery("#id_fecha").prop('disabled', true); django.jQuery("#id_producto").prop('disabled', true); django.jQuery("#id_proveedor").prop('disabled', true); django.jQuery("#id_cantidad_producto").prop('disabled', true); django.jQuery("#id_medida").prop('disabled', true); django.jQuery("#id_total").prop('disabled', true); django.jQuery("#id_aprobado").prop('disabled', true); django.jQuery("#id_cantidadrecibida").prop('disabled', true); django.jQuery("#id_fecharecepcion").prop('disabled', true); django.jQuery("#id_fechaemision").prop('disabled', true); django.jQuery("#id_factura").prop('disabled', true); django.jQuery("#id_tipopago").prop('disabled', true); django.jQuery("#id_estado").prop('disabled', true); } //fields dependientes del tipo de pago if(django.jQuery("select:last")) { django.jQuery(".field-diapago").hide(); django.jQuery(".field-meses").hide(); //django.jQuery(".field-total").hide(); } django.jQuery('#id_tipopago').change(function() { if (django.jQuery(this).find(':selected').val() === 'AMORTIZADO') { //alert('entra al if') django.jQuery(".field-diapago").slideDown('slow'); django.jQuery(".field-meses").slideDown('slow'); //django.jQuery(".field-total").slideDown('slow'); } else { django.jQuery(".field-diapago").slideUp('slow'); django.jQuery(".field-meses").slideUp('slow'); //django.jQuery(".field-total").slideUp('slow'); } }); //para que siga mostrando aunque no se haya usado el select if(django.jQuery("#id_tipopago").find(':selected').val() === 'AMORTIZADO'){ django.jQuery(".field-diapago").slideDown('slow'); django.jQuery(".field-meses").slideDown('slow'); }else{ django.jQuery(".field-diapago").slideUp('slow'); django.jQuery(".field-meses").slideUp('slow'); } /**if (django.jQuery("checkbox:last").not(":checked")) { //alert("hola") //alert(django.jQuery(".form-row field-fechafactura")) django.jQuery(".field-fecharecepcion").hide(); django.jQuery(".field-fechaemision").hide(); django.jQuery(".field-factura").hide(); hide_page=true; }else{ //alert("entra al else") //django.jQuery(".field-fecharecepcion").show(); //django.jQuery(".field-fechaemision").show(); //django.jQuery(".field-factura").show(); hide_page=false; } django.jQuery("#id_estado").click(function(){ hide_page=!hide_page; if(hide_page) { django.jQuery(".field-fecharecepcion").slideUp('slow'); django.jQuery(".field-fechaemision").slideUp('slow'); django.jQuery(".field-factura").slideUp('slow'); }else { django.jQuery(".field-fecharecepcion").slideDown('slow'); django.jQuery(".field-fechaemision").slideDown('slow'); django.jQuery(".field-factura").slideDown('slow'); } })**/ })
const { PORT } = require('./constant'); const LOCAL_HOST = '127.0.0.1'; const LOCAL_PORT = process.env[PORT] || 3000; const DOMAIN = `http://${LOCAL_HOST}:${LOCAL_PORT}`; const config = { LOCAL_HOST, LOCAL_PORT, DOMAIN, }; module.exports = config;
/** * Controller的路由表 * Created by yuansc on 2017/3/8. */ "use strict"; const router = require('koa-router')(); const config = require('config'); const ImageController = require('./image'); const UserController = require('./user'); const CommentController = require('./comment'); const NoteController = require('./note'); const HistoryController = require('./history'); const RelationController = require('./relations'); const FavoriteController = require('./favorite'); router.post('/users/login', UserController.login); router.get('/users/code', UserController.genQrCode); router.post('/images/upload', ImageController.upload); router.del('/images/del', ImageController.del); router.post('/comments/add', CommentController.add); router.get('/comments/list/:noteId', CommentController.list); router.post('/notes/add', NoteController.add); router.post('/notes/update', NoteController.update); router.get('/notes/:uid/list', NoteController.list); router.post('/notes/share', NoteController.share); router.post('/notes/copy', NoteController.copy); router.get('/notes/detail/:noteId', NoteController.detail); router.del('/notes/delete/:noteId', NoteController.delete); router.get('/notes/search', NoteController.search); router.get('/notes/scan', NoteController.scan); router.post('/favorites/add/:noteId', FavoriteController.add); router.del('/favorites/remove/:noteId', FavoriteController.remove); router.get('/favorites/list', FavoriteController.list); router.get('/history/list', HistoryController.list); router.get('/relations/list', RelationController.mine); router.all('/msg', async function(ctx){ console.log(ctx) console.log(ctx.request.body) console.log(ctx.request.query) ctx.body = 'ok' }); module.exports = router;
import { composeWithTracker } from 'react-komposer'; import {BookmarksList} from '/imports/ui/components/bookmarks-list'; import {LoadingContent} from '/imports/ui/components/loading'; import { Meteor } from 'meteor/meteor'; import Bookmarks from '/imports/api/bookmarks/bookmarks'; import {Images} from '/imports/api/bookmarks/bookmarks'; import {can} from '/imports/modules/permissions.js'; const composer = ( props, onData ) => { const subscription = can.view.folder(props.currentFolderId) ? Meteor.subscribe('bookmarks', props.currentFolderId) : Meteor.subscribe('emptyBookmarks'); if ( subscription.ready()) { const bookmarks = Bookmarks.find({}, {sort: {views: -1}}).fetch(); const imagesSub = Meteor.subscribe('webshots', props.currentFolderId); if ( imagesSub.ready() ) { const webshots = Images.find({}).fetch(); onData( null, { bookmarks, webshots } ); } } }; export default composeWithTracker( composer, LoadingContent )( BookmarksList );
$( document ).ready(function() { document.getElementById("details_button").onclick = function () { x = ("/employee/empprof_two/"+(document.getElementById("UsernameEmp1").value)) // console.log(x) location.href=x }; });
const puppeteer = require('puppeteer'); const URL_TEST = 'https://qa-routes.praktikum-services.ru/'; async function testBlueRedRound() { console.log('Запуск браузера'); const browser = await puppeteer.launch({headless: false, slowMo: 100}); console.log('Создание новой вкладки в браузере'); const page = await browser.newPage(); console.log('Переход по ссылке'); await page.goto(URL_TEST); console.log('Нахождение искомого элемента'); const blueRound = await page.$(".sc-gzVnrw gEcWAM"); const redRound = await page.$(".sc-gzVnrw eqLFUq"); console.log('Проверка условия тест-кейса'); if (!blueRound && !redRound ) { console.log("passed"); } else { console.log("false") } console.log('Закрытие браузера'); await browser.close(); } testBlueRedRound();
import React from 'react'; class PlayListEntry extends React.Component { constructor(props) { super(props); this.state = { }; } render() { return ( <div> <h4>PlayListEntry Component</h4> </div> ); } } export default PlayListEntry;