text
stringlengths
7
3.69M
import React, { Component } from 'react'; import Stream from './Stream'; import Navigation from './Navigation'; import Explore from './Explore'; import "fake-tweet/build/index.css"; class App extends Component { render() { return ( <div className="container-fluid"> <div className="row"> <div className="col-md-4"> <Navigation /> </div> <div className="col-md-4"> <Stream /> </div> <div className="col-md-4"> <Explore /> </div> </div> </div> ); } } export default App;
define(function(require) { var mandatoryKeys = {url: true, success: true}; var optionalKeys = {data: null, headers: null}; var defaultContentType = 'application/json'; var makeRequest = function(obj, method) { var areMandatoryKeysPresent = true; for (var key in mandatoryKeys) { var newKey = key.toLowerCase(); obj[newKey] = obj[key]; key = newKey if (obj[key] == undefined) { throw new Error(`${key=='success'?'AJAX':'HTTP'} required element: '${key}' not present`); } } var entity = obj.data || ''; var isPriorToRequest = true; var request = new XMLHttpRequest(); request.onreadystatechange = function() { //Conditions for success if (this.readyState == 4 && this.status == 200) { obj.success(this.response, this); } else { if (!isPriorToRequest && obj.error) { obj.error(this); } } } request.open(method, obj.url, true); //Set request headers if (obj.headers) { for (var key in obj.headers) { request.setRequestHeader(key, obj.headers[key]); } } //request.responseType = 'blob'; //console.log(request.responseType); console.log(request); request.send(entity);//JSON.stringify(entity)); }; return { //http object GET: function(obj) { makeRequest(obj, 'GET'); }, POST: function(obj) { makeRequest(obj, 'POST'); }, PUT: function(obj) { makeRequest(obj, 'PUT'); }, DELETE: function(obj) { makeRequest(obj, 'DELETE'); }, HEAD: function(obj) { makeRequest(obj, 'HEAD'); }, OPTIONS: function(obj) { makeRequest(obj, 'OPTIONS'); }, //TRACE: function(obj) { unsupported by XHR // makeRequest(obj); //}, //CONNECT: function(obj) { // makeRequest(obj); //}, } });
import React, { useState } from 'react'; import { Form, InputGroup, Col, Image, Button } from 'react-bootstrap'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faUpload } from '@fortawesome/free-solid-svg-icons'; import imgService from '../../Common/service/imgService'; import DnDItems from "../cmp/DnDItems"; import ErrMsg from '../../Common/cmp/ErrMsg'; import Banner from '../../Common/cmp/Banner'; import validate from '../../Common/service/validate'; function NewProjectForm(props) { const [state, setState] = useState({ field: { projName: {value:'', required: true, errors: []}, projDesc: {value:'', required: false}, projInst: {value:'', required: false}, qty: {value: 0, required: false}, img: {value: '', required: false, errors: []}, necItems: {value: '', required: false, errors: []} }, bannerIsShown: false, msg: "" }); const onInputChange = (e) => { const errors = validate(e.target, state) ; setState({...state, field : { ...state.field, [e.target.name] : { ...state.field[e.target.name], value : e.target.value, errors } } }) } const updateNecItems = (items) => { const necItemIds = items.map(item => item.id) setState((state) => ({...state, field: {...state.field, necItems : {...state.field.necItems, value: necItemIds }}})); } const getImgUrl = (ev) => { if (ev) { setState((state) => ({ ...state, msg: <div className="d-flex align-items-center justify-content-around"> <div>Your Image Is Being Uploaded</div> <div><Image src="./img/common/loader.gif" alt="" /></div> </div>, bannerIsShown: true })); imgService.uploadImg(ev) .then(res => { setState((state) => ({...state, field: {...state.field, img : {...state.field.img, value: res }}})); setState((state) => ({...state, msg : '', bannerIsShown: false})); }); } else { console.log('hee haw!')} } const onSubmit = (e) => { e.preventDefault(); if (Object.keys(state.field).every((k) => state.field[k].errors.length === 0)) { setState((state) => ({ ...state, msg: <div className="d-flex align-items-center justify-content-around"> <div>Thanks For Submitting a New Project !</div> <div><Image src="./img/common/loader.gif" alt="" /></div> </div>, bannerIsShown: true })); props.onAddThing('projects', state.field); } else { setState((state) => ({ ...state, msg: 'Some of the fields have issues.', bannerIsShown: true })); } }; const bannerHide = () => setState((state) => ({ ...state, bannerIsShown : false })); const bannerShow = () => setState((state) => ({ ...state, bannerIsShown : true })); return ( <div> <Form className="form" onSubmit={onSubmit}> <Form.Row> <Col sm={10} md={10}> <Form.Control className="mb-2" type="text" placeholder="Enter Project Name" name="projName" id="projName" onBlur={onInputChange} /> {state.field.projName.errors.length > 0 && <ErrMsg errors={state.field.projName.errors} />} </Col> <Col sm={1} md={1}> <Form.Control className="mb-2" type="number" placeholder="Stock" name="qty" id="qty" onBlur={onInputChange} /> </Col> <Col sm={1} md={1}> <InputGroup> <InputGroup.Text className="custom-file-upload"> <label for="img" className="pointer"> <FontAwesomeIcon icon={faUpload} /> </label> </InputGroup.Text> <Form.Control className="mb-2" type="file" placeholder="Upload a Picture" name="img" id="img" onChange={getImgUrl} /> </InputGroup> </Col> </Form.Row> <Form.Row> <Col> <Form.Control className="mb-2" type="text" placeholder="Enter The Project Description" name="projDesc" id="projDesc" onBlur={onInputChange} /> </Col> </Form.Row> <Form.Row> <Col> <Form.Control className="mb-2" as="textarea" rows={3} placeholder="Instructions for Building This Project" name="projInst" id="projInst" onBlur={onInputChange} /> </Col> </Form.Row> {/* <Form.Row> </Form.Row> */} <Form.Row className="d-flex flex-column"> <Col> <DnDItems items={props.items} onUpdateNecItems={updateNecItems}/> </Col> </Form.Row> <Form.Row> <Col> <Button block type="submit">Submit new Project</Button> </Col> </Form.Row> </Form> <Banner isBannerShown={state.bannerIsShown} onShowBanner={bannerShow} onHideBanner={bannerHide} txt={state.msg} /> </div> ) } export default NewProjectForm;
import axios from 'axios'; import { getProductDetailSuccess, getProductDetailFail, getProductDetailStart } from './'; import { toggleModal } from '../../index'; const key = '3a44e5154f1b4a47ad7c27d498a2c598'; const baseUrl = 'https://api.spoonacular.com'; /** * * @param {string} id * @returns {object} object */ const getProductDetail = (id) => { return dispatch => { setTimeout(() => dispatch(getProductDetailStart()), 100); setTimeout(() => dispatch(toggleModal()), 100); setTimeout(() => axios .get(`${baseUrl}/food/products/${id}?&apiKey=${key}`) .then(res => dispatch(getProductDetailSuccess(res.data))) .catch(err => dispatch(getProductDetailFail(err))), 1000); } } export default getProductDetail;
import React from 'react'; import Images from './Images'; import CenteralStore from './context/CenteralStore'; import Paginate from './componts/Paginate' const DisplayImages = (props) => { return ( <CenteralStore> <Images /> <Paginate /> </CenteralStore> ); }; export default DisplayImages;
function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } function startGame() { var url = " https://opentdb.com/api.php?amount=10"; $.ajax({ url: url, method: 'GET', }).done(function (response) { var centerDiv = $(".centered-div"); var questionIndex = 0; var wins = 0; var losses = 0; var correctAnswer; var maxSeconds = 20; var data = function getData() { let data = []; for (let i = 0; i < response.results.length; i++) { let qAndAs = {}; qAndAs.question = response.results[i].question; qAndAs.answers = response.results[i].incorrect_answers; qAndAs.correctAnswer = response.results[i].correct_answer; qAndAs.answers.push(qAndAs.correctAnswer); qAndAs.answers = qAndAs.answers.filter(each => each != undefined); shuffle(qAndAs.answers); data.push(qAndAs); }; return data; }(); function showData(qAndAs) { let questionDiv = $("<div>"); questionDiv.addClass("question"); let answerDiv = $("<div>"); answerDiv.addClass("answer"); answerDiv.attr("id", "answers"); let counterDiv = $("<div>"); let counterNumber = $("<h2>"); counterDiv.addClass("counter"); centerDiv.empty(); // Show question questionDiv.append($("<h2>").html(qAndAs.question)); centerDiv.append(questionDiv); //Show Counter counterDiv.append(counterNumber); centerDiv.append(counterDiv); // Show answers qAndAs.answers.forEach(function (answer) { let buttonDiv = $("<button>"); buttonDiv.addClass("answerButton"); answerDiv.append(buttonDiv.attr("data-answer", answer).html(answer)); centerDiv.append(answerDiv); centerDiv.append($("<br>")); }); } function showNextData() { correctAnswer = data[questionIndex].correctAnswer; showData(data[questionIndex]); } function showSuccess() { let answerDiv = $(".answer"); let h2Div = $("<h2>"); answerDiv.empty(); answerDiv.append(answerDiv.append(h2Div.text("Congratulations! That is the correct answer!"))); delayShow(); wins++; } function showFailure() { let answerDiv = $(".answer"); answerDiv.empty(); answerDiv.append(answerDiv.append($("<h2>").text("Oops! The correct answer is:"))); answerDiv.append(answerDiv.append($("<h2>").text(correctAnswer))); delayShow(); losses++; } function showTimeup() { let answerDiv = $(".answer"); answerDiv.empty(); answerDiv.append(answerDiv.append($("<h2>").text("Time is up! The correct answer is:"))); answerDiv.append(answerDiv.append($("<h2>").text(correctAnswer))); delayShow(); losses++; } function delayTimeup() { var id = setTimeout(function () { showTimeup(); }, 20000); return id; } function delayShow() { var id = setTimeout(function () { play(); }, 2000); return id; } var counter = { seconds: maxSeconds, intervalId: 0, run: function () { let self = counter; self.stop(); self.intervalId = setInterval(self.decrement, 1000); }, decrement: function () { let self = counter; self.seconds--; $(".counter").html("<h3>" + "Seconds left: " + self.seconds + "</h3>"); if (self.seconds === 0) { self.stop(); showTimeup(); } }, stop: function () { let self = counter; clearInterval(self.intervalId); $(".counter").empty(); self.seconds = maxSeconds; } } function play() { if (questionIndex < 10) { counter.run(); showNextData(); $(".answerButton").on("click", function (event) { event.preventDefault(); counter.stop(); if ($(this).attr("data-answer") == correctAnswer) { showSuccess(); } else { showFailure(); } }); } else { showStart() }; questionIndex++; } function showStart() { centerDiv.empty(); let answerDiv = $("<div>"); answerDiv.addClass("answer"); answerDiv.append(answerDiv.append($("<h2>").text("Wins: " + wins))); centerDiv.append(answerDiv); answerDiv = $("<div>"); answerDiv.addClass("answer"); centerDiv.append(answerDiv); answerDiv.append(answerDiv.append($("<h2>").text("Losses: " + losses))); centerDiv.append(answerDiv); var buttonDiv = $("<button>"); buttonDiv.addClass("btn btn-default start-button"); buttonDiv.attr("type", "submit"); buttonDiv.text("START"); centerDiv.append(buttonDiv); } play(); }).fail(function (err) { throw err; }) }; $(".centered-div").on("click", ".start-button", function (event) { event.preventDefault(); console.log("started"); startGame(); })
import Vue from 'vue'; import Vuex from 'vuex'; import state from '@/store/state'; import * as getters from '@/store/getters'; import * as mutations from '@/store/mutations'; import * as actions from '@/store/actions'; import * as modules from '@/store/modules'; Vue.use(Vuex); const strict = process.env.NODE_ENV !== 'production'; const plugins = []; const store = new Vuex.Store({ state, getters, actions, mutations, modules, plugins, strict, }); export default store;
export const onLoad = () => { window.gapi.load('auth2', function() { window.gapi.auth2.init( { client_id: `329385351437-1i1mg0trorrlnckai6mqscb3el21v4td.apps.googleusercontent.com`, } ); }); } export const googleSignOut = () => { if (window.gapi) { const auth2 = window.gapi.auth2.getAuthInstance() auth2.signOut() return true } }
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsAutoDelete = { name: 'auto_delete', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M15 2h-3.5l-1-1h-5l-1 1H1v2h14zM16 9c-.7 0-1.37.1-2 .29V5H2v12c0 1.1.9 2 2 2h5.68A6.999 6.999 0 0023 16c0-3.87-3.13-7-7-7zm0 12c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z"/><path d="M16.5 12H15v5l3.6 2.1.8-1.2-2.9-1.7z"/></svg>` };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = _default; exports.disconnect = disconnect; exports.listTables = listTables; exports.listViews = listViews; exports.listRoutines = listRoutines; exports.listTableColumns = listTableColumns; exports.listTableTriggers = listTableTriggers; exports.listTableIndexes = listTableIndexes; exports.listSchemas = listSchemas; exports.getTableReferences = getTableReferences; exports.getTableKeys = getTableKeys; exports.query = query; exports.executeQuery = executeQuery; exports.listDatabases = listDatabases; exports.getQuerySelectTop = getQuerySelectTop; exports.getTableCreateScript = getTableCreateScript; exports.getViewCreateScript = getViewCreateScript; exports.getRoutineCreateScript = getRoutineCreateScript; exports.wrapIdentifier = wrapIdentifier; exports.truncateAllTables = truncateAllTables; var _pg = _interopRequireDefault(require("pg")); var _sqlQueryIdentifier = require("sql-query-identifier"); var _utils = require("./utils"); var _logger = _interopRequireDefault(require("../../logger")); var _utils2 = require("../../utils"); var _errors = _interopRequireDefault(require("../../errors")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const logger = (0, _logger.default)('db:clients:postgresql'); const pgErrors = { CANCELED: '57014' }; /** * Do not convert DATE types to JS date. * It gnores of applying a wrong timezone to the date. * TODO: do not convert as well these same types with array (types 1115, 1182, 1185) */ _pg.default.types.setTypeParser(1082, 'text', val => val); // date _pg.default.types.setTypeParser(1114, 'text', val => val); // timestamp without timezone _pg.default.types.setTypeParser(1184, 'text', val => val); // timestamp async function _default(server, database) { const dbConfig = configDatabase(server, database); logger().debug('create driver client for postgres with config %j', dbConfig); const conn = { pool: new _pg.default.Pool(dbConfig) }; logger().debug('connected'); const defaultSchema = await getSchema(conn); return { /* eslint max-len:0 */ wrapIdentifier, disconnect: () => disconnect(conn), listTables: (db, filter) => listTables(conn, filter), listViews: filter => listViews(conn, filter), listRoutines: filter => listRoutines(conn, filter), listTableColumns: (db, table, schema = defaultSchema) => listTableColumns(conn, db, table, schema), listTableTriggers: (table, schema = defaultSchema) => listTableTriggers(conn, table, schema), listTableIndexes: (db, table, schema = defaultSchema) => listTableIndexes(conn, table, schema), listSchemas: (db, filter) => listSchemas(conn, filter), getTableReferences: (table, schema = defaultSchema) => getTableReferences(conn, table, schema), getTableKeys: (db, table, schema = defaultSchema) => getTableKeys(conn, db, table, schema), query: (queryText, schema = defaultSchema) => query(conn, queryText, schema), executeQuery: (queryText, schema = defaultSchema) => executeQuery(conn, queryText, schema), listDatabases: filter => listDatabases(conn, filter), getQuerySelectTop: (table, limit, schema = defaultSchema) => getQuerySelectTop(conn, table, limit, schema), getTableCreateScript: (table, schema = defaultSchema) => getTableCreateScript(conn, table, schema), getViewCreateScript: (view, schema = defaultSchema) => getViewCreateScript(conn, view, schema), getRoutineCreateScript: (routine, type, schema = defaultSchema) => getRoutineCreateScript(conn, routine, type, schema), truncateAllTables: (_, schema = defaultSchema) => truncateAllTables(conn, schema) }; } function disconnect(conn) { conn.pool.end(); } async function listTables(conn, filter) { const schemaFilter = (0, _utils.buildSchemaFilter)(filter, 'table_schema'); const sql = ` SELECT table_schema as schema, table_name as name FROM information_schema.tables WHERE table_type NOT LIKE '%VIEW%' ${schemaFilter ? `AND ${schemaFilter}` : ''} ORDER BY table_schema, table_name `; const data = await driverExecuteQuery(conn, { query: sql }); return data.rows; } async function listViews(conn, filter) { const schemaFilter = (0, _utils.buildSchemaFilter)(filter, 'table_schema'); const sql = ` SELECT table_schema as schema, table_name as name FROM information_schema.views ${schemaFilter ? `WHERE ${schemaFilter}` : ''} ORDER BY table_schema, table_name `; const data = await driverExecuteQuery(conn, { query: sql }); return data.rows; } async function listRoutines(conn, filter) { const schemaFilter = (0, _utils.buildSchemaFilter)(filter, 'routine_schema'); const sql = ` SELECT routine_schema, routine_name, routine_type FROM information_schema.routines ${schemaFilter ? `WHERE ${schemaFilter}` : ''} GROUP BY routine_schema, routine_name, routine_type ORDER BY routine_schema, routine_name `; const data = await driverExecuteQuery(conn, { query: sql }); return data.rows.map(row => ({ schema: row.routine_schema, routineName: row.routine_name, routineType: row.routine_type })); } async function listTableColumns(conn, database, table, schema) { const sql = ` SELECT column_name, data_type FROM information_schema.columns WHERE table_schema = $1 AND table_name = $2 `; const params = [schema, table]; const data = await driverExecuteQuery(conn, { query: sql, params }); return data.rows.map(row => ({ columnName: row.column_name, dataType: row.data_type })); } async function listTableTriggers(conn, table, schema) { const sql = ` SELECT trigger_name FROM information_schema.triggers WHERE event_object_schema = $1 AND event_object_table = $2 `; const params = [schema, table]; const data = await driverExecuteQuery(conn, { query: sql, params }); return data.rows.map(row => row.trigger_name); } async function listTableIndexes(conn, table, schema) { const sql = ` SELECT indexname as index_name FROM pg_indexes WHERE schemaname = $1 AND tablename = $2 `; const params = [schema, table]; const data = await driverExecuteQuery(conn, { query: sql, params }); return data.rows.map(row => row.index_name); } async function listSchemas(conn, filter) { const schemaFilter = (0, _utils.buildSchemaFilter)(filter); const sql = ` SELECT schema_name FROM information_schema.schemata ${schemaFilter ? `WHERE ${schemaFilter}` : ''} ORDER BY schema_name `; const data = await driverExecuteQuery(conn, { query: sql }); return data.rows.map(row => row.schema_name); } async function getTableReferences(conn, table, schema) { const sql = ` SELECT ctu.table_name AS referenced_table_name FROM information_schema.table_constraints AS tc JOIN information_schema.constraint_table_usage AS ctu ON ctu.constraint_name = tc.constraint_name WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name = $1 AND tc.table_schema = $2 `; const params = [table, schema]; const data = await driverExecuteQuery(conn, { query: sql, params }); return data.rows.map(row => row.referenced_table_name); } async function getTableKeys(conn, database, table, schema) { const sql = ` SELECT tc.constraint_name, kcu.column_name, CASE WHEN tc.constraint_type LIKE '%FOREIGN%' THEN ctu.table_name ELSE NULL END AS referenced_table_name, tc.constraint_type FROM information_schema.table_constraints AS tc JOIN information_schema.key_column_usage AS kcu USING (constraint_schema, constraint_name) JOIN information_schema.constraint_table_usage as ctu USING (constraint_schema, constraint_name) WHERE tc.table_name = $1 AND tc.table_schema = $2 AND tc.constraint_type IN ('PRIMARY KEY', 'FOREIGN KEY') `; const params = [table, schema]; const data = await driverExecuteQuery(conn, { query: sql, params }); return data.rows.map(row => ({ constraintName: row.constraint_name, columnName: row.column_name, referencedTable: row.referenced_table_name, keyType: row.constraint_type })); } function query(conn, queryText) { let pid = null; let canceling = false; const cancelable = (0, _utils2.createCancelablePromise)({ ..._errors.default.CANCELED_BY_USER, sqlectronError: 'CANCELED_BY_USER' }); return { execute() { return runWithConnection(conn, async connection => { const connClient = { connection }; const dataPid = await driverExecuteQuery(connClient, { query: 'SELECT pg_backend_pid() AS pid' }); pid = dataPid.rows[0].pid; try { const data = await Promise.race([cancelable.wait(), executeQuery(connClient, queryText)]); pid = null; return data; } catch (err) { if (canceling && err.code === pgErrors.CANCELED) { canceling = false; err.sqlectronError = 'CANCELED_BY_USER'; } throw err; } finally { cancelable.discard(); } }); }, async cancel() { if (!pid) { throw new Error('Query not ready to be canceled'); } canceling = true; try { const data = await driverExecuteQuery(conn, { query: `SELECT pg_cancel_backend(${pid});` }); if (!data.rows[0].pg_cancel_backend) { throw new Error(`Failed canceling query with pid ${pid}.`); } cancelable.cancel(); } catch (err) { canceling = false; throw err; } } }; } async function executeQuery(conn, queryText) { const data = await driverExecuteQuery(conn, { query: queryText, multiple: true }); const commands = identifyCommands(queryText).map(item => item.type); return data.map((result, idx) => parseRowQueryResult(result, commands[idx])); } async function listDatabases(conn, filter) { const databaseFilter = (0, _utils.buildDatabseFilter)(filter, 'datname'); const sql = ` SELECT datname FROM pg_database WHERE datistemplate = $1 ${databaseFilter ? `AND ${databaseFilter}` : ''} ORDER BY datname `; const params = [false]; const data = await driverExecuteQuery(conn, { query: sql, params }); return data.rows.map(row => row.datname); } function getQuerySelectTop(conn, table, limit, schema) { return `SELECT * FROM ${wrapIdentifier(schema)}.${wrapIdentifier(table)} LIMIT ${limit}`; } async function getTableCreateScript(conn, table, schema) { // Reference http://stackoverflow.com/a/32885178 const sql = ` SELECT 'CREATE TABLE ' || quote_ident(tabdef.schema_name) || '.' || quote_ident(tabdef.table_name) || E' (\n' || array_to_string( array_agg( ' ' || quote_ident(tabdef.column_name) || ' ' || tabdef.type || ' '|| tabdef.not_null ) , E',\n' ) || E'\n);\n' || CASE WHEN tc.constraint_name IS NULL THEN '' ELSE E'\nALTER TABLE ' || quote_ident($2) || '.' || quote_ident(tabdef.table_name) || ' ADD CONSTRAINT ' || quote_ident(tc.constraint_name) || ' PRIMARY KEY ' || '(' || substring(constr.column_name from 0 for char_length(constr.column_name)-1) || ')' END AS createtable FROM ( SELECT c.relname AS table_name, a.attname AS column_name, pg_catalog.format_type(a.atttypid, a.atttypmod) AS type, CASE WHEN a.attnotnull THEN 'NOT NULL' ELSE 'NULL' END AS not_null, n.nspname as schema_name FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n WHERE c.relname = $1 AND a.attnum > 0 AND a.attrelid = c.oid AND a.atttypid = t.oid AND n.oid = c.relnamespace AND n.nspname = $2 ORDER BY a.attnum DESC ) AS tabdef LEFT JOIN information_schema.table_constraints tc ON tc.table_name = tabdef.table_name AND tc.table_schema = tabdef.schema_name AND tc.constraint_Type = 'PRIMARY KEY' LEFT JOIN LATERAL ( SELECT column_name || ', ' AS column_name FROM information_schema.key_column_usage kcu WHERE kcu.constraint_name = tc.constraint_name AND kcu.table_name = tabdef.table_name AND kcu.table_schema = tabdef.schema_name ORDER BY ordinal_position ) AS constr ON true GROUP BY tabdef.schema_name, tabdef.table_name, tc.constraint_name, constr.column_name; `; const params = [table, schema]; const data = await driverExecuteQuery(conn, { query: sql, params }); return data.rows.map(row => row.createtable); } async function getViewCreateScript(conn, view, schema) { const createViewSql = `CREATE OR REPLACE VIEW ${wrapIdentifier(schema)}.${view} AS`; const sql = 'SELECT pg_get_viewdef($1::regclass, true)'; const params = [view]; const data = await driverExecuteQuery(conn, { query: sql, params }); return data.rows.map(row => `${createViewSql}\n${row.pg_get_viewdef}`); } async function getRoutineCreateScript(conn, routine, _, schema) { const sql = ` SELECT pg_get_functiondef(p.oid) FROM pg_proc p LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace WHERE proname = $1 AND n.nspname = $2 `; const params = [routine, schema]; const data = await driverExecuteQuery(conn, { query: sql, params }); return data.rows.map(row => row.pg_get_functiondef); } function wrapIdentifier(value) { if (value === '*') return value; const matched = value.match(/(.*?)(\[[0-9]\])/); // eslint-disable-line no-useless-escape if (matched) return wrapIdentifier(matched[1]) + matched[2]; return `"${value.replace(/"/g, '""')}"`; } async function getSchema(conn) { const sql = 'SELECT current_schema() AS schema'; const data = await driverExecuteQuery(conn, { query: sql }); return data.rows[0].schema; } async function truncateAllTables(conn, schema) { await runWithConnection(conn, async connection => { const connClient = { connection }; const sql = ` SELECT quote_ident(table_name) as table_name FROM information_schema.tables WHERE table_schema = $1 AND table_type NOT LIKE '%VIEW%' `; const params = [schema]; const data = await driverExecuteQuery(connClient, { query: sql, params }); const truncateAll = data.rows.map(row => ` TRUNCATE TABLE ${wrapIdentifier(schema)}.${wrapIdentifier(row.table_name)} RESTART IDENTITY CASCADE; `).join(''); await driverExecuteQuery(connClient, { query: truncateAll, multiple: true }); }); } function configDatabase(server, database) { const config = { host: server.config.host, port: server.config.port, user: server.config.user, password: server.config.password, database: database.database, max: 5 // max idle connections per time (30 secs) }; if (server.sshTunnel) { config.host = server.config.localHost; config.port = server.config.localPort; } if (server.config.ssl) { config.ssl = server.config.ssl; } return config; } function parseRowQueryResult(data, command) { const isSelect = data.command === 'SELECT'; return { command: command || data.command, rows: data.rows, fields: data.fields, rowCount: isSelect ? data.rowCount || data.rows.length : undefined, affectedRows: !isSelect && !isNaN(data.rowCount) ? data.rowCount : undefined }; } function identifyCommands(queryText) { try { return (0, _sqlQueryIdentifier.identify)(queryText); } catch (err) { return []; } } function driverExecuteQuery(conn, queryArgs) { const runQuery = connection => { const args = { text: queryArgs.query, values: queryArgs.params, multiResult: queryArgs.multiple }; // node-postgres has support for Promise query // but that always returns the "fields" property empty return new Promise((resolve, reject) => { connection.query(args, (err, data) => { if (err) return reject(err); resolve(data); }); }); }; return conn.connection ? runQuery(conn.connection) : runWithConnection(conn, runQuery); } async function runWithConnection({ pool }, run) { const connection = await pool.connect(); try { return await run(connection); } finally { connection.release(); } }
const sentinelImg = document.querySelectorAll('.film-gallery__item') const lazyImgs = document.querySelectorAll('.film-gallery__img') const options ={} const callback = lazyImgs =>{ lazyImgs.forEach(img=>{ if(img.isIntersecting){ img.src = img.dataset.src; } }) } const observer = new IntersectionObserver(callback, options) const el = sentinelImg.forEach(el => {observer.observe(el)}) // (async () => { // // console.log('hi') // const sentinelImg = document.querySelectorAll('.film-gallery__item') // const lazyImgs = document.querySelectorAll('.film-gallery__img') // const options ={ } // const callback = lazyImgs =>{ // lazyImgs.forEach(img=>{ // if(img.isIntersecting){ // img.src = img.dataset.src; // } // }) // } // const observer = new IntersectionObserver(callback, options) // const el = sentinelImg.forEach(el => {observer.observe(el)}) // })(); // // =++++ // // const observer = new IntersectionObserver(lazyImgs =>{ // // lazyImgs.forEach(img =>{ // // console.log('hi callback') // // }) // // }) // // observer.observe(sentinel) // // lazyImgs.forEach(image => { // // image.addEventListener('load', onImgLoaded) // // }) // // function onImgLoaded(e){ // // console.log('hey') // // }
/*jslint browser: true, white: true */ /*global CanvasRenderingContext2D, requestAnimationFrame, console, GAME */ // ------------------------------------------------------------------ // // This is the game object. Everything about the game is located in // this object. // // ------------------------------------------------------------------ GAME.playSound = function(whichSound) { GAME.sounds['audio/' + whichSound + '.' + GAME.audioExt].play(); }; GAME.pauseSound = function(whichSound) { GAME.sounds['audio/' + whichSound + '.' + GAME.audioExt].pause(); }; GAME.graphics = (function() { 'use strict'; GAME.canvas = document.getElementById('canvas-main'); GAME.context = GAME.canvas.getContext('2d'); GAME.blocksize = GAME.canvas.width / (Math.min(GAME.width, GAME.height) * 2); //------------------------------------------------------------------ // // Place a 'clear' function on the Canvas prototype, this makes it a part // of the canvas, rather than making a function that calls and does it. // //------------------------------------------------------------------ CanvasRenderingContext2D.prototype.clear = function() { this.save(); this.setTransform(1, 0, 0, 1, 0, 0); this.clearRect(0, 0, GAME.canvas.width, GAME.canvas.height); this.restore(); }; //------------------------------------------------------------------ // // Public function that allows the client code to clear the canvas. // //------------------------------------------------------------------ function clear() { GAME.context.clear(); } function drawImage(spec) { GAME.context.save(); GAME.context.translate(spec.center.x, spec.center.y); GAME.context.rotate(spec.rotation); GAME.context.translate(-spec.center.x, -spec.center.y); GAME.context.drawImage( spec.image, spec.center.x - spec.size / 2, spec.center.y - spec.size / 2, spec.size, spec.size); GAME.context.restore(); } //------------------------------------------------------------------ // // This is used to create a texture function that can be used by client // code for rendering. // //------------------------------------------------------------------ function Texture(spec) { var that = {}; //todo return that; } return { clear: clear, drawImage: drawImage }; }()); //------------------------------------------------------------------ // // This function performs the one-time game initialization. // //------------------------------------------------------------------ GAME.initialize = function initialize() { 'use strict'; GAME.playSound("theme"); var all_colors = [{ top: '#1879BD', bottom: '#084D79' }, { top: '#678834', bottom: '#093905' }, { top: '#EB7723', bottom: '#A80000' }]; var mousePosition = { x: 0, y: 0 }; var mousePressed = false; /** * Track the user's mouse position on mouse move. * @param {Event} event */ GAME.canvas.addEventListener('mousemove', function(event) { mousePosition.x = event.offsetX || event.layerX; mousePosition.y = event.offsetY || event.layerY; }); /** * Track the user's clicks. * @param {Event} event */ GAME.canvas.addEventListener('mousedown', function(event) { mousePressed = true; }); GAME.canvas.addEventListener('mouseup', function(event) { mousePressed = false; }); function Button(x, y, w, h, text, colors, action) { this.x = x; this.y = y; this.width = w; this.height = h; this.colors = colors; this.text = text; this.state = 'default'; // current button state var isClicking = false; /** * Check to see if the user is hovering over or clicking on the button. */ this.update = function() { // check for hover if (mousePosition.x >= this.x && mousePosition.x <= this.x + this.width && mousePosition.y >= this.y && mousePosition.y <= this.y + this.height) { this.state = 'hover'; // check for click if (mousePressed) { this.state = "active"; isClicking = true; } else { if (isClicking) { action(); } isClicking = false; } } else { this.state = 'default'; } }; /** * Draw the button. */ this.draw = function() { GAME.context.save(); GAME.context.font = '15px sans-serif'; var colors = this.colors[this.state]; var halfH = this.height / 2; // button GAME.context.fillStyle = colors.top; GAME.context.fillRect(this.x, this.y, this.width, halfH); GAME.context.fillStyle = colors.bottom; GAME.context.fillRect(this.x, this.y + halfH, this.width, halfH); // text var size = GAME.context.measureText(this.text); var x = this.x + (this.width - size.width / 2) / 2; var y = this.y + (this.height - 15) / 2 + 12; GAME.context.fillStyle = '#FFF'; GAME.context.fillText(this.text, x, y); GAME.context.restore(); }; } var bw = 200, bh = 50; var default_colors = { 'default': all_colors[0], 'hover': all_colors[1], 'active': all_colors[2] }; GAME.backButton = new Button(GAME.blocksize * GAME.width + 50, GAME.canvas.height / 2 + 100, bw, bh, 'Back', default_colors, function() { document.location.href = "../"; }); $.ajax({ url: 'http://localhost:3000/v1/controls', cache: false, type: 'GET', error: function() { alert('GET failed'); }, success: function(data) { for (var i = 0; i < 7; i++) { GAME.controls[data[i].name] = data[i].key; } } }); var fire = GAME.particleSystem({ image: GAME.images['img/fire.png'], center: { x: 0, y: 0 }, speed: { mean: 40, stdev: 10 }, lifetime: { mean: 2, stdev: 0.8 } }); GAME.currtime = performance.now(); GAME.falltimer = 0; GAME.sweeptimer = 0; GAME.sweeptime = 400; (function setVariables() { GAME.over = false; GAME.drewNameInput = false; GAME.paused = false; GAME.controls = []; GAME.pulse = 400; GAME.newblocktime = GAME.pulse * GAME.height; GAME.newblocktimer = GAME.newblocktime - 2000; GAME.level = 1; GAME.lines_cleared = 0; GAME.score = 0; GAME.level_threshold = 5; GAME.currentKey = 0; GAME.keyIsPressed = false; GAME.changed_flag = false; GAME.pending_block = null; GAME.particles = []; GAME.particle_timers = []; GAME.blocks = []; GAME.ground = []; GAME.grid = []; GAME.activeBlock = 0; for (var i = 0; i < GAME.width; i++) { GAME.grid[i] = []; GAME.ground[i] = []; for (var j = 0; j < GAME.height; j++) { GAME.grid[i][j] = 0; GAME.ground[i][j] = 0; } } makeNewBlock(); }()); function random(top) { var ret = Math.floor(Math.random() * top) + 1; if (ret < 0) return 0; return ret; } //------------------------------------------------------------------ // // This is the Game Loop function! // //------------------------------------------------------------------ function gameLoop() { var delta = performance.now() - GAME.currtime; if (!GAME.over) { GatherInput(); UpdateGameLogic(delta); } Render(delta); requestAnimationFrame(gameLoop); }; function GatherInput() { document.onkeydown = checkKey; document.onkeyup = releaseKey; function checkKey(e) { if (!GAME.keyIsPressed) { GAME.keyIsPressed = true; GAME.currentKey = e.keyCode; } } function releaseKey() { GAME.keyIsPressed = false; } } function UpdateGameLogic(delta) { GAME.currtime += delta; if (!GAME.paused) { if (GAME.lines_cleared >= GAME.level_threshold) { GAME.playSound("SFX_LevelUp"); GAME.lines_cleared -= GAME.level_threshold; GAME.level++; GAME.pulse -= 50; if (GAME.pulse < 150) { GAME.pulse = 150; } GAME.newblocktime = GAME.pulse * GAME.height; GAME.newblocktimer = GAME.newblocktime - 2000; } GAME.falltimer += delta; GAME.newblocktimer += delta; if (GAME.falltimer > GAME.pulse) { GAME.falltimer -= GAME.pulse; for (var i = 0; i < GAME.blocks.length; i++) { if (!fall(GAME.blocks[i])) { addToGround(i--); GAME.newblocktimer = GAME.newblocktime; } else { GAME.playSound("SFX_PieceSoftDrop"); } } } if (GAME.newblocktimer > GAME.newblocktime) { GAME.newblocktimer -= GAME.newblocktime; var l = GAME.blocks.length; GAME.activeBlock = l; moveIntoBoundsVert(GAME.pending_block); GAME.blocks[l] = GAME.pending_block; placeBlockOnGrid(GAME.pending_block); makeNewBlock(); } } else if (GAME.currentKey == GAME.controls['pause'] && !GAME.changed_flag) { GAME.paused = !GAME.paused; GAME.changed_flag = true; } if (!GAME.paused) { var k = GAME.currentKey; if (k != 0) { var active = GAME.blocks[GAME.activeBlock]; if (active) { removeBlockFromGrid(active); if (k == GAME.controls['pause'] && !GAME.changed_flag) { GAME.paused = !GAME.paused; } else if (k == GAME.controls['left']) { if (canMoveHoriz(active, -1)) { GAME.playSound("SFX_PieceSoftDrop"); move(active, -1); } } else if (k == GAME.controls['right']) { if (canMoveHoriz(active, 1)) { GAME.playSound("SFX_PieceSoftDrop"); move(active, 1); } } else if (k == GAME.controls['soft']) { if (canMoveDown(active)) { GAME.playSound("SFX_PieceSoftDrop"); moveDown(active, 1); GAME.falltimer = 0; } } else if (k == GAME.controls['hard']) { GAME.playSound("SFX_PieceHardDrop"); hardDrop(active); GAME.newblocktimer = GAME.pulse * GAME.height - 1000; } else if (k == GAME.controls['counterclock']) { GAME.playSound("SFX_PieceRotateLR"); rotateCounterClockwise(active); } else if (k == GAME.controls['clock']) { GAME.playSound("SFX_PieceRotateLR"); rotateClockwise(active); } placeBlockOnGrid(active); GAME.changed_flag = true; } } if (GAME.changed_flag) { GAME.currentKey = 0; GAME.changed_flag = false; } checkForClears(); } } function Render(delta) { GAME.graphics.clear(); GAME.backButton.update(); GAME.backButton.draw(); drawBoard(); drawPending(); drawParticles(delta); drawScore(); if (GAME.over) { GAME.context.fillStyle = "rgb(240, 240, 240)"; GAME.context.fillRect(0, GAME.canvas.height / 2 - GAME.canvas.height / 4, GAME.canvas.width, GAME.canvas.height / 3); GAME.context.fillStyle = "rgb(200, 0, 0)"; GAME.context.font = '70px sans-serif'; GAME.context.fillText("GAME OVER", GAME.canvas.width / 2 - 180, GAME.canvas.height / 2); if (!GAME.drewNameInput) { var div = document.getElementById("id-name-input-div"); var str = '<span class="inp-field-left" style="position:absolute;left:500px;top:225px;width:1000px;">'; str += 'Name: '; str += '<input type="text" id="id-name-input"/>'; str += '<input type="submit" value="Submit" onClick="GAME.submitHighScore();"/>'; str += '</span>'; div.innerHTML = str; GAME.drewNameInput = true; } } else if (GAME.paused) { GAME.context.fillStyle = "rgb(200, 0, 0)"; GAME.context.font = '70px sans-serif'; GAME.context.fillText("Paused", GAME.canvas.width / 2 - 90, GAME.canvas.height / 2); } } function drawBoard() { for (var i = 0; i < GAME.width; i++) { for (var j = 0; j < GAME.height; j++) { GAME.context.fillStyle = getColor(GAME.grid[i][j]); GAME.context.fillRect(i * GAME.blocksize, j * GAME.blocksize, GAME.blocksize, GAME.blocksize); } } } function drawPending() { var basex = GAME.blocksize * GAME.width + GAME.blocksize * 2; var basey = GAME.blocksize * 2; GAME.context.fillStyle = getColor(0); GAME.context.font = '15px sans-serif'; GAME.context.fillText("Next block:", basex, GAME.blocksize * 1.5); var temp = [{ x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 }]; var minx = 100; var miny = 100; for (var i = 0; i < 4; i++) { temp[i].x = GAME.pending_block.chunks[i].x; temp[i].y = GAME.pending_block.chunks[i].y; var b = temp[i]; if (b.x < minx) minx = b.x; if (b.y < miny) miny = b.y; } while (minx > 0) { minx--; for (var i = 0; i < 4; i++) { temp[i].x--; } } while (minx < 0) { minx++; for (var i = 0; i < 4; i++) { temp[i].x++; } } while (miny > 0) { miny--; for (var i = 0; i < 4; i++) { temp[i].y--; } } while (miny < 0) { miny++; for (var i = 0; i < 4; i++) { temp[i].y++; } } GAME.context.fillStyle = getColor(GAME.pending_block.color); for (var i = 0; i < 4; i++) { var b = temp[i]; GAME.context.fillRect(basex + b.x * GAME.blocksize, basey + b.y * GAME.blocksize, GAME.blocksize, GAME.blocksize); } } function drawParticles(delta) { if (GAME.particles.length > 0) { GAME.sweeptimer += delta; for (var i = 0; i < GAME.particles.length; i++) { GAME.particle_timers[i] += delta; if (GAME.particle_timers[i] < 3000) { var p = GAME.particles[i]; if (GAME.sweeptimer < GAME.sweeptime) { fire.setCenter({ x: (GAME.sweeptimer / GAME.sweeptime) * GAME.blocksize * GAME.width, y: GAME.blocksize / 2 + p * GAME.blocksize }); fire.create(); fire.create(); fire.create(); fire.create(); } } } fire.update(delta / 1000); fire.render(); if (fire.isEmpty()) { GAME.sweeptimer = 0; GAME.particles = []; GAME.particle_timers = []; } } } function drawScore() { var basex = GAME.blocksize * GAME.width + GAME.blocksize * 2; var basey = GAME.blocksize * 7; GAME.context.font = '15px sans-serif'; GAME.context.fillStyle = getColor(0); GAME.context.fillText("Level: " + GAME.level, basex, basey); GAME.context.fillText("Rows cleared: " + GAME.lines_cleared, basex, basey + 30); GAME.context.fillText("Score: " + GAME.score, basex, basey + 60); } function getColor(b) { switch (b) { case 0: return "rgb(50,50,50)"; case 1: return "rgb(255,0,0)"; case 2: return "rgb(255,0,255)"; case 3: return "rgb(255,255,0)"; case 4: return "rgb(0,255,255)"; case 5: return "rgb(0,0,255)"; case 6: return "rgb(200,200,200)"; case 7: return "rgb(0,255,0)"; } } function makeNewBlock() { var block = generateRandomBlock(); moveIntoBoundsHoriz(block); moveIntoBoundsVert(block); var temp = []; var hit = false; for (var i = 0; i < 4; i++) { if (block.chunks[i].y == 0) { temp[temp.length] = block.chunks[i]; if (GAME.grid[block.chunks[i].x][block.chunks[i].y] != 0) { hit = true; } } } var trycount = 0; var can_make = true; var dir = ((random(2) - 1 == 0) ? 1 : -1); if (hit) { for (var t = 0; t < GAME.width; t++) { for (var i = 0; i < temp.length; i++) { if (GAME.grid[temp[i].x][temp[i].y] != 0) { for (var j = 0; j < 4; j++) { block.chunks[j].x++; if (block.chunks[j].x >= GAME.width) { for (var k = j; k >= 0; k--) { block.chunks[k].x--; } for (var k = 0; k < 4; k++) { block.chunks[k].x -= GAME.width; } moveIntoBoundsHoriz(block); j = 4; } } trycount++; i = temp.length; if (trycount >= GAME.width - 1) { can_make = false; } } } } } if (can_make) { GAME.pending_block = block; } else { GAME.over = true; GAME.pauseSound("theme"); GAME.playSound("SFX_GameOver"); } } GAME.submitHighScore = function() { var name = document.getElementById("id-name-input").value; if (name == "") { name = "Anonymous"; } var score = GAME.score; console.log("Submitting score"); $.ajax({ url: 'http://localhost:3000/v1/high-scores?name=' + name + '&score=' + score, type: 'POST', error: function() { alert('POST failed'); }, success: function() { document.location.href = "../"; } }); } function fall(block) { if (canMoveDown(block)) { removeBlockFromGrid(block); moveDown(block, 1); placeBlockOnGrid(block); return true; } return false; } function checkForClears() { var rows = []; var clearcount = 0; for (var i = GAME.height - 1; i >= 0; i--) { var hasBlock = false; var blockCount = 0; for (var j = 0; j < GAME.width; j++) { if (GAME.ground[j][i] == 1) { hasBlock = true; blockCount++; } } if (!hasBlock) { break; } if (blockCount == GAME.width) { GAME.sweeptimer = 0; rows[clearcount++] = i; GAME.lines_cleared++; } } if (clearcount > 0) { var add = 0; switch (clearcount) { case 1: add = 40 * GAME.level; GAME.playSound("SFX_SpecialLineClearSingle"); break; case 2: add = 100 * GAME.level; GAME.playSound("SFX_SpecialLineClearDouble"); break; case 3: add = 300 * GAME.level; GAME.playSound("SFX_SpecialLineClearTriple"); break; case 4: add = 1200 * GAME.level; GAME.playSound("SFX_SpecialLineClearTriple"); break; } GAME.score += add; for (var i = 0; i < clearcount; i++) { clearRow(rows[i] + i); GAME.particles[GAME.particles.length] = rows[i]; GAME.particle_timers[GAME.particle_timers.length] = 0; } } } function clearRow(r) { for (var i = 0; i < GAME.width; i++) { GAME.ground[i][r] = 0; GAME.grid[i][r] = 0; } dropGround(r - 1); } function dropGround(r) { var hit = false; for (var y = r; y >= 0; y--) { for (var x = 0; x < GAME.width; x++) { if (GAME.ground[x][y] == 1) { if (y < GAME.height - 1) { GAME.grid[x][y + 1] = GAME.grid[x][y]; GAME.ground[x][y + 1] = 1; } GAME.grid[x][y] = 0; GAME.ground[x][y] = 0; if (!hit) { y++; hit = true; } } } } } function canMoveDown(block) { var ret = true; for (var i = 0; i < 4; i++) { var b = block.chunks[i]; var x = b.x; var y = b.y; if (isOnGround(x, y)) { ret = false; break; } } return ret; } function canMoveHoriz(block, dist) { if (dist == 0) return true; if (dist < 0) { for (var i = 0; i < 4; i++) { if (block.chunks[i].x == 0) { return false; } } } else { for (var i = 0; i < 4; i++) { if (block.chunks[i].x == GAME.width - 1) { return false; } } } return true; } function moveDown(block, dist) { if (dist > 0) { while (dist-- > 0) { for (var i = 0; i < 4; i++) { block.chunks[i].y++; } } } } function move(block, dist) { while (dist != 0) { if (canMoveHoriz(block, dist)) { for (var i = 0; i < 4; i++) { block.chunks[i].x += dist; } } if (dist < 0) dist++; else dist--; } } function addToGround(b) { var c = GAME.blocks[b]; for (var i = 0; i < 4; i++) { var chunk = c.chunks[i]; GAME.ground[chunk.x][chunk.y] = 1; } GAME.blocks.splice(b, 1); } function hardDrop(block) { while (canMoveDown(block)) { removeBlockFromGrid(block); moveDown(block, 1); placeBlockOnGrid(block); } } function moveIntoBoundsHoriz(block) { var c = block.chunks; var min = GAME.width; var max = -5; for (var i = 0; i < 4; i++) { if (c[i].x < min) { min = c[i].x; } if (c[i].x > max) { max = c[i].x; } } if (min < 0) { for (var j = min; j < 0; j++) { for (var i = 0; i < 4; i++) { c[i].x++; } } } else if (max > GAME.width - 1) { var diff = max - (GAME.width - 1); for (var j = 0; j < diff; j++) { for (var i = 0; i < 4; i++) { c[i].x--; } } } } function moveIntoBoundsVert(block) { var c = block.chunks; var min = 1; var max = -5; for (var i = 0; i < 4; i++) { if (c[i].y < min) { min = c[i].y; } if (c[i].y > max) { max = c[i].y; } } if (max > 0) { for (var j = 0; j < max; j++) { for (var i = 0; i < 4; i++) { c[i].y--; } } } else if (min < -3) { var diff = min + 3; for (var j = 0; j > diff; j--) { for (var i = 0; i < 4; i++) { c[i].y++; } } } } function removeBlockFromGrid(block) { for (var i = 0; i < 4; i++) { var b = block.chunks[i]; var x = b.x; var y = b.y; if (isInBounds(x, y)) { GAME.grid[x][y] = 0; } } } function placeBlockOnGrid(block) { for (var i = 0; i < 4; i++) { var b = block.chunks[i]; var x = b.x; var y = b.y; if (isInBounds(x, y)) { GAME.grid[x][y] = block.color; } } } function rotateCounterClockwise(block) { rotateClockwise(block); rotateClockwise(block); rotateClockwise(block); } function isInBounds(x, y) { return x >= 0 && x < GAME.width && y < GAME.height; } function isOnGround(x, y) { if (y < -1) { return false; } if (y >= GAME.height - 1) { return true; } return GAME.ground[x][y + 1] == 1; } function rotateClockwise(block) { var c = block.chunks; var d = [{ x: c[0].x, y: c[0].y }, { x: c[1].x, y: c[1].y }, { x: c[2].x, y: c[2].y }, { x: c[3].x, y: c[3].y }]; switch (block.color) { case 1: { switch (block.dir) { case 0: { d[0].x++; d[0].y--; d[2].x--; d[2].y++; d[3].x -= 2; d[3].y += 2; } break; case 1: { d[0].x--; d[0].y++; d[2].x++; d[2].y--; d[3].x += 2; d[3].y -= 2; } } } break; case 2: { switch (block.dir) { case 0: { d[0].x++; d[0].y--; d[2].x++; d[2].y++; d[3].x += 2; d[3].y += 2; } break; case 1: { d[0].x++; d[0].y++; d[2].x--; d[2].y++; d[3].x -= 2; d[3].y += 2; } break; case 2: { d[0].x--; d[0].y++; d[2].x--; d[2].y--; d[3].x -= 2; d[3].y -= 2; } break; case 3: { d[0].x--; d[0].y--; d[2].x++; d[2].y--; d[3].x += 2; d[3].y -= 2; } } } break; case 3: { switch (block.dir) { case 0: { d[0].x--; d[0].y++; d[2].x++; d[2].y++; d[3].x += 2; d[3].y += 2; } break; case 1: { d[0].x--; d[0].y--; d[2].x--; d[2].y++; d[3].x -= 2; d[3].y += 2; } break; case 2: { d[0].x++; d[0].y--; d[2].x--; d[2].y--; d[3].x -= 2; d[3].y -= 2; } break; case 3: { d[0].x++; d[0].y++; d[2].x++; d[2].y--; d[3].x += 2; d[3].y -= 2; } } } break; case 5: { switch (block.dir) { case 0: { d[0].x++; d[0].y--; d[2].x++; d[2].y++; d[3].y += 2; } break; case 1: { d[0].x--; d[0].y++; d[2].x--; d[2].y--; d[3].y -= 2; } } } break; case 6: { switch (block.dir) { case 0: { d[0].x--; d[0].y--; d[1].x++; d[1].y--; d[3].x--; d[3].y++; } break; case 1: { d[0].x++; d[0].y--; d[1].x++; d[1].y++; d[3].x--; d[3].y--; } break; case 2: { d[0].x++; d[0].y++; d[1].x--; d[1].y++; d[3].x++; d[3].y--; } break; case 3: { d[0].x--; d[0].y++; d[1].x--; d[1].y--; d[3].x++; d[3].y++; } } } break; case 7: { switch (block.dir) { case 0: { d[0].x--; d[0].y++; d[2].x++; d[2].y++; d[3].x += 2; } break; case 1: { d[0].x++; d[0].y--; d[2].x--; d[2].y--; d[3].x -= 2; } } } break; } var can_rotate = true; for (var i = 0; i < 4; i++) { var ox = d[i].x; var oy = d[i].y; if (isInBounds(ox, oy) && GAME.grid[ox][oy] != 0) { can_rotate = false; break; } } if (can_rotate) { for (var i = 0; i < 4; i++) { c[i].x = d[i].x; c[i].y = d[i].y; } var co = block.color; block.dir = ++block.dir % ((co == 1 || co == 5 || co == 7) ? 2 : 4); moveIntoBoundsHoriz(block); } } function generateRandomBlock() { var ret = []; var type = random(7); var orientation = random(4) - 1; /* 1 I 2 J 3 L 4 O 5 S 6 T 7 Z */ var len = GAME.width; switch (type) { case 1: //I { ret = { chunks: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 2, y: 0 }, { x: 3, y: 0 }], dir: 0, color: 1 }; move(ret, random(len - 3) - 1); for (var i = 0; i < orientation % 2; i++) { rotateClockwise(ret); } } break; case 2: //J { ret = { chunks: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: -1 }, { x: 1, y: -2 }], dir: 0, color: 2 }; move(ret, random(len - 1) - 1); for (var i = 0; i < orientation; i++) { rotateClockwise(ret); } } break; case 3: //L { ret = { chunks: [{ x: 1, y: 0 }, { x: 0, y: 0 }, { x: 0, y: -1 }, { x: 0, y: -2 }], dir: 0, color: 3 }; move(ret, random(len - 1) - 1); for (var i = 0; i < orientation; i++) { rotateClockwise(ret); } } break; case 4: //O { ret = { chunks: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: -1 }, { x: 0, y: -1 }], dir: 0, color: 4 }; move(ret, random(len - 1) - 1); } break; case 5: //S { ret = { chunks: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: -1 }, { x: 2, y: -1 }], dir: 0, color: 5 }; move(ret, random(len - 2) - 1); for (var i = 0; i < orientation % 2; i++) { rotateClockwise(ret); } } break; case 6: //T { ret = { chunks: [{ x: 1, y: 0 }, { x: 0, y: -1 }, { x: 1, y: -1 }, { x: 2, y: -1 }], dir: 0, color: 6 }; move(ret, random(len - 2) - 1); for (var i = 0; i < orientation; i++) { rotateClockwise(ret); } } break; case 7: //Z { ret = { chunks: [{ x: 2, y: 0 }, { x: 1, y: 0 }, { x: 1, y: -1 }, { x: 0, y: -1 }], dir: 0, color: 7 }; move(ret, random(len - 2) - 1); for (var i = 0; i < orientation % 2; i++) { rotateClockwise(ret); } } } return ret; } requestAnimationFrame(gameLoop); };
const head = Symbol('head'); const tail = Symbol('tail'); const length = Symbol('length'); /** Class representing a List. ***/ class List { /** * Create a List. * @param {...any} el - Elements of the list. */ constructor(...args) { this[length] = 0; this[head] = new ListNode(); this[tail] = null; args.forEach(this.push.bind(this)); } /** * Get the first element of the List. */ get head() { return this[head].getValue(); } /** * Get the tail of the List. * @returns {List} A list made with all elements but first. */ get tail() { return this[tail]; } /** * Get the lenght of the List. */ get length() { return this[length]; } /** * Add an element to the end of List. * @param {any} el - The element to be added. * @return {List} the List itself. */ push(el) { this[length]++; if (this[head].isEmpty()) { this[head] = new ListNode(el); return this; } if (this[tail] === null) { this[tail] = new List(); } return this[tail].push(el); } /** * @callback forEachCallback * @param {any} el - The current element being processed in the List. * @param {number} i - The index of the current element being processed in the List. * @param {List} list - The List that forEach() is being applied to. */ /** * Executes a provided function once per List element. * @param {forEachCallback} cb - Function to execute, takes 3 arguments. * @return {List} the List itself. */ forEach(cb) { let i = 0; for (let el of this) { cb(el, i, this); i++; } return this; } /** * @callback mapCallback * @param {any} el - The current element being processed in the List. * @param {number} i - The index of the current element being processed in the List. * @param {List} list - The List that map() is being applied to. */ /** * The map() method creates a new List with the results of calling a provided function on every element in this List. * @param {mapCallback} cb - Function to execute, takes 3 arguments. * @return {List} the List itself. */ map(cb) { const newList = new List(); this.forEach((el, i, list) => { newList.push(cb(el, i, list)); }); return newList; } /** * @callback filterCallback * @param {any} el - The current element being processed in the List. * @param {number} i - The index of the current element being processed in the List. * @param {List} list - The List that filter() is being applied to. */ /** * The filter() method creates a new List with all elements that pass the test implemented by the provided function. * @param {filterCallback} cb - Function to execute, takes 3 arguments. * @return {List} the List itself. */ filter(cb) { const newList = new List(); this.forEach((el, i, list) => { if (cb(el, i, list)) { newList.push(el); } }); return newList; } /** * @callback reduceCallback * @param {any} previousValue - The value previously returned in the last invocation of the callback, or initialValue, if first invocation. * @param {any} el - The current element being processed in the List. * @param {number} i - The index of the current element being processed in the List. * @param {List} list - The List that filter() is being applied to. */ /** * The reduce() method applies a function against an accumulator and each value of the List (from left-to-right) to reduce it to a single value. * @param {reduceCallback} cb - Function to execute, takes 3 arguments. * @param {any} initialValue - Value to use as the first argument to the first call of the reduceCallback. * @return {List} the List itself. */ reduce(cb, initialValue) { let reduceVal = initialValue; this.forEach((el, i, list) => { reduceVal = cb(reduceVal, el, i, list); }); return reduceVal; } *[Symbol.iterator]() { let list = this; while(list && !list[head].isEmpty()) { yield list[head].getValue(); list = list[tail]; } } /** * Convert the List to an array * @returns {array} */ toArray() { return List.toArray(this); } /** * Convert a List into an array * @param {List} list * @returns {array} */ static toArray(list) { if (list.constructor.name !== 'List') { throw new Error('Expect parameter to be an instance of List'); } let arr = []; list.forEach(el => arr.push(el)); return arr; } /** * Convert an array into a List * @param {arr} arr * @returns {List} */ static fromArray(arr) { if (arr.constructor.name !== 'Array') { throw new Error('Expect parameter to be an instance of Array'); } return new List(...arr); } } class ListNode { constructor(el = null) { this.el = el; } isEmpty() { return this.el === null; } getValue() { return this.el; } } export default List;
import express from 'express' import features from './routes/features.js' const app = express() const PORT = 3000 app.set('view engine', 'pug') app.use(express.static('public')) app.use(express.json()) app.use(express.urlencoded({extended: true})) app.listen(PORT, () => { console.log(`Server is running on port ${PORT}...`) }) app.get('/', (req, res) => { res.render('index') }) app.use('/features', features)
import MockAccountService from "./mock/MockAccountService"; const services = { loginService: MockAccountService }; let ServicePlugin = {}; ServicePlugin.install = function (Vue) { Vue.prototype.$services = services; }; export default ServicePlugin;
import React from 'react'; import Table from '@material-ui/core/Table/Table'; import TableRow from '@material-ui/core/TableRow/TableRow'; import TableCell from '@material-ui/core/TableCell/TableCell'; import TableHead from '@material-ui/core/TableHead/TableHead'; import TableBody from '@material-ui/core/TableBody/TableBody'; import Button from '@material-ui/core/Button'; import Paper from '@material-ui/core/Paper/Paper'; import Grid from '@material-ui/core/Grid/Grid'; import Typography from '@material-ui/core/Typography'; import NavLink from 'react-router-dom/NavLink'; import {connect} from "react-redux"; import {testAPICall} from "../reducers"; import compose from 'recompose/compose'; import {withStyles} from '@material-ui/core/styles'; import {GET_ACCOUNTS, GET_ALERTS, GET_CUSTOMERS, GET_TODOS, GET_USERS} from "../actions"; import Tooltip from "@material-ui/core/Tooltip/Tooltip"; import Fab from "@material-ui/core/Fab"; import AddIcon from '@material-ui/icons/Add'; import AddAccount from './addAccount'; const styles = theme => ({ root: { flexGrow: 1, height: 250, }, container: { flexGrow: 1, position: 'relative', }, paper: { padding: theme.spacing.unit * 2, textAlign: 'center', color: theme.palette.text.secondary, }, chip: { margin: `${theme.spacing.unit / 2}px ${theme.spacing.unit / 4}px`, }, inputRoot: { flexWrap: 'wrap', }, divider: { height: theme.spacing.unit * 2, }, rightIcon: { marginLeft: theme.spacing.unit, }, button: { margin: theme.spacing.unit / 2, }, suggestionsContainerOpen: { position: 'absolute', marginTop: theme.spacing.unit, marginBottom: theme.spacing.unit * 3, left: 0, right: 0, }, fab: { position: 'fixed', bottom: theme.spacing.unit * 2, right: theme.spacing.unit * 2, }, suggestion: { display: 'block' }, suggestionsList: { margin: 0, padding: 0, listStyleType: 'none' }, spacingDiv: { height: 1 * theme.spacing.unit, } }); class Accounts extends React.Component { state = { dialogOpen: false, }; handleClickOpen = () => { this.setState({ dialogOpen: true, }); }; handleClose = () => { this.setState({dialogOpen: false}); }; componentWillMount() { const {dispatch} = this.props; dispatch(testAPICall(`/api/v1/accounts/account/`, GET_ACCOUNTS)); dispatch(testAPICall(`/api/v1/auth/user/`, GET_USERS)); dispatch(testAPICall(`/api/v1/accounts/customer/`, GET_CUSTOMERS)); dispatch(testAPICall(`/api/v1/accounts/alert/`, GET_ALERTS)); dispatch(testAPICall(`/api/v1/accounts/todo/`, GET_TODOS)); } render() { const {accounts, alerts, toDos, customers, users, isSuperUser, classes} = this.props; return ( <div> <Grid container spacing={24}> <Grid item xs={12}> <Paper className={classes.paper}> <Typography variant="h4"> Accounts </Typography> </Paper> <div className={classes.spacingDiv}/> <Paper style={{maxWidth: '100%', overflowX: 'auto'}}> <Table> <TableHead> <TableRow> <TableCell> Name </TableCell> <TableCell> Customer </TableCell> <TableCell> Assignee </TableCell> <TableCell> Active Alerts </TableCell> <TableCell> Active To Dos </TableCell> </TableRow> </TableHead> <TableBody> {Object.keys(accounts).map(key => { const assignedUsers = accounts[key].assigned_users; let assigneeNames; if (Object.keys(users).length === 0) { assigneeNames = []; } else { assigneeNames = assignedUsers.map(assignee => { return `${users[assignee].first_name} ${users[assignee].last_name}`; }); } let assigneeNamesString = assigneeNames.join(", "); const customer = customers[accounts[key].customer]; let customerName; let customerId; if (customer === undefined) { customerName = ""; } else { customerName = customer.name; customerId = customer.id; } let alertCount = 0; Object.keys(alerts).forEach((value) => { if (String(alerts[value].account) === String(key)) { alertCount++; } }); let toDoCount = 0; Object.keys(toDos).forEach((value) => { if (String(toDos[value].account) === String(key)) { toDoCount++; } }); return ( <TableRow key={key}> <TableCell> <Button style={{ textTransform: 'inherit', font: 'inherit', textAlign: 'left', paddingLeft: 0, }} component={NavLink} to={`/accounts/${key}`}> {accounts[key].name} </Button> </TableCell> <TableCell> {isSuperUser && customerId !== undefined && ( <Button style={{ textTransform: 'inherit', font: 'inherit', textAlign: 'left', paddingLeft: 0, }} component={NavLink} to={`/customers/${customerId}`}> {customerName} </Button> )} {!isSuperUser && ( customerName )} </TableCell> <TableCell> {assigneeNamesString} </TableCell> <TableCell> {alertCount} </TableCell> <TableCell> {toDoCount} </TableCell> </TableRow> )})} </TableBody> </Table> </Paper> </Grid> </Grid> <Tooltip title="Add Account" placement="left"> <Fab onClick={this.handleClickOpen} className={classes.fab} color="secondary" > <AddIcon/> </Fab> </Tooltip> <AddAccount open={this.state.dialogOpen} onClose={this.handleClose} /> </div> ); } } const mapStateToProps = state => { return { isSuperUser: state.auth.isSuperUser, accounts: state.accounts.accounts, users: state.authentication.users, customers: state.accounts.customers, alerts: state.accounts.alerts, toDos: state.accounts.toDos, }; }; const mapDispatchToProps = dispatch => { return { dispatch: dispatch } }; export default compose( withStyles(styles), connect(mapStateToProps, mapDispatchToProps) )(Accounts)
var darkMode = document.querySelector("input") var body = document.querySelector("body") var agris = document.querySelectorAll(".agris") var ablanco = document.querySelectorAll("div .ablanco") var bgDark = document.querySelectorAll(".bgcards") var numGrande = document.querySelectorAll(".numGrande") var colorBordeDark = document.querySelectorAll(".colorBorde") darkMode.addEventListener("click", function(){ body.classList.toggle("body"); for(i=0;i < colorBordeDark.length; i++ ){ colorBordeDark[i].classList.toggle("colorBordeDark");} for(i=0;i < agris.length; i++ ){ agris[i].classList.toggle("gris");} for(i=0;i < ablanco.length; i++ ){ ablanco[i].classList.toggle("blanco1"); } for(i = 0 ; i < bgDark.length ; i++){ bgDark[i].classList.toggle("bgdark") } })
var mongoose = require('mongoose'); const mongoError = require('./MongoHelper'); var Schema = mongoose.Schema; mongoose.Promise = global.Promise; var MatchDataSchema = new Schema({ matchNumber: Number, teamNumber: Number, tournament: String, value: Number, cubesAcquired : Number, cubesScored : Number, startingPos : String, mobility : Boolean, autoPyramid : Number, autoGround : Number, autoCubePickup : Number, //a autoExchangeAttempt : Number, autoExchangeScored : Number, autoSwitchFarAttempt : Number, autoSwitchFarScored : Number, autoSwitchNearAttempt : Number, autoSwitchNearScored : Number, autoScaleFarAttempt : Number, autoScaleFarScored : Number, autoScaleNearAttempt : Number, autoScaleNearScored : Number, autoCubeAttempt : Number, //a autoCubeScored : Number, //a autoRobotAction : Object, ownSwitchFarAttempt : Number, ownSwitchFarScored : Number, ownSwitchNearAttempt : Number, ownSwitchNearScored : Number, scaleFarAttempt : Number, scaleFarScored : Number, scaleNearAttempt : Number, scaleNearScored : Number, oppSwitchFarAttempt : Number, oppSwitchFarScored : Number, oppSwitchNearAttempt : Number, oppSwitchNearScored : Number, teleExchangeAttempt : Number, teleExchangeScored : Number, teleSwitchAttempt : Number, teleSwitchScored : Number, teleScaleAttempt : Number, teleScaleScored : Number, teleOppSwitchAttempt : Number, teleOppSwitchScored : Number, telePickup : {1: Number, 2: Number, 3: Number, 4 : Number, humanLoadNear: Number, humanLoadFar: Number}, teleCubePickup : Number, teleCubeAttempt : Number, teleCubeScored : Number, teleRobotAction : Object, park : Boolean, carried : Boolean, hangAttempt : Boolean, hangSuccess : Boolean, noCarried : Number, comments : String, /* all of the data */ }); MatchDataSchema.statics.saveOne = async function(matchData){ console.log(matchData); return await this.findOneAndUpdate( {matchNumber: matchData.matchNumber, teamNumber: matchData.teamNumber}, matchData, {upsert: true}) .exec().catch(mongoError) } MatchDataSchema.statics.getMatchData = async function(matchNumber, teamNumber) { return await this.findOne() .where('matchNumber').equals(matchNumber) .where('teamNumber').equals(teamNumber) .exec().catch(mongoError) } MatchDataSchema.statics.getMatch = async function(matchNumber) { return await this.find() .where('matchNumber').equals(matchNumber) .exec().catch(mongoError) } MatchDataSchema.statics.getTeam = async function(teamNumber) { return await this.find() .where('teamNumber').equals(teamNumber) .exec().catch(mongoError) } MatchDataSchema.statics.getTeams = async function(teams) { return await this.find({ teamNumber: { $in: teams } } ) .exec().catch(mongoError) } const MatchData = mongoose.model('MatchData', MatchDataSchema, 'MatchDatas'); module.exports = MatchData;
import React, { useEffect } from 'react' import '../app/App.css'; import { Route, Switch } from 'react-router-dom' import SignUp from '../components/SignUp' import SignIn from '../components/SignIn' import Home from '../components/Home' import Introduction from '../components/Introduction' import { useDispatch } from 'react-redux' import { signInAction } from '../redux/action/userAction' import UserLayout from '../layout/UserLayout' import LectureLayout from '../layout/LectureLayout' import ProfileLayout from '../layout/ProfileLayout' import HomeworkLayout from '../layout/HomeworkLayout' import ProfileInform from '../components/ProfileInform' import ProfileChangePassword from '../components/ProfileChangePassword' import Compiler from '../components/Compiler' import TestLayout from '../layout/TestLayout' import CheckCode from '../components/CheckCode' import Translate from '../components/Translate' import Lecture from '../components/Lecture' import HomeworkStudents from '../components/HomeworkStudents' import Bang from '../components/Bang' import UserAuth from '../components/UserAuth' import TableOfStudents from '../components/TableOfStudents' import TableOfLecture from '../components/TableOfLecture' import HomeworkTeacher from '../components/HomeworkTeacher' import TableMark from '../components/TableMark' import TableOfHomework from '../components/TableOfHomework' import GPA from '../components/GPA' import CountDownTime from '../components/CountDownTime' import Homework from '../components/Homework' import HomeworkSubmit from '../components/HomeworkSubmit' function App() { const dispatch = useDispatch() useEffect(() => { const userInform = JSON.parse(localStorage.getItem('user')) if(userInform) { dispatch(signInAction(userInform)) } },[]) return ( <Switch> <Route path="/signin" component={SignIn} /> <Route path="/signup" component={SignUp} /> <UserLayout path="/"> <Switch> <Route exact path="/" component={Home} /> <Route path="/gpa" component={GPA} /> <Route path="/homeworkteacher" component={HomeworkTeacher} /> <UserAuth path="/tableoflecture" component={TableOfLecture} /> <UserAuth path="/tableofhomework" component={TableOfHomework} /> <UserAuth path="/tablemark" component={TableMark} /> <Route path="/mustsignin" component={Bang} /> <Route path="/introduction" component={Introduction} /> <UserAuth path="/compiler" component={Compiler} /> <UserAuth path="/translate" component={Translate} /> <Route path="/mustsignin" component={Bang} /> <ProfileLayout path="/profile"> <Switch> <UserAuth path="/profile/:ID/Inform" component={ProfileInform} /> <UserAuth path="/profile/:ID/changepassword" component={ProfileChangePassword} /> </Switch> </ProfileLayout> <TestLayout path="/checkcode"> <Switch> <UserAuth path="/checkcode/test:ID" component={CheckCode} /> </Switch> </TestLayout> <HomeworkLayout path="/homework"> <UserAuth path="/homework/test:ID" component={Homework} /> <UserAuth path="/homework/table:ID" component={HomeworkSubmit} /> </HomeworkLayout> <LectureLayout path="/studyc"> <UserAuth path="/studyc/lecture" component={Lecture} /> </LectureLayout> </Switch> </UserLayout> </Switch> ); } export default App;
alert('Welcome to Anime World'); let ask=confirm('Are you sure you want to enter the anime world'); if (ask==true) { x=" smart choice"; let animename=prompt('What is your favorite anime scene :'); let animecharacter=prompt('If you could meet an anime character who would it be?'); let soundtrack=prompt('What is your favorite anime soundtrack?'); let thing =prompt ('What is your favorite thing about anime?'); alert ('this is one'+animename+'of my favorite anime \n i guess ,me too! i which to meet'+animecharacter+'and every single character have own fascination,\n'+soundtrack+'maybe i dont know this sound track but cause its your favourite it will be mine too ;),\n I know its hard to tell one thing why you like the anime but'+thing+'its perfect'); } else{ x=" You lose a lot " } alert(x);
//document.querySelector shortcut const getElement = (attrValue) => { return document.querySelector(attrValue); } const $form = getElement('.form'); const $userList = getElement('.user-list'); const $nameField = getElement('#name'); const $phoneField = getElement('#phone'); const newElement = (tag, attributes) => { const element = document.createElement(tag); for (attr in attributes) { element.setAttribute(attr, attributes[attr]); } return element; } const deleteUserEnabled = (userList, classOfDeleteButton) => { userList.addEventListener('click', function (e) { const target = e.target if (target.className == classOfDeleteButton ) { const li = target.parentElement; userList.removeChild(li); } }) } const AddingUserEnabled = () => { $form.addEventListener('submit', function (e) { e.preventDefault(); const newUserField = newElement('li', {class: 'user'}); const newUserDetails = newElement('div', {class: 'user-data'}); const newUserName = newElement('div', {class: 'user-name'}); const newUserPhone = newElement('div', {class: 'user-phone'}); const deleteUserButton = newElement('button', {class: 'btn user-delete'}); newUserName.innerText = $nameField.value; newUserPhone.innerText = $phoneField.value; $userList.appendChild(newUserField); newUserField.appendChild(newUserDetails); newUserDetails.appendChild(newUserName); newUserDetails.appendChild(newUserPhone); newUserField.appendChild(deleteUserButton); }) } AddingUserEnabled(); deleteUserEnabled($userList, 'btn user-delete');
// Customer list card Component window.$Qmatic.components.card.CustomerListCardComponent = function (selector) { // @Override this.onInit = function (selector) { if(selector) { window.$Qmatic.components.card.CardBaseComponent.prototype.onInit.call(this, selector); this.hide(); } } this.show = function () { window.$Qmatic.components.card.CustomerListCardComponent.prototype.show.call(this); customer.populateAdditionalCustomersList(); } // @Override this.cleanUp = function () { window.$Qmatic.components.card.CardBaseComponent.prototype.cleanUp.call(this); } this.onInit.apply(this, arguments); } window.$Qmatic.components.card.CustomerListCardComponent.prototype = new window.$Qmatic.components.card.CardBaseComponent() window.$Qmatic.components.card.CustomerListCardComponent.prototype.constructor = window.$Qmatic.components.card.CustomerListCardComponent;
import React,{useState, useEffect} from "react"; import "./styles/output.css"; const App=(props)=> { const FONTSIZEARRAY = ['xs','sm','base','lg','xl','2xl','3xl','4xl','5xl','6xl','7xl','8xl','9xl']; const ALPHABET = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]; let interval; const fontSizeLength= FONTSIZEARRAY.length; const [sliderValue, setSliderValue]= useState(fontSizeLength-1); const [fontSize, setFontSize]= useState(FONTSIZEARRAY[fontSizeLength-1]); const [timerSpeed, setTimerSpeed]= useState(10); const [timer, setTimer]= useState(10); const [displaChar, setDisplayChar]= useState(ALPHABET[0]); const [gameDuration, setGameDuration]= useState(10); const randomChar= (max=ALPHABET.length)=> Math.floor(Math.random() * (max-1)); useEffect(() => { window.clearInterval(interval); if(timer>0){interval = window.setInterval(() => { setTimer(timer-1); }, timerSpeed*100);} else{ setTimer(10); } return () => { clearInterval(interval); }; }, [timer]); const handleFontChange=(event,b)=>{ const {value}= event.target; console.log("---------", randomChar()); setSliderValue(value); setFontSize(FONTSIZEARRAY[value]); // slideValue=slideValue+1; } const handleTimerSpeedChange=(event,b)=>{ const {value}= event.target; setTimerSpeed(value); } const handleDurationChange=(event,b)=>{ const {value}= event.target; setGameDuration(value); } // const setFontSize=()= return ( <div className="bg-gray-900 p-20 h-screen flex justify-center items-start flex-col"> <h1 className={`text-${fontSize} text-white`}>A</h1> <p className={'text-gray-400 mt-5 text-lg'}> Font Size </p> <input type="range" min="0" max="12" value={sliderValue} onChange={handleFontChange}/> <p className={'text-gray-400 mt-5 text-lg'}> Game Speed </p> <input type="range" min="1" max="10" value={timerSpeed} onChange={handleTimerSpeedChange}/> <p className={'text-gray-400 mt-5 text-lg'}> Game Duration : {gameDuration} </p> <input type="range" min="10" max="300" value={gameDuration} onChange={handleDurationChange}/> <p className={'text-gray-400 mt-5 text-xl'}> Time: </p> <p className={'text-gray-400 mt-5 text-9xl'}> {timer} </p> <button className="p-4 bg-green-600 rounded-lg font-bold text-white mt-5 hover:bg-gray-600"> Start </button> </div> ); } export default App;
import React from 'react' import './achievements.css' import Separator from '../../common/separator/index' import AchievemntsData from '../../data/achievements' function Achievements() { const data = AchievemntsData; return ( <div className="achievements"> <Separator /> <label className="section-title">Achievements</label> <div className="achievement-section"> <img src={require("../../../images/achievement.png").default} className="achievement-image"/> <ul className="achievement-list"> {data.map((item) => { return ( <li> <div className="achievement-list-item"> <p className="achievement-text">{item.achievement}</p> {item.certificate && <a href={item.certificate} className="achievement-certificate-button" target="_blank">certificate</a>} </div> </li> ) })} </ul> </div> </div> ) } export default Achievements
// Copyright 2012 Dmitry Monin. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Tooltip Action Component. */ goog.provide('morning.ui.TooltipAction'); goog.require('goog.ui.Component'); /** * Tooltip Action Component * * @constructor * @param {string} text * @param {string} name * @param {boolean} isPrimary * @extends {goog.ui.Component} */ morning.ui.TooltipAction = function(text, name, isPrimary) { goog.base(this); /** * Action text * * @type {string} * @private */ this.text_ = text; /** * Action name * * @type {string} */ this.name = name; /** * Is Primary Action? * * @type {boolean} */ this.isPrimary = isPrimary; }; goog.inherits(morning.ui.TooltipAction, goog.ui.Component); /** @inheritDoc */ morning.ui.TooltipAction.prototype.createDom = function() { var domHelper = this.getDomHelper(); var el = domHelper.createDom('span', 'tooltip-action', this.text_); if (this.isPrimary) { goog.dom.classlist.add(el, 'primary'); } this.decorateInternal(el); }; /** @inheritDoc */ morning.ui.TooltipAction.prototype.enterDocument = function() { goog.base(this, 'enterDocument'); this.getHandler().listen(this.getElement(), goog.events.EventType.CLICK, this.handleClick_); }; /** * Handles click event * * @param {goog.events.Event} e * @private */ morning.ui.TooltipAction.prototype.handleClick_ = function(e) { this.dispatchEvent(goog.ui.Component.EventType.ACTION); };
// Main viewmodel class define(['knockout', 'personViewModel', 'itemsViewModel'], function(ko, PersonViewModel, ItemsViewModel) { return function appViewModel() { var self = this; //initialize just one PersonViewModel and one ItemsViewModel self.personViewModel = new PersonViewModel(); self.itemsViewModel = new ItemsViewModel(); //switcher mechanism: self.person = ko.observable(self.personViewModel); //initialize with this self.items = ko.observable(null); self.showItemsEnabled = ko.observable(true); self.showPersonEnabled = ko.observable(false); self.reset = function(){ self.personViewModel = new PersonViewModel(); self.itemsViewModel = new ItemsViewModel(); self.showPerson(); } self.showItems = function(){ self.person(null); self.items(self.itemsViewModel); self.showItemsEnabled(false); self.showPersonEnabled(true); } self.showPerson = function(){ self.person(self.personViewModel); self.items(null); self.showItemsEnabled(true); self.showPersonEnabled(false); } }; });
import React, { PureComponent } from "react"; import PropTypes from "prop-types"; import "./Board.css"; import Cell from "./Cell"; import "./Board.css"; const cellColors = { unexplored: (10, 245, 22), exploredEmpty: (255, 8, 82), exploredOccupied: (255, 255, 255) }; export class Board extends PureComponent { createUIBoard() { var boardsize = this.props.board.length; var UIBoard = []; for (var i = 0; i < boardsize; i++) { UIBoard.push([<div />]); for (var j = 0; j < boardsize; j++) { UIBoard.push( <Cell parentBoard={this.props.board} uiBoard={UIBoard} position={[i, j]} /> ); } } return UIBoard; } render() { return <div>{this.createUIBoard()}</div>; } } export default Board;
const button = document.querySelector(".btn-btn") const input = document.querySelector("input") const list = document.querySelector(".list") button.addEventListener("click", function () { const text = input.value const item = document.createElement("li") item.innerHTML = text item.addEventListener("click", function () { item.style.color = "white" item.style.textDecoration = "line-through" }) list.append(item) input.value = "" }) ///////////////////////////////////
// Il programma chiede all’utente il numero di chilometri che vuole // percorrere e l’età del passeggero. var chilometri = parseInt(prompt("Quanti chilometri vuoi percorrere?")); var eta = parseInt(prompt("Quanti anni hai?")); // Il prezzo del biglietto è definito in base ai km (0.21 € al km) var prezzoBase = 0.21; var prezzoTratta= prezzoBase * chilometri; var euro = " €"; // controllo che le risposte siano inserite in maniera corretta if( isNaN(chilometri) || isNaN(eta)) { document.getElementById("avvertenza").innerHTML= "Attenzione, non hai inserito le risposte in modo corretto"; } else { // va applicato uno sconto del 20% per i minorenni e del 40% per gli over 65. if (eta < 18) { var prezzoTratta20 = prezzoTratta - prezzoTratta * (20 / 100); document.getElementById('prezzo').innerHTML = "Il tuo biglietto costa " + prezzoTratta20.toFixed(2) + euro; } else if (eta > 65) { var prezzoTratta40 = prezzoTratta - prezzoTratta * (40 / 100); document.getElementById('prezzo').innerHTML = "Il tuo biglietto costa " + prezzoTratta40.toFixed(2) + euro; } else{ prezzoTratta; document.getElementById('prezzo').innerHTML = "Il tuo biglietto costa " + prezzoTratta + euro; } }
angular.module('influences') .controller('mainCtrl', function(genreList) { this.genreList = genreList });
 //Chang datetime toString & - Num function parseDate(str, num) { var mdy = str.split('/'); return new Date(mdy[2], mdy[1], mdy[0] - num); } //Load Menu Right function loadmenuR(name) { var conRmenu = ""; conRmenu = "<div class='navbar-header'>" + "<div class='navbar-header-menu'>" + "<ul class='nav navbar-nav' style='padding-left: 20px; height: 50px; padding-top: 0px;margin-top: -15px;'>" + "<li style='padding-top: 25px; color: rgb(254, 254, 254);'>" + name + "</li>" + "<li style='padding: 15px;'><a href='#modal_UserInfo' data-toggle='modal'><img class='img_menu' src='/Img/user.png'></a></li>" + "</ul>" + "</div>" + "</div>"; var widthName = $("#idnav").width(); if (widthName < 285) { widthName = 285 } document.getElementById('menuR').innerHTML = conRmenu; if (($(document).width() - $("#idnav").width() - $("#menuR").width()) < 0) { document.getElementById('menuR').innerHTML = ""; } document.querySelector("#idnav").style.left = (($(document).width() - widthName - $("#menuR").width()) / 2).toString() + "px"; document.querySelector("#pwd").style.paddingLeft = ($(document).width() / 2).toString() + "px"; } function ChangePass() { if (!CheckText("old_Password", 1)) { ShowMessConfi('Vui lòng nhập mật khẩu cũ', 4000, 'warning'); return false; } if (!SaveAnything("ajax", "CheckPassword", JSON.stringify({ Zold: $('#old_Password').val() }))) { ShowMessConfi('Mật khẩu cũ không đúng', 4000, 'warning'); return false; } if (!CheckPassWord("new_Password", 8)) { ShowMessConfi('Mật khẩu phải ít nhất 8 ký tự và phải bao gồm chữ thường(a-z),chữ hoa(A-Z) và(0-9)', 4000, 'warning'); return false; } if ($("#old_Password").val() == $("#new_Password").val()) { ShowMessConfi('Mật khẩu mới không được giống mật khẩu cũ', 4000, 'warning'); return false; } // if (!CheckText("new_Password_c", 6)) { ShowMessConfi('Nhập lại mật khẩu phải từ 6 ký tự', 4000, 'warning'); return false; } if ($("#new_Password").val() != $("#new_Password_c").val()) { ShowMessConfi('Chưa trùng khớp với mật khẩu mới', 4000, 'warning'); return false; } ShowSaveConfi("mật khẩu mới"); $(document).ready(function () { $("#SsaveConfi").click(function () { if (!SaveAnything("ajax", "SaveChangePass", JSON.stringify({ Zold: $('#old_Password').val(), Znew: $('#new_Password').val() }))) { ShowMessConfi('Lưu thất bại', 4000, 'success'); return false; } ShowMessConfi('Lưu thành công', 4000, 'success'); $("#old_Password").val(""); $("#new_Password").val(""); $("#new_Password_c").val(""); }); }); } function CheckPassWord(id, num) { var ID = $("#" + id); var reg = /^([a-z])([A-Z])([0-9])*$/; var Checkaz = /^([a-zA-Z0-9])*$/.test(ID.val()); if (ID.val().length < num || ID.val() == null || ID.val() == "" || /^([a-zA-Z0-9])*$/.test(ID.val()) == false || /^([a-z])*$/.test(ID.val()) == true || /^([A-Z])*$/.test(ID.val()) == true || /^([0-9])*$/.test(ID.val()) == true || /^([a-zA-Z])*$/.test(ID.val()) == true || /^([a-z0-9])*$/.test(ID.val()) == true || /^([A-Z0-9])*$/.test(ID.val()) == true) { var div = ID.closest("div"); div.addClass("has-error"); $("#sp-" + id).addClass("glyphicon glyphicon-remove form-control-feedback"); ShowPopover(ID, '', 'Mật khẩu phải ít nhất ' + num + ' ký tự và phải bao gồm chữ thường(a-z),chữ hoa(A-Z) và(0-9)', 'top'); return false; } else { var div = $("#" + id).closest("div"); div.removeClass("has-error"); div.addClass("has-success"); $("#sp-" + id).removeClass("glyphicon glyphicon-remove form-control-feedback"); $("#sp-" + id).addClass("glyphicon glyphicon-ok form-control-feedback"); $("#" + id).popover('hide'); return true; } } function ShowPopover(id, titles, contents, placements) { $(id).popover({ title: titles, content: contents, placement: placements }).popover('show'); } function SaveAnything(book, name, valu) { var result = false; $.ajax( { type: "POST", url: book + ".aspx/" + name, data: valu, contentType: "application/json; charset=utf-8", dataType: "json", async: false, success: function (response) { result = response.d; }, error: function (response) { } }); return result; } function AjaxCall(book, name, valu, callback) { return $.ajax({ type: "POST", url: book + ".aspx/" + name, data: valu, contentType: "application/json; charset=utf-8", dataType: "json", success: callback, error: function (response) { alert("fail"); } }); } function CheckText(id, num) { if ($("#" + id).val().length < num || $("#" + id).val() == null || $("#" + id).val() == "") { var div = $("#" + id).closest("div"); div.addClass("has-error"); $("#sp-" + id).addClass("glyphicon glyphicon-remove form-control-feedback"); return false; } else { var div = $("#" + id).closest("div"); div.removeClass("has-error"); div.addClass("has-success"); $("#sp-" + id).removeClass("glyphicon glyphicon-remove form-control-feedback"); $("#sp-" + id).addClass("glyphicon glyphicon-ok form-control-feedback"); return true; } } function Checkddl(id, num) { if ($("#" + id).val().length < num || $("#" + id).val() == null || $("#" + id).val() == "" || $("#" + id).val() == "0") { var div = $("#" + id).closest("div"); div.addClass("has-error"); $("#sp-" + id).addClass("glyphicon glyphicon-remove form-control-feedback"); return false; } else { var div = $("#" + id).closest("div"); div.removeClass("has-error"); div.addClass("has-success"); $("#sp-" + id).removeClass("glyphicon glyphicon-remove form-control-feedback"); $("#sp-" + id).addClass("glyphicon glyphicon-ok form-control-feedback"); return true; } } //function CheckNum(id) { // $("#" + id).keydown(function (e) { // if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || (e.keyCode == 65 && e.ctrlKey === true) || (e.keyCode >= 35 && e.keyCode <= 40)) { // return; // } // if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) { // e.preventDefault(); // } // }); //} function CheckNum(id) { var rar = $("#" + id).val().replace(" ", ""); var chec = rar.replace("-", ""); var res = chec.replace(",", "."); $("#" + id).val(res); if (res == null || res == "") { var div = $("#" + id).closest("div"); div.addClass("has-error"); $("#sp-" + id).addClass("glyphicon glyphicon-remove form-control-feedback"); return false; } else { if ($.isNumeric(res) == true) { //$("#" + id).val(xugame); var div = $("#" + id).closest("div"); div.removeClass("has-error"); div.addClass("has-success"); $("#sp-" + id).removeClass("glyphicon glyphicon-remove form-control-feedback"); $("#sp-" + id).addClass("glyphicon glyphicon-ok form-control-feedback"); return true; } else { $("#" + id).val('0'); var div = $("#" + id).closest("div"); div.addClass("has-error"); $("#sp-" + id).addClass("glyphicon glyphicon-remove form-control-feedback"); return false; } } } function ShowMess(id, settime) { $('#' + id).modal('show'); setTimeout(function () { $('#' + id).modal('hide'); }, settime); } function ShowMessConfi(val, settime, type) { var con = "<div class='modal-dialog modal-sm'>" + "<div class='modal-content'>" + "<form class='form-horizontal' role='form'>" + "<div class='modal-header modal-header-" + type + "'>" + "<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>&times;</button>" + "<h2 class='modal-title'>Thông Báo</h2>" + "</div>" + "<div class='modal-body' style='margin-bottom: -30px;'>" + "<div class='form-group has-feedback'>" + "<div style='padding: 10px;'><p>" + val + "</p></div>" + "</div>" + "</div>" + "<div class='modal-footer'>" + "<button type='button' class='btn btn-default center-block' data-dismiss='modal'>Đóng</button>" + "</div>" + "</div>" + "</div>"; document.getElementById('MessNew').innerHTML = con; $('#MessNew').modal('show'); setTimeout(function () { $('#MessNew').modal('hide'); }, settime); } function ShowSaveConfi(val) { var con = "<div class='modal-dialog modal-sm'>" + "<div class='modal-content'>" + "<form class='form-horizontal' role='form'>" + "<div class='modal-header modal-header-success'>" + "<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>&times;</button>" + "<h2 class='modal-title'>Thông Báo</h2>" + "</div>" + "<div class='modal-body' style='margin-bottom: -30px;'>" + "<div class='form-group has-feedback'>" + "<div style='padding: 10px;'><p>Bạn có chắc muốn lưu lại " + val + " không ?</p></div>" + "</div>" + "</div>" + "<div class='modal-footer'>" + "<button type='button' id='SsaveConfi' class='btn btn-success' data-dismiss='modal'>Có</button>" + "<button type='button' class='btn btn-default' data-dismiss='modal'>Không</button>" + "</div>" + "</div>" + "</div>"; document.getElementById('MessSave').innerHTML = con; $('#MessSave').modal('show'); } //HTML function Listlb(ddl, type) { var result = ""; var ddlist = ""; for (var i = 0; i < ddl.length; i++) { var DS = ddl[i]; ddlist += "<a href='#' onclick='loadDetaildata(" + DS.Key + ")' class='list-group-item list-group-item-" + type + "'>" + DS.Name + "</a>"; } result = "<div class='list-group'>" + ddlist + "</div>"; return result; } function txtbox(name, id, num, numcheck) { var result = ""; result = "<div class='form-group has-feedback'>" + "<label for='contact-name' class='col-sm-4 control-label'>" + name + "</label>" + "<div class='col-sm-8 has-error'>" + "<input type='number' class='form-control' id='" + id + "' placeholder=''>" + "<span id='sp-" + id + "'></span>" + "</div>" + "</div>" return result; } function DDList(name, id, load) { var result = ""; var ddlist = ""; var ddl = JSON.parse(getList(load)); for (var i = 0; i < ddl.length; i++) { var DS = ddl[i]; ddlist += "<option value='" + DS.Key + "'>" + DS.Name + "</option>" } result = "<div class='form-group has-feedback'>" + "<label for='contact-name' class='col-sm-4 control-label'>" + name + "</label>" + "<div class='col-sm-8 has-error'>" + "<select id='" + id + "' class='selectpicker' data-live-search='true' style='display: none;'data-size='auto' data-width='100%'>" + "<option value='0'>Chọn</option>" + ddlist + "</select>" + "<span id='sp-" + id + "'></span>" + "</div>" + "</div>"; return result; }
import { primaryColor } from "../../assets/jss/mainStyle"; const styles = theme => ({ root: { [theme.breakpoints.down("sm")]: { margin: theme.spacing(3) / 2 }, [theme.breakpoints.up("sm")]: { margin: theme.spacing(3) } }, mainFeaturedPost: { marginBottom: theme.spacing(4) }, card: { backgroundColor: primaryColor, color: "white" }, postTitle: { margin: 12, fontWeight: 700 }, postText: { margin: 12, lineHeight: 1.8 }, cardMedia: { height: 250, }, footer: { textAlign: "center" }, logos: { marginTop: theme.spacing(2), width: "70vw", maxWidth: 600, height: "auto", [theme.breakpoints.up("sm")]: { marginLeft: theme.spacing(7) } } }); export default styles;
import { useState, useEffect } from "react"; import './App.css'; import axios from 'axios'; // import COUNTRIES from './all_countries.json'; // country data in file import { Table } from "./Table.js"; import format from 'number-format.js'; import { Default } from 'react-spinners-css'; export const ALL_REGIONS_SELECTED = "all regions"; export const UNCATEGORIZED_REGION = "uncategorized"; const DEFAULT_HASH = ""; function App() { const [searchStr,setSearchStr] = useState(""); const [selectedRegion,setSelectedRegion] = useState(ALL_REGIONS_SELECTED); const [allCountries,setAllCountries] = useState([]); const [sortBool,setSortBool] = useState(false); const [countryCode,setCountryCode] = useState(undefined); // null = kosovo const [regions,setRegions] = useState([]); const [requestIsPending,setRequestIsPending] = useState(false); useEffect(() => { const fetchData = async () => { setRequestIsPending(true); try { const result = await axios.get('https://restcountries.eu/rest/v2/all', { timeout: 10000 }); setAllCountries(result.data); hashChangeHandler(); } catch (err) { console.error(err); alert("Data fetching failed.\nPlease try again later."); //setAllCountries(COUNTRIES); // <-- backup possibility, use local file setRequestIsPending(false); } setRequestIsPending(false); }; fetchData(); }, []); useEffect(() => { // subscribe to hash changes window.addEventListener("hashchange", hashChangeHandler); return () => window.removeEventListener("hashchange", hashChangeHandler); },[]); useEffect(() => { let regionsSet = new Set(allCountries.map(y => y.subregion)); let regionsArray = Array.from(regionsSet); regionsArray.push(ALL_REGIONS_SELECTED); let indexOfEmptyValue = regionsArray.indexOf(""); regionsArray[indexOfEmptyValue] = UNCATEGORIZED_REGION; regionsArray.sort(); setRegions(regionsArray); },[allCountries]); function hashChangeHandler() { const hash = window.location.hash.replace(/^#/, ""); if(hash !== DEFAULT_HASH) { setCountryCode(hash); } else { setCountryCode(undefined); } } function CountryDetails(props) { if(props.code === undefined) { return null; } let countryData = allCountries.find(x => x.numericCode === props.code); if(countryData === undefined) { console.log("countryData undefined!"); window.location.hash = DEFAULT_HASH; return null; } return ( <div className="countryDetailsBackground" onClick={ props.closeCb }> <div className="countryDetails" onClick={ ev => ev.stopPropagation() }> <img src={countryData.flag} alt={""} width={250} /> <h3> {countryData.name} </h3> <div className="detailsSection"> <div className="detailsSubSection"> <p> capital: </p> <h4> {countryData.capital} </h4> </div> <div className="detailsSubSection"> <p> population: </p> <h4>{format('### ###.',countryData.population)}</h4> </div> </div> <div className="detailsSection"> <div className="detailsSubSection"> <p> languages: </p> {countryData.languages.map( lang => <h4 key={lang.name}>{lang.name}</h4> )} </div> <div className="detailsSubSection"> <p> currencies: </p> {countryData.currencies.map( curr => <h4 key={curr.name}>{curr.name}</h4> )} </div> </div> <button className="button" type="button" onClick={ props.closeCb }> Close </button> </div> </div> ) } function ProgressIndicator(props) { if (!props.visible) { return null; } return ( <div style={{position:"absolute", top:"30%"}}> <Default size={200} color={'white'} /> </div> ); } return ( <div id="mainContainer"> <div className="title"> restcountries.eu API demo </div> <div className="controls"> <div className="control_container"> Search from {selectedRegion} by country name: <div className="control_subcontainer"> <input type="text" value={searchStr} onChange={ev => setSearchStr(ev.target.value)} placeholder="enter country name here" /> <button type="button" className="button" onClick={() => setSearchStr("")} > Clear </button> </div> </div> <div className="control_container"> Show countries by region: <div className="control_subcontainer"> <select value={selectedRegion} onChange={ev => setSelectedRegion(ev.target.value)} > {regions.map( region => <option key={region} value={region}>{region}</option> )} </select> <button type="button" className="button" onClick={() => setSelectedRegion(ALL_REGIONS_SELECTED)} > Reset </button> </div> </div> </div> <div> <Table allCountries={allCountries} setAllCountries={setAllCountries} sortBool={sortBool} setSortBool={setSortBool} searchStr={searchStr} selectedRegion={selectedRegion} /> </div> <CountryDetails code={countryCode} closeCb={() => window.location.hash = DEFAULT_HASH} /> <ProgressIndicator visible={requestIsPending} /> </div> ); } export default App;
function response() { this.errorCode = 0; this.errorMessage = ''; this.result = null; }; response.prototype.code = function(num) { this.errorCode = num; return this; }; response.prototype.message = function(msg) { this.errorMessage = msg; return this; }; response.prototype.results = function(result) { this.result = result; return this; } module.exports = response;
'use strict'; var sendChannel; var constraints = {video: true}; /* **************************************************************** DOM elements **************************************************************** */ var sendTextarea = document.getElementById("dataChannelSend"); var receiveTextarea = document.getElementById("dataChannelReceive"); /* **************************************************************** Boolean checks **************************************************************** */ var isChannelReady; var isInitiator; var isStarted = false; /* **************************************************************** Streaming vars **************************************************************** */ var localStream; var pc; var remoteStream; var ephemeralStream; var turnReady; var localVideo = document.querySelector('#localVideo'); var remoteVideo = document.querySelector('#remoteVideo'); var activeVideo = document.querySelector('#activeVideo'); /* **************************************************************** User info **************************************************************** */ var room = location.pathname.split('/')[2]; /* **************************************************************** Getters **************************************************************** */ function getIsInitiator(){ return isInitiator; } function getIsStarted(){ return isStarted; } function getIsChannelReady(){ return isChannelReady; } function getLocalVideo(){ return localVideo; } function getremoteVideo(){ return remoteVideo; } function getConstraints(){ return constraints; } /* **************************************************************** Setters **************************************************************** */ function setIsInitiator(initiator){ isInitiator = initiator; } function setIsStarted(started){ isStarted = started; } function setIsChannelReady(ready){ isChannelReady = ready; } function setLocalStream(stream){ localStream = stream; } function setConstraints(c){ constraints = c; } /* **************************************************************** Initialization **************************************************************** */ var initConstraints = initializeServerConstraints(); var pc_config = initConstraints[0]; var pc_constraints = initConstraints[1]; var sdpConstraints = initConstraints[2]; // Envoi de message générique, le serveur broadcaste à tout le monde // par défaut (ce sevrait être que dans la salle courante...) // Il est important de regarder dans le code de ce fichier quand on envoit // des messages. function sendMessage(message){ console.log('Sending message: ', message); socket.emit('message', message); } getUserMedia(constraints, handleUserMedia, handleUserMediaError); console.log('Getting user media with constraints', constraints); // On regarde si on a besoin d'un serveur TURN que si on est pas en localhost console.log("hostname : "+location.hostname); if (location.hostname != "localhost" && location.hostname != "127.0.0.1") { requestTurn('https://computeengineondemand.appspot.com/turn?username=41784574&key=4080218913'); } // On démarre peut être l'appel (si on est appelant) que quand on a toutes les // conditons. Si on est l'appelé on n'ouvre que la connexion p2p // isChannelReady = les deux pairs sont dans la même salle virtuelle // via websockets // localStream = on a bien accès à la caméra localement, // !isStarted = on a pas déjà démarré la connexion. // En résumé : on établit la connexion p2p que si on a la caméra et les deux // pairs dans la même salle virtuelle via WebSockets (donc on peut communiquer // via WebSockets par sendMessage()...) function maybeStart() { console.log("MAYBE START"); //if (!isStarted && localStream && isChannelReady) { if (!isStarted){ // Ouverture de la connexion p2p createPeerConnection(); // on donne le flux video local à la connexion p2p. Va provoquer un événement // onAddStream chez l'autre pair. pc.addStream(localStream); console.log("stream add to peer"); // On a démarré, utile pour ne pas démarrer le call plusieurs fois isStarted = true; // Si on est l'appelant on appelle. Si on est pas l'appelant, on ne fait rien. if (isInitiator) { doCall(); } } } window.onbeforeunload = function(e){ sendMessage('bye'); } ///////////////////////////////////////////////////////// function createPeerConnection() { try { // Ouverture de la connexion p2p pc = new RTCPeerConnection(pc_config, pc_constraints); // ecouteur en cas de réception de candidature pc.onicecandidate = handleIceCandidate; console.log('Created RTCPeerConnnection with:\n' + ' config: \'' + JSON.stringify(pc_config) + '\';\n' + ' constraints: \'' + JSON.stringify(pc_constraints) + '\'.'); } catch (e) { console.log('Failed to create PeerConnection, exception: ' + e.message); alert('Cannot create RTCPeerConnection object.'); return; } // Ecouteur appelé quand le pair a enregistré dans la connexion p2p son // stream vidéo. pc.onaddstream = handleRemoteStreamAdded; // Ecouteur appelé quand le pair a retiré le stream vidéo de la connexion p2p pc.onremovestream = handleRemoteStreamRemoved; // Data channel. Si on est l'appelant on ouvre un data channel sur la // connexion p2p if (isInitiator) { try { // Reliable Data Channels not yet supported in Chrome sendChannel = pc.createDataChannel("sendDataChannel", {reliable: false}); // écouteur de message reçus sendChannel.onmessage = handleMessage; trace('Created send data channel'); } catch (e) { alert('Failed to create data channel. ' + 'You need Chrome M25 or later with RtpDataChannel enabled'); trace('createDataChannel() failed with exception: ' + e.message); } // ecouteur appelé quand le data channel est ouvert sendChannel.onopen = handleSendChannelStateChange; // idem quand il est fermé. sendChannel.onclose = handleSendChannelStateChange; } else { // ecouteur appelé quand le pair a enregistré le data channel sur la // connexion p2p pc.ondatachannel = gotReceiveChannel; } } function sendData() { var data = sendTextarea.value; sendChannel.send(data); trace('Sent data: ' + data); } // function closeDataChannels() { // trace('Closing data channels'); // sendChannel.close(); // trace('Closed data channel with label: ' + sendChannel.label); // receiveChannel.close(); // trace('Closed data channel with label: ' + receiveChannel.label); // localPeerConnection.close(); // remotePeerConnection.close(); // localPeerConnection = null; // remotePeerConnection = null; // trace('Closed peer connections'); // startButton.disabled = false; // sendButton.disabled = true; // closeButton.disabled = true; // dataChannelSend.value = ""; // dataChannelReceive.value = ""; // dataChannelSend.disabled = true; // dataChannelSend.placeholder = "Press Start, enter some text, then press Send."; // } // Le data channel est créé par l'appelant. Si on entre dans cet écouteur // C'est qu'on est l'appelé. On se contente de le récupérer via l'événement function gotReceiveChannel(event) { trace('Receive Channel Callback'); sendChannel = event.channel; sendChannel.onmessage = handleMessage; sendChannel.onopen = handleReceiveChannelStateChange; sendChannel.onclose = handleReceiveChannelStateChange; } function handleMessage(event) { trace('Received message: ' + event.data); receiveTextarea.value = event.data; } function handleSendChannelStateChange() { var readyState = sendChannel.readyState; trace('Send channel state is: ' + readyState); enableMessageInterface(readyState == "open"); } function handleReceiveChannelStateChange() { var readyState = sendChannel.readyState; trace('Receive channel state is: ' + readyState); enableMessageInterface(readyState == "open"); } function enableMessageInterface(shouldEnable) { console.log("enableMessageInterface"); if (shouldEnable) { dataChannelSend.disabled = false; dataChannelSend.focus(); dataChannelSend.placeholder = ""; //sendButton.disabled = false; } else { dataChannelSend.disabled = true; //sendButton.disabled = true; } } function handleIceCandidate(event) { // On a recu une candidature, c'est le serveur STUN qui déclenche l'event // quand il a réussi à déterminer le host/port externe. console.log('handleIceCandidate event: ', event); if (event.candidate) { // On envoie cette candidature à tout le monde. sendMessage({ type: 'candidate', label: event.candidate.sdpMLineIndex, id: event.candidate.sdpMid, candidate: event.candidate.candidate}); } else { console.log('End of candidates.'); } } // Exécuté par l'appelant uniquement function doCall() { // M.Buffa : les contraintes et les configurations (SDP) sont encore // supportées différements selon les browsers, et certaines propriétés du // standard officiel ne sont pas encore supportées... bref, c'est encore // un peu le bazar, d'où des traitement bizarres ici par exemple... var constraints = {'optional': [], 'mandatory': {'MozDontOfferDataChannel': true}}; // temporary measure to remove Moz* constraints in Chrome if (webrtcDetectedBrowser === 'chrome') { for (var prop in constraints.mandatory) { if (prop.indexOf('Moz') !== -1) { delete constraints.mandatory[prop]; } } } constraints = mergeConstraints(constraints, sdpConstraints); console.log('Sending offer to peer, with constraints: \n' + ' \'' + JSON.stringify(constraints) + '\'.'); // Envoi de l'offre. Normalement en retour on doit recevoir une "answer" pc.createOffer(setLocalAndSendMessage, null, constraints); } // Exécuté par l'appelé uniquement... function doAnswer() { console.log('Sending answer to peer.'); pc.createAnswer(setLocalAndSendMessage, null, sdpConstraints); } function mergeConstraints(cons1, cons2) { var merged = cons1; for (var name in cons2.mandatory) { merged.mandatory[name] = cons2.mandatory[name]; } merged.optional.concat(cons2.optional); return merged; } // callback de createAnswer et createOffer, ajoute une configuration locale SDP // A la connexion p2p, lors de l'appel de createOffer/answer par un pair. // Envoie aussi la description par WebSocket. Voir le traitement de la réponse // au début du fichier sans socket.on("message" , ...) partie "answer" et "offer" function setLocalAndSendMessage(sessionDescription) { // Set Opus as the preferred codec in SDP if Opus is present. // M.Buffa : là c'est de la tambouille compliquée pour modifier la // configuration SDP pour dire qu'on préfère un codec nommé OPUS (?) sessionDescription.sdp = preferOpus(sessionDescription.sdp); pc.setLocalDescription(sessionDescription); // Envoi par WebSocket sendMessage(sessionDescription); } // regarde si le serveur turn de la configuration de connexion // (pc_config) existe, sinon récupère l'IP/host d'un serveur // renvoyé par le web service computeengineondemand.appspot.com // de google. La requête se fait en Ajax, résultat renvoyé en JSON. function requestTurn(turn_url) { var turnExists = false; for (var i in pc_config.iceServers) { if (pc_config.iceServers[i].url.substr(0, 5) === 'turn:') { turnExists = true; turnReady = true; break; } } if (!turnExists) { console.log('Getting TURN server from ', turn_url); // No TURN server. Get one from computeengineondemand.appspot.com: var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if (xhr.readyState === 4 && xhr.status === 200) { var turnServer = JSON.parse(xhr.responseText); console.log('Got TURN server: ', turnServer); pc_config.iceServers.push({ 'url': 'turn:' + turnServer.username + '@' + turnServer.turn, 'credential': turnServer.password }); turnReady = true; } }; xhr.open('GET', turn_url, true); xhr.setRequestHeader('X-PINGOTHER', 'pingpong'); xhr.setRequestHeader('Content-Type', 'application/xml'); xhr.send(); } } // Ecouteur de onremotestream : permet de voir la vidéo du pair distant dans // l'élément HTML remoteVideo function handleRemoteStreamAdded(event) { console.log('Remote stream added.'); // reattachMediaStream(miniVideo, localVideo); attachMediaStream(remoteVideo, event.stream); remoteStream = event.stream; // waitForRemoteVideo(); } function handleRemoteStreamRemoved(event) { console.log('Remote stream removed. Event: ', event); } // bouton "on raccroche" function hangup() { console.log('Hanging up.'); stop(); sendMessage('bye'); } function handleRemoteHangup() { console.log('Session terminated.'); stop(); isInitiator = false; } // Fermeture de la connexion p2p function stop() { isStarted = false; // isAudioMuted = false; // isVideoMuted = false; pc.close(); pc = null; } /////////////////////////////////////////// // M.Buffa : tambouille pour bidouiller la configuration sdp // pour faire passer le codec OPUS en premier.... // // Set Opus as the default audio codec if it's present. function preferOpus(sdp) { var sdpLines = sdp.split('\r\n'); var mLineIndex; // Search for m line. for (var i = 0; i < sdpLines.length; i++) { if (sdpLines[i].search('m=audio') !== -1) { mLineIndex = i; break; } } if (mLineIndex === null) { return sdp; } // If Opus is available, set it as the default in m line. for (i = 0; i < sdpLines.length; i++) { if (sdpLines[i].search('opus/48000') !== -1) { var opusPayload = extractSdp(sdpLines[i], /:(\d+) opus\/48000/i); if (opusPayload) { sdpLines[mLineIndex] = setDefaultCodec(sdpLines[mLineIndex], opusPayload); } break; } } // Remove CN in m line and sdp. sdpLines = removeCN(sdpLines, mLineIndex); sdp = sdpLines.join('\r\n'); return sdp; } function extractSdp(sdpLine, pattern) { var result = sdpLine.match(pattern); return result && result.length === 2 ? result[1] : null; } // Set the selected codec to the first in m line. function setDefaultCodec(mLine, payload) { var elements = mLine.split(' '); var newLine = []; var index = 0; for (var i = 0; i < elements.length; i++) { if (index === 3) { // Format of media starts from the fourth. newLine[index++] = payload; // Put target payload to the first. } if (elements[i] !== payload) { newLine[index++] = elements[i]; } } return newLine.join(' '); } // Strip CN from sdp before CN constraints is ready. function removeCN(sdpLines, mLineIndex) { var mLineElements = sdpLines[mLineIndex].split(' '); // Scan from end for the convenience of removing an item. for (var i = sdpLines.length-1; i >= 0; i--) { var payload = extractSdp(sdpLines[i], /a=rtpmap:(\d+) CN\/\d+/i); if (payload) { var cnPos = mLineElements.indexOf(payload); if (cnPos !== -1) { // Remove CN payload from m line. mLineElements.splice(cnPos, 1); } // Remove CN line in sdp sdpLines.splice(i, 1); } } sdpLines[mLineIndex] = mLineElements.join(' '); return sdpLines; } var idVid = 0; function appendVideo(vid,usrname){ ephemeralStream = localStream; var text = "<div class='profil'><span class='color4'>"+usrname+"</span><img class='image-delete' src='images/croix.png' title='delete' onclick='tryBan(\""+usrname+"\");'><video id='streamVid_"+idVid+"' class='remoteVideo' onclick='makeVideoActive(ephemeralStream);' autoplay></video></div>"; text += "<script>var element = document.querySelector('#streamVid_"+idVid+"');attachMediaStream(element, ephemeralStream);</script>"; idVid += 1; $('#profils-container').append(text); } function makeVideoActive(videoStream){ attachMediaStream(activeVideo,videoStream); } //Fonction appelé par le 'valider' du prompt et de destruction de ce dernier function validerPassword(Password){ if(Password != null || Password != ""){ getSocket().emit('banIP',ip,Password); //alert("mot de passe " + Password + " enregistré."); var myPrompt = document.getElementById('myPrompt'); document.body.removeChild(myPrompt); } } /** Ban Part */ function tryBan(username){ var promptPassword = prompt("Please enter the administration password",""); if (promptPassword != null){ getSocket().emit('banIP',usrname,promptPassword); } }
var db = require('../../../config/db.config'); const Companymember = db.memberinfo; exports.create = (req, res) => { const newCompanyMember = new Companymember({ company_id: req.body.company_id, member_email_id: req.body.member_email_id, member_phoneno: req.body.member_phoneno, member_name: req.body.member_name, member_designation: req.body.member_designation, member_specialization: req.body.member_specialization, }); newCompanyMember.save().then(data =>{ return res.json({ status:200, data: data, message: "Data insert Successfully" }) }).catch(err =>{ return res.json({ message: "Something went to wrong "+err }) }) }; exports.findById = (req,res)=>{ if(req.body.id == '' || req.body.id == undefined){ return res.json({ status: 200, message: "Id can not be empty" }) } Companymember.findAll({where:{company_id: req.body.id}}).then(data=>{ return res.json({ status: 200, auth: true, data: data }) }).catch(err=>{ res.json("error"+err); }) } exports.deleteById = (req,res)=>{ Companymember.destroy({ where: { id: req.body.id } }).then(() =>{ res.json({ status:200, message:"Deleted successfully"}); }).catch(err =>{ res.json({ status:404, message:"record not found " +err}) }) } exports.update = (req, res) => { if(!req.body.memberId){ res.json({ status:200, message: "member Id can not be empty" }) } let data = req.body; Companymember.update({ ...data }, { where: { id: req.body.memberId } }).then(data => { res.json({ status:200, message: "Record update successfully" }) }).catch(err => { res.json({ status:200, message: "something went to wrong "+err }) }) };
define(["QDP"], function (QDP) { "use strict"; /** 初始化商户列表 * @param {JSON} filter * @param {JSON} column * @param {string} value */ var initMerchant = function (filter, column, value) { $("<select/>") .attr("id", filter.name) .addClass("form-control") .appendTo(column); QDP.form.initCache({ "api": QDP.api.merchant.alldatasapi, "target": $("#" + filter.name), "valuefn": function (index, item) { return item.id; }, "textfn": function (index, item) { return QDP.base64.decode(item.mch_name); }, "done": function () { $("#" + filter.name).attr("data-value", value); } }); } return { define: { name: "商户服务项目管理", version: "1.0.0.0", copyright: " Copyright 2017-2027 WangXin nvlbs,Inc." }, /** 加载模块 */ "init": function () { var options = { "apis": { "list": QDP.api.service.datas, "insert": QDP.api.service.add, "update": QDP.api.service.update, "delete": QDP.api.service.remove }, "helps": { "list": QDP.config.tooltip.compute, "insert": QDP.config.tooltip.compute, "update": QDP.config.tooltip.compute }, "texts": { insert: "新增商户服务项目", update: "编辑商户服务项目" }, "headers": { edit: { text: "商户服务项目" }, table: { text: "商户服务项目列表" } }, "actions": { insert: true, update: true, delete: true }, "columns": [ { "name": "_index", text: "序号" }, { "name": "id", primary: true }, { "name": "mch_id", text: "商户编号", "custom": initMerchant, edit: true, filter: true, filterindex: 1 }, { "name": "poi_id", text: "POIID", filter: true, filterindex: 2 }, { "name": "mch_name", text: "商户名称", filter: true, filterindex: 3 }, // { name: "name", text: "服务名称", dict: 'servicename', filter: true, filterindex: 4 }, { "name": "type", text: "服务类别", dict: 'servicetype', edit: true, filter: true, filterindex: 6 }, { "name": "car_type", text: "服务车型", dict: 'cartype', edit: true, filter: true, filterindex: 7 }, { "name": "contract_discount", text: "折扣券签约价", regex: /^((?:[0-9]\d*))(?:\.\d{1,2})?$/, message: '不是有效的价格类型,请输入正数,最多保留两位小数', edit: true, label: '元' }, { "name": "price", text: "店铺门市价", regex: /^((?:[0-9]\d*))(?:\.\d{1,2})?$/, message: '不是有效的价格类型,请输入正数,最多保留两位小数', edit: true, label: '元' }, { name: "free_discount", text: "免费券结算价", regex: /^((?:[0-9]\d*))(?:\.\d{1,2})?$/, message: '不是有效的价格类型,请输入正数,最多保留两位小数', edit: true, label: '元' }, { name: "status", text: "服务状态", dict: 'servicestate', filter: true, filterindex: 5 }, { name: "publish_status", text: "发布状态", dict: "publish_status" }, // { name: "online_status", text: "上线状态", dict: "online_status" }, // { name: "creator", text: "创建人"}, { name: "create_time", text: "创建时间", type: "datetime" }, { name: "begin_date", text: "开始时间", type: "date", filter: true, filterindex: 8, display: false }, { name: "end_date", text: "结束时间", type: "date", filter: true, filterindex: 9, display: false } ] }; QDP.generator.init(options); }, /** 卸载模块 */ "destroy": function () { } }; });
var pickuptime = { init: function(a, b) { this.setuptime = a; this.run(b) }, marketgetTime: function() { var k = this.setuptime; var g = new Date(); g.setDate(g.getDate() + k); var h = g.getDay(); var l = g.getHours(); var f = parseInt(h); var d = ""; var a = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"]; var e = new Array(); var b, j; for(var c = k; c < 7 + k; c++) { if(f == 7) { f = 0 } if(c == 0) { b = g.getMonth() + 1; j = g.getDate(); e.push(b + "-" + j ) } else { if(c == 1) { g.setDate(g.getDate() + 1); b = g.getMonth() + 1; j = g.getDate(); e.push(b + "-" + j + "" ) } else { if(c == 2) { g.setDate(g.getDate() + 1); b = g.getMonth() + 1; j = g.getDate(); e.push(b + "-" + j + "") } else { g.setDate(g.getDate() + 1); b = g.getMonth() + 1; j = g.getDate(); e.push(b + "-" + j + "") } } } f++; j++ } e.push(l); return e }, todoble: function(a) { if(a < 10) { a = a + ":30" } else { a = a + ":30" } return a }, run: function(f) { var c = this.marketgetTime(); console.log(c, 'c') var a = ""; for(var b = 8; b < 17; b++) { if(b <= c[3] + 1) { a += "<li class='pickuptime pickuptime-sp hide'>" + this.todoble(b) + "</li><li class='pickuptime pickuptime-sp hide'>" + (parseInt(b)+1) + ":" + '00' + "</li>" } else { if(b == Number(c[3]) + 2) { a += "<li class='pickuptime pickuptime-sp hide'>" + this.todoble(b) + "</li><li class='pickuptime pickuptime-sp hide'>" +(parseInt(b)+1)+ ":" + '00' + "</li>" } else { a += "<li class='pickuptime'>" + this.todoble(b) + "</li><li class='pickuptime'>" + (parseInt(b)+1)+ ":" + '00' + "</li>" } } } var e = "<div id='pickuptimeContener'><div class='pickuptime-close-empty'></div><div id='pickuptime'><p class='pickuptime-title'>请选择取货时间</p><div class='pickuptime-box'><div class='pickuptime-data'><p class='pickuptime-datap pickuptime-data-on'>" + c[0] + "</p><p class='pickuptime-datap'>" + c[1] + "</p><p class='pickuptime-datap'>" + c[2] + "</p><p class='pickuptime-datap'>" + c[3] + "</p><p class='pickuptime-datap'>" + c[4] + "</p><p class='pickuptime-datap'>" + c[5] + "</p><p class='pickuptime-datap'>" + c[6] + "</p></div>"; e += "<ul>" + a + "</ul></div><div class='pickuptime-close'>关闭</div></div>"; if($("#pickuptimeContener").length > 0) { $("#pickuptimeContener").remove() } $("body").append(e); var d = $(window).height() - $(".pickuptime-title").offset().top; // $(".pickuptime-close-empty").css("height", d + "px"); $(".pickuptime-close-empty").css("height", 400 + "px"); $(".pickuptime-close-empty,.pickuptime-close").on("click", function() { $("#pickuptimeContener").remove() }); $(".pickuptime-datap").on("click", function() { var g = $(this).index(); if(g != 0) { $(".pickuptime-sp").show() } else { $(".pickuptime-sp").hide() } $(this).addClass("pickuptime-data-on").siblings().removeClass("pickuptime-data-on") }); $(".pickuptime").on("click", function() { $(this).addClass("pickuptime-on").siblings().removeClass("pickuptime-on"); var g = $(".pickuptime-data-on").text() + " " + $(".pickuptime-on").text(); $(".pickuptime-close-empty").click(); if(Object.prototype.toString.call(f) === "[object Function]") { f(g) } else { return false } }) } };
module.exports = { GET_ERRORS: "GET_ERRORS", GET_USER_DATA: "GET_USER_DATA", ADD_USER_DATA: "ADD_USER_DATA", GET_USER: "GET_USER", ADD_DATA_SUCCESS: "ADD_DATA_SUCCESS", DELETE_USER_DATA: "DELETE_USER_DATA", FETCH_USER_DATA : "FETCH_USER_DATA" };
new Vue({ el: "#app", data: { money: 0, result: false, deposit: "", percent: "", time: "", rub: 0, currency: "RUB", rub_transfer_show: false, usd_transfer_show: false, currency1: "" }, methods: { calculation: function(){ this.currency1 = this.currency; this.result = true; this.rub = this.deposit for(let i = 0;i<this.time;i++){ this.rub = Number((this.rub * this.percent / 100) + Number(this.rub)); } let res = Math.round(this.rub); this.money = res; if(this.currency1 == "RUB"){ this.usd_transfer_show = true; this.rub_transfer_show = false; } else if (this.currency1 == "USD"){ this.rub_transfer_show = true; this.usd_transfer_show = false; } }, rub_transfer: function(){ this.money = this.money * 65,53; this.currency1 = "RUB"; this.rub_transfer_show = false; this.usd_transfer_show = true; }, usd_transfer: function(){ this.money = Math.round(this.money / 65,53); this.currency1 = "USD"; this.usd_transfer_show = false; this.rub_transfer_show = true; } } });
import React from 'react'; import PropTypes from 'prop-types'; import {withRouter} from 'react-router-dom'; import AnswerCard from './components/answer-card'; import {languageHelper} from '../../tool/language-helper'; class ArticleCardBarIdReact extends React.Component { constructor(props) { super(props); // state this.state = {}; // i18n this.text = ArticleCardBarIdReact.i18n[languageHelper()]; } render() { return ( <AnswerCard articleId={this.props.id} /> ); } } ArticleCardBarIdReact.i18n = [ {}, {} ]; ArticleCardBarIdReact.propTypes = { // self id: PropTypes.number.isRequired, // React Router match: PropTypes.object.isRequired, history: PropTypes.object.isRequired, location: PropTypes.object.isRequired }; export const ArticleCardBarId = withRouter(ArticleCardBarIdReact);
module.exports = [ { type: 'input', // 类型为 输入项 name: 'name', message: '请输入项目名称', default: 'vue-template' }, { type: 'input', // 类型为 输入项 name: 'description', message: '请输入项目描述', default: 'this is a description' }, { type: 'input', // 类型为 输入项 name: 'author', message: '请输入项目作者', default: 'Manfray' }, { type: 'list', // 即类型为 选择项 name: 'module', // 名称,作为下面 generator 函数 options 的键 message: '请选择你要生成的模块', // 提示语 choices: [ { name: 'Module1', value: 'module1' }, { name: 'Module2', value: 'module2' }, { name: 'Module3', value: 'module3' } ], default: 'module0', }, { type: 'input', // 类型为 输入项 name: 'moduleName', message: '请输入模块名称', default: 'myModule' } ]
/** * Created by julian on 25.04.16. * * Module: circle * * * A circle knows how to draw itself into a specified 2D context, * can tell whether a certain mouse position "hits" the object, * and implements the function createDraggers() to create a set of * draggers to manipulate itself. * */ /* requireJS module definition */ define(["util", "vec2", "Scene", "PointDragger"], (function(util,vec2,Scene,PointDragger) { "use strict"; /** * A simple circle that can be dragged and resized. * * @param center Array object representing [x,y] coordinates of the center. * @param radius The radius of the circle. * @param lineStyle object defining width and color attributes for line drawing, begin of the form { width: 2, color: "#00FF00" } * @constructor */ var Circle = function(center, radius, lineStyle) { console.log("creating circle at", center, "with radius of", radius); // draw style for drawing the line this.lineStyle = lineStyle || { width: "2", color: "#0000AA" }; // initial values in case either point is undefined this.center = center || [10,10]; this.radius = radius || 10; // draw this line into the provided 2D rendering context this.draw = function(context) { // draw actual line context.beginPath(); // set points to be drawn context.arc(this.center[0], this.center[1], this.radius, 0, 2 * Math.PI); // set drawing style context.lineWidth = this.lineStyle.width; context.strokeStyle = this.lineStyle.color; // actually start drawing context.stroke(); }; // checks for the mouse position is on the circle segment this.isHit = function(context,mousePos) { // what is my current position? var middle = this.center; // check whether distance between mouse and dragger's center // is less or equal ( radius + (line width)/2 ) var dx = mousePos[0] - middle[0]; var dy = mousePos[1] - middle[1]; var r = this.radius; return (dx*dx + dy*dy) <= (r*r); }; // return list of draggers to manipulate this Circle Circle.prototype.createDraggers = function() { var draggerStyle = { radius:4, color: this.lineStyle.color, width:0, fill:true } var draggers = []; // create closure and callbacks for dragger var _circle = this; /** * Callback to get the position of the Middle dragger. * @returns {*|number[]} */ var getPosMiddleDragger = function() { return _circle.center; }; /** * Callback to change the circle position. * @param dragEvent */ var setMiddle = function(dragEvent) { _circle.center = dragEvent.position; }; /** * * This method defines the dragger for the circle outter line. * Callback to get the position of the Radius dragger. * @returns {*[]} */ var radiusDragger = function() { return [ _circle.center[0], _circle.center[1] + (_circle.radius) ]; } /** * * calculates the length of the vector from the center to the cirle outer line. * Callback to change the circle radius. * @param dragEvent */ var setRadius = function(dragEvent) { _circle.radius = vec2.length(vec2.sub(dragEvent.position, _circle.center)); } draggers.push(new PointDragger(getPosMiddleDragger, setMiddle, draggerStyle)); draggers.push(new PointDragger(radiusDragger, setRadius, draggerStyle)); return draggers; }; }; // this module only exports the constructor for StraightLine objects return Circle; }));
import React, { Component } from 'react' /** * SVG 渐变:1.线性【垂直、水平】2.放射性 * SVG 渐变必须在 <defs> 标签中进行定义 */ export default class Gradient extends Component { render() { return ( <div > <svg width="100%" height="100%" style={{ position: "absolute" }} version="1.1" > {/* *********** 线性渐变 */} {/* 水平渐变 y值相等 start*/} <defs> <linearGradient id="horizon—color" x1="0%" y1="0%" x2="100%" y2="0%"> <stop offset="0%" style={{ 'stopColor': 'rgb(255, 255, 0)', 'stopOpacity': '1' }} /> <stop offset="50%" style={{ 'stopColor': 'rgb(0, 0, 205)', 'stopOpacity': '1' }} /> <stop offset="100%" style={{ 'stopColor': 'rgb(255,0,0)', 'stopOpacity': '1' }} /> </linearGradient> </defs> <defs> <linearGradient id="horizon-opacity" x1="0%" y1="0%" x2="100%" y2="0%"> <stop offset="0%" style={{ 'stopColor': 'rgb(255, 255, 0)', 'stopOpacity': '0.5' }} /> <stop offset="100%" style={{ 'stopColor': 'rgb(255,255,0)', 'stopOpacity': '1' }} /> </linearGradient> </defs> {/* 水平渐变 end*/} {/* 垂直渐变 x值相等 start*/} <defs> <linearGradient id="vertial-color" x1="0%" y1="0%" x2="0%" y2="100%"> <stop offset="0%" style={{ 'stopColor': 'rgb(255, 255, 0)', 'stopOpacity': '1' }} /> <stop offset="100%" style={{ 'stopColor': 'rgb(0,0,205)', 'stopOpacity': '1' }} /> </linearGradient> </defs> {/* 垂直渐变 end*/} {/* 左上角->右下角渐变 */} <defs> <linearGradient id="color" x1="0%" y1="0%" x2="100%" y2="100%"> <stop offset="0%" style={{ 'stopColor': 'rgb(255, 255, 0)' }} /> <stop offset="100%" style={{ 'stopColor': 'rgb(0,0,205)' }} /> </linearGradient> </defs> {/* ******************放射渐变 */} {/* * .cx与cy分别确定圆心的横坐标和纵坐标 * .r规定圆的半径尺寸。 * .fx与fy属性用来规定渐变焦点坐标,焦点通俗的说就是渐变的起点位置,此位置处颜色值保持最初状态。 * */} <defs> <radialGradient id="radialGradient-color" cx="50%" cy="50%" r="50%" fx="50%" fy="50%"> <stop offset="0%" style={{ 'stopColor': 'rgb(200, 200, 200)' }} /> <stop offset="100%" style={{ 'stopColor': 'rgb(0,0,205)' }} /> </radialGradient> </defs> <defs> <radialGradient id="radialGradient-color2" cx="20%" cy="50%" r="50%" fx="50%" fy="50%"> <stop offset="0%" style={{ 'stopColor': 'rgb(200, 200, 200)' }} /> <stop offset="100%" style={{ 'stopColor': 'rgb(0,0,205)' }} /> </radialGradient> </defs> <defs> <radialGradient id="radialGradient-color3" cx="50%" cy="20%" r="50%" fx="50%" fy="50%"> <stop offset="0%" style={{ 'stopColor': 'rgb(200, 200, 200)' }} /> <stop offset="100%" style={{ 'stopColor': 'rgb(0,0,205)' }} /> </radialGradient> </defs> <defs> <radialGradient id="radialGradient-color4" cx="20%" cy="20%" r="50%" fx="50%" fy="50%"> <stop offset="0%" style={{ 'stopColor': 'rgb(200, 200, 200)' }} /> <stop offset="100%" style={{ 'stopColor': 'rgb(0,0,205)' }} /> </radialGradient> </defs> <defs> <radialGradient id="radialGradient-color5" cx="50%" cy="50%" r="50%" fx="50%" fy="20%"> <stop offset="0%" style={{ 'stopColor': 'rgb(200, 200, 200)' }} /> <stop offset="100%" style={{ 'stopColor': 'rgb(0,0,205)' }} /> </radialGradient> </defs> <defs> <radialGradient id="radialGradient-color6" cx="70%" cy="50%" r="50%" fx="50%" fy="50%"> <stop offset="0%" style={{ 'stopColor': 'rgb(200, 200, 200)' }} /> <stop offset="100%" style={{ 'stopColor': 'rgb(0,0,205)' }} /> </radialGradient> </defs> <ellipse cx="200" cy="190" rx="85" ry="55" style={{ "fill": 'url(#horizon—color)' }} /> <ellipse cx="400" cy="190" rx="85" ry="55" style={{ "fill": 'url(#horizon-opacity)' }} /> <ellipse cx="600" cy="190" rx="85" ry="55" style={{ "fill": 'url(#vertial-color)' }} /> <ellipse cx="800" cy="190" rx="85" ry="55" style={{ "fill": 'url(#color)' }} /> <ellipse cx="200" cy="500" rx="85" ry="85" style={{ "fill": 'url(#radialGradient-color)' }} /> <ellipse cx="400" cy="500" rx="85" ry="85" style={{ "fill": 'url(#radialGradient-color2)' }} /> <ellipse cx="600" cy="500" rx="85" ry="85" style={{ "fill": 'url(#radialGradient-color3)' }} /> <ellipse cx="800" cy="500" rx="85" ry="85" style={{ "fill": 'url(#radialGradient-color4)' }} /> <ellipse cx="1000" cy="500" rx="85" ry="85" style={{ "fill": 'url(#radialGradient-color5)' }} /> <ellipse cx="1200" cy="500" rx="85" ry="85" style={{ "fill": 'url(#radialGradient-color6)' }} /> </svg> </div> ) } }
module.exports = function() { var AppControllerService = require('../app-controller-service/index.js'); $settingsWrapper = $('.settings-icon-wrapper'), $leaveGroupWrapper = $('.leave-group-icon-wrapper'), $leaveGroupModal = $('.leave-group-modal'), $leaveGroupAction = $('.leave-group-action'), GroupController = new AppControllerService('groups'), discussionId = $leaveGroupWrapper.attr('data-id'), $settingsWrapper.on('click', function(e) { e.preventDefault(); window.location.href = '/groups/edit/' + $(this).attr('data-id'); }); $leaveGroupWrapper.on('click', function(e) { e.preventDefault(); $leaveGroupModal.modal(); }); $leaveGroupAction.on('click', function() { GroupController.post({ discussionId: discussionId, }, function(err, response) { $('.discussion-list li[data-id=' + discussionId + ']').remove(); $leaveGroupModal.modal('toggle'); }, '/groups/leave/' + discussionId); }); };
import * as React from 'react'; import {Text} from 'react-native'; import {colors, fontScale, fontName} from '../utils'; export const TextComponent = (props) => { return ( <Text {...props} style={[ { color: colors.txtColor, fontSize: fontScale(14), fontFamily: fontName.PRIMARY_REGULAR, }, props.style, ]}> {props.children} </Text> ); };
DrunkCupid.Views.Messages = Backbone.CompositeView.extend({ template: JST['messages'], initialize: function () { this.listenTo(this.collection, 'reset', this.addMessages); this.addMessages(this.collection); }, render: function () { var content = this.template(); this.$el.html(content) return this; }, addMessages: function (collection) { this.subviews('.messages').each(function (msgSubview) { msgSubview.remove(); }); collection.each(function(msg) { this.addMessage(msg); }.bind(this)) }, addMessage: function (msg) { var messageView = new DrunkCupid.Views.Message({model: msg}); this.addSubview('.messages', messageView); } })
import React, {Component} from "react"; import { Link } from "react-router-dom"; //In javascript you dont need to specify folders in this server // just write name of nameofhtml to find href //This is the navigation/menu bar component export class Navbar extends Component { render() { return ( <div className="menu-area"> <ul> <li><Link className="nav-link" to="/">Home</Link></li> <li><Link className="nav-link" to="/signin">Sign in</Link></li> <li><input type="text" name="" id="search-bar" placeholder="Search product or category . . . "/></li> </ul> </div> ) } }
const express = require('express'); const http = require('http'); const WebSocket = require('ws'); const port = 9001; const server = http.createServer(express); const wss = new WebSocket.Server({ server }) let chats = {} wss.on('connection', function connection(ws) { ws.on('message', function incoming(data) { let json = data.toString() json = JSON.parse(json) let chatId = json.chatId let msg = json.message let userName = json.userName if (msg != "") { if (!chats.hasOwnProperty(chatId)) { chats[chatId] = new Set() } chats[chatId].add(ws) let toSend = {"userName": userName, "message": msg} wss.clients.forEach(function each(client) { if (client != ws && chats[chatId].has(client) && client.readyState === WebSocket.OPEN) { client.send(JSON.stringify(toSend)); } }) } else { if (!chats.hasOwnProperty(chatId)) { chats[chatId] = new Set() } chats[chatId].add(ws) } }) }) server.listen(port, function() { console.log(`Server is listening on ${port}!`) })
// /** // * 好友列表 // */ // import { requireNativeComponent,Platform,View, DeviceEventEmitter,} from 'react-native'; // import React, { Component, PureComponent } from "react"; // var MerchantFriendFrameLayout = requireNativeComponent('MerchantFriendFrameLayout', null); // var NativeFriendScreen = requireNativeComponent('NativeFriendScreen', null); // // import MerchantFriendFrameLayout from '../components/FragmentAndroid'; // // export default class FriendScreen extends Component { // componentDidMount() { // // } // render() { // return ( // Platform.OS=='ios'? // <NativeFriendScreen style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> // </NativeFriendScreen> // // :<MerchantFriendFrameLayout style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> // // </MerchantFriendFrameLayout> // :<MerchantFriendFrameLayout style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}/> // ); // } // } /** * 好友列表 */ import { requireNativeComponent, Platform, StatusBar, View, } from 'react-native'; import React, { Component, PureComponent } from 'react'; import SplashScreen from 'react-native-splash-screen'; import { connect } from 'react-redux'; import MerchantFriendFrameLayout from '../components/FragmentAndroid'; import { JOIN_AUDIT_STATUS } from '../const/user'; import ListEmptyCom from '../components/ListEmptyCom'; import Header from '../components/Header'; import CommonStyles from '../common/Styles'; import Button from '../components/Button'; // var MerchantFriendFrameLayout = requireNativeComponent('MerchantFriendFrameLayout', null); const NativeFriendScreen = requireNativeComponent('NativeFriendScreen', null); class FriendScreen extends Component { listener; componentDidMount() { Platform.OS === 'ios' ? null : this.fragment && this.fragment.create(); SplashScreen.hide(); // var xkMerchantEmitterModule = NativeModules.xkMerchantEmitterModule; // const myNativeEvt = new NativeEventEmitter(xkMerchantEmitterModule); //创建自定义事件接口 // this.listenerGoodsDetail=myNativeEvt.addListener('goodsDetail',(goodsInfo)=>this.handleJumpDetail(goodsInfo,'goodsDetail')); // this.listenerWelfareDetail=myNativeEvt.addListener('welfareDetail',(goodsInfo)=>this.handleJumpDetail(goodsInfo,'welfareDetail')); } componentWillUnmount() { // this.listenerGoodsDetail.remove() // this.listenerWelfareDetail.remove() componentWillMount() { StatusBar.setBarStyle('light-content'); } handleJumpDetail = (goodsInfo, key) => { // 批发商城 // console.log('goodsId',goodsInfo) // if(key=='goodsDetail'){ //goodsId 5be52bcf0334553f3f44eeac // this.props.navigation.navigate("SOMGoodsDetail", { // goodsId: goodsInfo // }); // }else{//goodsId {goodsId: "5c106cee033455043da7c820", sequenceId: "5c89b01c0334557fe4a6cca8"} // this.props.navigation.navigate('WMGoodsDetail', { // goodsId: goodsInfo.goodsId, // sequenceId: goodsInfo.sequenceId // }) // } } toAcitivePage = () => { const { firstMerchant, navPage } = this.props; navPage('AccountActive', { route: 'Friends', merchantType: firstMerchant.merchantType }); } render() { const { auditStatus, createdMerchant } = this.props.user || {}; if (auditStatus !== JOIN_AUDIT_STATUS.active || createdMerchant !== 1) { return ( <View style={[CommonStyles.flex_1, CommonStyles.flex_center, { backgroundColor: '#fff' }]}> <Header title="好友" /> <ListEmptyCom type={auditStatus !== JOIN_AUDIT_STATUS.un_active ? 'Friends_Not_Audit' : 'Friends_Not_Active'} style={{ paddingTop: 0 }}> <View style={{ marginTop: 60, display: auditStatus === JOIN_AUDIT_STATUS.un_active ? 'flex' : 'none' }}> <Button style={{ height: 44, width: 149, borderRadius: 4 }} type="primary" onPress={this.toAcitivePage} title="立即激活" /> </View> </ListEmptyCom> </View> ); } return ( Platform.OS == 'ios' ? <NativeFriendScreen style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }} /> // :<MerchantFriendFrameLayout style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> // </MerchantFriendFrameLayout> : ( <MerchantFriendFrameLayout ref={(ref) => { this.fragment = ref; }} /> ) ); } } export default connect(state => ({ user: state.user.user, firstMerchant: state.user.firstMerchant, }), { navPage: (routeName, params) => ({ type: 'userActive/navPage', payload: { routeName, params } }), })(FriendScreen);
const premiumModel = require("../models/premium"); module.exports = { premiumAccount: (req, res) => { phoneNumber = req.body.phoneNumber; console.log(phoneNumber); premiumModel.premiumAccount(phoneNumber).then(result => { res.json({ total: result.length, status: 200, data: result, message: "Success to get All Answer by ID Assessment" }); }); } };
const pool = require("../db/db"); class orders { getOrders = async (req, res) => { try { console.log(req.session); const userId = req.session.passport.user; console.log("getting orders"); const getUserOrders = await pool.query( "SELECT * FROM orders WHERE users_id = $1", [userId] ); res.json(getUserOrders.rows); } catch (error) { console.log(error); } }; } module.exports = orders;
import React, {Component} from 'react'; import PropTypes from 'prop-types'; import './LayoutApp.css'; import Navbar from './Navbar'; export default class LayoutApp extends Component { static propTypes = { component: PropTypes.func.isRequired, title: PropTypes.string.isRequired, route: PropTypes.object, }; render() { const Component = this.props.component; const {title, route} = this.props; const {path} = this.props.route.match; return ( <> {path !== '/' ? <div> {/** This navbar can be extended and use as a menu, we can also add sidebar */} <Navbar title={title}/> <main> <div className="container py-1"> <Component route={route}/> {this.props.loading && `loading`} </div> </main> </div> : <> <Component route={route}/> {this.props.loading && `loading`} </> } {/** We can add footer here */} </> ); } }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes var BACKSPACE = exports.BACKSPACE = 8; var DELETE = exports.DELETE = 46; var DOWN_ARROW = exports.DOWN_ARROW = 40; var ENTER = exports.ENTER = 13; var LEFT_ARROW = exports.LEFT_ARROW = 37; var RIGHT_ARROW = exports.RIGHT_ARROW = 39; var TAB = exports.TAB = 9; var UP_ARROW = exports.UP_ARROW = 38;
import React, { Component } from 'react'; import { object } from 'prop-types'; import { Container, Row, Col } from 'reactstrap'; import Layout from '../../../components/account/accountLayout'; import AccountCard from '../../../components/account/accountCard'; import AccountNav from '../../../components/account/accountNav'; import DashboardHeader from '../../../components/dashboardHeader'; import EditNotifications from '../../../components/account/editNotifications'; import CustomizeAlarmEvents from '../../../components/account/customizeAlarmEvents'; import AccountCardMessage from '../../../components/account/accountCardMessage'; export default class Notifications extends Component { static propTypes = { url: object, } static defaultProps = { url: {}, } state = { type: 'edit', // edit | customize | messageNotifications | messageEvents } changeType = (type) => { this.setState(() => ({ type })); } render() { const { type } = this.state; return ( <Layout> <DashboardHeader /> <Container> <AccountCard className="card"> <Row> <Col> <h2 className="mb-md">Account/Alarm Info</h2> </Col> </Row> <Row> <Col md={4}> <AccountNav pathname={this.props.url.pathname} /> </Col> <Col> <AccountCard> {/* EDIT */} {type === 'edit' ? <EditNotifications changeType={this.changeType} /> : ''} {/* CUSTOMIZE */} { type === 'customize' ? <CustomizeAlarmEvents changeType={this.changeType} /> : ''} {/* EVENTS UPDATED */} {type === 'messageEvents' ? <AccountCardMessage title="Alarm Events Updated" description="You have successfully updated your alarm event settings." action={() => this.changeType('edit')} /> : ''} {/* NOTIFICATIONS UPDATED */} {type === 'messageNotifications' ? <AccountCardMessage title="Notifications/Communications Updated" description="You have successfully updated your alarm notifications." action={() => this.changeType('edit')} /> : ''} </AccountCard> </Col> </Row> </AccountCard> </Container> </Layout> ); } }
// console.log("******Problem 1*******") // let x = true; // console.log(typeof x) // // console.log("******Problem 2*******"); // let y = null; // console.log(typeof y); // // console.log("********Problem 3*******"); // let z = undefined; // console.log(typeof z); // // console.log("*******Problem 4********"); // let a = 15; // console.log(typeof a); // // console.log("*******Problem 5*********"); // let b = "hello"; // console.log(typeof b); console.log("*********Rock Paper Scissors**************"); let choice = ["rock", "paper", "scissors"]; //ARARY OF CHOICES// const computer = choice[Math.floor(Math.random() * choice.length)] //COMPUTER CHOICE RANDOMIZED// let me = choice[Math.floor(Math.random() * choice.length)]; //MY CHOICE IS RANDOMIZED// let meRock = me === "rock"; // ABBREVIATION// let mePaper = me === "paper"; // ABBREVIATION// let meScissors = me === "scissors" // ABBREVIATION// let compRock = computer === "rock"; // ABBREVIATION// let compPaper = computer === "paper"; // ABBREVIATION// let compScissors = computer === "scissors"; // ABBREVIATION// if (me === computer) { console.log("Looks like a tie!"); } else if (meRock && compScissors ) { console.log("I win!"); } //************************************// else if (mePaper && compRock) { //**************LOGIC********************// console.log("I win!"); //**************************************// } else if (meScissors && compPaper) { console.log("I win!"); } else { console.log("I lose!") } //
var path = require('path'); module.exports = function (req, res) { req.galleon.query('getAttachment', { eID: req.params.eID, email: req.credentials.email, id: req.params.id.toString() }, function (error, attachment) { if (error) return res.status(400).json({ error: error.toString() }) if (attachment.cid) { console.log("CID ATTACHMENT", attachment) res.type(attachment.name); res.sendFile(path.basename(attachment.path), { root: path.dirname(attachment.path), dotfiles: 'deny', headers: { 'x-timestamp': Date.now(), 'x-sent': true } }, function (error) { console.log(error) if (error) res.status(error.status).end(); }) } else { res.download(attachment.path, attachment.name, function (error) { if (error) res.status(error.status).end(); }); } }) }
/** * Created by 琴瑟 on 2017/3/26. */ 'use strict'; const express=require('express'); const template=require('art-template'); const bodyParser=require('body-parser'); const router=require('./router.js'); const session=require('express-session');//处理session const cookieParser = require('cookie-parser');//解析cookie let app=express(); //配置模板开始 template.config('cache',false); app.set('views','./views'); app.engine('html',template.__express); app.set('view engine','html'); //模板结束 //解析body数据 app.use(bodyParser.urlencoded({extended:false})); //解析静态资源文件 app.use('/public',express.static('public')); //添加session的处理 app.use(session({ secret: 'itcast',//唯一标识一下 resave: false,//当某个用户的session没有发生改变,不用再次重复保存 saveUninitialized: true//一访问就存在session //cookie: { secure: true } 设置cookie中只有在https下有效 })); //放在路由前面,提前让req,具备解析cookie的属性 app.use(cookieParser()); //在路由判断以前,我统统判断一次,如果没有session进入到首页 app.use(function(req,res,next){ if((req.url==='/' ||req.url==='/index' ||req.url==='/add' ||req.url.startsWith('/edit') ||req.url.startsWith('/del')) &&!req.session.user){ res.redirect('login'); } //如果是index或者/ next(); }); app.use(router); //处理异常 app.use(function(err,req,res,next){ console.log('出异常了', err.stack); next(); }); app.listen(80,()=>{ console.log('服务器启动了'); });
var fs = require("fs"); const { openFilePromis, openTextFilePromise } = require("./filelibs.js"); const { Translate } = require("@google-cloud/translate").v2; const translate = new Translate(); function readTranscriptAndReturnFullSentences(data) { let sentences_start_ends = []; let new_data_array = data.split("\n"); // console.log(new_data_array); let filtered = new_data_array.filter((element) => element !== ""); //console.log(filtered); let just_text = []; let speakers_text_combined = []; filtered.forEach((element, i) => { let split_speaker_and_text = element.split(": "); let speaker = split_speaker_and_text[0]; let text = split_speaker_and_text[1]; console.log(speaker.length); if (split_speaker_and_text.length === 1) { console.log(""); let cells_before = filtered.slice(0, i); cells_before.reverse(); let speaker_present_from_prev = cells_before.find((cell) => { let internal_speaker = cell.split(": "); if (internal_speaker.length > 1) { return true; } }); let text = split_speaker_and_text[0]; speaker = speaker_present_from_prev.split(": ")[0]; speakers_text_combined.push({ speaker, text }); just_text.push(text); } else { // this is the standard case, where the sentence is split bny a ":" one time, delineating a speaker on the keft side and the text on the right side of the delinator let text = split_speaker_and_text[1]; just_text.push(text); speakers_text_combined.push({ speaker, text }); } }); // let all_words = []; // let all_words_no_special_chars = []; // just_text.forEach((element) => { // let words = element.split(" "); // words.forEach((we) => { // all_words.push(we); // all_words_no_special_chars.push( // we.replace(/[^\w\s]|_/g, "").replace(/\s+/g, " )") // ); // }); // }); return { just_text, speakers_text_combined }; } async function translateShopifyTextSpeakersAndText( full_sentences, language, filePrepend ) { try { const text = full_sentences.just_text.slice(0, 100); //const target = "fr"; const target = language; let passes = Math.round(full_sentences.just_text.length / 100); let sentences_and_translations = []; let combined_speakers_and_translations = []; let blobs = []; for (i = 0; i <= passes; i++) { let lower_limit = i * 100; let upper_limit = lower_limit + 100; blobs.push(full_sentences.just_text.slice(lower_limit, upper_limit)); } let speaker_blobs = []; for (i = 0; i <= passes; i++) { let lower_limit = i * 100; let upper_limit = lower_limit + 100; speaker_blobs.push( full_sentences.speakers_text_combined.slice(lower_limit, upper_limit) ); } let blob_file_string = "blobs.json"; fs.writeFile(blob_file_string, JSON.stringify(blobs), function (err) { if (err) { return console.log(err); } console.log(blob_file_string + " was saved!"); }); fs.writeFile("speaker_blobs.json", JSON.stringify(speaker_blobs), function ( err ) { if (err) { return console.log(err); } console.log("speaker_blobs.json " + " was saved!"); }); blobs.forEach(async (blob, i) => { const sentences_and_translations_result = await translateJustOneArray( blob, target ); let speaker_blob = speaker_blobs[i]; sentences_and_translations_result.forEach((result, ii) => { let speaker = speaker_blob[ii].speaker; let text_local = result.text_local; let translation = result.translation; let iteration = ii + i * 100; combined_speakers_and_translations.push({ speaker, text_local, translation, i, ii, iteration, }); }); sentences_and_translations = sentences_and_translations.concat( sentences_and_translations_result ); if ( combined_speakers_and_translations.length === full_sentences.just_text.length ) { let filename_language_string = filePrepend + "sentences_and_translations_shopify_" + language + ".json"; fs.writeFile( filename_language_string, JSON.stringify(sentences_and_translations), function (err) { if (err) { return console.log(err); } console.log(filename_language_string + " was saved!"); } ); let filename_language_string2 = filePrepend + "combined_speakers_and_translations" + language + ".json"; fs.writeFile( filename_language_string2, JSON.stringify(combined_speakers_and_translations), function (err) { if (err) { return console.log(err); } console.log(filename_language_string2 + " was saved!"); } ); return combined_speakers_and_translations; } }); console.log(sentences_and_translations[0]); console.log(combined_speakers_and_translations[0]); } catch (err) { console.log(err); } } async function translateJustOneArray(text, target) { let local_sentences_and_translations = []; let [translations] = await translate.translate(text, target); translations = Array.isArray(translations) ? translations : [translations]; console.log("Translations:"); translations.forEach((translation, i) => { let text_local = text[i]; local_sentences_and_translations.push({ text_local, translation }); console.log(`${text[i]} => (${target}) ${translation}`); }); return local_sentences_and_translations; } const newShopifyChain = async () => { // const data = await openFilePromise("align.json"); // let align_JSON = JSON.parse(data); // let export_array = returnAudacityLabels(align_JSON); const text_file_data = await openTextFilePromise( "Shopify_Master_s__Healthish_Transcript.txt" ); let full_sentences = readTranscriptAndReturnFullSentences(text_file_data); let filename_language_string = "healthish" + "_full_sentences_good" + "_fr_" + ".json"; fs.writeFile( filename_language_string, JSON.stringify(full_sentences), function (err) { if (err) { return console.log(err); } console.log(filename_language_string + " was saved!"); } ); // translateShopifyText(full_sentences.just_text, "fr", "healthish_v3_"); console.log("dave"); translateShopifyTextSpeakersAndText(full_sentences, "fr", "healthish_v3_"); }; newShopifyChain();
// User Avatar Centering, if too small! var logoHeight = $('#avatarWrapper img').height(); if (logoHeight < 350) { var margintop = (350 - logoHeight) / 2; $('#avatarWrapper img').css('margin-top', margintop); }
var postcss = require('postcss'); /* postcss alter property value (papv) */ module.exports = postcss.plugin('postcss-alter-property-value', function (options) { var options = options || {}; /* Helper util */ function regexTest(whenRegex, decl) { if (!whenRegex || !decl || typeof whenRegex !== 'object') { return false; } if (whenRegex.value !== undefined) { var regex = new RegExp(whenRegex.value, whenRegex.flags || ''); if (regex.test(decl.value)) { return { ok: true, type: 'value' }; } } else if (whenRegex.prop !== undefined) { var regex = new RegExp(value.whenRegex.prop, value.whenRegex.flags || ''); if (regex.test(decl.prop)) { return { ok: true, type: 'prop' }; } } return false; } return function (root, result) { var props = Object.keys(options); props.map(function (prop, index) { root.walkDecls(prop, function (decl) { var value = options[prop]; if (typeof value === 'object') { if (!value) { decl.prop = prop + '__papv__disable-all-by-not-set'; } else if (!value.task) { // no task if not set } else { switch (value.task) { case 'disable': if (value.whenValueEquals === undefined && value.whenRegex === undefined) { decl.prop = prop + '__papv_disable-all'; } else if (value.whenValueEquals !== undefined && value.whenValueEquals === decl.value) { decl.prop = prop + '__papv_disable-by-value'; } else if (value.whenRegex) { var regexTest = regexTest(value.whenRegex, decl); if (regexTest) { decl.prop = prop + '__papv_disable_by-regex'; } } break; case 'changeProp': if (value.whenValueEquals === undefined && value.whenRegex === undefined) { decl.value = decl.value + ' /* papv - changePropAll from [' + decl.prop + '] */'; decl.prop = value.to; } else if (value.whenValueEquals !== undefined && value.whenValueEquals === decl.value) { decl.value = decl.value + ' /* papv - changeProp from [' + decl.prop + '] */'; decl.prop = value.to; } else if (value.whenRegex) { var regexTest = regexTest(value.whenRegex, decl); if (regexTest) { decl.value = decl.value + ' /* papv - changeProp from [' + decl.prop + '] */'; decl.prop = value.to; } } break; case 'changeValue': if (value.whenValueEquals === undefined && value.whenValueRegex === undefined) { decl.value = value.to + ' /* papv - changeValueAll from [' + decl.value + '] */'; } else if (value.whenValueEquals !== undefined && value.whenValueEquals === decl.value) { decl.value = value.to + ' /* papv - changeValue from [' + decl.value + '] */'; } else if (value.whenRegex) { decl.value = value.to + ' /* papv - changeValue from [' + decl.value + '] */'; } break; case 'remove': if (value.whenValueEquals === undefined && value.whenValueRegex === undefined) { decl.remove(); } else if (value.whenValueEquals !== undefined && value.whenValueEquals === decl.value) { decl.remove(); } else if (value.whenRegex) { decl.remove(); } break; default: result.warn('unknown task: [' + value.task + ']'); break; } } } }); }); }; });
module.exports = [ '/fr/', { title: 'Général', children: [ 'basics/introduction-car' ] }, { title: 'Développeurs', children: [ '/fr/developers/' ] }, ]
import React from 'react'; import {StyleSheet, Text, View, Image, TouchableOpacity} from 'react-native'; const NavigationBarIcon = props => { return ( <View style={styles.navigationIcon}> <TouchableOpacity onPress={props.onPress}> <Image source={props.iconImage} /> <Text style={props.active ? styles.iconTextActive : styles.iconText}> {props.IconText} </Text> </TouchableOpacity> </View> ); }; export default NavigationBarIcon; const styles = StyleSheet.create({ navigationIcon: { // backgroundColor: 'pink', flex: 1, alignItems: 'center', justifyContent: 'center', }, iconText: { fontSize: 10, fontWeight: 'bold', color: '#545454', marginTop: 4, }, iconTextActive: { fontSize: 10, fontWeight: 'bold', color: '#43AB4A', marginTop: 4, }, });
import Utils from 'utils/util.js'; // 工具函数 App({ /** * 当小程序初始化完成时,会触发 onLaunch(全局只触发一次) */ onLaunch: function () { var that = this; // that.globalData.windowHeight = wx.getSystemInfoSync().windowHeight // that.globalData.windowWidth = wx.getSystemInfoSync().windowWidth let systemInfo = wx.getSystemInfoSync() // px转换到rpx的比例 let pxToRpxScale = 750 / systemInfo.windowWidth; // 状态栏的高度 let ktxStatusHeight = systemInfo.statusBarHeight * pxToRpxScale // 导航栏的高度 let navigationHeight = 44 * pxToRpxScale // window的宽度 let ktxWindowWidth = systemInfo.windowWidth * pxToRpxScale that.globalData.windowWidth = ktxWindowWidth // window的高度 let ktxWindowHeight = systemInfo.windowHeight * pxToRpxScale that.globalData.windowHeight = ktxWindowHeight // 屏幕的高度 let ktxScreentHeight = systemInfo.screenHeight * pxToRpxScale that.globalData.screentHeight = ktxScreentHeight // 底部tabBar的高度 let tabBarHeight = ktxScreentHeight - ktxStatusHeight - navigationHeight - ktxWindowHeight that.globalData.tabBarHeight = tabBarHeight // wx.login({ // success: res => { // if (res.code) { // wx.request({ // url: that.globalData.authUrl+'/wx/auth/token', // data: { // code: res.code, // mode: 'sweb' // }, // method: "POST", // header: { // 'content-type': 'application/json', // 'login-type': 'wx' // }, // success: function (res) { // var token = res.data.object.accessToken; // var openid = res.data.object.openid; // that.globalData.openid = openid; // that.globalData.token = token; // wx.setStorageSync('openid', openid); // wx.setStorageSync('token', token); // } // }); // } // } // }); }, /** * 动态设置页面标题 */ setPageTitle: function(title) { wx.setNavigationBarTitle({ title: title //页面标题为路由参数 }) }, /** * 设置全局变量 */ globalData: { userInfo:null, openid: 0, token:'', baseHttpUrl: 'http://localhost:10001', baseUrl: 'https://localhost', authUrl: 'https://localhost:8443', // baseHttpUrl: 'http://www.allenyll.com:10001', // baseUrl: 'https://www.allenyll.com', // authUrl: 'https://www.allenyll.com:8443', bearer: 'Bearer ', onLoadStatus: true, page: 1, limit: 10, isIphoneX: false, windowHeight: 0, windowWidth: 0, screentHeight: 0, tabBarHeight: 0 }, // 工具函数 utils: Utils })
import axios from "axios"; import React, { useState, useEffect, useRef } from "react"; export const ThreatsHistory = () => { const [threats, setThreats] = useState([]); const countRef = useRef(0); useEffect(() => { retrieveAllThreats(); }, [countRef]); const retrieveAllThreats = () => { axios .get(`/api/threats/`, { headers: { 'Content-Type': 'application/json', Authorization: `Token ${localStorage.getItem('token')}` } }) .then((response) => { setThreats(response.data); }) .catch((e) => { console.error(e); }); }; const getDuration = (initial, final) => { let time = final - initial let minutes = Math.floor(time / 60); let seconds = time - minutes * 60; return `${minutes}m ${seconds}s` } return ( <div className="row justify-content-center div-table"> <h2>Threat's History</h2> <table id="table" className="table table-bordered table-hover"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Level</th> <th scope="col">Duration</th> <th scope="col">Beaten By</th> <th scope="col">Battle Duration</th> <th scope="col">Location</th> </tr> </thead> <tbody> {threats && threats.map((threat, index) => { return !threat.isActive && ( <tr key={threat.id} > <td>{threat.name}</td> <td>{threat.level}</td> <td>{getDuration(threat.start_timestamp, threat.battle_end_timestamp)}</td> {!threat.battle_with ? ( <td></td> ) : ( <td>{threat.battle_with.name}</td> )} <td>{getDuration(threat.battle_start_timestamp, threat.battle_end_timestamp)}</td> <td>{threat.location}</td> </tr> ) } )} {!threats && <tr> <td colSpan="4" className="text-center"> <div className="spinner-border spinner-border-lg align-center"></div> </td> </tr> } {threats && !threats.length && <tr> <td colSpan="4" className="text-center"> <div className="p-2">No Data To Display</div> </td> </tr> } </tbody> </table> </div> ); };
import Vue from "vue"; import Router from "vue-router"; import Home from "./views/Home.vue"; import BolsasFavoritas from "./views/BolsasFavoritas.vue"; import PreMatriculas from "./views/PreMatriculas.vue"; Vue.use(Router); export default new Router({ routes: [ // { // path: "/", // name: "home", // component: Home, // }, { path: '*', name: 'home', component: Home }, { path: "/index.html", redirect: "/" }, { path: "/BolsasFavoritas", name: "BolsasFavoritas", component: BolsasFavoritas, }, { path: "/PreMatriculas", name: "PreMatriculas", component: PreMatriculas, }, { path: "*", } ] });
/* * && -> false && true -> false "o valor mesmo" * || -> true || false -> true "retorna o valor verdadeiro" * Falsy - Valores falsos: * false * 0 * '' "" `` * null / undefined * NaN */ const a = 0; const b = null; const c = 'false'; const d = false; const e = NaN; console.log(a || b || c || d || e); // const userColor = null; // const defaultColor = userColor || 'purple'; // console.log(defaultColor); // function speakHi () { // return 'Oi'; // } // let willExecute = 'João'; // console.log(willExecute && speakHi());
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) import Layout from '../views/layout/index' import sysManageRouter from '../router/modules/sys-manage' import sysChart from '../router/modules/sys-chart' export const constantRoutes = [{ path: '/login', name: 'Login', component: () => import( /* webpackChunkName: "login" */ '~/views/login/index'), meta: { title: '系统登录' }, hidden: true }, { path: '/404', component: () => import( /* webpackChunkName: "error 404" */ '~/views/error-page/404'), hidden: true }, { path: '/401', component: () => import( /* webpackChunkName: "error 401" */ '~/views/error-page/401'), hidden: true }] const asyncRoute = [ ...sysManageRouter, ...sysChart ] asyncRoute.map((item) => { console.log('map',item) item.component = Layout }) export const asyncRoutes = [ ...asyncRoute, { path: '*', redirect: '/404', hidden: true } ] const createRouter = () => new Router({ scrollBehavior: () => ({ y: 0 }), routes: constantRoutes }) const router = createRouter() export function resetRouter() { const newRouter = createRouter() router.matcher = newRouter.matcher } export default router
var map; /*varios marker */ function loadResults(data) { var items, markers_data = []; if (data.data.length > 0) { items = data.data; for (var i = 0; i < items.length; i++) { var item = items[i]; if (item.gpsLat != undefined && item.gpsLon != undefined) { var icon = 'http://panico.coder.com.ar:8080/micropanicweb/img/'+item.icono; var fecha = moment(item.fechaOperacion); fecha = fecha.format("DD-MM-YYYY HH:MM"); var leyenda = item.username + '<br />' + item.razonSocial + '<br />' + item.tel + '<br/>' + fecha; var url = '<a href="eventos/' + item.id + '">' + leyenda + '</a>'; //console.log(url); markers_data.push({ lat: item.gpsLat, lng: item.gpsLon, title: item.username, icon: { size: new google.maps.Size(32, 32), url: icon }, infoWindow: { content: url } }); } } } map.addMarkers(markers_data); } /*un solo marker*/ function loadResult(data) { item = data.data; if (item.gpsLat != undefined && item.gpsLon != undefined) { var icon = 'http://panico.coder.com.ar:8080/micropanicweb/img/'+item.icono; var fecha = moment(item.fechaOperacion); fecha = fecha.format("DD-MM-YYYY HH:MM"); var leyenda = item.username + '<br />' + item.razonSocial + '<br />' + item.tel + '<br/>' + fecha; var url = '<a href="#">' + leyenda + '</a>'; //console.log(url); map.addMarker({ lat: item.gpsLat, lng: item.gpsLon, title: item.username, icon: { size: new google.maps.Size(32, 32), url: icon }, infoWindow: { content: url } }); //anidimos panorama map.addControl({ position: 'top_right', content: 'Vista panoramica', style: { margin: '5px', padding: '1px 6px', border: 'solid 1px #717B87', background: '#fff' }, events: { click: function () { panorama = GMaps.createPanorama({ el: '#map', lat: item.gpsLat, lng: item.gpsLon, }); } } }); } } function printResults(data) { $('#datosjson').text(JSON.stringify(data)); // prettyPrint(); } $(document).on('click', '.pan-to-marker', function (e) { e.preventDefault(); var position, lat, lng, $index; $index = $(this).data('marker-index'); alert($index); position = map.markers[$index].getPosition(); lat = position.lat(); lng = position.lng(); map.setCenter(lat, lng); });
const GRID_MOVEMENT_RATIO = 1;
// Generated by CoffeeScript 1.6.2 (function() { var CLIENT_ID, CLIENT_SECRET, ECT, MSG, OAuth2Client, PPL, REDIRECT_URL, app, ectRenderer, express, googleapis, io, models, mongoose, oauth2Client, port, scopes; express = require('express'); app = express(); port = 80; models = require('./models'); mongoose = require('mongoose'); MSG = mongoose.model('msg'); PPL = mongoose.model('ppl'); app.use(express["static"](__dirname + '/public')); app.set('views', __dirname + '/views'); ECT = require('ect'); ectRenderer = ECT({ watch: true, root: __dirname + '/views' }); app.engine('.html', ectRenderer.render); app.get('/', function(req, res) { return res.render('layout.html'); }); googleapis = require('googleapis'); OAuth2Client = googleapis.OAuth2Client; CLIENT_ID = '998322373435.apps.googleusercontent.com'; CLIENT_SECRET = 'U8QgUx2ygHzI-n5txUPMgcYV'; REDIRECT_URL = 'http://localhost/oauth2callback'; oauth2Client = new OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL); scopes = ['https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email']; app.get('/login', function(req, res) { googleapis.discover('oauth2', 'v2').execute(function(err, client) { var url; url = oauth2Client.generateAuthUrl({ access_type: 'offline', scope: scopes.join(' ') }); return res.send("<a href='" + url + "'>click to login</a>"); }); return console.dir(req.headers); }); app.get('/oauth2callback', function(req, res) { var code; code = req.query.code; console.log("OAUth Response Code: " + code); res.send(code); return oauth2Client.getToken(code, function(err, tokens) { console.log(tokens); oauth2Client.credentials = tokens; return googleapis.discover('oauth2', 'v2').execute(function(err, client) { console.log(' - - - - - - - - - - - - '); console.log(client); console.log(' - - - - - - - - - - - - '); return client.oauth2.userinfo.get({ email: 'email' }).withAuthClient(oauth2Client).execute(function(err, profile) { var person; if (err) { console.log('An error occurred'); return console.dir(err); } else { console.log('Profile 1 :: '); person = new PPL({ google_id: profile.id, email: profile.email, verified_email: profile.verified_email, name: profile.name, given_name: profile.given_name, family_name: profile.family_name, google_link: profile.link, picture: profile.picture, gender: profile.gender, locale: profile.locale, google_id_token: tokens.id_token, google_refresh_token: tokens.refresh_token, google_access_token: tokens.access_token, google_oauth_code: code }); return person.save(function(err) { if (err) { return err; } else { return console.log("Person: " + person); } }); } }); }); }); }); io = require('socket.io').listen(app.listen(port)); io.sockets.on('connection', function(socket) { var clock, d; console.log('client connected '); console.log(socket.id); d = new Date(); clock = d.toLocaleTimeString(); socket.emit('message', { m: 'welcome to the chat ' + clock }); return socket.on('send', function(data) { var msg; io.sockets.emit('message', data); console.log("Sent Data: "); console.dir(data); msg = new MSG({ m: data.m, n: "Yash Kumar", t: new Date().getTime() }); return msg.save(function(err) { if (err) { return err; } else { return console.log("Saved Message: " + msg); } }); }); }); console.log("Listening on port " + port); }).call(this);
import debug from 'debug' import {handleActions} from 'redux-actions' import reduceReducers from 'reduce-reducers' import constants from './constants' import pageReducerFactory, {getPageDefaultState} from '../shared/page/reducers' import actions from './action-types' import ApiHelper from '../api/helper' const dbg = debug('app:patients:reducers') const defaultState = { someState: 'default', ...getPageDefaultState(constants.RESOURCE, {limit: 100, sort: ApiHelper.getSortParam('firstName', true)}), ...getPageDefaultState(constants.ALT_PAGE_KEY, {limit: constants.LIMIT}) } const skillReducer = handleActions( { [actions.SOME_ACTION]: (state, action) => { dbg('some-action: state=%o, action=%o', state, action) return { someState: action.payload } } } ) export default (state = defaultState, action) => reduceReducers( pageReducerFactory(constants.RESOURCE), pageReducerFactory(constants.ALT_PAGE_KEY), skillReducer )(state, action)
import Vue from 'vue' const state = { user: [] } const getters = { checkUser (state) { console.log(state.user) if (state.user.name) { console.log('12312312') return 'Alex ' + state.user.name[0] } return false } } const actions = { logOut ({ commit }) { let user = [] commit('addUser', user) Vue.cookie.delete('token') }, signUp ({ commit }, user) { user.name = Vue.cookie.get('token') Vue.cookie.get('token') commit('addUser', user) } } const mutations = { addUser (state, user) { state.user = user console.log(user) console.log(state.user) } } export default { state, getters, actions, mutations }
import { INSOYA_HOST } from '../config'; import Post from '../containers/Post'; import Info from '../components/Info'; const MENUS = [ { icon: 'archive', title: '메이플 정보', component: Post, menus: [ { group: 'news', title: '새소식', url: `${INSOYA_HOST}zboard.php?id=bbs11&divpage=1` }, { group: 'info', title: '정보나눔터', url: `${INSOYA_HOST}zboard.php?id=maple_info&divpage=2` }, ], }, { icon: 'comments', title: '메이플 커뮤니티', component: Post, menus: [ { group: 'maple', title: '메이플 토크', url: `${INSOYA_HOST}zboard.php?id=talkmaple&divpage=18` }, { group: 'reboot', title: '리부트 토크', url: `${INSOYA_HOST}zboard.php?id=talkmaple_world_etc&category=5` }, { group: 'world', title: '해외 토크', url: `${INSOYA_HOST}zboard.php?id=talkmaple_world_etc&category=1` }, { group: 'mobile', title: '모바일 메이플', url: `${INSOYA_HOST}zboard.php?id=maple_mobile&divpage=1` }, ], }, { icon: 'users', title: '직업별 토크', component: Post, menus: [ { group: 'jobtalk', title: '전체보기', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9` }, { group: 'common', title: '공통', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&category=999&divpage=9` }, { group: 'hero', title: '히어로', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=111` }, { group: 'paladin', title: '팔라딘', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=112` }, { group: 'dark-knight', title: '다크나이트', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=113` }, { group: 'soul-master', title: '소울마스터', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=121` }, { group: 'mikhail', title: '미하일', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=122` }, { group: 'aran', title: '아란', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=131` }, { group: 'demon-slayer', title: '데몬슬레이어', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=141` }, { group: 'demon-avenger', title: '데몬어벤져', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=142` }, { group: 'blaster', title: '블래스터', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=143` }, { group: 'kaiser', title: '카이저', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=151` }, { group: 'zero', title: '제로', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=161` }, { group: 'pink-bin', title: '핑크빈', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=191` }, { group: 'archmage-fire', title: '아크메이지 (불/독)', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=211` }, { group: 'archmage-ice', title: '아크메이지 (썬/콜)', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=212` }, { group: 'bishop', title: '비숍', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=213` }, { group: 'flame-wizard', title: '플레임위자드', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=221` }, { group: 'evan', title: '에반', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=231` }, { group: 'luminous', title: '루미너스', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=232` }, { group: 'battle-mage', title: '배틀메이지', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=241` }, { group: 'kinesis', title: '키네시스', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=271` }, { group: 'bow-master', title: '보우마스터', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=311` }, { group: 'master-archer', title: '신궁', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=312` }, { group: 'wind-breaker', title: '윈드브레이커', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=321` }, { group: 'mercedes', title: '메르세데스', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=331` }, { group: 'wild-hunter', title: '와일드헌터', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=341` }, { group: 'night-lord', title: '나이트로드', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=411` }, { group: 'shadower', title: '섀도어', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=412` }, { group: 'duel-blader', title: '듀얼블레이더', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=413` }, { group: 'night-walker', title: '나이트워커', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=421` }, { group: 'phantom', title: '팬텀', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=431` }, { group: 'xenon', title: '제논', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=811` }, { group: 'viper', title: '바이퍼', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=511` }, { group: 'captain', title: '캡틴', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=512` }, { group: 'canon-shooter', title: '캐논슈터', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=513` }, { group: 'striker', title: '스트라이커', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=521` }, { group: 'eunwol', title: '은월', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=531` }, { group: 'mechanic', title: '메카닉', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=541` }, { group: 'angelic-buster', title: '엔젤릭버스터', url: `${INSOYA_HOST}zboard.php?id=talkmaple_job&divpage=9&category=551` }, ], }, { icon: 'globe', title: '인소야 포럼', component: Post, menus: [ { group: 'art', title: '아트 센터', url: `${INSOYA_HOST}zboard.php?id=forum_art&divpage=1` }, { group: 'free', title: '자유 토크', url: `${INSOYA_HOST}zboard.php?id=talkfree&divpage=8` }, { group: 'humor', title: '유머', url: `${INSOYA_HOST}zboard.php?id=talkfree&category=5&divpage=8` }, { group: 'game', title: '게임', url: `${INSOYA_HOST}zboard.php?id=talkfree&category=4&divpage=8` }, { group: 'computer', title: '컴퓨터/휴대폰', url: `${INSOYA_HOST}zboard.php?id=talkfree&category=2&divpage=8` }, { group: 'animation', title: '애니메이션', url: `${INSOYA_HOST}zboard.php?id=talkfree&category=3&divpage=8` }, ], }, { icon: 'user', title: '프로필', component: Info }, ]; export default MENUS;
import React from "react"; class RadiantTitle extends React.Component { constructor(props) { super(props); this.state = { addLight: false, }; // this.handleLighting = this.handleLighting.bind(this); } // handleLighting(lightState) { // this.lightTimeout = setTimeout(() => { // this.setState(() => ({ // addLight: !lightState, // })); // }, 1000); // } // componentDidMount() { // this.setState({ // addLight: !this.state.addLight, // }); // } // componentDidUpdate() { // this.handleLighting(this.state.addLight); // console.log(this.state); // } // componentWillUnmount() { // clearTimeout(this.lightTimeout); // } render() { return ( <h1 className={`app-title ${this.addLight ? "app-title-light" : null}`}> {this.props.children} </h1> ); } } export default RadiantTitle;
import React from 'react'; import T from 'prop-types'; import styles from './Stats.module.css'; const getRandomColor = () => { // eslint-disable-next-line no-bitwise const color = `#${((Math.random() * 0xffffff) | 0).toString(16)}`; return color; }; const Stats = ({ title, stats }) => ( <section className={styles.stats_section}> {title && <h2 className={styles.title}>{title}</h2>} <ul className={styles.stat_list}> {stats.map(stat => ( <li key={stat.id} className={styles.item} style={{ backgroundColor: getRandomColor() }} > <span className={styles.label}>{stat.label}</span> <span className={styles.percentage}>{stat.percentage}%</span> </li> ))} </ul> </section> ); Stats.defaultProps = { title: '', }; Stats.propTypes = { title: T.string, stats: T.arrayOf( T.shape({ id: T.string.isRequired, label: T.string.isRequired, percentage: T.number.isRequired, }).isRequired, ).isRequired, }; export default Stats;
import { track,LightningElement, api } from 'lwc'; export default class OmdbComponent extends LightningElement { @track data; @track error; fetchMovieName(event){ console.log('the entered movie name'+this.template.querySelector('lightning-input').value); let endPoint = "https://www.omdbapi.com/?s="+this.template.querySelector('lightning-input').value+"&apikey=696d01ae"; fetch( endPoint, { method : "GET" } ) .then(function(response) { return response.json(); }) .then(data => { if(data.Error){ this.error = true; } else{ this.error = false; this.data = data.Search; } }); } }
let input = [ "JS devs use Node.js for", "server-side JS", "JS devs use JS", "-- JS for devs" ]; function solve(strArr) { let test = strArr.join("\n"); let words = test.toLowerCase().split(/\W+/).filter(e => e !== ""); let result = new Set(); for (let word of words ) { result.add(word); } console.log([...result].join(", ")); //js, devs, use, node, for, server, side } solve(input);
var Package = require('dgeni').Package; var jsdocPackage = require('dgeni-packages/jsdoc'); var nunjucksPackage = require('dgeni-packages/nunjucks'); var ngdocPackage = require('dgeni-packages/ngdoc'); var linksPackage = require('dgeni-packages/links'); var gitPackage = require('dgeni-packages/git'); var path = require('canonical-path'); var url = require('url'); module.exports = new Package('fit-docs-package', [ jsdocPackage, nunjucksPackage, ngdocPackage, gitPackage]) .processor(require('./processors/create_index_processor')) .processor(require('./processors/modulePackageNameProcessor')) .processor(require('dgeni-packages/ngdoc/processors/memberDocs')) .config(function(debugDumpProcessor) { debugDumpProcessor.$enabled = true; }) .config(function(readFilesProcessor, writeFilesProcessor) { readFilesProcessor.basePath = path.resolve(__dirname,'../public'); readFilesProcessor.sourceFiles = [ { include: 'modules/*/*.js', exclude: 'bower_components/**' } ]; writeFilesProcessor.outputFolder = 'dgeni-docs'; }) .config(function(parseTagsProcessor) { // parseTagsProcessor.tagDefinitions.push(require('./tagdefs/ngdoc.js')); // parseTagsProcessor.tagDefinitions.push(require('./tagdefs/methodOf.js')); // parseTagsProcessor.tagDefinitions.push(require('./tagdefs/memberOf.js')); parseTagsProcessor.tagDefinitions.push(require('./tagdefs/example.js')); }) .config(function(readFilesProcessor, writeFilesProcessor, renderDocsProcessor, templateFinder, templateEngine, getInjectables) { var outputPath = path.resolve(readFilesProcessor.basePath, writeFilesProcessor.outputFolder); console.log(outputPath); renderDocsProcessor.helpers.getRelativeBasePath = function(doc) { console.log(doc.path, doc.outputPath, url.resolve(doc.outputPath, outputPath)); return url.resolve(doc.outputPath, outputPath); // doc.path='/a/b/c' -> '../../..' }; templateFinder.templateFolders.unshift(path.resolve(__dirname, 'templates')); templateEngine.config.tags = { variableStart: '{$', variableEnd: '$}' }; templateFinder.templatePatterns = [ '${ doc.template }', '${ doc.id }.${ doc.docType }.template.html', // 'FitFactory.module.template.html' '${ doc.id }.template.html', // 'FitFactory.template.html' '${ doc.docType }.template.html', // 'module.template.html' 'base.template.html' ].concat(templateEngine.templatePatterns); }) .config(function(inlineTagProcessor, getLinkInfo) { // inlineTagProcessor.$enabled = false; getLinkInfo.relativeLinks = true; }) .config(function(computePathsProcessor) { computePathsProcessor.pathTemplates = []; computePathsProcessor.pathTemplates.push({ docTypes: ['js'], pathTemplate: '${id}.html', outputPathTemplate: '${path}' }); computePathsProcessor.pathTemplates.push({ docTypes: ['module'], pathTemplate: '${area}/${name}/index.html', outputPathTemplate: '${path}' }); computePathsProcessor.pathTemplates.push({ docTypes:['componentGroup'], pathTemplate: '${area}/${moduleName}/${groupType}/index.html', outputPathTemplate: '${path}' }); computePathsProcessor.pathTemplates.push({ docTypes: ['controller', 'directive', 'service'], pathTemplate: '${area}/${module}/${docType}/${name}.html', outputPathTemplate: '${path}' }); }) .config(function(computeIdsProcessor, getAliases) { computeIdsProcessor.idTemplates.push({ docTypes: ['index'], idTemplate: 'index-doc', getAliases: function(doc) { return [doc.id]; } }); computeIdsProcessor.idTemplates.push({ docTypes: ['controller'], idTemplate: 'module:${module}.${docType}:${name}', getAliases: getAliases }); }) // .config(function(generateExamplesProcessor, generateProtractorTestsProcessor) { // generateExamplesProcessor.deployments = [{ name: 'default' }]; // generateProtractorTestsProcessor.deployments = [{ name: 'default' }]; // });
/* eslint-disable no-debugger */ import React, { useState, useEffect } from "react" import PropTypes from "prop-types" const Blog = ({ blog, incrementLikes, handleDelete, user }) => { const [detailsVisible, setDetailsVisible] = useState(false) function handleView() { console.log("visibility toggled to", !detailsVisible) setDetailsVisible(!detailsVisible) } const blogStyle = { border: "solid", borderWidth: 0.2, marginTop: 10, marginBottom: 5, maxWidth: "20%", } const headerStyle = { backgroundColor: "lightgrey", } return ( <div className="blogentry" style={blogStyle}> <div className="blogtitlebar" onClick={handleView} style={headerStyle}> {blog.title} by {blog.author} </div> {detailsVisible && ( <BlogDetails blog={blog} incrementLikes={incrementLikes} handleDelete={handleDelete} user={user} /> )} </div> ) } const BlogDetails = ({ blog, incrementLikes, handleDelete, user }) => { const [likes, setLikes] = useState(blog.likes) const [visible, setVisible] = useState(false) // This part was problematic, as the `blog` didn't have the populated user data // from MongoDB at first. This is fixed with a dirty hack in App.addBlog useEffect(() => { if (user !== null && blog.user.username === user.username) { setVisible(true) } }, []) const showForCurrentUser = { display: visible ? "" : "none" } // This is really ugly and hacky solution async function handleLikes(event) { const id = event.target.dataset.blogid // The likes value doesn't really matter as the backend will // always just increment the existing value with PATCH const updateData = { likes: 1 } const updatedBlog = await incrementLikes(id, updateData) blog = updatedBlog // TODO: should we set the blog as a React state instead of blog.likes? setLikes(updatedBlog.likes) } return ( <div className="blogdetails"> <div className="author">Author: {blog.author}</div> <div className="url">Url: {blog.url}</div> <div className="likes"> Likes: {likes} <LikeButton id={blog.id} handleLikes={handleLikes} /> </div> <div style={showForCurrentUser}> <button className="deletebutton" data-blogid={blog.id} onClick={handleDelete} > Delete </button> </div> </div> ) } BlogDetails.propTypes = { blog: PropTypes.object.isRequired, incrementLikes: PropTypes.func.isRequired, handleDelete: PropTypes.func.isRequired, user: PropTypes.object, } const LikeButton = ({ id, handleLikes }) => { return ( <> <button className="likebutton" data-blogid={id} onClick={handleLikes}> Like </button> </> ) } export default Blog
app.controller('profile', [ '$scope', '$rootScope', '$http', '$routeParams', function ($scope, $rootScope, $http, $routeParams) { var api = $rootScope.site_url + 'users'; $scope.errorClass = 'red-text'; //View User $scope.loader = () => { $http.get(api + '/view?data=user_id,name,email,gender,phone,dob,img').then(function (response) { var uInfo = response.data; for (let user of uInfo) { user.dob = new Date(user.dob); $scope.u = user; } // console.log(uInfo); }); }; $scope.loader(); //Update Profile $scope.updateProfile = function (data) { console.log('console:', data); $('#form').ajaxForm({ type: 'POST', url: api + '/profile', data: data, success: function (data) { if (data === '1') { $scope.loader(); swal('Good Job!', 'Profile Updated!', 'success'); $scope.errorMsg = ''; } else { $scope.errorMsg = data; } }, }); }; }, ]);
// import http from 'http' // import getSummonerByName from '../../src/Summoner/getSummonerByName' // jest.mock('http', () => ({ // get: jest.fn(), // })); describe('getSummonerByName()', () => { test('it should make the correct get request', () => { // expect.assertions(1); // return getSummonerByName('VinnyVudoo') // .then(() => { // expect(true).toHaveBeenCalledWith('') // }) expect(true).toBe(true) }) })
/** * @package eat * @author Codilar Technologies * @license https://opensource.org/licenses/OSL-3.0 Open Software License v. 3.0 (OSL-3.0) * @link http://www.codilar.com/ */ var config = { 'paths': { 'irpHandler': 'Codilar_Irp/js/irp_block_handler' } };
import React, { Component } from "react"; import { Button, Image, Menu, Responsive, Segment, Visibility, Container } from "semantic-ui-react"; import styled from "styled-components"; import HomePageHeading from "./HomePageHeading"; import logo from "../../assets/Pandora.svg"; import background from "../../assets/pitchblur.jpg"; const StyledSegment = styled(Segment)` &&& { padding: 0em; min-height: 540px; background-position: 50% 10%; background-repeat: no-repeat; background-size: cover; background-image: url(${background}); background-color: #88afdd; border: none; @media only screen and (min-width: 768px){ min-height: 740px; } } `; // background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1600 900'%3E%3Cpolygon fill='%235c8fd8' points='957 450 539 900 1396 900'/%3E%3Cpolygon fill='%234775b6' points='957 450 872.9 900 1396 900'/%3E%3Cpolygon fill='%234c81cc' points='-60 900 398 662 816 900'/%3E%3Cpolygon fill='%23456ca5' points='337 900 398 662 816 900'/%3E%3Cpolygon fill='%235180c4' points='1203 546 1552 900 876 900'/%3E%3Cpolygon fill='%233b5b8a' points='1203 546 1552 900 1162 900'/%3E%3Cpolygon fill='%23517ab7' points='641 695 886 900 367 900'/%3E%3Cpolygon fill='%23466797' points='587 900 641 695 886 900'/%3E%3Cpolygon fill='%234d6fa3' points='1710 900 1401 632 1096 900'/%3E%3Cpolygon fill='%23264c85' points='1710 900 1401 632 1365 900'/%3E%3Cpolygon fill='%231a4e99' points='1210 900 971 687 725 900'/%3E%3Cpolygon fill='%231c3c6b' points='943 900 1210 900 971 687'/%3E%3C/svg%3E"); export default class DesktopContainer extends Component { state = {}; render() { const { children } = this.props; return ( <Responsive maxWidth={5680}> <Visibility once={false}> <StyledSegment as={Segment}> <Menu size="small" secondary borderless pointing={false} style={{ padding: "0.5em 0", width: "100%" }} > <Container> <Menu.Item as="a"> <Image size="mini" src={logo} /> </Menu.Item> <Menu.Item position="right"> <Button style={{ background: "none", color: "#fff", fontSize: "1.3em", fontWeight: 600, borderRadius: 0, padding: "1em", paddingRight: "0.5em" }} > Publica tu Empresa </Button> <Button style={{ background: "none", color: "#fff", fontSize: "1.3em", fontWeight: 600, borderRadius: 0, padding: "1em", paddingLeft: "0.5em" }} > Inicia Sesion </Button> <Button style={{ background: "#483df6", color: "#fff", fontSize: "1.3em", fontWeight: 600, borderRadius: "2px" }} > Registrate </Button> </Menu.Item> </Container> </Menu> <HomePageHeading /> </StyledSegment> </Visibility> {children} </Responsive> ); } }
import React from 'react'; import styled from 'styled-components' const SearchFilterContainer = styled.div` background: lightgreen; width: 100%; height:80px; ` const SearchFilter = () => { return ( <SearchFilterContainer> Search Filter </SearchFilterContainer> ); } export default SearchFilter;
// Method is a property of an object let restaurant = { name: 'ASB', guessCapacity: 75, guestCount: 0, checkAvailanility : function(partySize) { let seatsLeft = this.guessCapacity - this.guestCount return partySize <= seatsLeft }, seatParty : function(partySize) { this.guestCount = this.guestCount + partySize }, removeParty : function (partySize) { this.guestCount = this.guestCount - partySize } } //SeatParty // RemoveParty restaurant.seatParty(72) console.log(restaurant.checkAvailanility(4)) restaurant.removeParty(5) console.log(restaurant.checkAvailanility(4))
export const RevealCells = (cells, xCoord, yCoord, newSafeCells) => { let toShow = []; toShow.push(cells[xCoord][yCoord]); while (toShow.length !== 0) { let one = toShow.pop(); let i = one.x; let j = one.y; if (!one.revealed) { newSafeCells--; one.revealed = true; } if (one.value !== 0) { break; } // reveal adjacent cells if (i > 0 && j > 0 && cells[i - 1][j - 1].value === 0 && !cells[i - 1][j - 1].revealed) { toShow.push(cells[i - 1][j - 1]); } if (i < cells.length - 1 && j < cells[0].length - 1 && cells[i + 1][j + 1].value === 0 && !cells[i + 1][j + 1].revealed) { toShow.push(cells[i + 1][j + 1]); } if (i > 0 && j < cells[0].length - 1 && cells[i - 1][j + 1].value === 0 && !cells[i - 1][j + 1].revealed) { toShow.push(cells[i - 1][j + 1]); } if (i < cells.length - 1 && j > 0 && cells[i + 1][j - 1].value === 0 && !cells[i + 1][j - 1].revealed) { toShow.push(cells[i + 1][j - 1]); } if (i > 0 && cells[i - 1][j].value === 0 && !cells[i - 1][j].revealed) { toShow.push(cells[i - 1][j]); } if (j < cells[0].length - 1 && cells[i][j + 1].value === 0 && !cells[i][j + 1].revealed) { toShow.push(cells[i][j + 1]); } if (i < cells.length - 1 && cells[i + 1][j].value === 0 && !cells[i + 1][j].revealed) { toShow.push(cells[i + 1][j]); } if (j > 0 && cells[i][j - 1].value === 0 && !cells[i][j - 1].revealed) { toShow.push(cells[i][j - 1]); } // reveal if (i > 0 && j > 0 && !cells[i - 1][j - 1].revealed) { cells[i - 1][j - 1].revealed = true; newSafeCells--; } if (j > 0 && !cells[i][j - 1].revealed) { cells[i][j - 1].revealed = true; newSafeCells--; } if (i < cells.length - 1 && j > 0 && !cells[i + 1][j - 1].revealed) { cells[i + 1][j - 1].revealed = true; newSafeCells--; } if (i > 0 && !cells[i - 1][j].revealed) { cells[i - 1][j].revealed = true; newSafeCells--; } if (i < cells.length - 1 && !cells[i + 1][j].revealed) { cells[i + 1][j].revealed = true; newSafeCells--; } if (i > 0 && j < cells[0].length - 1 && !cells[i - 1][j + 1].revealed) { cells[i - 1][j + 1].revealed = true; newSafeCells--; } if (j < cells[0].length - 1 && !cells[i][j + 1].revealed) { cells[i][j + 1].revealed = true; newSafeCells--; } if (i < cells.length - 1 && j < cells[0].length - 1 && !cells[i + 1][j + 1].revealed) { cells[i + 1][j + 1].revealed = true; newSafeCells--; } } return {cells, newSafeCells} } export const RevealAdjacentCells = (cells, xCoord, yCoord, newSafeCells) => { let toShow = []; let lostGame = false; let losingX, losingY; toShow.push(cells[xCoord][yCoord]); while (toShow.length !== 0) { let one = toShow.pop(); let i = one.x; let j = one.y; // reveal if (i > 0 && j > 0 && !cells[i - 1][j - 1].revealed && !cells[i - 1][j - 1].flagged) { cells[i - 1][j - 1].revealed = true; newSafeCells--; if (cells[i - 1][j - 1].value !== 'X') { if (cells[i - 1][j - 1].value === 0) { ({cells, newSafeCells} = RevealCells(cells, i - 1, j - 1, newSafeCells)); } } else { losingX = i - 1; losingY = j - 1; lostGame = true; } } if (j > 0 && !cells[i][j - 1].revealed && !cells[i][j - 1].flagged) { cells[i][j - 1].revealed = true; newSafeCells--; if (cells[i][j - 1].value !== 'X') { if (cells[i][j - 1].value === 0) { ({cells, newSafeCells} = RevealCells(cells, i, j - 1, newSafeCells)); } } else { losingX = i; losingY = j - 1; lostGame = true; } } if (i < cells.length - 1 && j > 0 && !cells[i + 1][j - 1].revealed && !cells[i + 1][j - 1].flagged) { cells[i + 1][j - 1].revealed = true; newSafeCells--; if (cells[i + 1][j - 1].value !== 'X') { if (cells[i + 1][j - 1].value === 0) { ({cells, newSafeCells} = RevealCells(cells, i + 1, j - 1, newSafeCells)); } } else { losingX = i + 1; losingY = j - 1; lostGame = true; } } if (i > 0 && !cells[i - 1][j].revealed && !cells[i - 1][j].flagged) { cells[i - 1][j].revealed = true; newSafeCells--; if (cells[i - 1][j].value !== 'X') { if (cells[i - 1][j].value === 0) { ({cells, newSafeCells} = RevealCells(cells, i - 1, j, newSafeCells)); } } else { losingX = i - 1; losingY = j; lostGame = true; } } if (i < cells.length - 1 && !cells[i + 1][j].revealed && !cells[i + 1][j].flagged) { cells[i + 1][j].revealed = true; newSafeCells--; if (cells[i + 1][j].value !== 'X') { if (cells[i + 1][j].value === 0) { ({cells, newSafeCells} = RevealCells(cells, i + 1, j, newSafeCells)); } } else { losingX = i + 1; losingY = j - 1; lostGame = true; } } if (i > 0 && j < cells[0].length - 1 && !cells[i - 1][j + 1].revealed && !cells[i - 1][j + 1].flagged) { cells[i - 1][j + 1].revealed = true; newSafeCells--; if (cells[i - 1][j + 1].value !== 'X') { if (cells[i - 1][j + 1].value === 0) { ({cells, newSafeCells} = RevealCells(cells, i - 1, j + 1, newSafeCells)); } } else { losingX = i - 1; losingY = j + 1; lostGame = true; } } if (j < cells[0].length - 1 && !cells[i][j + 1].revealed && !cells[i][j + 1].flagged) { cells[i][j + 1].revealed = true; newSafeCells--; if (cells[i][j + 1].value !== 'X') { if (cells[i][j + 1].value === 0) { ({cells, newSafeCells} = RevealCells(cells, i, j + 1, newSafeCells)); } } else { losingX = i; losingY = j + 1; lostGame = true; } } if (i < cells.length - 1 && j < cells[0].length - 1 && !cells[i + 1][j + 1].revealed && !cells[i + 1][j + 1].flagged) { cells[i + 1][j + 1].revealed = true; newSafeCells--; if (cells[i + 1][j + 1].value !== 'X') { if (cells[i + 1][j + 1].value === 0) { ({cells, newSafeCells} = RevealCells(cells, i + 1, j + 1, newSafeCells)); } } else { losingX = i + 1; losingY = j + 1; lostGame = true; } } } return {cells, newSafeCells, lostGame, losingX, losingY} } export const CountFlags = (cells, xCoord, yCoord) => { let count = 0; // count if (xCoord > 0 && yCoord > 0 && cells[xCoord - 1][yCoord - 1].flagged) { count++; } if (yCoord > 0 && cells[xCoord][yCoord - 1].flagged) { count++; } if (xCoord < cells.length - 1 && yCoord > 0 && cells[xCoord + 1][yCoord - 1].flagged) { count++; } if (xCoord > 0 && cells[xCoord - 1][yCoord].flagged) { count++; } if (xCoord < cells.length - 1 && cells[xCoord + 1][yCoord].flagged) { count++; } if (xCoord > 0 && yCoord < cells[0].length - 1 && cells[xCoord - 1][yCoord + 1].flagged) { count++; } if (yCoord < cells[0].length - 1 && cells[xCoord][yCoord + 1].flagged) { count++; } if (xCoord < cells.length - 1 && yCoord < cells[0].length - 1 && cells[xCoord + 1][yCoord + 1].flagged) { count++; } return count; }
const Discord = require('discord.js'); const client = new Discord.Client(); const prefix = '!'; const bot = new Discord.Client({disableEveryone: true}); client.on("ready", async() => { console.log(`${bot.user.username} is online!!!`); client.user.setActivity("Lucius", {type:"Rerolling for"}); }); //aaaaaaaaaaaaaaaaaaa client.on('message',function(message) { if(message.content == 'soulgear') { message.channel.send("https://www.youtube.com/watch?v=7x0aUgpEJa0"); } if(message.content == 'czpatan') { message.channel.send("https://imgur.com/iNYNrT6"); } if(message.content == 'brackpatan') { message.channel.send("https://imgur.com/tCv9nby"); } if(message.content == 'gracearcstar') { message.channel.send("https://imgur.com/7yLD5F2"); } if(message.content == 'lifesarcstar') { message.channel.send("https://imgur.com/81th8JU"); } if(message.content == '373arcstar') { message.channel.send("https://imgur.com/zpVDHml"); } if(message.content == 'czarcstar') { message.channel.send("https://imgur.com/vaH2yCL"); } if(message.content == 'graceogdoad') { message.channel.send("https://imgur.com/24MWKVa"); } if(message.content == 'slimeogdoad') { message.channel.send("430k https://imgur.com/CI7P6Uz"); } //cdfh if(message.content == 'cdfhogdoad') { message.channel.send("570k https://imgur.com/iulAFMQ"); } if(message.content == 'cdfhzaratan') { message.channel.send("83k https://imgur.com/surBFkM"); } if(message.content == 'cdfhterion') { message.channel.send("105k https://imgur.com/jiP2dEr"); } if(message.content == 'cdfharcstar') { message.channel.send("530k https://imgur.com/NIxzsNq"); } }); client.on('message',function(message) { if(message.content == 'therethere') { message.channel.send("https://imgur.com/Kgr7HkN"); } if(message.content == 'floriavs3musk') { message.channel.send("https://imgur.com/d1X2MZO"); } if(message.content == 'imnotsalty') { message.channel.send("https://imgur.com/PSeSDWW"); } if(message.content == 'watchin') { message.channel.send("https://imgur.com/9v69zMi"); } if(message.content == 'shikkari') { message.channel.send("https://imgur.com/tU2VQQW"); } if(message.content == 'uguh') { message.channel.send("https://imgur.com/1ajKXE9"); } if(message.content == 'imawhale') { message.channel.send("https://imgur.com/FoZAon2"); } if(message.content == 'ohmygah') { message.channel.send("https://imgur.com/MAI37HS"); } if(message.content == 'waaa') { message.channel.send("https://imgur.com/YSsMqIY"); } if(message.content == 'hah?') { message.channel.send("https://imgur.com/Ns25fcY"); } if(message.content == 'oyaoya') { message.channel.send("https://imgur.com/ogavh0h"); } if(message.content == 'imconcern') { message.channel.send("https://imgur.com/PoRlAV3"); } }); client.login(process.env.BOT_TOKEN);
const entrance = { sender: '발신자', isPrivate: true, postcardCount: 4, writtenCount: 1000, movePage: false, }; export default entrance;
var express = require("express"); var app = express(); var bodyParser = require("body-parser"); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use("/", express.static(__dirname + "/public")); var port = 3000; app.set("view engine", "ejs"); var model = require("./model"); var logic = require("./logic"); var routes = require("./routes"); app.use("/", routes); app.listen(port, function (req, res) { console.log("Server started!, listening on port " + port); });
const jwt = require('jsonwebtoken') const knex = require('knex')({ client: "mysql", connection: { host: process.env.host, user: process.env.user, password: process.env.password, database: process.env.database } }) exports.departments = (req, res) => { knex.select('*').from('department') .then((data) => { res.send(data) }).catch((err) => { res.send({ err: err.message }) }) } exports.department_id = (req, res) => { knex.select('*').from('department').where('department_id', req.params.id) .then((data) => { res.send(data) }).catch((err) => { res.send({ err: err.message }) }) } exports.category = (req, res) => { knex.select('*').from('category') .then((data) => { res.send(data) }).catch((err) => { res.send({ err: err.message }) }) } exports.category_id = (req, res) => { knex.select('*').from('category').where('category_id', req.params.id) .then((data) => { res.send(data) }).catch((err) => { res.send({ err: err.message }) }) } exports.category_inDepartment = (req, res) => { knex.select('*').from('category').where('department_id', req.params.id) .then((data) => { res.send(data) }).catch((err) => { res.send({ err: err.message }) }) } exports.attribute = (req, res) => { knex.select('*').from('attribute') .then((data) => { res.send(data) }).catch((err) => { res.send({ err: err.message }) }) } exports.attribute_id = (req, res) => { knex.select('*').from('attribute').where('attribute_id', req.params.id) .then((data) => { res.send(data) }).catch((Err) => { res.send({ err: err.message }) }) } exports.attribute_values = (req, res) => { knex.select('attribute_value_id', 'value') .from('attribute_value') .where('attribute_id', req.params.id) .then((data) => { res.send(data); }).catch((err) => { res.send({ err: err.message }) }) } exports.attribute_inProduct = (req, res) => { knex.select('*').from('attribute') .join('attribute_value', function () { this.on('attribute.attribute_id', 'attribute_value.attribute_id') }) .join('product_attribute', function () { this.on('attribute_value.attribute_value_id', 'product_attribute.attribute_value_id') }) .where('product_attribute.product_id', req.params.id) .then((data) => { let arr = [] for (let x of data) { var dict = { attribute_name: x.name, attribute_value_id: x.attribute_value_id, attribute_value: x.value } arr.push(dict) } res.send(arr) }).catch((err) => { res.send({ err: err.message }) }) } exports.product = (req, res) => { knex.select('*').from('product') .then((data) => { res.send(data) }).catch((err) => { res.send({ err: err.message }) }) } exports.product_search = (req, res) => { const search = req.query.query_string console.log(req.query.query_string) knex.select('name', 'description', 'price', 'discounted_price', 'thumbnail').from('product').where("name", 'like', `%${search}%`).orWhere('description', 'like', `%${search}%`) .then((data) => { res.send(data) }).catch((err) => { res.send({ err: err.message }) }) } exports.product_id = (req, res) => { knex.select('*').from('product').where('product_id', req.params.id) .then((data) => { res.send(data) }).catch((err) => { res.send({ err: err.message }) }) } exports.product_inCategory = (req, res) => { knex.select('*').from('product') .join('product_category', function () { console.log(this.on('product.product_id', 'product_category.product_id')) }) .where('product_category.category_id', req.params.id) .then((data) => { res.send(data) }).catch((err) => { res.send({ err: err.message }) }) } exports.product_inDepartment = (req, res) => { knex.select( 'product.product_id', 'product.name', 'product.description', 'product.price', 'product.discounted_price', 'product.thumbnail' ) .from('product') .join('product_category', function () { console.log((this.on('product.product_id', 'product_category.product_id'))) }) .join('category', function () { console.log(this.on('product_category.category_id', 'category.category_id')) }) .join('department', function () { console.log(this.on('category.department_id', 'department.department_id')) }) .where('department.department_id', req.params.id) .then((data) => { res.send(data); }).catch((err) => { res.send({ err: err.message }) }) } exports.product_details = (req, res) => { knex.select("*").from('product').where('product_id', req.params.id) .then((data) => { res.send(data) }).catch((err) => { res.send({ err: err.message }) }) } exports.product_location = (req, res) => { knex.select( 'category.category_id', 'category.name as category_name', 'category.department_id', 'department.name as department_name' ).from('product') .join('product_category', function () { this.on('product.product_id', 'product_category.product_id') }) .join('category', function () { this.on('product_category.category_id', 'category.category_id') }) .join('department', function () { this.on('category.department_id', 'department.department_id') }) .where('product.product_id', req.params.id) .then((data) => { res.send(data) }).catch((err) => { res.send({ err: err.message }) }) } exports.product_review_get = (req, res) => { knex.select('*').from('review').where('review_id', req.params.id).then((data) => { res.send(data) }).catch((err) => { res.send({ err: err.message }) }) } exports.product_review_post = (req, res) => { knex.select('*').from('customer').where('customer_id', 1).then((data) => { knex('review').insert({ review: req.body.review, rating: req.body.rating, product_id: req.params.id, created_on: new Date, customer_id: data[0].customer_id }).then((data2) => { res.send('review add successfully') }).catch((err) => { console.log(err) }) }) } exports.customer_post = (req, res) => { knex('customer').insert({ name: req.body.name, email: req.body.email, password: req.body.password, credit_card: req.body.credit_card, address_1: req.body.address_1, address_2: req.body.address_2, city: req.body.city, region: req.body.region, postal_code: req.body.postal_code, country: req.body.country, shipping_region_id: req.body.shipping_region_id, day_phone: req.body.day_phone, eve_phone: req.body.eve_phone, mob_phone: req.body.mob_phone }).then(() => { res.send({ message: 'Signup successfully' }) }).catch((err) => { res.send({ err: err.message }) }) } exports.customer_get = (req, res) => { knex.select('*').from('customer') .then((data) => { res.send(data) }).catch((err) => { res.send({ err: err.message }) }) } exports.customer_put = (req, res) => { knex('customer').where('email', req.body.email) .update({ credit_card: req.body.credit_card, address_1: req.body.address_1, address_2: req.body.address_2, city: req.body.city, region: req.body.region, postal_code: req.body.postal_code, country: req.body.country, shipping_region_id: req.body.shipping_region_id, day_phone: req.body.day_phone, eve_phone: req.body.eve_phone, mob_phone: req.body.mob_phone }).then(() => { res.send({ message: 'updated successfully' }) }).catch((err) => { console.log({ err: err.message }) }) } exports.login = (req, res) => { knex.select('email', 'password').from('customer').where('email', req.body.email) .then((data) => { if (data[0].password === req.body.password) { var token = jwt.sign(req.body, "siddik", { expiresIn: "24h" }) res.cookie('token', token) res.send({ message: 'login successfully' }) } else { res.send({ message: 'please check the password' }) } }).catch((err) => { res.send({ err: err.message }) }) } exports.shoppingcart_add = (req, res) => { knex('shopping_cart').insert({ cart_id: req.body.cart_id, product_id: req.body.product_id, attributes: req.body.attributes, quantity: req.body.quantity, buy_now: req.body.buy_now }).then(() => { knex.select( 'item_id', 'name', 'attributes', 'shopping_cart.product_id', 'price', 'quantity', 'image').from('shopping_cart').join('product', function () { this.on('shopping_cart.product_id', 'product.product_id') }).then((data) => { res.send(data) }).catch((err) => { console.log({ err: err.message }) }) }).catch((err) => { res.send({ err: err.message }) }) } exports.shoppingcart_id = (req, res) => { knex.select('item_id', 'name', 'attributes', 'shopping_cart.product_id', 'price', 'quantity', 'image').from('shopping_cart').join('product', function () { this.on('shopping_cart.product_id', 'product.product_id') }).where('shopping_cart.cart_id', req.params.cart_id) .then((data) => { res.send(data) }).catch((err) => { console.log(err) }) } exports.shoppingcart_update = (req, res) => { knex('shopping_cart').where('shopping_cart.item_id', req.params.id) .update({ 'quantity': req.body.quantity }).then((data) => { knex.select('item_id', 'product.name', 'shopping_cart.attributes', 'shopping_cart.product_id', 'product.price', 'shopping_cart.quantity', 'product.image').from('shopping_cart').where('shopping_cart.item_id', req.params.id).join('product', function () { this.on('shopping_cart.product_id', 'product.product_id') }).then((data) => { res.send(data) }).catch((err) => { console.log({ err: err.message }) }) }).catch((err) => { console.log({ err: err.message }) }) } exports.shoppingcart_empty = (req, res) => { knex('shopping_cart').where('cart_id', req.params.id).del().then((data) => { res.send({ message: 'cart remove successfully' }) }).catch((err) => { res.send({ err: err.message }) }) } exports.moveTo = (req, res) => { knex.select('*').from('later').where('item_id', req.params.id) .then((data) => { if (data.length > 0) { knex('cart').insert(data[0]) .then((data2) => { knex.select('*').from('later').where('item_id', req.params.id).del() .then((data3) => { res.send({ message: 'data move to shoppind cart to cart successfully' }) }).catch((err) => { res.send({ err: err.message }) }) }).catch((err) => { res.send({ err: err.message }) }) } else { res.send({ message: 'this id item is not found' }) } }).catch((err) => { res.send({ err: err.message }) }) } exports.totalAmount = (req, res) => { knex.select('price', 'quantity').from('shopping_cart').join('product', function () { this.on('shopping_cart.product_id', 'product.product_id') }).where('shopping_cart.cart_id', req.params.id).then((data) => { let dic = {} let a = data[0].price * data[0].quantity dic.totalAmount = a res.send(dic) }).catch((err) => [ res.send({ err: err.message }) ]) } exports.savedForLater = (req, res) => { knex.select("*").from('shopping_cart').where('item_id', req.params.id).then((data) => { knex('later').insert(data[0]).then((data2) => { knex.select("*").from('shopping_cart').where('item_id', req.params.id).del().then((data3) => { res.send({ message: 'data move from shopping cart to save for later' }) }).catch((err) => { res.send({ err: err.message }) }) }).catch((err) => { res.send({ err: err.message }) }) }).catch((err) => { res.send({ err: err.message }) }) } exports.getSaved = (req, res) => { knex.select( 'item_id', 'product.name', 'shopping_cart.attributes', 'product.price').from('shopping_cart').join('product', function () { this.on('shopping_cart.product_id', 'product.product_id') }).where('shopping_cart.cart_id', req.params.id).then((data) => { res.send(data) }).catch((err) => { res.send({ err: err.message }) }) } exports.removedProduct = (req, res) => { knex.select('*').from('shopping_cart').where('item_id', req.params.id).del().then((data) => { res.send({ message: 'product removed successfully from shopping cart' }) }).catch((Err) => { res.send({ err: err.message }) }) } exports.tax = (req, res) => { knex.select('*').from('tax').then((data) => { res.send(data) }).catch((err) => { res.send({ err: err.message }) }) } exports.tax_id = (req, res) => { knex.select('*').from('tax').where('tax_id', req.params.id).then((data) => { res.send(data) }).catch((err) => { console.log(err) }) } exports.shipping = (req, res) => { knex.select('*').from('shipping_region').then((data) => { res.send(data) }).catch((err) => { res.send({ err: err.message }) }) } exports.shipping_id = (req, res) => { knex.select('*').from('shipping').where('shipping_region_id', req.params.id).then((data) => { res.send(data) }).catch((err) => { res.send({ err: err.message }) }) } exports.order = (req, res) => { knex.select('*').from('shopping_cart').where('cart_id', req.body.cart_id).join('product', function () { this.on('shopping_cart.product_id', 'product.product_id') }).then((data) => { knex('orders').insert({ 'total_amount': data[0].quantity * data[0].price, 'created_on': new Date(), "customer_id": res.user.customer_id, "shipping_id": req.body.shipping_id, "tax_id": req.body.tax_id }).then((data2) => { console.log(data, '2') knex("order_detail").insert({ "unit_cost": data[0].price, "quantity": data[0].quantity, "product_name": data[0].name, "attributes": data[0].attributes, "product_id": data[0].product_id, "order_id": data2[0] }).then((data3) => { console.log(data3, '3') knex.select('*').from('shopping_cart').where('cart_id', req.body.cart_id).del() .then((data4) => { res.send({ order_status: 'ordered successfully', order_id: data2[0] }) }).catch((err) => { res.send({ err: err.message }) }) }).catch((err) => { res.send({ err: err.message }) }) }).catch((err) => { res.send({ err: err.message }) }) }).catch((err) => { res.send({ err: err.message }) }) } exports.order_id = (req, res) => { knex.select('orders.order_id', 'product.product_id', 'order_detail.attributes', 'product.name as product_name', 'order_detail.quantity', 'product.price', 'order_detail.unit_cost').from('orders') .join('order_detail', function () { this.on('orders.order_id', 'order_detail.order_id') }).join('product', function () { this.on('order_detail.product_id', 'product.product_id') }).where('orders.order_id', req.params.id) .then((data) => { res.send(data) }).catch((err) => { res.send({ err: err.message }) }) } exports.order_inCustomer = (req, res) => { knex.select('*').from('customer').where('customer_id', req.params.id).then((data) => { res.send(data) }).catch((err) => { res.send({ err: err.message }) }) } exports.shortDetails = (req, res) => { knex.select('orders.order_id', 'orders.total_amount', 'orders.created_on', 'orders.shipped_on', 'orders.status', 'order_detail.product_name as name').from('orders').join('order_detail', function () { this.on('orders.order_id', 'order_detail.order_id') }).where('order_detail.order_id', req.params.id).then((data) => { res.send(data) }).catch((err) => { res.send({ err: err.message }) }) }
export default { name: 'ionicons-v5', mediaPlayer: { play: 'ion-play', pause: 'ion-pause', volumeOff: 'ion-volume-off', volumeDown: 'ion-volume-low', volumeUp: 'ion-volume-high', settings: 'ion-settings', speed: 'ion-flash', language: 'ion-logo-closed-captioning', selected: 'ion-checkmark', fullscreen: 'ion-expand', fullscreenExit: 'ion-contract', bigPlayButton: 'ion-play' } }
;(function ( $, window, document, undefined ) { var plugin_name = 'touchslide', defaults = { autoslide: true, parent_selector: null, ul_selector: 'ul', li_selector: 'li', duration: 500, threshold: .2 }; // The actual plugin constructor function TouchSlide( el, options ) { this.el = el; this.$el = $(el); this.options = $.extend({}, defaults, options); this.init(); } $.extend(TouchSlide.prototype, { init: function(){ this.getElements(); this.style(); this.position(); this.setHandlers(); this.display(this.active); }, getElements: function(){ this.$overflow = (this.options.parent_selector) ? this.$el.find(this.options.parent_selector) : this.$el; this.$panel = this.$el.find(this.options.ul_selector); this.$slides = this.$panel.find('li'); this.$infos = this.$el.find('.workitems .workitem'); this.len = this.$slides.length; this.percent = 100/this.len; this.active = 0; }, style: function(){ this.$overflow.css({ 'position': 'relative', 'overflow': 'hidden' }); this.$panel.css({ 'position':'relative', 'width':this.len*100 + '%', 'overflow':'hidden' }); this.$slides.css({ 'float':'left', 'width':(this.percent) + '%' }); this.$slides.each(function(i, slide){ $(slide).attr({'data-index':i}); }); }, position: function(){ this.updateOffset(this.getOffset()); }, getOffset: function(){ return -this.active*this.percent; }, getSlide: function(){ return this.$slides.filter('[data-index='+this.active+']'); }, updateOffset:function(offset){ var offset = offset + '%'; this.$panel.css({ '-webkit-transform':'translate3d('+ offset +',0,0)', 'transform':'translate3d('+ offset +',0,0)', }); }, setHandlers: function(){ var that = this, current_width = this.$el.width(), viewing_percentage = 100/this.len, moved, new_offset, current_offset, dir; this.$el = this.$el.hammer(); this.$el.on('dragstart', function(e){ e.preventDefault(); current_offset = that.getOffset(); that.$panel.css({ 'transition':0 + 'ms', }); }) .on('dragend', function(e){ e.preventDefault(); that.$panel.css({ 'transition':that.options.duration + 'ms' }); var above_threshold = Math.abs(moved) > that.options.threshold; if(new_offset > 0){ that.updateOffset(0); }else if(new_offset < (that.percent - 100)){ that.updateOffset(that.percent -100); }else{ if(new_offset > current_offset && above_threshold){ that.active = that.active -= 1; that.position(); that.$el.trigger('new:active'); }else if(above_threshold){ that.active = that.active += 1; that.position(); that.$el.trigger('new:active'); }else{ that.updateOffset(current_offset); } } }) .on('drag', function(e){ e.preventDefault(); var total; moved = e.gesture.deltaX/current_width; total = viewing_percentage * moved; new_offset = current_offset + total; that.updateOffset(new_offset); }) .on('new:active', function(){ that.display(that.active); }); }, display: function(index){ $target = this.getSlide(index); this.$slides.find('.active').removeClass('active'); $target.find('a').addClass('active'); this.changeCaption($target); }, changeCaption: function($target){ var id = $target.attr('data-id'), $info = this.$infos.filter('[id='+ id +']'); this.$infos.filter('.active').removeClass('active'); $info.addClass('active'); } }); $.fn[plugin_name] = function ( options ) { return this.each(function () { if ($.data(this, 'plugin_' + plugin_name)){ var old_instance = $.data(this, 'plugin_' + plugin_name); old_instance.$el.off('dragstart'); old_instance.$el.off('dragend'); old_instance.$el.off('drag'); } $.data(this, 'plugin_' + plugin_name, new TouchSlide( this, options )); }); } })( jQuery, window, document );
var pageSize = 25; Ext.define('gigade.SiteAnalyticsList', { extend: 'Ext.data.Model', fields: [ { name: "sa_id", type: "int" }, { name: "sa_date", type: "string" }, { name: "sa_session", type: "int" }, { name: "sa_user", type: "int" }, { name: "sa_create_time", type: "string" }, { name: "sa_create_user", type: "int" }, { name: "s_sa_create_user", type: "string" }, { name: "s_sa_date", type: "string" }, { name: "s_sa_create_time", type: "string" }, { name: "sa_pageviews", type: "int" }, { name: "sa_pages_session", type: "string" }, { name: "sa_bounce_rate", type: "string" }, { name: "sa_avg_session_duration", type: "string" }, { name: "sa_modify_time_query", type: "string" }, { name: "sa_modify_username", type: "string" }, ] }); var SiteAnalyticsListStore = Ext.create('Ext.data.Store', { model: 'gigade.SiteAnalyticsList', autoLoad: true, proxy: { type: 'ajax', url: '/SiteManager/GetSiteAnalyticsList', reader: { type: 'json', root: 'data', totalProperty: 'totalCount' } } }); var DateStore = Ext.create('Ext.data.Store', { fields: ['txt', 'value'], data: [ { "txt": "所有日索引", "value": "0" }, { "txt": "單日日索引", "value": "1" }, ] }); var sm = Ext.create('Ext.selection.CheckboxModel', { listeners: { selectionchange: function (sm, selections) { var row = Ext.getCmp("SiteAnalyticsList").getSelectionModel().getSelection(); Ext.getCmp("SiteAnalyticsList").down('#edit').setDisabled(selections.length == 0); Ext.getCmp("SiteAnalyticsList").down('#delete').setDisabled(selections.length == 0); } } }); SiteAnalyticsListStore.on('beforeload', function () { Ext.apply(SiteAnalyticsListStore.proxy.extraParams, { serch_sa_date: Ext.getCmp("serch_sa_date").getValue(), search_con: Ext.getCmp("search_con").getValue(), }); }); /***************************新增***********************/ onAddClick = function () { editFunction(null, SiteAnalyticsListStore); } /*********************編輯**********************/ onEditClick = function () { var row = Ext.getCmp("SiteAnalyticsList").getSelectionModel().getSelection();//獲取選中的行數 if (row.length > 1) { Ext.Msg.alert(INFORMATION, ONE_SELECTION); } else if (row.length == 1) { editFunction(row[0], SiteAnalyticsListStore); } } //刪除 onDeleteClick = function () { var row = Ext.getCmp("SiteAnalyticsList").getSelectionModel().getSelection(); Ext.Msg.confirm(CONFIRM, Ext.String.format("刪除選中" + row.length + "條數據?", row.length), function (btn) { if (btn == 'yes') { var rowIDs = ''; for (var i = 0; i < row.length; i++) { rowIDs += row[i].data["sa_id"] + ','; } Ext.Ajax.request({ url: '/SiteManager/DeleteSiteAnalyticsById',//執行方法 method: 'post', params: { ids: rowIDs }, success: function (response) { var result = Ext.decode(response.responseText); if (result.success) { Ext.Msg.alert(INFORMATION, "刪除成功!"); for (var i = 0; i < row.length; i++) { SiteAnalyticsListStore.remove(row[i]); } } else { Ext.Msg.alert(INFORMATION, "無法刪除!"); } }, failure: function () { Ext.Msg.alert(INFORMATION, FAILURE); } }); } }); } Ext.onReady(function () { function Query() { SiteAnalyticsListStore.removeAll(); Ext.getCmp("SiteAnalyticsList").store.loadPage(1, { params: { serch_sa_date: Ext.getCmp("serch_sa_date").getValue(), search_con: Ext.getCmp("search_con").getValue(), } }); } outExcel = function () { var params = 'search_con=' + Ext.getCmp("search_con").getValue() + '&serch_sa_date=' + Ext.htmlEncode(Ext.Date.format(new Date(Ext.getCmp('serch_sa_date').getValue()), 'Y-m-d')) window.open('/SiteManager/ExportExcel?' + params); } var form = Ext.create('Ext.form.Panel', { bodyPadding: 10, layout: 'anchor', height: 100, margin: '0 10 0 0', width: 600, border: false, url: '/SiteManager/ImportExcel', items: [ { xtype: 'fieldcontainer', layout: 'hbox', items: [ { xtype: 'filefield', id: 'ImportExcel', width: 400, labelWidth:70, anchor: '100%', name: 'ImportExcel', fieldLabel: '匯入Excel', allowBlank: false, buttonText: '選擇Excel...' }, { xtype: 'displayfield', margin:'0 0 0 10', value: '<a href="/Template/SiteAnalytics/SiteAnalytics.xlsx">範例下載</a>' }, ], } ], buttonAlign: 'right', buttons: [ { text: '匯入', formBind: true, disabled: true, handler: function () { var form = this.up('form').getForm(); if (form.isValid()) { form.submit({ waitMsg: '正在匯入...', params: { ImportExcel: Ext.htmlEncode(Ext.getCmp('ImportExcel').getValue()) }, success: function (form, action) { var result = Ext.decode(action.response.responseText); if (result.success=='true') { Ext.Msg.alert("提示信息", "匯入成功"); SiteAnalyticsListStore.load(); } else { Ext.Msg.alert("提示信息", "匯入失敗"); } }, failure: function () { Ext.Msg.alert("提示信息", "匯入失敗"); } }); } } } ] }); var SiteAnalyticsList = Ext.create('Ext.grid.Panel', { id: 'SiteAnalyticsList', store: SiteAnalyticsListStore, width: document.documentElement.clientWidth, columnLines: true, frame: true, flex: 9.8, columns: [ { header: "編號", dataIndex: 'sa_id', width: 80, align: 'center' }, { header: "日索引", dataIndex: 's_sa_date', width: 150, align: 'center' }, { header: "造訪數", dataIndex: 'sa_session', align: '120', align: 'center' }, { header: "使用者", dataIndex: 'sa_user', align: '120', align: 'center' }, { header: "瀏覽量", dataIndex: 'sa_pageviews', width: 50, align: 'center' }, { header: "單次造訪頁數", dataIndex: 'sa_pages_session', width: 120, align: 'center' }, { header: "跳出率", dataIndex: 'sa_bounce_rate', align: '120', align: 'center' }, { header: "平均停留時間(s)", dataIndex: 'sa_avg_session_duration', width: 165, align: 'center' }, { header: "創建人", dataIndex: 's_sa_create_user', align: '80', align: 'center' }, { header: "創建時間", dataIndex: 's_sa_create_time', width: 165, align: 'center' }, { header: "異動人員", dataIndex: 'sa_modify_username', width: 120, align: 'center' }, { header: "異動時間", dataIndex: 'sa_modify_time_query', width: 120, align: 'center' } ], tbar: [ { xtype: 'button', text: "新增", id: 'add', iconCls: 'icon-user-add', handler: onAddClick }, '-', { xtype: 'button', text: "編輯", id: 'edit', iconCls: 'icon-user-edit', disabled: true, handler: onEditClick }, '-', { xtype: 'button', text: "刪除", id: 'delete', iconCls: 'icon-user-remove', disabled: true, handler: onDeleteClick }, '-', { xtype: 'button', text: "匯出Excel", id: 'outExcel', icon: '../../../Content/img/icons/excel.gif', handler: outExcel }, '->', { xtype: 'combobox', fieldLabel: '查詢條件', displayField: 'txt', id:'search_con', labelWidth:65, valueField: 'value', editable:false, value: '1', store: DateStore, listeners: { 'select': function () { if (Ext.getCmp('search_con').getValue() == 0) { Ext.getCmp('serch_sa_date').setDisabled(true); } else { Ext.getCmp('serch_sa_date').setDisabled(false); } } } }, { xtype: 'datefield', format: 'Y-m-d', //disabled:true, id: 'serch_sa_date', name: 'serch_sa_date', editable: false, value:new Date() }, { xtype: 'button', text:'查詢', handler: function () { Query() } }, { xtype: 'button', text: '重置', handler: function () { Ext.getCmp('search_con').setValue('0'); Ext.getCmp('serch_sa_date').setValue(new Date()); Ext.getCmp('serch_sa_date').setDisabled(true); } }, ], bbar: Ext.create('Ext.PagingToolbar', { store: SiteAnalyticsListStore, pageSize: pageSize, displayInfo: true, displayMsg: "當前顯示記錄" + ': {0} - {1}' + "總計" + ': {2}', emptyMsg: "沒有記錄可以顯示" }), listeners: { scrollershow: function (scroller) { if (scroller && scroller.scrollEl) { scroller.clearManagedListeners(); scroller.mon(scroller.scrollEl, 'scroll', scroller.onElScroll, scroller); } } }, selModel: sm }); Ext.create('Ext.container.Viewport', { layout: 'vbox', items: [form,SiteAnalyticsList], renderTo: Ext.getBody(), autoScroll: true, listeners: { resize: function () { SiteAnalyticsList.width = document.documentElement.clientWidth; this.doLayout(); } } }); ToolAuthority(); // SiteAnalyticsListStore.load({ params: { start: 0, limit: 25 } }); });
import { createStore, combineReducers } from 'redux' import User from './Reducers/User' import Currencies from './Reducers/Currencies' import Trades from './Reducers/Trades' import Offers from './Reducers/Offers' import OpenTrades from './Reducers/OpenTrades' import Settings from './Reducers/Settings' const rootReducer = combineReducers({ User, Currencies, Trades, Offers, OpenTrades, Settings }) export default createStore(rootReducer)
import backgroundTemplates from './backgroundTemplates'; const _ = require('underscore'); export default backgroundFactory = function (key, detailsEncoding) { const bgClass = _.findWhere(backgroundTemplates, {key: key}).classFunction; const bg = new bgClass(); if (detailsEncoding) { bg.decodeDetails(detailsEncoding); } return bg; }
var mongoose = require('mongoose'); // Project Schema var GraduationSchema = mongoose.Schema({ username: { type: String, index:true }, coursecode: { type: String }, coursetitle: { type: String }, semester: { type: String }, coursecredit: { type: String }, gradepoint:{ type:String }, grade: { type: String } }); var Graduations = module.exports = mongoose.model('Graduations', GraduationSchema,'graduations'); //profiles will be saving to profiles collection // module.exports.findOneAndUpdate = function(query,newProfile, callback){ // newProfile.save(callback); // };
import { ADD_MESSAGE } from "../constants/messages"; let nextMessageId = 0; export const add = (text, userName) => ({ type: ADD_MESSAGE, id: nextMessageId++, text, userName, date: new Date().getTime() });
/** Os triângulos podem ser classificados em 3 tipos quanto ao tamanho de seus lados: Equilátero: Os três lados são iguais. Isósceles: Dois lados iguais. Escaleno: Todos os lados são diferentes. Crie uma função que recebe os comprimentos dos três lados de um triângulo e retorne sua classificação quanto ao tamanho de seus lados. (Neste exemplo deve-se abstrair as condições matemáticas de existência de um triângulo). */ function validaForma(lado1, lado2, lado3){ this.lado1 = lado1 this.lado2 = lado2 this.lado3 = lado3 this.teste = function(){ if (lado1 == lado2 != lado3 || lado2 == lado3 != lado1){ console.log('Isósceles: Dois lados iguais.'); }else if (lado1 != lado2 != lado3) { console.log('Escaleno: Todos os lados são diferentes.'); }else if (lado1 == lado2 == lado3){ console.log('Equilátero: Os três lados são iguais.'); } } } const teste1 = new validaForma(0, 9, 9) teste1.teste()
const Joi = require('joi') const Boom = require('boom') const BaseRoute = require('./base/baseRoute') const failAction = (req, headers, error) => { throw error } const headers = Joi.object({ authorization: Joi.string().required() }).unknown() class CardRoutes extends BaseRoute { constructor(db) { super() this._db = db } list() { return { path: '/cards', method: 'GET', config: { tags: ['api'], description: 'List cards', notes: 'You can paginate and filter the results', validate: { // payload -> body // headers -> head // params -> na URL :id // query -> ?skip=10 query: { skip: Joi.number().integer().default(0), limit: Joi.number().integer().default(10), name: Joi.string().min(3).max(100) }, headers, failAction } }, handler: (req, headers) => { try { const { skip, limit, name } = req.query let query = name ? { name: { $regex: `.*${name}*.` } } : {} return this._db.read(query, skip, limit) // Hapi resolves promises } catch (error) { console.log('Internal error', error) return Boom.internal() } } } } create() { return { path: '/cards', method: 'POST', config: { tags: ['api'], description: 'Create card', notes: 'You can create a card by passing all the values', validate: { failAction, headers, payload: { name: Joi.string().required().min(3).max(100), types: Joi.string().required().min(4).max(20), attribute: Joi.string().required().min(4).max(20), level: Joi.number().integer().required().default(0), atk: Joi.string().required().min(1).max(9), def: Joi.string().required().min(1).max(9) } } }, handler: async (req, headers) => { try { const { name, types, attribute, level, atk, def } = req.payload const { _id } = await this._db.create({ name, types, attribute, level, atk, def }) return { _id, message: "The card was created with success :)" } } catch (error) { console.log('Internal Error!', error) return Boom.internal() } } } } update() { return { path: '/cards/{id}', method: 'PATCH', config: { tags: ['api'], description: 'Update cards', notes: 'You can update a card by passing its id and the values that you want to change', validate: { params: { id: Joi.string().required() }, headers, payload: { name: Joi.string().min(3).max(100), types: Joi.string().min(4).max(20), attribute: Joi.string().min(4).max(20), level: Joi.number().integer().default(0), atk: Joi.string().min(1).max(9), def: Joi.string().min(1).max(9) } } }, handler: async (req) => { try { const { id } = req.params const { payload } = req const updateDataString = JSON.stringify(payload) const updateData = JSON.parse(updateDataString) // removing all undefined keys, since all the attrs are NOT required() const res = await this._db.update(id, updateData) return (res.nModified === -1) ? Boom.preconditionFailed('It was NOT possible to update the card :(') : { message: 'The card was updated with success :)' } } catch (error) { console.log('Internal Error', error) return Boom.internal() } } } } delete() { return { path: '/cards/{id}', method: 'DELETE', config: { tags: ['api'], description: 'Delete card', notes: 'You can delete a card by its id', validate: { failAction, headers, params: { id: Joi.string().required() } } }, handler: async (req) => { try { const { id } = req.params const res = await this._db.delete(id) return (res.n !== 1) ? Boom.preconditionFailed('It was not possible to remove this card :(') : { message: 'The card was deleted with success :)' } } catch (error) { console.log('Internal Error', error) return Boom.internal() } } } } } module.exports = CardRoutes