text
stringlengths
7
3.69M
// @flow import { expect } from 'chai'; import sinon from 'sinon'; import composeGenerateChangelog from '../generateChangelog'; describe('post / generateChangelog', function(){ beforeEach(function(){ const pkg = this.pkg = {}; const log = { info: sinon.spy(), verbose: sinon.spy(), }; const config = this.config = { plugins: { generateNotes: sinon.stub().callsFake((c, cb) => { setImmediate(() => { cb(null, 'changelog.md'); }); }), }, }; const getConfig = this.getConfig = sinon.stub().returns(config); this.generateChangelog = composeGenerateChangelog(log, getConfig); }); it('returns a promise', function () { const { pkg, generateChangelog } = this; const result = generateChangelog(pkg); expect(result).to.be.instanceof(Promise); }); it('calls generateNotes', function () { const { pkg, config, getConfig, generateChangelog } = this; generateChangelog(pkg); expect(config.plugins.generateNotes.called).to.be.true; expect(config.plugins.generateNotes.calledWith(config, sinon.match.func)).to.be.true; }); it('resolves the generated notes', async function () { const { pkg, generateChangelog } = this; const result = await generateChangelog(pkg); // expect(result).to.equal('changelog.md'); expect(result.changelog).to.equal('changelog.md'); }); });
#!/usr/bin/env node 'use strict'; require('dotenv').config({ silent: true }); const chalk = require('chalk'); const values = require('lodash.values'); const axios = require('axios'); const urlJoin = require('url-join'); const assets = require('../build/manifest.json'); const logError = text => console.error(chalk.red(text)); const mapAssets = assets => values(assets) .map(file => urlJoin(process.env.CDN_URL, file)) .filter(filename => /\.(css|js)$/.test(filename)); const payload = { version: 2, active: true, assets: { default: mapAssets(assets) } }; axios({ url: process.env.PLUGINATOR_URL, method: 'post', data: payload, auth: { username: process.env.PLUGINATOR_USER, password: process.env.PLUGINATOR_PASS } }) .then(() => { console.log(chalk.green('SUCCESS: You published a plugin with the following files:')); for (let context in payload.assets) { console.log(chalk.yellow(context + ':')); for (let file of payload.assets[context]) { console.log(' ' + chalk.magenta.underline(file)); } } }) .catch((e) => { logError(`${e.status}: ${e.statusText}`); process.exit(1); });
var { pool } = require('../util/DB.js'); var request = require('request') var fs = require('fs') const host = 'https://tecnico.itsc.ec' /** * Funcion que retorna el nombre, id y url de todos los servidores disponibles * * @returns {Promise<Array<{id:number, name:string, url:string}>>} Info basica de los servidores */ async function getAllServers () { var query = ` select tb_servidoresidempiere_id as id, name as name, url from tb_servidoresidempiere where isactive = 'Y'`; var { rows } = await pool.query(query); return rows; } /** * Funcion que retorna el nombre, id de todos los servidores disponibles con ssh * * @returns {Promise<Array<{id:number, name:string, url:string}>>} Info basica de los servidores */ async function getAllServersSSH () { var query = ` select tb_servidoresidempiere_id as id, name as name from tb_servidoresidempiere where isactive = 'Y' and hasSSH = 'Y'`; var { rows } = await pool.query(query); return rows; } /** * Funcion que recibe una lista de IDs de servidores y retorna una lista con su data * * @param {Array<number>} servers_arr id de los servidores * @returns {Promise<Array<{id:number, username:string, password:string, name:string, url:string, port:number, dir_ssh:string, pwd_ssh:string}>>} Arreglo de info de servidores */ async function getServerData (servers_arr) { servers_arr = servers_arr.map(sv => Number(sv)); var query = ` select TB_ServidoresIdempiere_ID as id, username, password, name, url, Port::integer as port, UserSSH as dir_ssh, PasswordSSH as pwd_ssh from tb_servidoresidempiere where isactive = 'Y' and tb_servidoresidempiere_id in (${servers_arr.join(',')})`; var { rows } = await pool.query(query); return rows } /** * Funcion que envia un requerimiento POST multipart/form-data con un paquete .jar a un servidor iDempiere * Similar al de la interfaz OSGI * * @author Edgar Carvajal <https://fercarvo.github.io> * * @param {ReadableStream} file Archivo que sera enviado * @param {string} filename nombre del archivo a ser enviado * @param {Object} server servidor que recibira el request * @param {string} server.url url del servidor * @param {string} server.username usuario de iDempiere * @param {string} server.password clave del usuario de iDempiere * @returns {Promise<{servidor:string, data:string, resolved:boolean}>} Si resolved es true, se subio con exito */ function sendPackage(file, filename, server) { var btoa = txt => Buffer.from(txt, 'binary').toString('base64'); return new Promise(resolve => { var options = { method: 'POST', url: `${server.url}/osgi/system/console/bundles`, headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0', 'Cache-Control': 'no-cache', 'Authorization': `Basic ${btoa(server.username + ":" + server.password)}`, 'content-type': 'multipart/form-data;' }, formData: { action: 'install', bundlestart: 'start', refreshPackages: 'refresh', bundlestartlevel: '1', bundlefile: { value: file, options: { filename: filename, contentType: null } } }, timeout: 1000*120 //Si se demora mas de 1 minuto y medio se cancela la conexion } request(options, function (error, response) { if (error) { resolve({ servidor: server.url, data: error.message, resolved: false }) } else if (response && (response.statusCode === 200 || response.statusCode === 302) ) { resolve({ servidor: server.url, data: response.statusMessage, resolved: true }) } else { resolve({ servidor: server.url, data: `HTTP code: ${response.statusCode}, message: ${response.statusMessage}`, resolved: false }) } }) }) } /** * * Funcion que llama al web service CrearPackInWeb que debera estar instalado y funcionando en dicho * servidor iDempiere, esta funcion es un fork de nodejs_idempierewebservice * * @link nodejs_idempierewebservice https://github.com/fercarvo/nodejs_idempierewebservice * * @author Edgar Carvajal <https://fercarvo.github.io> * * @param {string} url_file path del archivo donde podra descargarse la data * @param {string} file_name nombre del archivo .zip * @param {Object} server servidor a recibir el web service * @param {string} server.name nombre del servidor * @param {string} server.url url del servidor * @param {string} server.username usuario de iDempiere * @param {string} server.password clave del usuario de iDempiere * @returns {Promise<{data:string | {server:string,body:string}, resolved:boolean}>} Si resolved true, exito */ function callWebService(url_file, file_name, server) { var soap = ` <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:_0="http://idempiere.org/ADInterface/1_0"> <soapenv:Header/> <soapenv:Body> <_0:runProcess> <_0:ModelRunProcessRequest> <_0:ModelRunProcess> <_0:serviceType>CrearPackInWeb</_0:serviceType> <_0:ParamValues> <_0:field column="esSistema"> <_0:val>Y</_0:val> </_0:field> <_0:field column="name"> <_0:val>${file_name}</_0:val> </_0:field> <_0:field column="url"> <_0:val>${host + url_file}</_0:val> </_0:field> </_0:ParamValues> </_0:ModelRunProcess> <_0:ADLoginRequest> <_0:user>${server.username}</_0:user> <_0:pass>${server.password}</_0:pass> <_0:lang>es_EC</_0:lang> <_0:ClientID>0</_0:ClientID> <_0:RoleID>0</_0:RoleID> <_0:OrgID>0</_0:OrgID> <_0:WarehouseID>0</_0:WarehouseID> <_0:stage>0</_0:stage> </_0:ADLoginRequest> </_0:ModelRunProcessRequest> </_0:runProcess> </soapenv:Body> </soapenv:Envelope>` return new Promise(resolve => { var options = { method: 'POST', url: `${server.url}/ADInterface/services/ModelADService`, headers: { 'Cache-Control': 'no-cache', 'Content-Type': 'text/xml; charset=utf-8' }, body: soap, timeout: 60*1000 //Si se demora mas de 1 minuto se cancela la conexion } request(options, function (error, response, body) { if (error) { return resolve({ data: error.message + ' servidor: ' + server.name, resolved: false }) } else if (response && (response.statusCode === 200 || response.statusCode === 302) ) { return resolve({ data: {server: server.name, body}, resolved: true }) } else { resolve({ data: response.statusCode + ' ' + response.statusMessage + ' ' + server.name, resolved: false }) } }) }) } /** * Funcion que renombra un archivo, cortar y pegar * * @param {string} oldpath viejo nombre (path) * @param {string} newpath nuevo nombre (path) */ async function rename (oldpath, newpath) { return new Promise((resolve, reject) => { fs.rename(oldpath, newpath, err => err ? reject(err) : resolve()) }) } module.exports = { getAllServers, getAllServersSSH, getServerData, sendPackage, rename, callWebService }
'use strict'; const OGMNeoObjectParse = require('./ogmneo-parse'); const OGMNeoRelationQuery = require('./ogmneo-relation-query'); const { OGMNeoOperation, OGMNeoOperationBuilder } = require('./ogmneo-operation'); const OGMNeoOperationExecuter = require('./ogmneo-operation-executer'); const _ = require('lodash'); /** * @class OGMRelation */ class OGMRelation { /** * Creates a relation between two nodes if they both exists. * * @static * @param {integer} nodeId - Id of the start node in the relation. * @param {integer} otherNodeId - Id of the end node in the relation. * @param {string} type - Case sensitive relation type name. * @param {object} [properties={}] - Relation properties. * @param {bool} [unique=false] - If include unique clause on create statement. * @returns {Promise.<object|Error>} Created relation literal object if fulfilled, or some neo4j error if rejected. */ static relate(nodeId, type, otherNodeId, properties = {}, unique = false) { try { let operation = this.relateOperation(nodeId, type, otherNodeId, properties, unique); return OGMNeoOperationExecuter.execute(operation); } catch (error) { return Promise.reject(error); } } /** * Operation that creates a relation between two nodes if they both exists. * * @static * @param {integer} nodeId - First in relation node id. * @param {integer} otherNodeId - Second in relation node id. * @param {string} type - Case sensitive relation type name. * @param {object} [properties={}] - Relation properties. * @param {bool} [unique=false] - If include unique clause on create statement. * @returns {OGMNeoOperation} Operation that creates the relation between nodes. * @throws {Error} Will throw an error if the ids from node was not integers. * @throws {Error} Will throw an error if a relatioship type was not an non-empty string. */ static relateOperation(nodeId, type, otherNodeId, properties = {}, unique = false) { OGMNeoObjectParse.parseProperties(properties); let value = _.omitBy(properties, _.isUndefined); if (_.isInteger(nodeId) && _.isInteger(otherNodeId)) { if (_.isString(type) && !_.isEmpty(type)) { let uniqueQuery = (unique) ? 'UNIQUE' : ''; let cypher = `MATCH (n1) WHERE ID(n1)=${nodeId} ` + `MATCH (n2) WHERE ID(n2)=${otherNodeId} ` + `CREATE ${uniqueQuery} (n1)-[r:${type} ${OGMNeoObjectParse.objectString(value)}]->(n2) ` + 'RETURN r'; return OGMNeoOperationBuilder.create() .cypher(cypher) .type(OGMNeoOperation.WRITE) .object(value) .then((result) => { let record = _.first(result.records); return OGMNeoObjectParse.recordToRelation(record); }).build(); } else { throw new Error('A relatioship type must be specified'); } } else { throw new Error('Ids from node must to be integers'); } } /** * Merges a relation between two nodes if they both exists. * * @static * @param {integer} nodeId - Id of the start node in the relation. * @param {integer} otherNodeId - Id of the end node in the relation. * @param {string} type - Case sensitive relation type name. * @param {object} [properties={}] - Relation properties. * @param {bool} [unique=false] - If include unique clause on create statement. * @returns {Promise.<object|Error>} Created relation literal object if fulfilled, or some neo4j error if rejected. */ static relateMerge(nodeId, type, otherNodeId, properties = {}, unique = false) { try { let operation = this.relateMergeOperation(nodeId, type, otherNodeId, properties, unique); return OGMNeoOperationExecuter.execute(operation); } catch (error) { return Promise.reject(error); } } /** * Operation that creates a relation between two nodes if they both exists. * * @static * @param {integer} nodeId - First in relation node id. * @param {integer} otherNodeId - Second in relation node id. * @param {string} type - Case sensitive relation type name. * @param {object} [properties={}] - Relation properties. * @param {bool} [unique=false] - If include unique clause on create statement. * @returns {OGMNeoOperation} Operation that creates the relation between nodes. * @throws {Error} Will throw an error if the ids from node was not integers. * @throws {Error} Will throw an error if a relatioship type was not an non-empty string. */ static relateMergeOperation(nodeId, type, otherNodeId, properties = {}, unique = false) { OGMNeoObjectParse.parseProperties(properties); let value = _.omitBy(properties, _.isUndefined); if (_.isInteger(nodeId) && _.isInteger(otherNodeId)) { if (_.isString(type) && !_.isEmpty(type)) { let uniqueQuery = (unique) ? 'UNIQUE' : ''; let cypher = `MATCH (n1) WHERE ID(n1)=${nodeId} ` + `MATCH (n2) WHERE ID(n2)=${otherNodeId} ` + `MERGE ${uniqueQuery} (n1)-[r:${type} ${OGMNeoObjectParse.objectString(value)}]->(n2) ` + 'RETURN r'; return OGMNeoOperationBuilder.create() .cypher(cypher) .type(OGMNeoOperation.WRITE) .object(value) .then((result) => { let record = _.first(result.records); return OGMNeoObjectParse.recordToRelation(record); }).build(); } else { throw new Error('A relatioship type must be specified'); } } else { throw new Error('Ids from node must to be integers'); } } /** * Update a relation propeties if it exists. * * @static * @param {integer} relationId - Relation node id. * @param {object} newProperties - Relation NEW properties. * @returns {Promise.<object|Error>} Updated relation literal object if fulfilled, or some neo4j error if rejected. */ static update(relationId, newProperties) { try { let operation = this.updateOperation(relationId, newProperties); return OGMNeoOperationExecuter.execute(operation); } catch (error) { return Promise.reject(error); } } /** * Operation that updates a relation propeties if it exists. * * @static * @param {integer} relationId - Relation node id. * @param {object} newProperties - Relation NEW properties. * @returns {OGMNeoOperation} Operation that creates the relation between nodes. * @throws {Error} Will throw an error if the id from relation node was not integer. */ static updateOperation(relationId, newProperties) { OGMNeoObjectParse.parseProperties(newProperties); let value = _.omitBy(newProperties, _.isUndefined); if (_.isInteger(relationId)) { let propertiesString = OGMNeoObjectParse.objectString(value); let cypher = 'MATCH p=(n1)-[r]->(n2) ' + `WHERE ID(r)=${relationId} SET r+=${propertiesString} RETURN r`; return OGMNeoOperationBuilder.create() .cypher(cypher) .type(OGMNeoOperation.WRITE) .object(value) .then((result) => { let record = _.first(result.records); return (record != null) ? OGMNeoObjectParse.recordToRelation(record) : null; }).build(); } else { throw new Error('Relation id must to be integer'); } } /** * Set or update newPropeties on all relation nodes that matches parameters query. * * @static * @param {object} newProperties - New properties ot be set or updated. * @param {OGMNeoRelationQuery} query - Query filter. * @returns {Promise.<array|Error>} Updated nodes if fulfilled, or some neo4j error if rejected. */ static updateMany(newProperties, query) { try { let operation = this.updateManyOperation(newProperties, query); return OGMNeoOperationExecuter.execute(operation); } catch (error) { return Promise.reject(error); } } /** * Operation that set or update newPropeties on all relation nodes that matches parameters query. * * @static * @param {object} newProperties - New properties ot be set or updated. * @param {OGMNeoRelationQuery} query - Query filter. * @returns {OGMNeoOperation} Operation that updates properties on the relation nodes. * @throws {Error} Will throw an error if query was not an instance of ogmneo.RelationQuery. * @throws {Error} Will throw an error if newProperties was not an object. * @throws {Error} Will throw an error if newProperties was was empty. */ static updateManyOperation(newProperties, query) { if (_.isObject(newProperties)) { let value = _.omitBy(newProperties, _.isUndefined); if (!_.isEmpty(value)) { OGMNeoObjectParse.parseProperties(value); if (query != null && query instanceof OGMNeoRelationQuery) { let cypherMatch = query.matchCypher(); let propertiesString = OGMNeoObjectParse.objectString(value); let cypher = `${cypherMatch} SET r+=${propertiesString} RETURN r`; return OGMNeoOperationBuilder.create() .cypher(cypher) .type(OGMNeoOperation.WRITE) .object(value) .then((result) => { return result.records.map(record => OGMNeoObjectParse.recordToRelation(record)); }).build(); } else { throw new Error('The query object can\'t be null and must be an instance of OGMNeoRelationQuery'); } } else { throw new Error('newProperties must be an object with at least one valid property to update'); } } else { throw new Error('newProperties must be an object'); } } /** * Find relation nodes. * * @static * @param {OGMNeoRelationQuery} query - Query filter. * @returns {Promise.<array|Error>} Found relation if fulfilled, or some neo4j error if rejected. */ static find(query) { try { let operation = this.findOperation(query); return OGMNeoOperationExecuter.execute(operation); } catch (error) { return Promise.reject(error); } } /** * An operation that finds relation nodes that matches queries. * * @static * @param {OGMNeoRelationQuery} query - Query filter. * @returns {OGMNeoOperation} Operation that find the relation nodes. * @throws {Error} Will throw an error if the query object was null or not an instance of OGMNeoRelationQuery. */ static findOperation(query) { if (query != null && query instanceof OGMNeoRelationQuery) { let cypher = query.queryCypher(); return OGMNeoOperationBuilder.create() .cypher(cypher) .type(OGMNeoOperation.READ) .then((result) => { return result.records.map(record => OGMNeoObjectParse.parseRelation(record)); }).build(); } else { throw new Error('The query object can\'t be null and must be an instance of OGMNeoRelationQuery'); } } /** * Find one relation node. * * @static * @param {OGMNeoRelationQuery} query - Query filter. * @returns {Promise.<object|Error>} Found relation if fulfilled, or some neo4j error if rejected. */ static findOne(query) { try { let operation = this.findOneOperation(query); return OGMNeoOperationExecuter.execute(operation); } catch (error) { return Promise.reject(error); } } /** * Operation to find one relation node that matches query. * * @static * @param {OGMNeoRelationQuery} query - Query filter. * @returns {OGMNeoOperation} Operation that find one relation node. * @throws {Error} Will throw an error if the query object was null or not an instance of OGMNeoRelationQuery. */ static findOneOperation(query) { if (query != null && query instanceof OGMNeoRelationQuery) { query.limit(1); let operation = this.findOperation(query); operation.then = (result) => { let record = _.first(result.records); return (record != null) ? OGMNeoObjectParse.parseRelation(record) : null; }; return operation; } else { throw new Error('The query object can\'t be null and must be an instance of OGMNeoRelationQuery'); } } /** * Find relation nodes with start and end nodes populated. * * @static * @param {OGMNeoRelationQuery} query - Query filter. * @returns {Promise.<array|Error>} Found populated relation if fulfilled, or some neo4j error if rejected. */ static findPopulated(query) { try { let operation = this.findPopulatedOperation(query); return OGMNeoOperationExecuter.execute(operation); } catch (error) { return Promise.reject(error); } } /** * Operation that find relation nodes with start and end nodes populated. * * @static * @param {OGMNeoRelationQuery} query - Query filter. * @returns {OGMNeoOperation} Operation that find relations nodes. * @throws {Error} Will throw an error if the query object was null or not an instance of ogmneo.RelationQuery. */ static findPopulatedOperation(query) { if (query != null && query instanceof OGMNeoRelationQuery) { let cypher = query.queryPopulatedCypher(); return OGMNeoOperationBuilder.create() .cypher(cypher) .type(OGMNeoOperation.READ) .then((result) => { return result.records.map(record => OGMNeoObjectParse.recordToRelationPopulated(record)); }).build(); } else { throw new Error('The query object can\'t be null and must be an instance of OGMNeoRelationQuery'); } } /** * Find one Populated relation node. * * @static * @param {OGMNeoRelationQuery} query - Query filter. * @returns {Promise.<object|Error>} Populated found relation if fulfilled, or some neo4j error if rejected. */ static findOnePopulated(query) { try { let operation = this.findOnePopulatedOperation(query); return OGMNeoOperationExecuter.execute(operation); } catch (error) { return Promise.reject(error); } } /** * Operation to find one populated relation node. * * @static * @param {OGMNeoRelationQuery} query - Query filter. * @returns {OGMNeoOperation} Operation that find one populated relation node. * @throws {Error} Will throw an error if the query object was null or not an instance of ogmneo.RelationQuery. */ static findOnePopulatedOperation(query) { if (query != null && query instanceof OGMNeoRelationQuery) { query.limit(1); let operation = this.findPopulatedOperation(query); operation.then = (result) => { let record = _.first(result.records); return (record != null) ? OGMNeoObjectParse.recordToRelationPopulated(record) : null; }; return operation; } else { throw new Error('The query object can\'t be null and must be an instance of OGMNeoRelationQuery'); } } /** * Find start and end nodes for the relation. Do not return relation properties to find relation properties use find or find populated. * * @static * @param {OGMNeoRelationQuery} query - Query filter. * @param {string} [nodes='both'] - The return nodes. 'both'/null = return start and end nodes, 'start' = return start nodes, 'end' = return end nodes * @param {boolean} [distinct = false] - Add distinct clause to cypher return. * @returns {Promise.<array|Error>} Found populated relation if fulfilled, or some neo4j error if rejected. */ static findNodes(query, nodes = 'both', distinct = false) { try { let operation = this.findNodesOperation(query, nodes, distinct); return OGMNeoOperationExecuter.execute(operation); } catch (error) { return Promise.resolve(error); } } /** * Operation to find start and end nodes for the relation. Do not return relation properties to find relation properties use find or find populated. * * @static * @param {OGMNeoRelationQuery} query - Query filter. * @param {string} [nodes='both'] - The return nodes. 'both'/null = return start and end nodes, 'start' = return start nodes, 'end' = return end nodes * @param {boolean} [distinct = false] - Add distinct clause to cypher return. * @returns {OGMNeoOperation} Operation that find start and end nodes with query. * @throws {Error} Will throw an error if the query object was null or not an instance of ogmneo.RelationQuery. */ static findNodesOperation(query, nodes = 'both', distinct = false) { if (query != null && query instanceof OGMNeoRelationQuery) { let cypher = query.queryNodesCypher(nodes, distinct); return OGMNeoOperationBuilder.create() .cypher(cypher) .type(OGMNeoOperation.READ) .then((result) => { return result.records.map(record => OGMNeoObjectParse.recordToRelationStartEndNodes(record, nodes)); }).build(); } else { throw new Error('The query object can\'t be null and must be an instance of OGMNeoRelationQuery'); } } /** * Count relation nodes. * * @static * @param {OGMNeoRelationQuery} query - Query filter. * @returns {Promise.<integer|Error>} Count of relations if fulfilled, or some neo4j error if rejected. */ static count(query) { try { let operation = this.countOperation(query); return OGMNeoOperationExecuter.execute(operation); } catch (error) { return Promise.reject(error); } } /** * Operation that counts relation nodes. * * @static * @param {OGMNeoRelationQuery} query - Query filter. * @returns {OGMNeoOperation} Operation that count nodes with query. * @throws {Error} Will throw an error if the query object was null or not an instance of ogmneo.RelationQuery. */ static countOperation(query) { if (query != null && query instanceof OGMNeoRelationQuery) { let cypher = query.countCypher(); return OGMNeoOperationBuilder.create() .cypher(cypher) .type(OGMNeoOperation.READ) .then((result) => { let record = _.first(result.records); return (record != null) ? record.get('count').low : 0; }).build(); } else { throw new Error('The query object can\'t be null and must be an instance of OGMNeoRelationQuery'); } } /** * Check if there is relation nodes that matches parameters query. * * @static * @param {OGMNeoRelationQuery} query - Query filter. * @returns {Promise.<boolean|Error>} True if there is some relation matching parameters and false otherwise if fulfilled, or some neo4j error if rejected. */ static exists(query) { return new Promise((resolve, reject) => { this.count(query) .then((count) => { resolve(count !== 0); }).catch((error) => { reject(error); }); }); } /** * Delete relation by id. * * @static * @param {integer} relationId - relation node id. * @returns {Promise.<boolean|Error>} Deleted relation node if fulfilled, or some neo4j error if rejected. */ static deleteRelation(relationId) { try { let operation = this.deleteRelationOperation(relationId); return OGMNeoOperationExecuter.execute(operation); } catch (error) { return Promise.reject(error); } } /** * Operation that deletes a relation by id. * * @static * @param {integer} relationId - relation node id. * @returns {OGMNeoOperation} Operation that deletes a node with id. * @throws {Error} Will throw an error if the relation id was not an integer value. */ static deleteRelationOperation(relationId) { if (_.isInteger(relationId)) { let cypher = `MATCH p=(n1)-[r]->(n2) WHERE ID(r)=${relationId} DELETE r RETURN r`; return OGMNeoOperationBuilder.create().cypher(cypher) .type(OGMNeoOperation.WRITE) .then((result) => { let record = _.first(result.records); return (record != null) ? OGMNeoObjectParse.recordToRelation(record) : null; }).build(); } else { throw new Error('Relation id must to be an integer number'); } } /** * Deletes all relation nodes that matches parameters query. * * @static * @param {OGMNeoRelationQuery} query - Query filter. * @returns {Promise.<array|Error>} Deleted nodes if fulfilled, or some neo4j error if rejected. */ static deleteMany(query) { try { let operation = this.deleteManyOperation(query); return OGMNeoOperationExecuter.execute(operation); } catch (error) { return Promise.reject(error); } } /** * Operation that deletes all relation nodes that matches parameters query. * * @static * @param {OGMNeoRelationQuery} query - Query filter. * @returns {OGMNeoOperation} Operation that deletes nodes with query. * @throws {Error} Will throw an error if the query object was null or not an instance of ogmneo.RelationQuery. */ static deleteManyOperation(query) { if (query != null && query instanceof OGMNeoRelationQuery) { let cypherMatch = query.matchCypher(); let cypher = `${cypherMatch} DELETE r RETURN r`; return OGMNeoOperationBuilder.create() .cypher(cypher) .type(OGMNeoOperation.WRITE) .then((result) => { return result.records.map(record => OGMNeoObjectParse.recordToRelation(record)); }).build(); } else { throw new Error('The query object can\'t be null and must be an instance of OGMNeoRelationQuery'); } } } module.exports = OGMRelation;
import AccountImage from "./images/account.png"; import Typeingicon from "./icons/typing.gif"; export default { Accountimage : AccountImage, ShowTypeing : Typeingicon }
import React, { Component } from 'react'; import { connect } from 'react-redux'; import * as actions from './actions'; import { MyStylesheet } from './styles'; import DynamicStyles from './dynamicstyles'; import { redMinus, RedPlus, CheckedBox, EmptyBox } from './svg' import { UTCStringFormatDateforProposal, CreateInvoice, inputDateObjOutputAdjString, calculatetotalhours, inputUTCStringForLaborID, inputUTCStringForMaterialIDWithTime } from './functions' import { Link } from 'react-router-dom'; import MakeID from './makeids'; class Invoices extends Component { constructor(props) { super(props) this.state = { width: 0, height: 0, activeinvoiceid: false, updated: new Date(), approved: '', showlabor: true, showmaterials: true, showequipment: true,spinner:false } this.updateWindowDimensions = this.updateWindowDimensions.bind(this) } componentDidMount() { window.addEventListener('resize', this.updateWindowDimensions); this.updateWindowDimensions(); const dynamicstyles = new DynamicStyles(); const csicodes = dynamicstyles.getcsis.call(this) if(!csicodes) { dynamicstyles.loadcsis.call(this) } } componentWillUnmount() { window.removeEventListener('resize', this.updateWindowDimensions); } updateWindowDimensions() { this.setState({ width: window.innerWidth, height: window.innerHeight }); } getactiveinvoicekey() { let dynamicstyles = new DynamicStyles(); let key = false; if (this.state.activeinvoiceid) { let invoiceid = this.state.invoiceid; let myproject = dynamicstyles.getproject.call(this); if (myproject.hasOwnProperty("invoices")) { // eslint-disable-next-line myproject.invoices.myinvoice.map((myinvoice, i) => { if (myinvoice.invoiceid === invoiceid) { key = i; } }) } } return key; } getactivebackground(item) { if (item.invoiceid === this.state.activeinvoiceid) { return ({ backgroundColor: '#F2C4D2' }) } } handleequipmentprofit(profit, equipmentid) { let dynamicstyles = new DynamicStyles(); const myuser = dynamicstyles.getuser.call(this) if (myuser) { let myproject = dynamicstyles.getproject.call(this); if (myproject) { let i = dynamicstyles.getprojectkeybyid.call(this, myproject.projectid); const myequipment = dynamicstyles.getactualequipmentbyid.call(this, equipmentid) if (myequipment) { let j = dynamicstyles.getactualequipmentkeybyid.call(this, equipmentid); myuser.company.projects.myproject[i].actualequipment.myequipment[j].profit = profit; this.props.reduxUser(myuser); if (myequipment.invoiceid) { dynamicstyles.updateinvoice.call(this, myequipment.invoiceid) } else { this.setState({ render: 'render' }) } } } } } handlematerialprofit(profit, materialid) { console.log(profit,materialid) let dynamicstyles = new DynamicStyles(); const myuser = dynamicstyles.getuser.call(this) if (myuser) { let myproject = dynamicstyles.getproject.call(this) if (myproject) { let i = dynamicstyles.getprojectkey.call(this); const mymaterial = dynamicstyles.getactualmaterialbyid.call(this, materialid) if (mymaterial) { let j = dynamicstyles.getactualmaterialkeybyid.call(this, materialid); console.log(i,j) myuser.company.projects.myproject[i].actualmaterials.mymaterial[j].profit = profit; this.props.reduxUser(myuser); if (mymaterial.invoiceid) { dynamicstyles.updateinvoice.call(this, mymaterial.invoiceid) } else { this.setState({ render: 'render' }) } } } } } handlelaborprofit(profit, laborid) { let dynamicstyles = new DynamicStyles(); const myuser = dynamicstyles.getuser.call(this) if (myuser) { let myproject = dynamicstyles.getproject.call(this); if (myproject) { let i = dynamicstyles.getprojectkeybyid.call(this, myproject.projectid); const mylabor = dynamicstyles.getactuallaborbyid.call(this, laborid); if (mylabor) { let j = dynamicstyles.getactuallaborkeybyid.call(this, laborid); myuser.company.projects.myproject[i].actuallabor.mylabor[j].profit = profit; this.props.reduxUser(myuser); if (mylabor.invoiceid) { dynamicstyles.updateinvoice.call(this, mylabor.invoiceid) } else { this.setState({ render: 'render' }) } } } } } checkinvoiceitem(item) { let result = 'add'; if (item.invoiceid === this.state.activeinvoiceid) { result = 'remove' } return result; } addItem(item) { let dynamicstyles = new DynamicStyles(); const myuser = dynamicstyles.getuser.call(this) if (myuser) { if (this.state.activeinvoiceid) { let invoiceid = this.state.activeinvoiceid; let i = dynamicstyles.getprojectkey.call(this) let result = this.checkinvoiceitem(item); let j = false; if (result === 'add') { if (item.hasOwnProperty("laborid")) { j = dynamicstyles.getactuallaborkeybyid.call(this, item.laborid) myuser.company.projects.myproject[i].actuallabor.mylabor[j].invoiceid = invoiceid; this.props.reduxUser(myuser); this.setState({ render: 'render' }) } else if (item.hasOwnProperty("materialid")) { j = dynamicstyles.getactualmaterialkeybyid.call(this, item.materialid) myuser.company.projects.myproject[i].actualmaterials.mymaterial[j].invoiceid = invoiceid; this.props.reduxUser(myuser); this.setState({ render: 'render' }) } else if (item.hasOwnProperty("equipmentid")) { j = dynamicstyles.getactualequipmentkeybyid.call(this, item.equipmentid); myuser.company.projects.myproject[i].actualequipment.myequipment[j].invoiceid = invoiceid; this.props.reduxUser(myuser); this.setState({ render: 'render' }) } } else if (result === 'remove') { if (item.hasOwnProperty("laborid")) { j = dynamicstyles.getactuallaborkeybyid.call(this, item.laborid) myuser.company.projects.myproject[i].actuallabor.mylabor[j].invoiceid = "" this.props.reduxUser(myuser); this.setState({ render: 'render' }) } else if (item.hasOwnProperty("materialid")) { j = dynamicstyles.getactualmaterialkeybyid.call(this, item.materialid) myuser.company.projects.myproject[i].actualmaterials.mymaterial[j].invoiceid = "" this.props.reduxUser(myuser); this.setState({ render: 'render' }) } else if (item.hasOwnProperty("equipmentid")) { j = dynamicstyles.getactualequipmentkeybyid.call(this, item.equipmentid); myuser.company.projects.myproject[i].actualequipment.myequipment[j].invoiceid = "" this.props.reduxUser(myuser); this.setState({ render: 'render' }) } } } } } showinvoiceids() { let dynamicstyles = new DynamicStyles(); let myuser = dynamicstyles.getuser.call(this); let invoices = []; if (myuser) { let myproject = dynamicstyles.getproject.call(this); if (myproject) { if (myproject.hasOwnProperty("invoices")) { // eslint-disable-next-line myproject.invoices.myinvoice.map(myinvoice => { invoices.push(this.showinvoiceid(myinvoice)) }) } } } return invoices; } handlecheckicon(invoiceid) { const styles = MyStylesheet(); const dynamicstyles = new DynamicStyles(); const checkButton = dynamicstyles.getcreateproposal.call(this) if (this.state.activeinvoiceid === invoiceid) { return (<button style={{ ...styles.generalButton, ...checkButton, ...styles.addRightMargin }} onClick={() => { this.makeinvoiceactive(invoiceid) }}>{redMinus()}</button>) } else { return (<button style={{ ...styles.generalButton, ...checkButton, ...styles.addRightMargin }} onClick={() => { this.makeinvoiceactive(invoiceid) }}>{RedPlus()}</button>) } } makeinvoiceactive(invoiceid) { if (this.state.activeinvoiceid === invoiceid) { this.setState({ activeinvoiceid: false }) } else { this.setState({ activeinvoiceid: invoiceid }) } } getmaterialprofitbyid(materialid) { let dynamicstyles = new DynamicStyles(); let myproject = dynamicstyles.getproject.call(this); let profit = 0; if (myproject) { if (myproject.hasOwnProperty("actualmaterials")) { // eslint-disable-next-line myproject.actualmaterials.mymaterial.map(mymaterials => { if (mymaterials.materialid === materialid) { profit = mymaterials.profit; } }) } } return profit; } getlaborprofitbyid(laborid) { let dynamicstyles = new DynamicStyles(); let myproject = dynamicstyles.getproject.call(this); let profit = 0; if (myproject) { if (myproject.hasOwnProperty("actuallabor")) { // eslint-disable-next-line myproject.actuallabor.mylabor.map(mylabor => { if (mylabor.laborid === laborid) { profit = mylabor.profit; } }) } } return profit; } showinvoiceid(myinvoice) { const styles = MyStylesheet(); const dynamicstyles = new DynamicStyles(); const regularFont = dynamicstyles.getRegularFont.call(this) const invoiceid = myinvoice.invoiceid; let updateinfo = ""; if (myinvoice.updated) { updateinfo = `Updated ${UTCStringFormatDateforProposal(myinvoice.updated)}` } return (<div style={{ ...styles.generalFlex, ...styles.generalFont, ...regularFont, ...styles.marginLeft60 }} key={myinvoice.invoiceid}> <div style={{ ...styles.flex1 }} onClick={() => { this.makeinvoiceactive(invoiceid) }}> {this.handlecheckicon(myinvoice.invoiceid)} <span style={{ ...regularFont, ...styles.generalFont }}> Invoice ID {myinvoice.invoiceid} {updateinfo}</span> </div> </div>) } getequipmentprofitbyid(equipmentid) { let dynamicstyles = new DynamicStyles(); let myproject = dynamicstyles.getproject.call(this); let profit = 0; if (myproject) { if (myproject.hasOwnProperty("actualequipment")) { // eslint-disable-next-line myproject.actualequipment.myequipment.map(myequipment => { if (myequipment.equipmentid === equipmentid) { profit = myequipment.profit; } }) } } return profit; } showequipmentitem(item) { let dynamicstyles = new DynamicStyles() const styles = MyStylesheet(); const smallFont = dynamicstyles.getSmallFont.call(this); const myequipment = dynamicstyles.getequipmentfromid.call(this, item.myequipmentid); const csi = dynamicstyles.getcsibyid.call(this, item.csiid) const totalhours = Number(calculatetotalhours(item.timeout, item.timein)) const profitField = dynamicstyles.getprofitfield.call(this) const equipmentrate = item.equipmentrate; const largeField = dynamicstyles.getitemfieldlarge.call(this) const amount = Number(totalhours * Number(item.equipmentrate)) const profit = Number(item.profit) / 100; const checkequipment = () => { let check = true; if (item.settlementid) { check = false; } return check; } const showequipmentrate = () => { if (checkequipment()) { return (<input type="text" style={{ ...styles.generalFont, ...smallFont, ...largeField }} onChange={event => { this.handleequipmentrate(event.target.value, item.equipmentid) }} value={equipmentrate} />) } else { return equipmentrate; } } const showprofit = () => { if (checkequipment()) { return ( <div style={{ ...styles.generalContainer }}> Profit <input type="text" style={{ ...styles.generalField, ...smallFont, ...styles.generalFont, ...profitField }} value={this.getequipmentprofitbyid(item.equipmentid)} onChange={event => { this.handleequipmentprofit(event.target.value, item.equipmentid) }} /> </div>) } } return ( <div style={{ ...styles.generalFlex, ...styles.generalFont, ...smallFont, ...styles.bottomMargin15 }} key={item.equipmentid}> <div style={{ ...styles.flex3, ...this.getactivebackground(item) }} > <span onClick={() => { this.addItem(item) }}>{myequipment.equipment} CSI: {csi.csi} - {csi.title} TimeIn{inputUTCStringForLaborID(item.timein)} TimeOut {inputUTCStringForLaborID(item.timeout)} Total Hours:{totalhours.toFixed(2)} x $</span> {showequipmentrate()} <span onClick={() => { this.addItem(item) }}> = {amount} x {`${Number(1 + profit).toFixed(2)}`} = ${Number(amount * (1 + profit)).toFixed(2)} </span> </div> <div style={{ ...styles.flex1 }}> {showprofit()} </div> </div> ) } showmaterialitem(item) { const styles = MyStylesheet(); const dynamicstyles = new DynamicStyles() const profitField = dynamicstyles.getprofitfield.call(this) const getprofit = () => { if (item.profit) { return Number(1 + (item.profit / 100)) } else { return 1; } } const profit = getprofit(); const csi = dynamicstyles.getcsibyid.call(this, item.csiid) const material = dynamicstyles.getmymaterialfromid.call(this, item.mymaterialid) const amount = Number(item.quantity * item.unitcost); const smallFont = dynamicstyles.getSmallFont.call(this) const proposalFieldLarge = dynamicstyles.getitemfieldlarge.call(this) const proposalFieldSmall = dynamicstyles.getitemfieldsmall.call(this) const checkmaterial = () => { let check = true; if (item.settlementid) { check = false; } return check; } const showprofit = () => { if (checkmaterial()) { return (<div style={{ ...styles.generalContainer }}> Profit <input type="text" style={{ ...styles.generalField, ...smallFont, ...styles.generalFont, ...profitField }} value={this.getmaterialprofitbyid(item.materialid)} onChange={event => { this.handlematerialprofit(event.target.value, item.materialid) }} /> </div>) } } const showunitcost = () => { if (checkmaterial()) { return (<input type="text" value={item.unitcost} onChange={event => { this.handlematerialunitcost(event.target.value, item.materialid) }} style={{ ...styles.generalFont, ...smallFont, ...proposalFieldSmall }} />) } else { return item.unitcost; } } const showquantity = () => { if (checkmaterial()) { return (<input type="text" value={item.quantity} onChange={event => { this.handlematerialquantity(event.target.value, item.materialid) }} style={{ ...styles.generalFont, ...smallFont, ...proposalFieldLarge }} />) } else { return item.quantity; } } const showunit = () => { if (checkmaterial()) { return (<input type="text" value={item.unit} onChange={event => { this.handlematerialunit(event.target.value, item.materialid) }} style={{ ...styles.generalFont, ...smallFont, ...proposalFieldSmall }} />) } else { return item.unit; } } return ( <div style={{ ...styles.generalFlex, ...styles.generalFont, ...smallFont, ...styles.bottomMargin15 }} key={item.materialid}> <div style={{ ...styles.flex3, ...this.getactivebackground(item) }} > <span onClick={() => { this.addItem(item) }}>{inputUTCStringForMaterialIDWithTime(item.timein)} {material.material} CSI: {csi.csi}-{csi.title}</span> {showquantity()} <span onClick={() => { this.addItem(item) }}> x $ </span> {showunitcost()} <span onClick={() => { this.addItem(item) }}> / </span> {showunit()} <span onClick={() => { this.addItem(item) }}> = ${amount.toFixed(2)} x {profit} = ${Number(amount * profit).toFixed(2)} </span> </div> <div style={{ ...styles.flex1 }}> {showprofit()} </div> </div> ) } showlaboritem(item) { const styles = MyStylesheet(); const dynamicstyles = new DynamicStyles(); const smallFont = dynamicstyles.getSmallFont.call(this) const amount = (Number(calculatetotalhours(item.timeout, item.timein)) * Number(item.laborrate)) const employee = dynamicstyles.getemployeebyproviderid.call(this, item.providerid); const csi = dynamicstyles.getcsibyid.call(this, item.csiid) const totalhours = Number(calculatetotalhours(item.timeout, item.timein)) const profitField = dynamicstyles.getprofitfield.call(this) const largeField = dynamicstyles.getitemfieldlarge.call(this); const getprofit = () => { if (item.profit) { return Number(1 + (item.profit / 100)) } else { return 1; } } const checklabor = () => { let check = true; if (item.settlementid) { check = false; } return check; } const profit = getprofit(); const showprofit = () => { if (checklabor()) { return (<div style={{ ...styles.generalContainer }}> Profit <input type="text" style={{ ...styles.generalField, ...smallFont, ...styles.generalFont, ...profitField }} value={this.getlaborprofitbyid(item.laborid)} onChange={event => { this.handlelaborprofit(event.target.value, item.laborid) }} /> </div>) } } const showlaborrate = () => { if (checklabor()) { return (<input type="text" value={item.laborrate} style={{ ...styles.generalFont, ...largeField, ...smallFont }} onChange={event => { this.handlelaborrate(event.target.value, item.laborid) }} />) } else { return (item.laborrate) } } return ( <div style={{ ...styles.generalFlex, ...styles.generalFont, ...smallFont, ...styles.bottomMargin15 }} key={item.laborid}> <div style={{ ...styles.flex3, ...this.getactivebackground(item) }}> <span onClick={() => { this.addItem(item) }}>{employee.firstname} {employee.lastname} TimeIn{inputUTCStringForLaborID(item.timein)} TimeOut {inputUTCStringForLaborID(item.timeout)} CSI {csi.csi}-{csi.title} Total Hours {totalhours.toFixed(2)} Hrs at $ </span> {showlaborrate()} <span onClick={() => { this.addItem(item) }}> = ${amount.toFixed(2)} x {profit} = ${Number(amount * profit).toFixed(2)}</span> </div> <div style={{ ...styles.flex1 }}> {showprofit()} </div> </div> ) } showallpayitems() { const dynamicstyles = new DynamicStyles(); let items = []; let payitems = dynamicstyles.getAllActual.call(this) if (payitems.hasOwnProperty("length")) { // eslint-disable-next-line payitems.map(item => { if (item.hasOwnProperty("laborid")) { if (this.state.showlabor) { items.push(this.showlaboritem(item)) } } if (item.hasOwnProperty("materialid")) { if (this.state.showmaterials) { items.push(this.showmaterialitem(item)) } } if (item.hasOwnProperty("equipmentid")) { if (this.state.showequipment) { items.push(this.showequipmentitem(item)) } } }) } return items; } showinvoicelink() { const styles = MyStylesheet(); const dynamicstyles = new DynamicStyles(); const headerFont = dynamicstyles.getHeaderFont.call(this) if (this.state.activeinvoiceid) { let companyid = this.props.match.params.companyid; let projectid = this.props.match.params.projectid; let invoiceid = this.state.activeinvoiceid; let providerid = this.props.match.params.providerid; return ( <div style={{ ...styles.generalContainer, ...styles.generalFont, ...headerFont, ...styles.alignCenter }}> <Link to={`/${providerid}/company/${companyid}/projects/${projectid}/invoices/${invoiceid}`} style={{ ...styles.generalLink, ...headerFont, ...styles.generalFont }}> View Invoice ID: {invoiceid} </Link> </div>) } else { return; } } handlelaborrate(laborrate, laborid) { const dynamicstyles = new DynamicStyles(); const myuser = dynamicstyles.getuser.call(this) if (myuser) { let myproject = dynamicstyles.getproject.call(this); if (myproject) { let i = dynamicstyles.getprojectkeybyid.call(this, myproject.projectid); const mylabor = dynamicstyles.getactuallaborbyid.call(this, laborid); if (mylabor) { let j = dynamicstyles.getactuallaborkeybyid.call(this, laborid); myuser.company.projects.myproject[i].actuallabor.mylabor[j].laborrate = laborrate; this.props.reduxUser(myuser); if (mylabor.invoiceid) { dynamicstyles.updateinvoice.call(this, mylabor.invoiceid) } else { this.setState({ render: 'render' }) } } } } } handleequipmentrate(equipmentrate, equipmentid) { let dynamicstyles = new DynamicStyles(); const myuser = dynamicstyles.getuser.call(this) if (myuser) { let myproject = dynamicstyles.getproject.call(this); if (myproject) { let i = dynamicstyles.getprojectkeybyid.call(this, myproject.projectid); const myequipment = dynamicstyles.getactualequipmentbyid.call(this, equipmentid) if (myequipment) { let j = dynamicstyles.getactualequipmentkeybyid.call(this, equipmentid); myuser.company.projects.myproject[i].actualequipment.myequipment[j].equipmentrate = equipmentrate; this.props.reduxUser(myuser); if (myequipment.invoiceid) { dynamicstyles.updateinvoice.call(this, myequipment.invoiceid) } else { this.setState({ render: 'render' }) } } } } } handlematerialunit(unit, materialid) { let dynamicstyles = new DynamicStyles(); const myuser = dynamicstyles.getuser.call(this) if (myuser) { let myproject = dynamicstyles.getproject.call(this) if (myproject) { let i = dynamicstyles.getprojectkey.call(this); const mymaterial = dynamicstyles.getactualmaterialbyid.call(this, materialid) if (mymaterial) { let j = dynamicstyles.getactualmaterialkeybyid.call(this, materialid); myuser.company.projects.myproject[i].actualmaterials.mymaterial[j].unit = unit; this.props.reduxUser(myuser) if (mymaterial.invoiceid) { dynamicstyles.updateinvoice.call(this, mymaterial.invoiceid) } else { this.setState({ render: 'render' }) } } } } } handlematerialunitcost(unitcost, materialid) { let dynamicstyles = new DynamicStyles(); const myuser = dynamicstyles.getuser.call(this) if (myuser) { let myproject = dynamicstyles.getproject.call(this) if (myproject) { let i = dynamicstyles.getprojectkey.call(this); const mymaterial = dynamicstyles.getactualmaterialbyid.call(this, materialid) if (mymaterial) { let j = dynamicstyles.getactualmaterialkeybyid.call(this, materialid); myuser.company.projects.myproject[i].actualmaterials.mymaterial[j].unitcost = unitcost; this.props.reduxUser(myuser) if (mymaterial.invoiceid) { dynamicstyles.updateinvoice.call(this, mymaterial.invoiceid) } else { this.setState({ render: 'render' }) } } } } } handlematerialquantity(quantity, materialid) { let dynamicstyles = new DynamicStyles(); const myuser = dynamicstyles.getuser.call(this) if (myuser) { let myproject = dynamicstyles.getproject.call(this) if (myproject) { let i = dynamicstyles.getprojectkey.call(this); const mymaterial = dynamicstyles.getactualmaterialbyid.call(this, materialid) if (mymaterial) { let j = dynamicstyles.getactualmaterialkeybyid.call(this, materialid); myuser.company.projects.myproject[i].actualmaterials.mymaterial[j].quantity = quantity; this.props.reduxUser(myuser) if (mymaterial.invoiceid) { dynamicstyles.updateinvoice.call(this, mymaterial.invoiceid) } else { this.setState({ render: 'render' }) } } } } } createnewinvoice() { const dynamicstyles = new DynamicStyles(); let myuser = dynamicstyles.getuser.call(this); const makeID = new MakeID() if (myuser) { let invoiceid = makeID.invoiceid.call(this) let providerid = myuser.providerid; let updated = inputDateObjOutputAdjString(this.state.updated); let approved = this.state.approved; let newinvoice = CreateInvoice(invoiceid, providerid, updated, approved); let myproject = dynamicstyles.getproject.call(this); let i = dynamicstyles.getprojectkey.call(this); if (myproject.hasOwnProperty("invoices")) { myuser.company.projects.myproject[i].invoices.myinvoice.push(newinvoice) } else { myuser.company.projects.myproject[i].invoices = { myinvoice: [newinvoice] } } this.props.reduxUser(myuser) this.setState({ activeinvoiceid: invoiceid }) } } render() { let dynamicstyles = new DynamicStyles(); let styles = MyStylesheet(); let proposalButton = dynamicstyles.getcreateproposal.call(this) const regularFont = dynamicstyles.getRegularFont.call(this) const myuser = dynamicstyles.getuser.call(this) const checkfield = dynamicstyles.getcheckfield.call(this) const headerFont = dynamicstyles.getHeaderFont.call(this) const laboricon = () => { if (this.state.showlabor) { return (<div style={{ ...styles.generalContainer }}> <button style={{ ...styles.generalButton, ...checkfield }} onClick={() => { this.setState({ showlabor: false }) }}>{CheckedBox()}</button> </div>) } else { return (<div style={{ ...styles.generalContainer }}> <button style={{ ...styles.generalButton, ...checkfield }} onClick={() => { this.setState({ showlabor: true }) }}>{EmptyBox()}</button> </div>) } } const materialicon = () => { if (this.state.showmaterials) { return (<div style={{ ...styles.generalContainer }}> <button style={{ ...styles.generalButton, ...checkfield }} onClick={() => { this.setState({ showmaterials: false }) }}>{CheckedBox()}</button> </div>) } else { return (<div style={{ ...styles.generalContainer }}> <button style={{ ...styles.generalButton, ...checkfield }} onClick={() => { this.setState({ showmaterials: true }) }}>{EmptyBox()}</button> </div>) } } const equipmenticon = () => { if (this.state.showequipment) { return (<div style={{ ...styles.generalContainer }} onClick={() => { this.setState({ showequipment: false }) }}> <button style={{ ...styles.generalButton, ...checkfield }}>{CheckedBox()}</button> </div>) } else { return (<div style={{ ...styles.generalContainer }}> <button style={{ ...styles.generalButton, ...checkfield }} onClick={() => { this.setState({ showequipment: true }) }}>{EmptyBox()}</button> </div>) } } if (myuser) { const project = dynamicstyles.getproject.call(this); if (project) { return ( <div style={{ ...styles.generalFlex }}> <div style={{ ...styles.flex1 }}> <div style={{ ...styles.generalContainer, ...styles.alignCenter }}> <Link style={{ ...styles.generalLink, ...styles.generalFont, ...headerFont, ...styles.boldFont }} to={`/${myuser.profile}/company/${myuser.company.url}/projects/${project.title}`} > /{project.title}</Link> </div> <div style={{ ...styles.generalContainer, ...styles.alignCenter }}> <Link style={{ ...styles.generalLink, ...styles.generalFont, ...headerFont, ...styles.boldFont }} to={`/${myuser.profile}/company/${myuser.company.url}/projects/${project.title}/invoices`} > /invoices</Link> </div> <div style={{ ...styles.generalFlex }}> <div style={{ ...styles.flex1, ...styles.generalFont }}> <button style={{ ...styles.generalButton, ...proposalButton }} onClick={() => { this.createnewinvoice() }}>{RedPlus()}</button><span style={{ ...styles.generalFont, ...regularFont }}>Create New Invoice</span> </div> </div> <div style={{ ...styles.generalFlex, ...styles.marginLeft30 }}> <div style={{ ...styles.flex1, ...styles.generalFont }}> <button style={{ ...styles.generalButton, ...proposalButton }}>{redMinus()}</button><span style={{ ...styles.generalFont, ...regularFont }}>My Invoices</span> </div> </div> {this.showinvoiceids()} <div style={{ ...styles.generalFlex, ...styles.bottomMargin15 }}> <div style={{ ...styles.flex1 }}> <span style={{ ...regularFont, ...styles.generalFont }}>Labor</span> {laboricon()} </div> <div style={{ ...styles.flex1 }}> <span style={{ ...regularFont, ...styles.generalFont }}>Equipment</span> {equipmenticon()} </div> <div style={{ ...styles.flex1 }}> <span style={{ ...regularFont, ...styles.generalFont }}>Materials</span> {materialicon()} </div> </div> {this.showallpayitems()} {this.showinvoicelink()} {dynamicstyles.showsaveproject.call(this)} </div> </div> ) } else { return (<div style={{ ...styles.generalContainer, ...regularFont }}> <span style={{ ...styles.generalFont, ...regularFont }}>Project Not Found </span> </div>) } } else { return (<div style={{ ...styles.generalContainer, ...regularFont }}> <span style={{ ...styles.generalFont, ...regularFont }}>Please Login to Invoices </span> </div>) } } } function mapStateToProps(state) { return { myusermodel: state.myusermodel, navigation: state.navigation, projectid: state.projectid, allusers: state.allusers, allcompanys: state.allcompanys, csis: state.csis } } export default connect(mapStateToProps, actions)(Invoices);
var express = require('express'); var app = express(); const dba = require("./rundbbuild.js"); const query = require("./dbqueries.js"); let db = dba.connect(); app.use(express.json()); app.get('/', function(req, res) { res.sendFile("index.html", { root: __dirname }) }); app.get('/api/messages', function(req, res) { query.getAllMessages(db, req, res); }); app.get('/api/sort-users', function(req, res) { query.organiseUsers(db, req, res); }); app.get('/api/get-messages-from-franklins', function(req, res) { query.getFromFranklins(db, req, res); }); app.post('/api/create-user', function(req,res) { console.log("This is the req",req.body); query.createUser(db,req,res); }); app.put('/api/update-steve', function(req,res) { query.updateSteveJobs(db,req,res) }); app.put('/api/archive-steve', function(req,res) { query.archiveJobs(db,req,res); }); app.delete('/api/delete-messages', function(req,res) { query.deleteOldMess(db,req,res) }); app.post('/api/post-message', function(req,res) { console.log("This is the req",req.body); query.postAMessage(db,req,res); }); app.listen(3000, function () { dba.init(db); console.log('Server is listening on port 3000. Ready to accept requests!'); });
export default function (req, res){ let smtpEndpoint = "email-smtp.us-west-2.amazonaws.com"; let smtpUsername = "AKIA5MALYI2EVYIDAF53"; let smtpPassword = "BGUVqAVzmTmTm6VqKJ0Aw8MYQKLFZ+1IfIv5RBQjbTwV"; let senderAddress = "order.farmoreco@gmail.com"; let subject = `${req.body.product} Sample Request by ${req.body.name}`; let body_text = `Coffee Sample Request (${req.body.product}) <br/> -------------------------------------------------------------<br/><br/> Dear Sir/Madam: <br/> <br/> ${req.body.message} <br/> <br/> Regards, <br/><br/> Name: ${req.body.name} <br/> Email: ${req.body.email}<br/><br/> Company Name: ${req.body.companyName}<br/> Phone: ${req.body.phone}<br/> `; let body_html = `<html> <head></head> <body> <h1>Coffee Sample Request ${req.body.product} </h1> <p> Dear Sir/Madam: <br/> <br/> ${req.body.message} </p> <p> Regards, <br/> <br/> Name: ${req.body.name} <br/> Email: ${req.body.email} <br/> <br/> Company Name: ${req.body.companyName} <br/> Phone: ${req.body.phone} <br/> </p> </body> </html>`; let nodemailer = require('nodemailer') const transporter = nodemailer.createTransport({ port: 465, host: smtpEndpoint, auth: { user: smtpUsername, pass: smtpPassword, }, secure: true, }); const mailData = { from: senderAddress, // to: "info@farmore.co", to: "sebastian@farmore.co", subject: subject, text: body_text, html: body_text } transporter.sendMail(mailData,function(err, info){ if(err){ res.status(err.responseCode).json({status: err}); }else{ res.status(200).json({status:"success"}); } }) } export const config = { api:{ externalResolver: true, }, }
var _ = fis.util; var path = require('path'); module.exports = function(ret, conf,settings,opt) { //主要就是根据settings里面的设置,从ret里面拿出对应的文件,把文件内容抽出来放到settings的key路径下,生成一个文件 var src = ret.src; var packroute = {}; var sources = []; var root = fis.project.getProjectPath();// 拿到项目根路径 // 如果有settings,就把settings放到packroute里面 if (settings && Object.keys(settings).length) { packroute = settings; }; // 将所有文件都push到source里面 Object.keys(src).forEach(function(key) { sources.push(src[key]); }); // 定义查询方法 function find(reg, rExt) { if (src[reg]) { return [src[reg]]; } else if (reg === '**') { // do nothing } else if (typeof reg === 'string') { reg = _.glob(reg); } // 如果是正则,就在sources里寻找匹配的 return sources.filter(function (file) { reg.lastIndex = 0; return (reg === '**' || reg.test(file.subpath)) && (!rExt || file.rExt === rExt); }); } // 获取所有的符合条件 Object.keys(packroute).forEach(function(subpath, index) { var patterns = packroute[subpath]; // 拿到的配置路径是不是数组,不是的话组一个数组 if (!Array.isArray(patterns)) { patterns = [patterns]; }; // 循环数组 var valid = patterns.every(function(pattern) { return typeof pattern === 'string' || pattern instanceof RegExp;// 我不需要这个正则的情况吧?加上吧还是 }); if (!valid) { throw new TypeError('only string or RegExp are allowed') }; // 定义输出文件 var pkg = fis.file.wrap(path.join(root, subpath)); // 如果有同名文件,报警 if (typeof ret.src[pkg.subpath] !== 'undefined') { fis.log.warning('there is a namesake file of package [' + subpath + ']'); } // 循环读取限制条件 var list = []; patterns.forEach(function(pattern, index) { var exclude = typeof pattern === 'string' && pattern.substring(0, 1) === '!'; var mathes = find(pattern, pkg.rExt); list = _[exclude ? 'difference' : 'union'](list, mathes); }); // 拿到list就是符合条件的文件集合 var content = '['; list.forEach(function(file) { var c = file.getContent(); // 派送事件 var message = { file: file, content: c, pkg: pkg }; fis.emit('pack:file', message); c = message.content; // 拼接content字符串 content += c; content += ','; }); content = content.substring(0, content.length - 1); content += ']'; pkg.setContent(content); ret.pkg[pkg.subpath] = pkg; }); }
import React from 'react' import { Paper, Typography } from '@material-ui/core' import { makeStyles } from '@material-ui/core/styles'; import CountUpText from './CountUpText'; const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, }, paper: { padding: theme.spacing(2), color: theme.palette.text.secondary, marginTop: '16px', }, })); const IncomeExpenseCard = (props) => { const classes = useStyles(); return ( <Paper className={classes.paper}> <Typography variant="h6">{props.type}</Typography> <CountUpText amount={props.amount}/> </Paper> ) } export default IncomeExpenseCard;
/** * @theroyalwhee0/dynasty:src/members/depends.js */ /** * Imports. */ const { transformDeps } = require('../depends'); /** * Depends factory. */ function dependsFactory() { return function depends(...deps) { deps = transformDeps(deps); function dependsParam(item) { item.depends = Object.assign(item.depends || { }, deps); return Promise.resolve(item); }; return Promise.resolve(dependsParam); }; } /** * Exports. */ module.exports = dependsFactory;
import './App.css' import React from 'react'; import TopBar from "./Components/TopBar"; import TripList from "./Components/TripList"; import Stats from "./Components/Stats"; class App extends React.Component{ state = { collapsed: false, result: "Loading..." }; render(){ return ( <div> <TopBar/> <div style={{display:"flex", flexDirection:"row", justifyContent:"space-around"}}> <Stats/> <div style={{border : '0.2px solid black', marginTop : '40px'}}> </div> <TripList/> </div> </div> ); } } export default App;
const { restore } = require('utilities/helpers/restoreCommenRefsHelper'); /** * Make any changes you need to make to the database here */ exports.up = async function up(done) { const { fieldsCount, wobjectsCount, postsCount, objectTypesCount, } = await restore(); console.log('Restore Comments Refs to separate collection finish!'); console.log(`Restored: types - ${objectTypesCount}, wobjects - ${wobjectsCount}, fields - ${fieldsCount}, posts - ${postsCount}`); done(); }; /** * Make any changes that UNDO the up function side effects here (if possible) */ exports.down = function down(done) { done(); };
/** * @fileoverview Send Funds Constants * @author Gabriel Womble */ const SELECTING_ADDRESSES = 'addresses'; const SELECTING_CONTACTS = 'contacts'; const MESSAGE_KEYS = { FAIL: 'fail', SUCCESS: 'success', TO_ADDRESS: 'toAddress', }; export { MESSAGE_KEYS, SELECTING_ADDRESSES, SELECTING_CONTACTS, };
"use strict"; app.controller('AppCtrl', function($scope, $ionicModal, $timeout, $q, CustomTourFact, AllPlacesFact, AuthFact, BookmarkFact, $ionicSideMenuDelegate) { // Cards that will be displayed on whichever page $scope.MarkerCards; // All places available in memory $scope.AllPlaces; let displayalert = null; //The purpose of this function is to get all of the markers, art and historical, from the Nashville Gov API and place them in one array. function getAllPlaces(){ return $q.all( [AllPlacesFact.getAllHistoricalMarkers(), AllPlacesFact.getAllArtInPublicPlacesMarkers(), AllPlacesFact.getAllMetroPublicArtMarkers()] ) .then((data)=>{ $scope.AllPlaces = data[0].concat(data[1]).concat(data[2]); $scope.AllPlaces = $scope.AllPlaces.sort($scope.sortAllPlaces); console.log("All places", $scope.AllPlaces); $scope.MarkerCards = $scope.AllPlaces; }); } $scope.sortAllPlaces = (x, y) => { // Determines if the place is a historical marker or artwork // Returns the name of the place to be used when sorting function getPlaceName(place) { if (place.title) { return place.title.toLowerCase(); } else if (place.artwork) { return place.artwork.toLowerCase(); } } return getPlaceName(x) < getPlaceName(y) ? -1 : 1; } // Execute on start getAllPlaces(); // ADD TO ROUTE/TOUR FUNCTIONALITY // Stores current marker for Add to Route modal $scope.selectedMarker; // Stores active tour/route for Add to Route modal $scope.activeTour = {id: ""}; $scope.newTour = {name: "", places: {}}; // Add to Route modal $scope.tourModal = function(markerUID) { // Create the login modal and show it $ionicModal.fromTemplateUrl('templates/tourModal.html', { scope: $scope }).then(function(modal) { $scope.modal = modal; setSelectedMarker(markerUID); $scope.modal.show(); }); }; // Triggered in the route/tour modal to close it $scope.closeTourModal = function() { $scope.modal.hide(); $scope.modal.remove(); }; $scope.doAddToRoute = function() {; // Prepare place object let newPlace = { dateAdded: Date.now() } // Preparing a new route/tour to be added to Firebase if ($scope.activeTour.id == "new") { newPlace.order = 1; $scope.newTour.userId = $scope.loggedInUser.uid; $scope.newTour.dateAdded = Date.now(); $scope.newTour.public = false; $scope.newTour.places[$scope.selectedMarker.uid] = newPlace; console.log($scope.newTour); // Ship off to Firebase CustomTourFact.pushNewTour($scope.newTour) .then((tourUID) => { // Add new Tour to user object with provided tourUID $scope.loggedInUser.customTours[tourUID] = $scope.newTour; // Clear New Tour object $scope.newTour = {name: "", places: {}}; }) // If we're just adding to an existing tour on Firebase } else { // Assign an Order to the place, according to how many places already exist on this route if ($scope.loggedInUser.customTours[$scope.activeTour.id].places) { newPlace.order = Object.keys($scope.loggedInUser.customTours[$scope.activeTour.id].places).length + 1; //Limit number of routes added to a custom tour to 23 if (newPlace.order >= 24) { displayalert = true } } else { newPlace.order = 1; } console.log(displayalert) if (displayalert) { alert("You may not add more than 23 places to a tour!") displayalert = false; } else { CustomTourFact.putNewPlace($scope.activeTour.id,$scope.selectedMarker.uid,newPlace) .then((response)=> { // Add newly created place to user object if ($scope.loggedInUser.customTours[$scope.activeTour.id].places) { $scope.loggedInUser.customTours[$scope.activeTour.id].places[$scope.selectedMarker.uid] = newPlace; } else { $scope.loggedInUser.customTours[$scope.activeTour.id].places = {}; $scope.loggedInUser.customTours[$scope.activeTour.id].places[$scope.selectedMarker.uid] = newPlace; } }) } } $scope.modal.hide(); $scope.modal.remove(); } function setSelectedMarker(uid) { for (let i = 0; i < $scope.AllPlaces.length; i++) { if ($scope.AllPlaces[i].uid == uid) { $scope.selectedMarker = $scope.AllPlaces[i]; } } } $ionicSideMenuDelegate.canDragContent(false); $scope.AddToBookmarks = (marker, index)=>{ // Saves a markercard to the users bookmarks console.log("working", marker) marker.userId = AuthFact.getUserId(); $scope.MarkerCards[index].isBookmarked = true; BookmarkFact.addBookmark(marker); } // Current Firebase Logged-In User Object $scope.loggedInUser = null; // Form data for the login modal $scope.loginData = {}; // Triggered in the login modal to close it $scope.closeLogin = function() { $scope.modal.hide(); $scope.modal.remove(); }; // Open the login modal $scope.login = function() { // Create the login modal and show it $ionicModal.fromTemplateUrl('templates/login.html', { scope: $scope }).then(function(modal) { $scope.modal = modal; $scope.modal.show(); }); }; // Switch to the register modal $scope.register = function() { // Remove the login modal $scope.modal.hide(); $scope.modal.remove(); // Create the register modal and show it $ionicModal.fromTemplateUrl('templates/register.html', { scope: $scope }).then(function(modal) { $scope.modal = modal; $scope.modal.show(); }); } // Auto-Login Handler firebase.auth().onAuthStateChanged(function(user) { if (user) { $scope.loggedInUser = user; // Retrieve custom tours for this user on login CustomTourFact.retrieveCustomTours(user.uid) .then((tours)=> { $scope.loggedInUser.customTours = tours; }) // Retrieve bookmarks for this user on login areMarkersBookmarked(user); } else { $scope.loggedInUser = null; } console.log("Current Logged In User", $scope.loggedInUser) }); // Retrieve user bookmarks and update AllPlaces with new detail function areMarkersBookmarked (user){ BookmarkFact.getAllBookmarks(user.uid) .then((bookmarks)=>{ console.log("bookmarked markers", bookmarks); Object.keys(bookmarks).map((key)=>{ $scope.AllPlaces.forEach((marker, index)=>{ if (bookmarks[key].uid === marker.uid){ $scope.AllPlaces[index].isBookmarked = true; } }) }) }) } // Logout $scope.logout = function() { firebase.auth().signOut() .then(function(data){ console.log("success log out", data) $scope.loggedInUser = null; }) } // Google Login $scope.google = function() { var provider = new firebase.auth.GoogleAuthProvider(); firebase.auth().signInWithRedirect(provider) .then(function(result) { // This gives you a Google Access Token. You can use it to access the Google API. var token = result.credential.accessToken; // The signed-in user info. $scope.loggedInUser = result.user; }).catch(function(error) { console.error(`Error with Registration, ${error.code}: ${error.message}`); // The email of the user's account used. var email = error.email; // The firebase.auth.AuthCredential type that was used. var credential = error.credential; }); } // Firebase Login with Email and Password $scope.doLogin = function() { firebase.auth().signInWithEmailAndPassword($scope.loginData.username, $scope.loginData.password) .then(function(data) { $scope.loggedInUser = data; $scope.modal.hide(); $scope.modal.remove(); }) .catch(function(error) { console.error(`Error with Login, ${error.code}: ${error.message}`); }); }; // Firebase Registration with Email and Password $scope.doRegistration = function() { if ($scope.loginData.password !== $scope.loginData.passwordConfirmation) { console.error("Passwords do not match.") } else { firebase.auth().createUserWithEmailAndPassword($scope.loginData.username, $scope.loginData.password) .then(function(data) { $scope.loggedInUser = data; $scope.modal.hide(); $scope.modal.remove(); }) .catch(function(error) { // Handle Errors here. console.error(`Error with Registration, ${error.code}: ${error.message}`); }); }; } })
import Em from 'ember'; import layout from './template'; import ExpFrameBaseComponent from '../exp-frame-base/component'; import ExpandAssets, {videoAssetOptions} from '../../mixins/expand-assets'; let { $ } = Em; /** * @module exp-player * @submodule frames */ /** * A frame to display video instructions to the user. * * A video is displayed to the left, and a transcript or summary in a scrolling box to the right. (The transcript can * be omitted if desired, but in that case you must provide complete captioning for the video!) * * The participant is required to either scroll to the bottom of the transcript or watch the video to proceed. * * Each element of the 'transcriptBlocks' parameter is rendered using {{#crossLink "Exp-text-block"}}{{/crossLink}}. ```json "frames": { "intro-video": { "kind": "exp-lookit-instruction-video", "instructionsVideo": [ { "src": "https://raw.github.com/UCDOakeslab/Baby_MR_Lookit/master/Lookit Introduction Part 1_Edited.mp4", "type": "video/mp4" } ], "introText": "Welcome to the study! Please watch this video to get started. \n(Or you can read the summary to the right if you prefer.)", "transcriptTitle": "Video summary", "transcriptBlocks": [ { "title": "Background information about the study", "listblocks": [ { "text": "Your baby does not need to be with you at this point in the study. We will let you know when it is time to get your baby." }, { "text": "Mental rotation, or the ability to manipulate internal representations of objects, is an important spatial ability. Spatial abilities are important for understanding objects, reading maps, mathematical reasoning, and navigating the world. Thus, the development of mental rotation is an important milestone. In the current study, we are interested in examining whether babies in general can mentally rotate simple objects." } ] }, { "title": "Preview of what your baby will see" }, { "listblocks": [ { "text": "Your baby will be shown two identical Tetris shapes on the screen; one on the left and one on the right. The shapes appear and disappear, changing their orientation each time they reappear. On one side, the rotation will always be possible. Sometimes, on the other side, a mirror image of the shape will be presented. If babies can mentally rotate objects, they should spend different amounts of time watching these two kinds of stimuli." } ] }, { "title": "What's next?", "listblocks": [ { "text": "Because this is an online study, we will check to make sure that your webcam is set up and working properly on the next page, so we can record your baby’s looking behavior during the study." }, { "text": "Following that page, you will be given an opportunity to review the consent information and we will ask that you record a short video of yourself giving consent to participate in this study." }, { "text": "We will then ask you questions about your baby's motor abilities." }, { "text": "After you are finished with the consent page and questions, you will be provided with more detailed information about what to do during the study and how to get started." } ] } ], "warningText": "Please watch the video or read the transcript before proceeding.", "nextButtonText": "Next", "title": "Study instructions", "showPreviousButton": false } } * ``` * @class Exp-lookit-instruction-video * @extends Exp-frame-base * @extends Expand-assets */ export default ExpFrameBaseComponent.extend(ExpandAssets, { layout: layout, type: 'exp-lookit-instruction-video', assetsToExpand: { 'audio': [ ], 'video': [ 'instructionsVideo' ], 'image': [ ] }, frameSchemaProperties: { /** * Title to show at top of frame * * @property {String} title * @default 'Study instructions' */ title: { type: 'string', description: 'Title for frame', default: 'Study instructions' }, /** * Intro text to show at top of frame * * @property {String} introText * @default 'Welcome! Please watch this video to learn how the study will work. \n You can read through the information to the right if you prefer.' */ introText: { type: 'string', description: 'Intro text to show at top of frame', default: 'Welcome! Please watch this video to learn how the study will work. You can read the transcript to the right if you prefer.' }, requireWatchOrRead: { type: 'Boolean', description: 'Whether to require that the participant watches the video (or reads the whole transcript) to move on', default: true }, /** * Text to show above Next button if participant has not yet watched video or read transcript. Only used if * requireWatchOrRead is true. * * @property {String} warningText * @default 'Please watch the video or read the transcript before proceeding.' */ warningText: { type: 'string', description: 'Text to show above Next button if participant has not yet watched video or read transcript', default: 'Please watch the video or read the transcript before proceeding.' }, /** * The location of the instructions video to play. This can be either * an array of {'src': 'https://...', 'type': '...'} objects (e.g. providing both * webm and mp4 versions at specified URLS) or a single string relative to baseDir/<EXT>/. * * @property {Object} instructionsVideo */ instructionsVideo: { anyOf: videoAssetOptions, description: 'Object describing the instructions video to show' }, /** * Title to show above video transcript/overview. Generally this should be either "Video transcript" or * "Video summary" depending on whether you're providing a word-for-word transcript or a condensed summary. * It may * * @property {String} transcriptTitle * @default 'Video transcript' */ transcriptTitle: { type: 'string', description: 'Title to show above video transcript/overview', default: 'Video transcript' }, /** * Array of blocks for {{#crossLink "Exp-text-block"}}{{/crossLink}}, providing a transcript of the video * or an overview of what it said. A transcript can be broken down into bullet points to make it more readable. * * If you've also provided closed captions throughout the video, you can use this space just to provide key * points. * * If this is left blank ([]) no transcript is displayed. * * @property {Object[]} transcriptBlocks * @param {String} title Title of this section * @param {String} text Paragraph text of this section * @param {Object[]} listblocks Object specifying bulleted points for this section. Each object is of the form: * {text: 'text of bullet point', image: {src: 'url', alt: 'alt-text'}}. Images are optional.* */ transcriptBlocks: { type: 'array', items: { type: 'object', properties: { title: { type: 'string' }, text: { type: 'string' }, listblocks: { type: 'array', items: { type: 'object', properties: { text: { type: 'string' }, image: { type: 'object', properties: { src: { type: 'string' }, alt: { type: 'string' } } } } } } } }, default: [] }, /** * Whether to show a 'previous' button * * @property {Boolean} showPreviousButton * @default true */ showPreviousButton: { type: 'boolean', default: true }, /** * Text to display on the 'next frame' button * * @property {String} nextButtonText * @default 'Start the videos! \n (You\'ll have a moment to turn around.)' */ nextButtonText: { type: 'string', default: 'Start the videos! \n (You\'ll have a moment to turn around.)' } }, meta: { data: { type: 'object', properties: { } } }, hasCompletedFrame: Em.computed('playedVideo', 'readTranscript', 'requireWatchOrRead', function() { return (!this.get('requireWatchOrRead') || this.get('playedVideo') || this.get('readTranscript')); }), showWarning: false, playedVideo: false, readTranscript: false, actions: { mediaPlayed() { this.set('playedVideo', true); this.set('showWarning', false); }, checkIfDoneThenNext() { if (!this.get('hasCompletedFrame')) { this.set('showWarning', true); } else { this.send('next'); } } }, didInsertElement() { this._super(...arguments); let $transcript = $('div.transcript'); let _frame = this; // See https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#Determine_if_an_element_has_been_totally_scrolled if ($transcript.length) { // First check if the transcript is already scrolled to end because it doesn't need to scroll. Allow slight // buffer (2px) as Chrome doesn't always think we've scrolled to very bottom. if ($transcript[0].scrollHeight - $transcript[0].scrollTop <= $transcript[0].clientHeight + 2) { _frame.set('readTranscript', true); _frame.set('showWarning', false); } // And check upon scrolling if we've reached the bottom $transcript.bind('scroll', function() { if (this.scrollHeight - this.scrollTop <= this.clientHeight + 2) { _frame.set('readTranscript', true); _frame.set('showWarning', false); } }); } } });
import axios from 'axios'; var instance = { baseURL: 'http://192.168.65.50:3000/api', } localStorage.setItem('_token', 'tGdTHiYbJObGsYyhZVFwo6HNfuPYIZA7EnaV8IaFaZ2NNe8zWCpvRSdlcvZMLDWf') const _token = localStorage.getItem('_token') module.exports = { // Get functions fetchAssetList: function(){ return axios.get(instance.baseURL+"/Assets") .then(function(response){ return response.data; }) }, // Post functions profileLogin(credentials){ /* axios.request({ method:'post', url: instance.baseURL+"/Profiles/login", data: credentials }).then(response => { if(response.data.code == 200){ const token = response.data.id; localStorage.setItem('glarToken', token); } else if(response.data.code == 204){ console.log("Username password do not match"); alert("username password do not match") } else{ console.log("Username does not exists"); alert("Username does not exist"); } console.log(response); }) .catch(function (error) { console.log(error); });*/ }, profileLogout: function(_token){ console.log(_token) return axios.post(instance.baseURL+"/Profiles/logout?access_token="+ _token) .then(function (response) { instance.defaults.headers.common['Authorization'] = null console.log(response); }) .catch(function (error) { console.log(error); }); }, getSeverity: function() { return axios.get(instance.baseURL+"/Severities?access_token="+_token) .then(function(response) { return response.data; }) }, getTeamId: function() { return axios.get(instance.baseURL+"/Teams?access_token="+_token) .then(function(response) { return response.data }) }, getElements: function() { return axios.get(instance.baseURL+"/Elements?access_token="+_token) .then(function(response) { return response.data }) }, getSites: function() { return axios.get(instance.baseURL+"/CompanySites?access_token="+_token) .then(function(response) { return response.data }) } }
#!/usr/bin/env node 'use strict'; process.title = 'arc-repo'; const repo = require('../lib/arc-repo'); const program = require('commander'); const colors = require('colors/safe'); const allowedCommands = ['create']; const action = (command, repoName) => { if (allowedCommands.indexOf(command) === -1) { console.log(); console.log(colors.red(` Error: command ${command} is unknown.`)); console.log(); process.exit(1); } if (repoName && !/^[a-zA-Z0-9_-]*$/.test(repoName)) { console.log(); console.log(colors.red(` Error: name ${repoName} is invalid.`)); console.log(); process.exit(1); } try { program.repoName = repoName; const script = new repo.ArcRepo(command, program); script.run().then(() => { process.exit(0); }).catch((err) => { console.log(colors.red(' ' + err.message)); process.exit(1); }); } catch (e) { console.log(e); console.log(colors.red(' ' + e.message)); program.outputHelp(); process.exit(1); } }; program .arguments('<command> [repo-name]') .option('--token', 'Github access token. Set GITHUB_TOKEN variable to omnit it.') .option('--verbose', 'Print output to console.') .action(action); program.on('--help', function() { console.log(' Commands:'); console.log(''); console.log(' create Creates a repository in ARC\'s ogranization with default ' + 'configuration.'); console.log(' create --description, -D Description of the repository '); console.log(''); console.log(' Examples:'); console.log(''); console.log(' $ arc repo create repo-name'); console.log(''); }); program.parse(process.argv);
if (!Object.entries) { Object.entries = function (obj) { var ownProps = Object.keys(obj), i = ownProps.length, resArray = new Array(i); while (i--) { resArray[i] = [ownProps[i], obj[ownProps[i]]]; } return resArray; }; } if (!Object.values) { Object.values = function values(O) { return reduce(ownKeys(O), function (v, k) { return concat(v, typeof k === 'string' && isEnumerable(O, k) ? [O[k]] : []) }, []) } }
const readlineSync = require("readline-sync") function askTvSerie() { let title = readlineSync.question('Name of the tv serie ? : ') let title = readlineSync.question('Production year ? : ') let title = readlineSync.question('Cast : ') console.log('Distance between point A & point B : ' + dist); {"serie-title": "Lambert", "production_year": 42, "cast": { "cast1": "JavaScript", "cast2": "advanced" } }
import fs from "fs"; import path from "path"; import { marked } from "marked"; marked.setOptions({ renderer: new marked.Renderer(), gfm: true, tables: true, breaks: false, pedantic: false, sanitize: false, smartLists: true, smartypants: false, headerIds: false, }); function isFileMarkdown(filePath) { return path.basename(filePath).split(".")[1] === "md"; } function filenameToHTML(filePath) { return `${path.basename(filePath).split(".")[0]}.html`; } /** * Convert meta markdown files to HTML. * * Never throws, all errors are caught. * * @param {Object} options * @param {string} options.inputFileBasePaths The base paths from which meta markdown files will be * read * @param {string} options.outputFileBasePath The base path to which converted HTML files will be * written */ export default async function datagenMeta({ inputFileBasePaths, outputFileBasePath }) { await Promise.all( inputFileBasePaths.map(async (folder) => { // Read markdown meta directory let files; try { files = await fs.promises.readdir(folder); } catch (err) { console.error(`Error reading meta directory ${folder}: ${err.message}`); } await Promise.all( files.map(async (file) => { if (!isFileMarkdown(file)) return; const filePath = path.join(folder, file); // Read markdown files let data; try { data = await fs.promises.readFile(filePath, "utf8"); } catch (err) { console.error(`Error reading meta file ${filePath}: ${err.message}`); } // Convert markdown to HTML let content; try { content = marked(data); } catch (err) { console.error(`Error running marked on ${filePath}: ${err.message}`); } // Write HTML to file const outputPath = path.join(outputFileBasePath, folder, filenameToHTML(file)); try { await fs.promises.writeFile(outputPath, content); console.log(`Wrote ${outputPath}`); } catch (err) { console.error(`Error writing meta HTML ${outputPath}: ${err.message}`); } }) ); }) ); }
import { BrowserRouter, Route, Switch } from "react-router-dom"; import { Account } from "./components/account/Account"; import { PrivateComponent } from "./components/general/PrivateComponent"; import { PrivateRoute } from "./components/general/PrivateRoute"; import { Layout } from "./components/general/Layout"; import { Profile } from "./components/profile/Profile"; import { Users } from "./components/users/Users"; function App() { return ( <BrowserRouter> <Switch> <Route path="/account"> <Account /> </Route> <PrivateRoute path="/"> <Layout> <Switch> <Route exact path="/"> <PrivateComponent /> </Route> <Route path="/users"> <Users /> </Route> <Route exact path="/profile"> <Profile /> </Route> <Route> <h1 className="bg-warning text-center text-white m-2 p-2">Not Found</h1> </Route> </Switch> </Layout> </PrivateRoute> </Switch> </BrowserRouter> ); } export default App;
$("button").click(function(){ var questionOne=$(".Q1").val(); var questionTwo=$(".Q2").val(); if (questionOne <=16 && questionTwo==="sweet"){ $("body").append("<img src =https://i.pinimg.com/originals/04/25/7e/04257edbe4db45db6ea41ebb32c08a66.jpg>"); $("body").append("<p>You are a sweet and loving person. You love to help others around you, but sometimes you can lose control with your emotions.</p>"); } else if (questionOne<=16 && questionTwo==="hothead") { $("body").append("<img src =https://i.pinimg.com/736x/68/d9/f0/68d9f0504c780ab33c4271d36cd1970e.jpg>"); $("body").append("<p> If you got this that means you are a little bit of a hothead! You strive for the top and you won’t let anyone get in your way.</p>"); } }); //} else if ( ) { //} else if ( ) { //} else { //}
const {keyBy, pipe, get, filter, trimCharsStart, keys} = require('lodash/fp'); const Request = require('request'); const Promise = require('bluebird'); const {compare, satisfies} = require('semver'); const request = Promise.promisify(Request, {multiArgs: true}); const NODE_VERSIONS = 'https://nodejs.org/dist/index.json'; const getNodeVersions = () => request({uri: NODE_VERSIONS, json: true}).then(([response, body]) => { if (response.statusCode !== 200) throw new Error("nodejs.org isn't available"); return body; }); const DOCKER_TAGS = version => `https://hub.docker.com/v2/repositories/library/node/tags/${version}/`; const isAvailableOnDocker = version => request({uri: DOCKER_TAGS(version), json: true}).then(([response, body]) => { if (response.statusCode !== 200) throw new Error(`Node's image ${version} isn't available`); return body; }); const findFulfilled = fun => arr => Promise.resolve(arr).reduce((acc, value) => { if (acc) return acc; return fun(value) .return(value) .catch(() => null); }, null); const findLatest = range => { const versionsP = getNodeVersions(); const mapVersionsP = versionsP.then(keyBy(pipe(get('version'), trimCharsStart('v')))); const latestAvailableVersionP = mapVersionsP .then(keys) .then(v => v.sort(compare).reverse()) .then(filter(v => satisfies(v, range))) .then(findFulfilled(isAvailableOnDocker)); return Promise.all([latestAvailableVersionP, mapVersionsP]).spread(get); }; module.exports = {findLatest, getNodeVersions};
function palindrome_check(str) { var strReverse = str.split('').reverse().join(''); if (str == strReverse) { return `${str} is a palindrome.`; } else{ return `${str} is not a palindrome.`; } } console.log(palindrome_check("nursesrun"));
$(function () { $('.input') .mouseenter(function() { $(this).children('.help-text').fadeIn(100); }) .mouseleave(function () { $(this).children('.help-text').fadeOut(100); }); $('.help').click(function () { $('.help-text').fadeIn(100); }); });
import { h } from 'preact'; import { styled } from 'goober'; import { useContext } from 'preact/hooks'; import { NavContext, ConfigContext, NotifyContext } from '../qbm.jsx'; //#region css const PathItem = styled('button')` flex: auto; display: flex; justify-content: space-between; align-items: center; min-width: 0; border: none; cursor: pointer; box-sizing: border-box; height: 30px; line-height: 30px; padding: 0px; &:not(:first-child) { margin-left: -9px; } &:hover * { background-color: var(--hover-color); } &:focus, &:focus * { outline: none; background-color: var(--hover-color); } &:active * { background-color: var(--active-color); } &:first-child::before { content: ""; height: 30px; width: 26px; background-color: var(--bg-color); background-image: var(--folder-icon); background-size: 16px 16px; background-position: 10px center; background-repeat: no-repeat; } &:first-child:hover::before, &:first-child:focus::before { outline: none; background-color: var(--hover-color); } &:first-child:active::before { background-color: var(--active-color); } &:not(:first-child)::before { content: ""; width: 0; height: 0; border-style: solid; border-width: 15px 0 15px 10px; border-color: var(--bg-color) transparent var(--bg-color) transparent; } &:not(:first-child):hover::before, &:not(:first-child):focus::before { outline: none; border-color: var(--hover-color) transparent var(--hover-color) transparent; } &:not(:first-child):active::before { border-color: var(--active-color) transparent var(--active-color) transparent; } &:not(:last-child)::after { content: ""; width: 0; height: 0; border-style: solid; border-width: 15px 0 15px 10px; border-color: transparent transparent transparent var(--bg-color); z-index: 2; } &:not(:last-child):hover::after, &:not(:last-child):focus::after { outline: none; border-color: transparent transparent transparent var(--hover-color); } &:not(:last-child):active::after { border-color: transparent transparent transparent var(--active-color); } `; const Text = styled('a')` color: var(--text-color); background-color: var(--bg-color); text-decoration: none; flex: auto; padding-left: 5px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; text-align: left !important; button:last-child & { font-weight: bold; } `; //#endregion /** * * @param {{ * id: string * title: string * }} props */ export function QbmPathItem(props) { const naviage = useContext(NavContext); const config = useContext(ConfigContext); const notify = useContext(NotifyContext); const hoverEnterSpeed = { slow: 800, medium: 500, fast: 200 }; const openFolder = () => { naviage('folder', props.id); }; const onMouseOver = () => { if (config.hoverEnter === 'off' || props.last) return; this._clickTimeout = setTimeout(() => openFolder(), hoverEnterSpeed[config.hoverEnter]); }; const onMouseOut = () => { if (this._clickTimeout) { clearTimeout(this._clickTimeout); } }; const onClick = () => { if (props.last) { chrome.bookmarks.getChildren(props.id, results => { chrome.storage.local.set({ startup: [props.id, results.length] }); notify({target: props.title, action: chrome.i18n.getMessage("set_startup_done")}); }); }else{ openFolder(); } }; return ( <PathItem role="link" tabIndex="0" onClick={onClick} onMouseOver={onMouseOver} onMouseOut={onMouseOut} title={props.last ? chrome.i18n.getMessage("set_startup"):""}> <Text >{props.title}</Text> </PathItem> ); }
import React from 'react'; import { Image } from 'react-native'; import { createStackNavigator, createBottomTabNavigator } from 'react-navigation'; import PlogScreen from '../screens/PlogScreen'; import HistoryScreen from '../screens/HistoryScreen'; import LocalScreen from '../screens/LocalScreen'; import ProfileScreen from '../screens/ProfileScreen'; import MoreScreen from '../screens/MoreScreen'; import Header from '../components/Header'; const Icons = { Plog: require('../assets/images/plog.png'), History: require('../assets/images/history.png'), Local: require('../assets/images/local.png'), Profile: require('../assets/images/profile.png'), More: require('../assets/images/more.png'), } const makeTabNavigationOptions = ({navigation}) => ({ tabBarLabel: navigation.state.routeName, tabBarIcon: (<Image source={Icons[navigation.state.routeName]} />), }); const makeStackNavigationOptions = ({navigation}) => ({ headerTitle: (<Header text={navigation.state.routeName} icon={Icons[navigation.state.routeName]} />), headerStyle: { backgroundColor: '#fff', borderBottomColor: 'purple', borderBottomWidth: 4 } }); const sharedStackOptions = { defaultNavigationOptions: makeStackNavigationOptions }; const Plog = createStackNavigator({ Plog: PlogScreen, }, {...sharedStackOptions}); Plog.navigationOptions = makeTabNavigationOptions; const History = createStackNavigator({ History: HistoryScreen, }, {...sharedStackOptions}); History.navigationOptions = makeTabNavigationOptions; const Local = createStackNavigator({ Local: LocalScreen, }, {...sharedStackOptions}); Local.navigationOptions = makeTabNavigationOptions; const Profile = createStackNavigator({ Profile: ProfileScreen, }, {...sharedStackOptions}); Profile.navigationOptions = makeTabNavigationOptions; const More = createStackNavigator({ More: MoreScreen, }, {...sharedStackOptions}); More.navigationOptions = makeTabNavigationOptions; export default createBottomTabNavigator({ Plog, History, Local, Profile, More });
import { GET_API_URL, POST_API_URL } from './constants'; export const getScoreFromApi = () => fetch(GET_API_URL) .then((data) => data.json()) .then((data) => data); export const addScoreToApi = (score) => fetch(POST_API_URL, { method: 'post', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(score), }); export default getScoreFromApi;
import React, { Component } from 'react'; import Layout from 'organisms/layout'; import Header from 'organisms/header'; import Footer from 'organisms/footer'; class SimplePage extends Component { render() { const { title, content } = this.props; return ( <Layout> <Header /> <section> <h1>{ title }</h1> <div dangerouslySetInnerHTML={ { __html: content, } } /> </section> <Footer /> </Layout> ); } } export default SimplePage;
import {StyleSheet} from 'react-native'; export default StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', marginHorizontal: 16, }, title: { textAlign: 'center', marginVertical: 8, }, tinyLogo: { width: 50, height: 50, }, });
/* Clase 5 - Arreglos */ // Es una coleccion de datos relacionados // Se almacenan en una variable var premierLeague = ["Chelsea", "Manchester United", "Liverpool", "Arsenal"]; // Presentan un indexado iniciando con 0 console.log(premierLeague[3]); // Otra forma de hacer un arreglo es usando la notación de objetos var la_liga = new Array("Barcelona", "Real Madrid", "Atletico Madrid"); // Para saber si un arreglo tiene información utilizamos el metodo la_liga.length; // Cambiar un valor de un arreglo la_liga[1] = "Valencia"; // Ordenar de forma invertida un arreglo la_liga.reverse;
function painting() { const canvas = document.getElementById('canvas') if(canvas.getContext) { const gra = canvas.getContext('2d') console.log(gra) // 线性渐变 const linear = gra.createLinearGradient(0, 150, 0, 0) linear.addColorStop(.1, 'rgb(200, 0, 0)') linear.addColorStop(.7, '#fff') linear.addColorStop(.9, '#c6c776') gra.fillStyle = linear gra.fillRect(100, 10, 330, 330) // 径向渐变 const radial = gra.createRadialGradient(45, 45, 10, 45, 45, 30) radial.addColorStop(0, '#A7D30C') radial.addColorStop(.9, '#019F62') radial.addColorStop(1, 'rgba(1, 159, 98, 0)') gra.fillStyle = radial gra.fillRect(0, 0, 150, 150) // 图片的两种绘画方式,第一种 // let img = new Image() // img.src = './timg.jpg' // img.onload = () => { // const background = gra.createPattern(img, 'no-repeat') // gra.fillStyle = background // gra.fillRect(0, 0, 500, 500) // } // 图片的两种绘画方式,第二种 // let img = new Image() // img.src = './timg.jpg' // img.onload = () => { // gra.drawImage(img, 0, 0, 200, 200) // } // 图片使用clit let img = new Image() img.src = './timg.jpg' img.onload = () => { gra.beginPath() gra.arc(300, 300, 200, Math.PI*2, false) gra.fill() gra.clip() gra.drawImage(img, 70, 80) } } }
import {StyleSheet, Platform} from 'react-native'; import Dimensions from 'Dimensions' let width = Dimensions.get('window').width, height = Dimensions.get('window').height; export default StyleSheet.create({ profile_top:{ flexDirection: 'column', justifyContent:'center', alignItems: 'center', backgroundColor: '#F1F3F5', height: height*0.4, }, profile_btm:{ flex: 1, width, alignItems: 'flex-end', height: height*0.6, backgroundColor: '#F1F3F5', }, profile_btm_header: { width, height: 50, borderTopWidth : 1, borderTopColor: '#E0E4E7', // backgroundColor: '#F1F3F5', flexDirection: 'row', alignItems: 'center', justifyContent: "center", }, profile_btm_header_menu:{ // borderWidth: 1, // borderColor: "black", width: width/2, alignItems: 'center', justifyContent: "center", // textAlign: 'center' }, profile_img:{ width: 90, height: 90, borderRadius: 45, borderWidth: 0.5, borderColor: '#5e5e5e', marginBottom: 10, }, profile_name:{ fontWeight: '700', fontSize: 22, marginBottom: 5, }, profile_univ:{ fontWeight: '200', color: '#5e5e5e', fontSize:13, marginRight: 10, // marginBottom:15, }, profile_selfIntro:{ fontSize:13, fontWeight: '200', }, // profile_btm:{ // borderTopWidth:1, // borderColor: '#dbdbdb', // height: Dimensions.get('window').height/2, // width: Dimensions.get('window').width, // justifyContent: 'center', // alignItems: 'center' // }, setting_list:{ height: 50, borderBottomWidth:1, borderColor: '#dbdbdb', justifyContent: 'center', paddingLeft: 15, }, setting_txt:{ fontSize: 13, }, setting_selfInt:{ borderTopWidth: 1, borderBottomWidth: 1, borderColor:'#dbdbdb', padding: 10, backgroundColor: '#fff', width: width, }, setting_proj:{ borderWidth: 1, borderColor:'#dbdbdb', padding: 10, borderRadius: 5, backgroundColor: '#fff', }, setting_detail:{ marginTop:20, marginBottom:20, marginLeft:10, fontWeight: '400', }, setting_input:{ width: width, height: 40, borderTopWidth: 1, borderBottomWidth: 1, borderColor:'#dbdbdb', padding: 5, backgroundColor: '#fff', }, modal: { flex: 1, justifyContent: 'flex-end', alignItems: 'center', backgroundColor: 'rgba(0,0,0,0.2)', // backgroundColor: 'transparent' }, modalBtn:{ backgroundColor: 'white', borderRadius: 10, padding: 10, width: width/1.1, height: height/15, alignItems:'center', marginBottom: 10, justifyContent:'center', }, projct_row:{ flexDirection: 'row', height: 50, padding: 10, backgroundColor: '#fff', marginBottom: 1, alignItems: 'center', // justifyContent: "space-between", }, projct_exit:{ flexDirection: 'column', height: 50, paddingTop: 3, paddingBottom:10, paddingLeft: 10, paddingRight:10, backgroundColor: '#fff', }, projct_exit_row:{ flexDirection: 'row', alignItems: 'center', }, projct_row_title:{ marginRight: 10, width: width/4 }, projct_row_time:{ width: width/3.5, }, proj_box_cont: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', marginBottom: 10, }, proj_box:{ padding: 5, borderWidth: 1, borderColor:'#dbdbdb', borderRadius:3, backgroundColor: '#fff', marginRight: 5, }, proj_box_text: { fontSize: 10 }, pic_cont: { flex: 1, flexDirection: 'column', justifyContent: 'flex-end', alignItems: 'center' }, pic_table:{ marginTop: 22, height: 200, width: width, backgroundColor: '#fff' }, pic_table_top:{ height: 30, borderBottomWidth: 1, borderBottomColor: '#dbdbdb', borderTopWidth: 1, borderTopColor: '#dbdbdb', justifyContent: 'center', alignItems: 'flex-end' }, detail_pro:{ flex: 1, flexDirection: 'column', backgroundColor: '#F1F3F5', }, detail_pro_top:{ justifyContent: 'center', alignItems: 'center', padding: 10, height: height/2.1 }, detail_pro_btm:{ padding: 15 }, detail_pro_title:{ flexDirection: 'column', alignItems: 'flex-start', justifyContent: 'flex-start', marginBottom: 15 }, detail_pro_univ:{ fontSize: 12, }, detail_pro_name:{ fontSize: 30, }, detail_proj_part:{ paddingTop: 5, paddingBottom: 5, paddingLeft: 15, paddingRight: 15, borderWidth: 1, borderColor:'#dbdbdb', borderRadius:10, backgroundColor: '#fff', margin: 7 }, proj_comp: { flex: 1, // height: height*0.5, marginBottom: 45, }, pro_comp:{ width, flexDirection: 'row', // justifyContent: 'flex-end' }, timeline: { width: width*0.8, }, timelineYear: { backgroundColor: "#FFC122", // paddingVertical: 5, // paddingHorizontal: 15, borderRadius: 10, height: 20, width: 50, left: -27, }, timelineYearText: { color: '#fff', backgroundColor: "transparent", fontWeight: '800', lineHeight: 20, textAlign: 'center' }, h_line: { width: width*0.2, borderRightWidth : 4, borderRightColor: '#5e5e5e', }, sectionHeader: { margin: 10, paddingBottom: 10, borderBottomWidth: 1, borderBottomColor: "black", alignItems: "center", flexDirection: "row", justifyContent: "space-between", }, sectionHeaderText: { fontWeight: "500", fontSize: 15 }, historyContainer: { margin: 10, padding: 10, backgroundColor: '#fff', shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.3, shadowRadius: 2, // boxShadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24) }, projectSelects: { flexDirection: "row", alignItems: 'center', }, projectSelectsName: { fontWeight: "800", fontSize: 15, width: 120, }, selectOptions: { flex: 1, flexDirection: 'column', justifyContent: 'flex-end', }, selectOptionsTable:{ width, backgroundColor: '#fff' }, selectOptionsTop:{ width, height: 32, alignItems: 'flex-end', paddingVertical: 7, paddingRight: 7, backgroundColor: '#fff', borderBottomWidth: 1, borderBottomColor: '#dbdbdb', borderTopWidth: 1, borderTopColor: '#dbdbdb', }, selectOptionsTopText: { fontSize: 15, // fontWeight: "700", }, gridFeedsCont: { borderColor: '#F1F3F5', padding: 10, borderWidth: 1, width: width/3, height: width/3, backgroundColor: '#fff', justifyContent: 'center', alignItems: 'center', }, gridFeedImage: { width: width/3, height: width/3, resizeMode:'contain', }, gridFeedsFlatList: { flex: 1, width: width }, gridFeedsContText: { fontSize: 15, fontWeight: '400' } })
import React, { Component } from 'react'; import injectSheet from 'react-jss'; import background from './background.jpg'; const styles = { containerStyle: { border: 'none', display: 'inline-block', position: 'relative', '&:hover $controlsStyle': { opacity: '1' } }, videoStyle: { width: '100%', height: 'auto' }, overlayStyle: { position: 'absolute', right: '0px', top: '0px', margin: '10px', padding: '5px 5px', height: '20%' }, controlsStyle: { position: 'absolute', bottom: '5px', width: '100%', textAlign: 'center', margin: 'auto', opacity: '0', transition: '.5s ease' } }; const videoStyle = { width: '500px' }; class Video extends Component { render() { const { incomingAudio, incoming, outgoing, classes, fullScreen } = this.props; return ( <div className={classes.containerStyle} ref={fullScreen}> <video className={classes.videoStyle} // style={videoStyle} autoPlay allowFullScreen ref={incoming} poster={background} /> <audio autoPlay ref={incomingAudio} /> <video className={classes.overlayStyle} muted autoPlay ref={outgoing} /> <div className={classes.controlsStyle}>{this.props.children}</div> </div> ); } } export default injectSheet(styles)(Video);
import React, { Component } from 'react' import Input from '@material-ui/core/Input' import FormControl from '@material-ui/core/FormControl' import FormHelperText from '@material-ui/core/FormHelperText' import InputLabel from '@material-ui/core/InputLabel' import Button from '@material-ui/core/Button' import Paper from '@material-ui/core/Paper' import Grid from '@material-ui/core/Grid' import { withFormik, Form,Field } from 'formik' import Typography from '@material-ui/core/Typography' import * as Yup from 'yup' import {useHistory } from "react-router-dom"; // const ButtonSubmit = () => ( // <Route render={({ history}) => ( // <Button // variant='extendedFab' // color='primary' // type='submit' // onClick={() => { history.push('/todo') }} // > // Log in // </Button> // )} /> // ) class LoginForm extends Component { render() { return ( <form onSubmit={this.props.handleSubmit}> <Grid container justify='center' alignContent='center'> <Grid item xs={6} md={4}> <Paper elevation={4} style={{ padding: '20px 15px', marginTop: '30px' }}> <Typography variant="headline" gutterBottom> Log in </Typography> <FormControl fullWidth margin='normal'> <InputLabel>User Name</InputLabel> <Field name='username' render={({ field }) => ( <Input fullWidth {...field} /> )} /> {this.props.touched.username && <FormHelperText>{this.props.errors.username}</FormHelperText>} </FormControl> <FormControl fullWidth margin='normal'> <InputLabel>Password</InputLabel> <Field name='password' render={({ field }) => ( <Input fullWidth type='password' {...field} /> )} /> {this.props.touched.password && <FormHelperText>{this.props.errors.password}</FormHelperText>} </FormControl> <FormControl fullWidth margin='normal'> {/* <ButtonSubmit> Log in</ButtonSubmit> */} <Button variant='extendedFab' color='primary' type='submit' >Log In </Button> </FormControl> </Paper> </Grid> </Grid> </form> ) } } const FormikForm = withFormik({ mapPropsToValues() { // Init form field return { username: '', password: '', } }, handleSubmit: (values,{ props }) => { setTimeout(() => { alert(JSON.stringify(values, null, 2)); props.history.push('/todo'); }, 1000); }, validationSchema: Yup.object().shape({ // Validate form field username: Yup.string() .required('Username is required') .min(5, 'Username must have min 5 characters') .max(10, 'Username have max 10 characters'), password: Yup.string() .required('Password is required') .min(8, 'Password must have min 8 characters') .max(10, 'Password have max 10 characters'), }), })(LoginForm) export default FormikForm
import * as PropTypes from 'prop-types'; import * as React from 'react'; /** * @uxpincomponent */ export default class Modal extends React.Component { render() { return ( <div class={`chi-backdrop -center ${this.props.portal ? '-portal' : ''} `} style={{width: '100%', height: '100%'}}> <div class="chi-backdrop__wrapper"> <section class={` chi-modal ${this.props.portal ? '-portal' : ''} `} role="dialog" aria-label="Modal description" aria-modal="true"> <header class="chi-modal__header"> <h2 class="chi-modal__title">Modal Title</h2> <button class="chi-button -icon -close" data-dismiss="modal" aria-label="Close"> <div class="chi-button__content"> <i class="chi-icon icon-x"></i> </div> </button> </header> <div class="chi-modal__content"> <p class="-text -m--0">Modal content</p> </div> <footer class="chi-modal__footer"> <button class="chi-button" data-dismiss="modal">Cancel</button> <button class="chi-button -primary">Save</button> </footer> </section> </div> </div> ); } } /* eslint-disable sort-keys */ Modal.propTypes = { portal: PropTypes.bool }; /* eslint-enable sort-keys */ Modal.defaultProps = { portal: true };
import React, { Component } from 'react'; import { connect } from 'react-redux'; import ModelDetails from './ModelDetails' class RenderModels extends Component { render() { return ( <div style={{ textAlign: "-webkit-center" }} > { this.props.store.map((model, indx) => { return ( <ModelDetails key={indx} model={model} /> ) }) } </div> ) } } const mapStateToProps = (store) => { return { store } } export default connect(mapStateToProps)(RenderModels);
const fs = require('fs'); function myRequire(name) { const code = fs.readFileSync(name, 'utf8'); const codeFn = new Function('exports', 'require', 'module', '__filename', '__dirname', `${code} return module.exports;`) const myModule = { exports: {}, }; return codeFn(myModule.exports, myRequire, myModule, __filename, __dirname); } const a = myRequire('./a.js'); console.log(a);
import React from 'react' import { string } from 'prop-types' import './assets/paragraph.css' export const Paragraph = ({ text }) => ( <p className="paragraph">{ text }</p> ) Paragraph.propTypes = { text: string.isRequired, }
const path = require('path') module.exports = { entry: path.join(process.cwd(), 'src/index.js'), output: { path: path.join(process.cwd(), 'output/image-webpack-loader'), filename: 'bundle.js', }, module: { rules: [ { test: /\.(gif|png|jpe?g|svg)$/i, use: [ { loader: 'file-loader', options: { name: '[name].[ext]', }, }, { loader: 'image-webpack-loader', options: { // Example options from: // https://github.com/tcoopman/image-webpack-loader/#usage mozjpeg: { progressive: true, quality: 65, }, // optipng.enabled: false will disable optipng optipng: { enabled: false, }, pngquant: { quality: '65-90', speed: 4, }, gifsicle: { interlaced: false, }, // the webp option will enable WEBP webp: { quality: 75, }, }, }, ], }, ], }, }
var adminApp = angular.module('adminApp', ['ngSanitize', 'angularFileUpload']); var uploadUrl = (window.location.protocol || 'http:') + '//localhost/building-directory/adm-upload-logo.php'; adminApp.filter('regex', function () { return function (input, field, regex, modifier) { var patt = new RegExp(regex, modifier); var out = []; for (var i = 0; i < input.length; i++) { if (patt.test(input[i][field])) out.push(input[i]); } return out; }; }); adminApp.controller('adminCtrl', ['$scope', '$sce', '$http', '$timeout', '$upload', function ($scope, $sce, $http, $timeout, $upload) { $scope.companies = []; $scope.company = {}; $scope.showLoginOrConsole = true; $scope.showWhichConsole = null; $scope.username = null; $scope.loginResultMessage = null; $scope.loginUsername = null; $scope.loginPassword = null; $scope.reset = function () { $scope.companies = []; $scope.company = {}; $scope.showLoginOrConsole = true; $scope.showWhichConsole = null; $scope.username = null; $scope.loginResultMessage = null; $scope.loginUsername = null; $scope.loginPassword = null; }; $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8"; $scope.queryCompany = function (id) { $scope.company = {}; //list-of-company $http.get('adm-query-co.php?coid=' + id). success(function (data, status, headers, config) { $scope.company = data; }). error(function (data, status, headers, config) { // log error }); }; $scope.listCompanies = function () { $scope.companies = []; //list-of-company $http.get('adm-list-co.php'). success(function (data, status, headers, config) { $scope.companies = data; }). error(function (data, status, headers, config) { // log error }); }; $scope.showComgt = function () { $scope.showWhichConsole = "comgt"; $scope.scrollTop(); }; $scope.preCreateCo = function () { $scope.createcoResultCode = null; $scope.createcoResultMessage = null; $scope.company = {}; $scope.showWhichConsole = "cocreate"; $scope.scrollTop(); $("#uploadSmallLogoFileCreate").val(null); $scope.uploadSmallLogoFileCreateResultCode = null; $scope.uploadSmallLogoFileCreateResultMessage = null; $("#uploadLargeLogoFileCreate").val(null); $scope.uploadLargeLogoFileCreateResultCode = null; $scope.uploadLargeLogoFileCreateResultMessage = null; }; $scope.createCo = function (co) { $http.post('adm-create-co.php', {sort_number: co.sort_number, name: co.name, small_logo_path: co.small_logo_path, large_logo_path: co.large_logo_path, lift_bank: co.lift_bank, phone: co.phone, email: co.email, levels: co.levels, website: co.website, information: co.information}). success(function (data, status, headers, config) { $scope.createcoResultCode = data["result_code"]; $scope.createcoResultMessage = data["result_message"]; if ($scope.createcoResultCode === '0') { } else { } $scope.listCompanies(); }). error(function (data, status, headers, config) { // log error }); }; $scope.preModifyCo = function (co) { $scope.modifycoResultCode = null; $scope.modifycoResultMessage = null; $scope.queryCompany(co.company_id); $scope.showWhichConsole = "comodify"; $scope.scrollTop(); $("#uploadSmallLogoFileModify").val(null); $scope.uploadSmallLogoFileModifyResultCode = null; $scope.uploadSmallLogoFileModifyResultMessage = null; $("#uploadLargeLogoFileModify").val(null); $scope.uploadLargeLogoFileModifyResultCode = null; $scope.uploadLargeLogoFileModifyResultMessage = null; }; $scope.modifyCo = function (co) { $http.post('adm-modify-co.php', {company_id: co.company_id, sort_number: co.sort_number, name: co.name, small_logo_path: co.small_logo_path, large_logo_path: co.large_logo_path, lift_bank: co.lift_bank, phone: co.phone, email: co.email, levels: co.levels, website: co.website, information: co.information}). success(function (data, status, headers, config) { $scope.modifycoResultCode = data["result_code"]; $scope.modifycoResultMessage = data["result_message"]; if ($scope.modifycoResultCode === '0') { } else { } $scope.listCompanies(); }). error(function (data, status, headers, config) { // log error }); }; $scope.preRemoveCo = function (co) { $scope.removecoResultCode = null; $scope.removecoResultMessage = null; $scope.queryCompany(co.company_id); $scope.showWhichConsole = "coremove"; $scope.scrollTop(); }; $scope.removeCo = function (co) { $http.post('adm-remove-co.php', {company_id: co.company_id}). success(function (data, status, headers, config) { $scope.removecoResultCode = data["result_code"]; $scope.removecoResultMessage = data["result_message"]; if ($scope.removecoResultCode === '0') { } else { } $scope.listCompanies(); }). error(function (data, status, headers, config) { // log error }); }; $scope.login = function () { $http.post('adm-login.php', {"login_username": $scope.loginUsername, "login_password": $scope.loginPassword}). success(function (data, status, headers, config) { $scope.loginResultCode = data["result_code"]; $scope.loginResultMessage = data["result_message"]; if ($scope.loginResultCode === '0') { $scope.loginUsername = null; $scope.loginPassword = null; $scope.showLoginOrConsole = false; $scope.showWhichConsole = "comgt"; $scope.username = data["username"]; $scope.oldUsername = $scope.username; $scope.newUsername = $scope.username; } else { $scope.showLoginOrConsole = true; $scope.username = null; } $scope.listCompanies(); }). error(function (data, status, headers, config) { // log error }); }; $scope.logout = function () { $http.post('adm-logout.php', {}). success(function (data, status, headers, config) { }). error(function (data, status, headers, config) { // log error }); $scope.reset(); }; $scope.saveAccount = function () { $http.post('adm-save-account.php', {"old_username": $scope.oldUsername, "old_password": $scope.oldPassword, "new_username": $scope.newUsername, "new_password": $scope.newPassword, "new_password_again": $scope.newPasswordAgain}). success(function (data, status, headers, config) { $scope.saveaccountResultCode = data["result_code"]; $scope.saveaccountResultMessage = data["result_message"]; if ($scope.saveaccountResultCode === '0') { $scope.username = $scope.newUsername; $scope.oldUsername = $scope.newUsername; $scope.oldPassword = null; $scope.newPassword = null; $scope.newPasswordAgain = null; } }); }; $scope.scrollTop = function () { $("html, body").animate({scrollTop: 0}, "slow"); }; $scope.fileReaderSupported = window.FileReader != null; $scope.uploadRightAway = true; $scope.upload = []; $scope.selectedFiles = []; $scope.onSelectSmallLogoFileCreate = function ($files) { return $scope.onFileSelect($files, 0, function (data, status, headers, config) { $scope.uploadSmallLogoFileCreateResultCode = data["result_code"]; $scope.uploadSmallLogoFileCreateResultMessage = data["result_message"]; if ($scope.uploadSmallLogoFileCreateResultCode === '0') { $scope.company.small_logo_path = data['file_uploaded']; } else { $scope.company.small_logo_path = ''; } }, function (data, status, headers, config) { $scope.company.small_logo_path = ''; $scope.uploadSmallLogoFileCreateResultMessage = data; }); }; $scope.onSelectLargeLogoFileCreate = function ($files) { return $scope.onFileSelect($files, 1, function (data, status, headers, config) { $scope.uploadLargeLogoFileCreateResultCode = data["result_code"]; $scope.uploadLargeLogoFileCreateResultMessage = data["result_message"]; if ($scope.uploadLargeLogoFileCreateResultCode === '0') { $scope.company.large_logo_path = data['file_uploaded']; } else { $scope.company.large_logo_path = ''; } }, function (data, status, headers, config) { $scope.company.large_logo_path = ''; $scope.uploadLargeLogoFileCreateResultMessage = data; }); }; $scope.onSelectSmallLogoFileModify = function ($files) { return $scope.onFileSelect($files, 2, function (data, status, headers, config) { $scope.uploadSmallLogoFileModifyResultCode = data["result_code"]; $scope.uploadSmallLogoFileModifyResultMessage = data["result_message"]; if ($scope.uploadSmallLogoFileModifyResultCode === '0') { $scope.company.small_logo_path = data['file_uploaded']; } else { $scope.company.small_logo_path = ''; } }, function (data, status, headers, config) { $scope.company.small_logo_path = ''; $scope.uploadSmallLogoFileModifyResultMessage = data; }); }; $scope.onSelectLargeLogoFileModify = function ($files) { return $scope.onFileSelect($files, 3, function (data, status, headers, config) { $scope.uploadLargeLogoFileModifyResultCode = data["result_code"]; $scope.uploadLargeLogoFileModifyResultMessage = data["result_message"]; if ($scope.uploadLargeLogoFileModifyResultCode === '0') { $scope.company.large_logo_path = data['file_uploaded']; } else { $scope.company.large_logo_path = ''; } }, function (data, status, headers, config) { $scope.company.large_logo_path = ''; $scope.uploadLargeLogoFileModifyResultMessage = data; }); }; $scope.onFileSelect = function ($files, uploadIndex, cbSuccess, cbError) { if ($scope.upload[uploadIndex] != null) { $scope.upload[uploadIndex].abort(); } $scope.upload[uploadIndex] = null; $scope.selectedFiles[uploadIndex] = null; if ($files.length > 0) { $scope.selectedFiles[uploadIndex] = $files[0]; var $file = $files[0]; if ($scope.fileReaderSupported && $file.type.indexOf('image') > -1) { var fileReader = new FileReader(); fileReader.readAsDataURL($file); } if ($scope.uploadRightAway) { $scope.start(uploadIndex, cbSuccess, cbError); } } }; $scope.start = function (uploadIndex, cbSuccess, cbError) { //$upload.upload() $scope.upload[uploadIndex] = $upload.upload({ url: uploadUrl, method: $scope.httpMethod, headers: {'file-upload-index': uploadIndex}, data: {}, file: $scope.selectedFiles[uploadIndex], fileFormDataName: 'logoFile' }).success(function (data, status, headers, config) { cbSuccess(data, status, headers, config); }).error(function (data, status, headers, config) { cbError(data, status, headers, config); }); }; }]);
import React from 'react' import { StyleSheet } from 'quantum' import { Input } from 'bypass/ui/input' import { Tooltip } from 'bypass/ui/tooltip' import { Condition } from 'bypass/ui/condition' import Legend from './Legend' import Title from '../Title' const styles = StyleSheet.create({ self: { width: '100%', }, indent: { padding: '0 10px', }, }) const Format = ({ indent, value, errors = {}, onChange, onBlur }) => ( <div className={styles({ indent })}> <div> <Title> {__i18n('CHECK.FORMAT_LABEL')} </Title> </div> <div> <Input value={value} onBlur={onBlur} onChange={onChange} placeholder={__i18n('CHECK.FORMAT_PLCHLDR')} /> <Condition match={errors.format}> <Tooltip message align='top' offset='10px 0' > {__i18n('CHECK.FORMAT_TOOLTIP')} </Tooltip> </Condition> </div> <Legend /> </div> ) export default Format
const Post = require("../models/post"); const Comment = require("../models/comment"); const Like = require('../models/like'); module.exports.create = function (req, res) { Post.create( { content: req.body.content, user: req.user._id, }, async function (err, post) { if (err) { req.flash("error", err); return; } //req.flash("success", "Post Published Successfully"); if (req.xhr) { let post_detail = await Post.findById(post._id).populate("user"); // console.log("*&*post", post); // console.log("*&*user.name",post_detail.user.name); let posts = await Post.find({}); return res.status(200).json({ data: { posts: posts, post: post, name: post_detail.user.name, //msg: req.flash("success", "Post Created Successfully"), }, message: "Post Created", }); } req.flash("success", "Post Published Successfully"); return res.redirect("back"); } ); }; module.exports.destroy = async function (req, res) { console.log("checking the req.params.id", req.params.id.user); // Post.findById(req.params.id, function (err, post) { // if (err) { // console.log("error while deleting the post"); // return; // } // if (post) { // if (post.user == req.user.id) { // post.remove(); // Comment.deleteMany({ post: req.params.id }, function (err) { // if (err) { // console.log( // "error while deleting the comments related to the post" // ); // return; // } // return res.redirect("back"); // }); // } // } else { // return res.redirect("back"); // } // }); try { let post = await Post.findById(req.params.id); if (post) { if (post.user == req.user.id) { //changes here await Like.deleteMany({likeable:post, onModel: 'Post'}) await Like.deleteMany({_id:{$in:post.comments}}) post.remove(); await Comment.deleteMany({ post: req.params.id }); if (req.xhr) { let posts = await Post.find({}); return res.status(200).json({ data: { posts: posts, post_id: req.params.id, }, message: "post deleted", }); } req.flash("success", "Post and related comments are Deleted"); return res.redirect("back"); } else { req.flash("error", "You Cannot Delete the post"); return res.redirect("back"); } } else { return res.redirect("back"); } } catch (err) { req.flash("error", err); return res.redirect("back"); } };
App.factory("currentUser", ['$rootScope', function ($rootScope) { var user = function () { var UserId = localStorage.getItem("UserId"); var username = localStorage.getItem("Username"); var token = localStorage.getItem("Token"); var TimeStamp = localStorage.getItem("TimeStamp"); var Expiration = localStorage.getItem("Expiration") var InnerClaims = []; if (localStorage.getItem("InnerClaims") != "undefined") { InnerClaims = JSON.parse(localStorage.getItem("InnerClaims")); } return { Username: username, Token: token, InnerClaims: InnerClaims, UserId: UserId, TimeStamp: TimeStamp, Expiration: Expiration } } var IsAuthenticated = function () { return localStorage.getItem("Token"); } var isInRole = function (roles) { if (IsAuthenticated()) { if (Array.isArray(roles) == false) { var isAdmin = $.inArray(roles, user().InnerClaims.Roles); if (isAdmin != -1) { return true; } } else { return _Util.Intersect(roles, user().InnerClaims.Roles) } } return false; } var login = function(loginObject) { var reAuthObject = JSON.parse(loginObject); localStorage.setItem("TimeStamp", reAuthObject.TimeStamp); localStorage.setItem("UserId", reAuthObject.UserId); localStorage.setItem("Username", reAuthObject.Username); localStorage.setItem("Token", reAuthObject.Token); localStorage.setItem("Expiration", reAuthObject.Expiration); localStorage.setItem("InnerClaims", JSON.stringify(reAuthObject.InnerClaims)); } var logout = function () { localStorage.removeItem("Username"); localStorage.removeItem("Token"); localStorage.removeItem("InnerClaims"); localStorage.removeItem("UserId"); localStorage.removeItem("TimeStamp"); localStorage.removeItem("Expiration"); $rootScope.$emit("LoggedOut"); $rootScope.LoggedIn = false; } return { user: user, login: login, logout: logout, IsAuthenticated: IsAuthenticated, isInRole: isInRole } }]);
import React from 'react'; import { useLightbox } from "simple-react-lightbox" import LightBox from '../LightBox' import { useForm } from 'react-hook-form'; import styled from 'styled-components' const FormStyled = styled.div` .form{ width:300px; padding:16px; border-radius:10px; margin:auto; background-color:#ccc; label{ width:72px; font-weight:bold; display:inline-block; } input{ width:180px; padding:3px 10px; border:1px solid #f6f6f6; border-radius:3px; background-color:#f6f6f6; margin:8px 0; display:inline-block; } .error{ color: red; text-align: right; font-size: .7em; } .submit{ width:100%; padding:8px 16px; margin-top:32px; border:1px solid #000; border-radius:5px; display:block; color:#fff; background-color:#000; &:hover{ cursor:pointer; background-color:navy; } } } .SRLWrapper{ display:none; } ` export default function SForm() { const { register, handleSubmit, errors, reset } = useForm(); const { openLightbox, closeLightbox } = useLightbox(); const onSubmit = (data) => { console.log(data) openLightbox(0); reset(); setTimeout(() => closeLightbox(), 5000) }; return ( <FormStyled> <form className="form" onSubmit={handleSubmit(onSubmit)}> <div> <label htmlFor="Name">Name</label> <input type="text" placeholder="Name" name="Name" ref={register({ required: true, minLength: 2, maxLength: 80 })} /> {errors.Name && errors.Name.type === "required" && <p className="error">This is required</p>} {errors.Name && errors.Name.type === "minLength" && <p className="error">This is field required min length to 2</p>} {errors.Name && errors.Name.type === "maxLength" && <p className="error">This is field required max length to 80</p>} </div> <div> <label htmlFor="Email">Email</label> <input type="text" placeholder="Email" name="Email" ref={register({ required: true, pattern: /^\S+@\S+$/i })} /> {errors.Email && errors.Email.type === "required" && <p className="error">This is required</p>} {errors.Email && errors.Email.type === "pattern" && <p className="error">Invalid email </p>} </div> <div> <label htmlFor="Phone">Phone</label> <input type="tel" placeholder="Phone" name="Phone" ref={register({ required: true, minLength: 6, maxLength: 15 })} /> {errors.Phone && errors.Phone.type === "required" && <p className="error">This is required</p>} {errors.Phone && errors.Phone.type === "minLength" && <p className="error">This is field required min length to 6</p>} {errors.Phone && errors.Phone.type === "maxLength" && <p className="error">This is field required max length to 15</p>} </div> <div> <label htmlFor="Age">Age</label> <input type="number" placeholder="+18" name="Age" ref={register({ required: true, max: 100, min: 18 })} /> {errors.Age && errors.Age.type === "required" && <p className="error">This is required</p>} {errors.Age && errors.Age.type === "min" && <p className="error">You must be over than 18 years old</p>} {errors.Age && errors.Age.type === "max" && <p className="error">You must be less than 100 years old</p>} </div> <input className="submit" type="submit" value="Send" /> </form> <div className="SRLWrapper"> <LightBox></LightBox> </div> </FormStyled> ) }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.defaults = { serverName: null, mainPort: 4237, buildPort: 4238, password: "", sessionSecret: null, maxRecentBuilds: 10 }; // Loaded by start.ts exports.server = null; function setServerConfig(serverConfig) { exports.server = serverConfig; } exports.setServerConfig = setServerConfig;
const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin') var pathToPhaser = path.join(__dirname, "/node_modules/phaser/"); var phaser = path.join(pathToPhaser, "dist/phaser.js"); const filesRule = { test: /\.(png|jpe?g|gif|svg)$/i, use: [ { loader: 'file-loader', }, ], } const tsRule = { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/ } const phaserRule = { test: /phaser\.js$/, loader: "expose-loader?Phaser" } module.exports = { entry: { app: './src/index.ts', vendors: ['phaser'] }, devtool: 'inline-source-map', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js' }, module: { rules: [ filesRule, tsRule, phaserRule ], }, resolve: { extensions: [".wasm", ".mjs", ".js", ".jsx", ".ts", ".tsx", ".json"], alias: { "@": path.resolve(__dirname, 'src'), phaser: phaser }, modules: [ path.resolve(__dirname, 'node_modules') ] }, devServer: { contentBase: './dist', hot: true, }, plugins: [ new HtmlWebpackPlugin({ title: 'Flappy Bird ANN Genetic Algorithm' }), new webpack.DefinePlugin({ 'typeof CANVAS_RENDERER': JSON.stringify(true), 'typeof WEBGL_RENDERER': JSON.stringify(true) }), ], optimization: { splitChunks: { cacheGroups: { commons: { test: /[\\/]node_modules[\\/]/, name: 'vendors', chunks: 'all' } } } } };
OC.L10N.register( "core", { "Please select a file." : "Bonvolu elekti dosieron.", "File is too big" : "Dosiero tro grandas.", "Unknown filetype" : "Ne konatas dosiertipo", "Invalid image" : "Ne validas bildo", "Updated database" : "Ĝisdatiĝis datumbazo", "Updated \"%s\" to %s" : "Ĝisdatiĝis “%s” al %s", "%s (incompatible)" : "%s (nekongrua)", "Following apps have been disabled: %s" : "Jenaj aplikaĵoj malkapablas: %s", "Sunday" : "dimanĉo", "Monday" : "lundo", "Tuesday" : "mardo", "Wednesday" : "merkredo", "Thursday" : "ĵaŭdo", "Friday" : "vendredo", "Saturday" : "sabato", "Sun." : "dim.", "Mon." : "lun.", "Tue." : "mar.", "Wed." : "mer.", "Thu." : "ĵaŭ.", "Fri." : "ven.", "Sat." : "sab.", "Su" : "Di", "Mo" : "Lu", "Tu" : "Ma", "We" : "Me", "Th" : "Ĵa", "Fr" : "Ve", "Sa" : "Sa", "January" : "Januaro", "February" : "Februaro", "March" : "Marto", "April" : "Aprilo", "May" : "Majo", "June" : "Junio", "July" : "Julio", "August" : "Aŭgusto", "September" : "Septembro", "October" : "Oktobro", "November" : "Novembro", "December" : "Decembro", "Jan." : "Jan.", "Feb." : "Feb.", "Mar." : "Mar.", "Apr." : "Apr.", "May." : "Maj.", "Jun." : "Jun.", "Jul." : "Jul.", "Aug." : "Aŭg.", "Sep." : "Sep.", "Oct." : "Okt.", "Nov." : "Nov.", "Dec." : "Dec.", "Settings" : "Agordo", "Saving..." : "Konservante...", "seconds ago" : "sekundoj antaŭe", "I know what I'm doing" : "mi scias, kion mi faras", "No" : "Ne", "Yes" : "Jes", "Choose" : "Elekti", "Ok" : "Akcepti", "Error loading message template: {error}" : "Eraris ŝargo de mesaĝa ŝablono: {eraro}", "read-only" : "nurlega", "_{count} file conflict_::_{count} file conflicts_" : ["{count} dosierkonflikto","{count} dosierkonfliktoj"], "One file conflict" : "Unu dosierkonflikto", "New Files" : "Novaj dosieroj", "Already existing files" : "Jam ekzistantaj dosieroj", "Which files do you want to keep?" : "Kiujn dosierojn vi volas konservi?", "If you select both versions, the copied file will have a number added to its name." : "Se vi elektos ambaŭ eldonojn, la kopiota dosiero havos numeron aldonitan al sia nomo.", "Cancel" : "Nuligi", "Continue" : "Daŭri", "(all selected)" : "(ĉiuj elektitas)", "({count} selected)" : "({count} elektitas)", "Error loading file exists template" : "Eraris ŝargo de ŝablono pri ekzistanta dosiero", "Very weak password" : "Tre malforta pasvorto", "Weak password" : "Malforta pasvorto", "So-so password" : "Mezaĉa pasvorto", "Good password" : "Bona pasvorto", "Strong password" : "Forta pasvorto", "Error occurred while checking server setup" : "Eraris kontrolo de servila agordo", "Shared" : "Kunhavata", "Shared with {recipients}" : "Kunhavata kun {recipients}", "Error" : "Eraro", "Error while sharing" : "Eraro dum kunhavigo", "Error while unsharing" : "Eraro dum malkunhavigo", "The public link will expire no later than {days} days after it is created" : "La publika ligilo senvalidiĝos ne pli malfrue ol {days} tagojn post ĝi kreiĝos", "Expiration" : "Eksvalidiĝo", "Link" : "Ligilo", "Edit" : "Redakti", "Remove" : "Forigi", "Copy to clipboard" : "Kopii al tondejo", "Name" : "Nomo", "Filename" : "Dosiernomo", "Password" : "Pasvorto", "Share" : "Kunhavigi", "Save" : "Konservi", "Email link to person" : "Retpoŝti la ligilon al ulo", "Shared with you and the group {group} by {owner}" : "Kunhavigita kun vi kaj la grupo {group} de {owner}", "Shared with you by {owner}" : "Kunhavigita kun vi de {owner}", "group" : "grupo", "notify by email" : "avizi per retpoŝto", "Unshare" : "Malkunhavigi", "can share" : "kunhavebla", "can edit" : "povas redakti", "create" : "krei", "change" : "ŝanĝi", "delete" : "forigi", "access control" : "alirkontrolo", "Could not unshare" : "Ne malkunhaveblas", "Share details could not be loaded for this item." : "Kunhavaj detaloj ne ŝargeblis por ĉi tiu ero.", "No users or groups found for {search}" : "Neniu uzanto aŭ grupo troviĝis por {search}", "User" : "Uzanto", "Group" : "Grupo", "Share with people on other ownClouds using the syntax username@example.com/owncloud" : "Kunhaviki kun homoj en aliaj ownCloud-oj uzante la sintakson uzantonomo@ekzemplo.com/owncloud", "Error removing share" : "Eraris forigo de kunhavigo", "Non-existing tag #{tag}" : "Ne ekzistas etikedo #{tag}", "invisible" : "nevidebla", "({scope})" : "({scope})", "Delete" : "Forigi", "Rename" : "Alinomigi", "The object type is not specified." : "Ne indikiĝis tipo de la objekto.", "Enter new" : "Enigu novan", "Add" : "Aldoni", "Edit tags" : "Redakti etikedojn", "Error loading dialog template: {error}" : "Eraris ŝargo de dialoga ŝablono: {error}", "No tags selected for deletion." : "Neniu etikedo elektitas por forigo.", "unknown text" : "nekonata teksto", "Hello world!" : "Saluton, mondo!", "Hello {name}, the weather is {weather}" : "Saluton, {name}, la vetero estas {weather}", "Hello {name}" : "Saluton, {name}", "_download %n file_::_download %n files_" : ["elŝuti %n dosieron","elŝuti %n dosierojn"], "An error occurred." : "Eraro okazis.", "Please reload the page." : "Bonvolu reŝargi la paĝon.", "The update was unsuccessful. Please report this issue to the <a href=\"https://github.com/owncloud/core/issues\" target=\"_blank\">ownCloud community</a>." : "La ĝisdatigo estis malsukcese. Bonvolu raporti tiun problemon al la <a href=\"https://github.com/owncloud/core/issues\" target=\"_blank\">ownClouda komunumo</a>.", "The update was successful. There were warnings." : "La ĝisdatigo sukcesis. Estis avertoj.", "The update was successful. Redirecting you to ownCloud now." : "La ĝisdatigo estis sukcesa. Alidirektante nun al ownCloud.", "Searching other places" : "Serĉante en aliaj lokoj", "No search results in other folders" : "Neniu serĉorezulto en aliaj dosierujoj", "Personal" : "Persona", "Users" : "Uzantoj", "Apps" : "Aplikaĵoj", "Admin" : "Administranto", "Help" : "Helpo", "Access forbidden" : "Aliro estas malpermesata", "File not found" : "Dosiero ne troviĝis", "The share will expire on %s." : "La kunhavo senvalidiĝos je %s.", "Technical details" : "Teĥnikaj detaloj", "Remote Address: %s" : "Fora adreso: %s", "Request ID: %s" : "Peta identigilo: %s", "Type: %s" : "Tipo: %s", "Code: %s" : "Kodo: %s", "Message: %s" : "Mesaĝo: %s", "File: %s" : "Dosiero: %s", "Line: %s" : "Linio: %s", "Create an <strong>admin account</strong>" : "Krei <strong>administran konton</strong>", "Username" : "Uzantonomo", "Storage & database" : "Memoro kaj datumbazo", "Data folder" : "Datuma dosierujo", "Configure the database" : "Agordi la datumbazon", "Only %s is available." : "Nur %s disponeblas.", "Database user" : "Datumbaza uzanto", "Database password" : "Datumbaza pasvorto", "Database name" : "Datumbaza nomo", "Database tablespace" : "Datumbaza tabelospaco", "Database host" : "Datumbaza gastigo", "SQLite will be used as database." : "SQLite uziĝos kiel datumbazo.", "For larger installations we recommend to choose a different database backend." : "Por pli grandaj instaloj ni rekomendas elekti malsaman datumbazomotoron.", "Finish setup" : "Fini la instalon", "Finishing …" : "Finante...", "Need help?" : "Ĉu necesas helpo?", "See the documentation" : "Vidi la dokumentaron", "Log out" : "Elsaluti", "Search" : "Serĉi", "Please contact your administrator." : "Bonvolu kontakti vian administranton.", "Please try again or contact your administrator." : "Bonvolu provi ree aŭ kontakti vian administranton.", "Login" : "Ensaluti", "Wrong password." : "Malĝusta pasvorto.", "Stay logged in" : "Daŭri ensalutinta", "Alternative Logins" : "Alternativaj ensalutoj", "Use the following link to reset your password: {link}" : "Uzu la jenan ligilon por restarigi vian pasvorton: {link}", "New password" : "Nova pasvorto", "New Password" : "Nova pasvorto", "Reset password" : "Rekomenci la pasvorton", "Thank you for your patience." : "Dankon pro via pacienco.", "%s will be updated to version %s" : "%s ĝisdatiĝos al eldono %s", "These apps will be updated:" : "Ĉi tiuj aplikaĵoj ĝisdatiĝos:", "Start update" : "Ekĝisdatigi" }, "nplurals=2; plural=(n != 1);");
export const Tips = (tipsObj) => { return ` <div class="Tips"> <p>TIPS</p> <p class="tip__topic">${tipsObj.topic} = ${tipsObj.text}</p> <p>TEMPERATURE OF WATER</p> <p class="temperature">${tipsObj.temp}</p> </div> ` }
const WIDTH = 120, HEIGHT = 130; const img = new Image(); img.src="Images/imgbin_sprite-2d-computer-graphics-unity-animation-png.png"; img.onload = () => img.loaded = true; const canvas = document.getElementById('frame'); const ctx = canvas.getContext('2d'); function render(){ if(!img.loaded) return; draw(); } var move = 4; let i = 0; function draw(){ const x = WIDTH * i++; const y = HEIGHT * move; ctx.clearRect(0, 0, WIDTH, HEIGHT); ctx.drawImage(img, x, y, WIDTH, HEIGHT, 0, 0, WIDTH, HEIGHT); if(i >= 10) i=0; } var KEY_MAP = { ArrowUp: 6, ArrowDown: 4, ArrowLeft: 5, ArrowRight: 7 } document.addEventListener('keydown', function(e){ const code = e.code; if(!KEY_MAP[code]) return; move = KEY_MAP[code]; }) setInterval(render, 100);
function solution(dartResult) { let answer = [] let stgData = dartResult.split(''); for (let i = 1; i <= 3; i++) { let stgPoint; let stgPrice; if (stgData[1] === '0') { if (stgData[2] == '*' || stgData[2] == '#') { stgPoint = stgData.splice(0, 3); stgPrice = stgData.splice(0, 1)[0]; } else { stgPoint = stgData.splice(0, 3) } } else { if (stgData[2] == '*' || stgData[2] == '#') { stgPoint = stgData.splice(0, 2); stgPrice = stgData.splice(0, 1)[0]; } else { stgPoint = stgData.splice(0, 2); } } let area = stgPoint.splice(stgPoint.length - 1, 1)[0]; let point = stgPoint.join(''); if (area == 'S') { point = Math.pow(point, 1); } else if (area == 'D') { point = Math.pow(point, 2); } else if (area == 'T') { point = Math.pow(point, 3); } if (stgPrice !== undefined) { if (stgPrice === '*') { point = point * 2; if (answer.length > 0) { answer[answer.length - 1] = answer[answer.length - 1] * 2; } } else if (stgPrice === '#') { point = point * -1; } } answer.push(point); } return answer.reduce((p, v) => p + v, 0); }
import React from 'react'; import ReactDOM from 'react-dom'; import {BrowserRouter, Route, Link} from 'react-router-dom'; // var Provider = require('react-redux'); import {Provider} from 'react-redux'; import counterStore from './Store'; // import {Counter} from './Components/Counter' import CounterContainer from './Containers/CounterContainer'; import 'bootstrap/dist/css/bootstrap.min.css'; // Provider provides the store // hydrate is used for server side rendering ReactDOM.hydrate( <Provider store={counterStore}> <BrowserRouter> <React.Fragment> <Route path='/' exact component={CounterContainer}></Route> </React.Fragment> </BrowserRouter> </Provider>, document.getElementById('app') )
import Vue from 'vue' import Vuex from 'vuex' import AuthModule from './modules/auth' import NavModule from './modules/navigation' import UsersModule from './modules/users' Vue.use(Vuex) export default new Vuex.Store({ modules: { auth: AuthModule, navigation: NavModule, users: UsersModule } })
import React, { Component} from 'react'; import { StyleSheet, Text, View, Platform, TouchableHighlight, WebView} from 'react-native'; import { StackNavigator } from 'react-navigation'; export default class VehiclesScreen extends React.Component { static navigationOptions = { title: 'Vehicles Screen', }; render() { const { navigate } = this.props.navigation; return ( <View style={styles.container} > <Text> Vehicles Screen </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', justifyContent: 'center', }, checklistView: { flex: 1, backgroundColor: 'salmon', justifyContent: 'center', alignItems: 'center', borderStyle: 'solid', borderRightWidth: 1, }, checklistText: { color: 'white', fontSize: 25, alignItems: 'center', padding: 26, }, vehiclesView: { flex: 1, backgroundColor: 'blanchedalmond', justifyContent: 'center', alignItems: 'center', borderStyle: 'solid', }, vehiclesText: { color: 'white', fontSize: 25, padding: 26, }, movingHelpView: { flex: 1, backgroundColor: 'indianred', justifyContent: 'space-around', alignItems: 'center', borderStyle: 'solid', borderTopWidth: 1, }, movingHelpText: { color: 'white', fontSize: 25, padding: 26, }, storageView: { flex: 1, backgroundColor: 'pink', justifyContent: 'center', alignItems: 'center', borderStyle: 'solid', borderTopWidth: 1, }, storageText: { color: 'white', fontSize: 25, padding: 26, }, });
import React, { useState } from 'react'; import styled from 'styled-components'; import * as Buttons from '../ui/Buttons'; import * as Form from '../ui/Form'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faPlus, faMinus } from '@fortawesome/free-solid-svg-icons'; import { useMutation } from '@apollo/react-hooks' import { ADD_MEAL } from '../mutations'; const NewMealModalContainer = styled.div` display: flex; flex-direction: column; align-items: center; position: absolute; height: 100vh; width: 100vw; background: white; padding: 20px; box-shadow: 12px 12px 12px lightgray; overflow: scroll; ` const IngredientContainer = styled.div` display: flex; align-items: center; ` const Icons = styled(FontAwesomeIcon)` margin: 10px; ` const ButtonContainer = styled.div` display: flex; justify-content: space-evenly; ` export default function NewMealModal(props) { const [ingredients, setIngredients] = useState(['', '', '']); const [mealName, setMealName] = useState(''); const [description, setDescription] = useState(''); const [directions, setDirections] = useState(''); const [addMeal, { data, error, loading }] = useMutation(ADD_MEAL); const handleOnChange = updateFx => e => { updateFx(e.target.value); }; const handleNameUpdate = handleOnChange(setMealName); const handleDescriptionupdate = handleOnChange(setDescription); const handleDirectionsUpdate = handleOnChange(setDirections); const onSubmit = async e => { e.preventDefault(); const newMealPayload = { meal: { name: mealName, description, directions, ingredients } }; addMeal({ variables: { input: newMealPayload } }); props.setNewModalOpen(false); } const updateSelectedIngredient = i => e => { const tempIngredients = [...ingredients]; tempIngredients[i] = e.target.value; setIngredients(tempIngredients); } const deleteCurrentIngredient = i => e => { const tempIngredients = [...ingredients]; setIngredients(tempIngredients.filter((x, i2) => i2 === i ? false : true)); } const addIngredientAfter = i => () => { const tempIngredients = [...ingredients]; tempIngredients.splice(i + 1, 0, '') setIngredients(tempIngredients); } if (data) { console.log(data); } else if (error) { console.log('this is the error!', error); } else if (loading) { console.log('loading'); } return ( <NewMealModalContainer> <Form.container onSubmit={onSubmit}> <h2>Add New Meal</h2> <Form.label> Meal Name* <Form.input onChange={handleNameUpdate} /> </Form.label> <Form.label> Description <Form.input onChange={handleDescriptionupdate} /> </Form.label> <Form.label> Ingredients* {ingredients.map((ing, ind) => <IngredientContainer key={ind}> <Form.input onChange={updateSelectedIngredient(ind)} type="text" value={ing} /> <Icons onClick={deleteCurrentIngredient(ind)} icon={faMinus} /> <Icons onClick={addIngredientAfter(ind)} icon={faPlus} /> </IngredientContainer> )} </Form.label> <Form.label> Directions <Form.textarea onChange={handleDirectionsUpdate} /> </Form.label> <ButtonContainer> <Buttons.submit type="submit" value="Save" /> <Buttons.secondary>Cancel</Buttons.secondary> </ButtonContainer> </Form.container> </NewMealModalContainer> ) }
var fs = require('fs'); var google = require('googleapis'); var TOKEN_STORE = './.gdrive'; module.exports = function(api, ver, scopes, Wrapper) { return function(info, callback) { var self = this; if (self._client) { callback(self._client); } else { var oauth2Client = new google.auth.OAuth2(info.clientId, info.clientSecret, info.redirectUrl); acquireToken(oauth2Client, scopes, function() { var client = api({ version: ver, auth: oauth2Client }); callback(self._client = new Wrapper(client)); }); } }; }; function acquireToken(oauth2Client, scopes, callback) { var TOKENS = null; try { TOKENS = JSON.parse(fs.readFileSync(TOKEN_STORE, 'utf8')); } catch (x) { console.warn(x); } if (TOKENS) { oauth2Client.setCredentials({ access_token: TOKENS.access_token, refresh_token: TOKENS.refresh_token, expiry_date: TOKENS.expiry_date }); // bug https://github.com/google/google-api-nodejs-client/issues/260 var expiryDate = oauth2Client.credentials.expiry_date; var isTokenExpired = expiryDate ? expiryDate <= (new Date()).getTime() : false; if (isTokenExpired) { oauth2Client.refreshAccessToken(function(err, tokens) { console.log(err || tokens); if (!err) { fs.writeFileSync(TOKEN_STORE, JSON.stringify(tokens)); callback(); } }); } else { callback(); } return; } var url = oauth2Client.generateAuthUrl({ access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token) scope: scopes // If you only need one scope you can pass it as string }); console.log(url); var readline = require('readline'); var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question("code? ", function(code) { oauth2Client.getToken(code, function(err, tokens) { // Now tokens contains an access_token and an optional refresh_token. Save them. console.log(err || tokens); if(!err) { oauth2Client.setCredentials(tokens); fs.writeFileSync(TOKEN_STORE, JSON.stringify(tokens)); callback(); } }); rl.close(); }); }
import * as React from 'react'; import {View, Text, TouchableOpacity, StyleSheet, TextInput, FlatList, Image} from 'react-native'; import {Header, Icon} from 'react-native-elements'; import {SafeAreaProvider} from 'react-native-safe-area-context'; import firebase from 'firebase'; import db from '../config'; import { ScrollView } from 'react-native-gesture-handler'; var msgs =[]; export default class CommunityScreen extends React.Component{ constructor(){ super(); this.state={ userId: firebase.auth().currentUser.email, theMessage: "", allMessages: [] } } updateMsg=()=>{ db.collection("messages").add({ userId: this.state.userId, message: this.state.theMessage, timeStamp: firebase.firestore.FieldValue.serverTimestamp() }) } // refMsgs=async()=>{ // db.collection("messages") // .onSnapshot((snapshot)=>{ // var allMessages = snapshot.docs.map((doc)=>doc.data()) // this.setState({ // allMessages: allMessages // }) // }) // } refMsgs=async()=>{ var msgRef = db.collection("messages"); var msgList; msgRef.onSnapshot((snapshot)=>{ snapshot.docs.map((doc)=>{ msgList = doc.data(); msgs.push(msgList) this.setState({ allMessages: msgs }) }) console.log(msgs.length) }) msgs.sort(function(msg1, msg2){ return msg1.timeStamp - msg2.timeStamp }) console.log(msgs.length.toString()) console.log(this.state.allMessages) } componentDidMount(){ this.refMsgs(); console.log(this.state.userId); } keyExtractor = (item, index)=>index.toString(); renderItem=({item})=>{ return( <View> <Text> {item.message} </Text> </View> ) } render(){ return( <SafeAreaProvider> <View style={styles.container}> {/* //the Header */} <Header centerComponent={{text: "Community Chat", style:{fontSize: 25, fontFamily: "Bahnschrift", color: "#68D693"}}} leftComponent={ <Icon name="bars" type="font-awesome" color="#FFFFFF" onPress={ ()=>{ this.props.navigation.toggleDrawer() } } /> } /> <View> <View style={{borderBottomWidth: 2}}> <FlatList data={this.state.allMessages} renderItem={this.renderItem} keyExtractor={this.keyExtractor} /> </View> </View> {/* // text input to type the message */} <View> <TextInput placeholder="Express your feelings(We will keep you anonymous)" style={styles.textInputStyle} multiline={true} onChangeText={ (text)=>{ this.setState({ theMessage: text })}} /> </View> {/* // the send button */} <View> <TouchableOpacity onPress={this.updateMsg} style={styles.sendButton} > <Image source={require("../assets/paper-plane (1).png")} style={{width: 45, height: 45}} /> <Text style={{fontFamily: "Bahnschrift", fontSize: 17, opacity: 0.65}}> Send </Text> </TouchableOpacity> </View> </View> </SafeAreaProvider> ) } } const styles= StyleSheet.create({ container: { flex: 1, backgroundColor: "#D9D9D9" }, textInputStyle: { marginTop: 550, width: 600, height: 60, borderWidth: 2, borderRadius: 5, alignItems: "center", justifyContent: "center", fontSize: 20, fontFamily: "Bahnschrift", marginLeft: 450, shadowColor: "#000", shadowOffset: { width: 8, height: 4 }, shadowRadius: 10.32, shadowOpacity: 0.30, elevation: 16 }, userMsg: { color: "#000" }, nonUserMsg: { color: "#92D428" }, sendButton: { marginLeft: 1050, marginTop: -60, // backgroundColor: '#000', width: 100, height: 50, justifyContent: "center", textAlign: "center", alignItems: "center" }, fontStyle: { fontFamily: "Bahnschrift", fontSize: 30, fontWeight: "bold", color: "#025920", marginTop: -300, marginLeft: 670, opacity: 0.50 } })
const chalk = require('chalk'); colorLogger = (level, color, msg) => { if ( console[level] && chalk[color] ) { return console[level](chalk[color](msg)); } else if ( !console[level] ) { throw new Error('Not a valid log-level...!!!'); } else { return console[level](msg); } } module.exports = colorLogger;
/** * Copyright 2016 Google Inc. * * 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. */ goog.provide('audioCat.state.command.RemoveTrackCommand'); goog.require('audioCat.state.command.Command'); /** * Removes a track. * @param {!audioCat.state.Track} track The track to remove. * @param {!audioCat.utility.IdGenerator} idGenerator Generates IDs unique * throughout the application. * @constructor * @extends {audioCat.state.command.Command} */ audioCat.state.command.RemoveTrackCommand = function( track, idGenerator) { goog.base(this, idGenerator, true); /** * The track to remove. * @private {!audioCat.state.Track} */ this.track_ = track; /** * The index of the removed track. If null, the index had not been computed * yet. This means that the command had not been performed yet. * @private {?number} */ this.trackIndex_ = null; /** * The solo-ed state of the track upon removal. This is important to note * since removing a solo-ed track means that the other tracks won't play. We * hence unsolo the track when it's removed. And then, if the track is ever * added back, we solo it. * @private {boolean} */ this.soloedStateUponRemoval_ = track.getSoloedState(); }; goog.inherits(audioCat.state.command.RemoveTrackCommand, audioCat.state.command.Command); /** @override */ audioCat.state.command.RemoveTrackCommand.prototype.perform = function(project, trackManager) { var track = this.track_; if (this.soloedStateUponRemoval_) { // If we remove a solo-ed track, all the other tracks will be silent. // That's ... definitely not what we want. track.setSoloedState(false); } this.trackIndex_ = trackManager.removeTrackGivenObject(track); }; /** @override */ audioCat.state.command.RemoveTrackCommand.prototype.undo = function(project, trackManager) { // The perform method of this function must have been executed before undo can // be executed. var track = this.track_; trackManager.addTrack(track, /** @type {number} */ (this.trackIndex_)); track.setSoloedState(this.soloedStateUponRemoval_); }; /** @override */ audioCat.state.command.RemoveTrackCommand.prototype.getSummary = function( forward) { return (forward ? 'Remov' : 'Un-remov') + 'ed track ' + this.track_.getName() + '.'; };
// TODO: Not fully functioning, needs additional features var db = require("../models"); module.exports = function(app) { app.get("/api/weeks", function(req, res) { db.Week.findAll({ }).then(function(dbWeek) { res.json(dbWeek); }); }); app.get("/api/weeks/:id", function(req, res) { db.Week.findOne({ where: { id: req.params.id } }).then(function(dbWeek) { res.json(dbWeek); }); }); app.post("/api/weeks", function(req, res) { db.Week.create(req.body).then(function(dbWeek) { res.json(dbWeek); }); }); app.delete("/api/weeks/:id", function(req, res) { db.Week.destroy({ where: { id: req.params.id } }).then(function(dbWeek) { res.json(dbWeek); }); }); };
//https://www.npmjs.com/package/google-map-react //https://www.npmjs.com/package/react-geocode import React, { Component } from 'react' import GoogleMapReact from 'google-map-react' import Geocode from 'react-geocode' import mapStyles from './mapStyles' import ButtonRound from '../buttonRound/buttonRound' // pin const AnyReactComponent = ({ text }) => <img src={text} /> Geocode.setApiKey('AIzaSyCl_dsFh-W92B-JNqfjKfo0ZHUSJ7roDNo') class SimpleMap extends Component { constructor(props) { super(props) this.state = { cords: { lat: 36.16, lng: -115.13, }, } this.mapWraper = React.createRef() this.setWidth = this.setWidth.bind(this) this.getLatLng = this.getLatLng.bind(this) } static defaultProps = { center: { lat: 36.16, lng: -115.13, }, zoom: 12, createMapOptions: function (maps) { return { panControl: false, mapTypeControl: false, scrollwheel: false, styles: this.customStyles.mapStyles, } }, } getLatLng(address) { Geocode.fromAddress(address.replace('<p>', '').replace('</p>', '')).then( response => { const { lat, lng } = response.results[0].geometry.location return this.setState({ cords: { lat, lng } }) }, error => { console.error(error) } ) } setWidth() { this.setState({ wraperWidth: this.mapWraper.current.offsetWidth }) } componentDidMount() { this.getLatLng(this.props.address) this.setWidth() } render() { return ( // Important! Always set the container height explicitly <div ref={this.mapWraper}> <div style={{ height: `${this.state.wraperWidth}px`, width: '100%', padding: '10px 0', }} > <GoogleMapReact bootstrapURLKeys={{ key: 'AIzaSyCl_dsFh-W92B-JNqfjKfo0ZHUSJ7roDNo', }} defaultCenter={this.state.cords} defaultZoom={this.props.zoom} options={this.props.createMapOptions} customStyles={mapStyles} customCords={this.state.cords} > <AnyReactComponent lat={this.state.cords.lat} lng={this.state.cords.lng} text={ 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBkPSJNMTIgMGMtNC4xOTggMC04IDMuNDAzLTggNy42MDIgMCA2LjI0MyA2LjM3NyA2LjkwMyA4IDE2LjM5OCAxLjYyMy05LjQ5NSA4LTEwLjE1NSA4LTE2LjM5OCAwLTQuMTk5LTMuODAxLTcuNjAyLTgtNy42MDJ6bTAgMTFjLTEuNjU3IDAtMy0xLjM0My0zLTNzMS4zNDItMyAzLTMgMyAxLjM0MyAzIDMtMS4zNDMgMy0zIDN6Ii8+PC9zdmc+' } /> </GoogleMapReact> </div> <div style={{ marginTop: '15px', }} > <ButtonRound innerText="Get Directions" pos="start" action={`https://www.google.com/maps/dir//${this.props.address .replace('<p>', '') .replace('</p>', '') .split(' ') .join('+')}/data=`} type="link" /> </div> </div> ) } } export default SimpleMap
function callback(first, second, call) { console.log(first, second, call); call(first, second); } function sum(first, second) { console.log(`Total sum ${first+second}`); } callback(1, 2, sum);
// // Generic Ajax Resource Provider // import $ from 'jquery'; import {extend} from 'underscore'; class ResourceProvider { constructor(settings) { this.settings = settings; return this; } defaultSettings() { return { dataType: 'json', type: 'GET', contentType: 'application/json' }; } send() { return $.ajax(extend(this.defaultSettings(), this.settings)); } } export default ResourceProvider;
// Instance of a map intended for drawing to a div. // // * `parent` (required DOM element) // Can also be an ID of a DOM element // * `provider` (required MM.MapProvider or URL template) // * `location` (required MM.Location) // Location for map to show // * `zoom` (required number) MM.mapByCenterZoom = function(parent, layerish, location, zoom) { var layer = MM.coerceLayer(layerish), map = new MM.Map(parent, layer, false); map.setCenterZoom(location, zoom).draw(); return map; }; // Instance of a map intended for drawing to a div. // // * `parent` (required DOM element) // Can also be an ID of a DOM element // * `provider` (required MM.MapProvider or URL template) // * `locationA` (required MM.Location) // Location of one map corner // * `locationB` (required MM.Location) // Location of other map corner MM.mapByExtent = function(parent, layerish, locationA, locationB) { var layer = MM.coerceLayer(layerish), map = new MM.Map(parent, layer, false); map.setExtent([locationA, locationB]).draw(); return map; };
import { createViewport } from 'bypass/app/utils' import { load } from '../actions' export default function getRoutes({ dispatch }) { return [{ path: 'sells', onEnter() { dispatch(load()) }, getComponent(location, callback) { System.import('../containers/Sells').then(Sells => callback(null, createViewport(Sells))) }, }] }
import ReactDOM from "react-dom"; import {attrFlag, componentNamespace} from "./identifiers"; /** * TODO: 通过解析树获取而非dom关系 * node === self * parent === self ce. * parent.parent === parent root. * parent.parent.parent === parent ce. * 获取父节点 * @param context * @return {*} */ export function getParent(context) { const node = ReactDOM.findDOMNode(context); const targetContainer = node.parentNode.parentNode; const id = targetContainer.parentNode.getAttribute(attrFlag); return { customElement: targetContainer.parentNode, container: targetContainer, id: id, } } /** * 是否存在某种自定义标签的子代元素 * @param context * @param tagName * @return {boolean} */ export function hasChildOfTag(context, tagName) { const node = ReactDOM.findDOMNode(context); const children = node.children; for (const child of children) { if (child.nodeName === `${componentNamespace}-${tagName}`.toUpperCase()) { return true; } } return false; } /** * 父元素是否为某种ce * @param context * @param tagName * @return {boolean} */ export function parentIsTag(context, tagName) { const parent = getParent(context); if (parent.customElement) { console.log(parent.customElement.nodeName, tagName); return parent.customElement.nodeName === `${componentNamespace}-${tagName}`.toUpperCase(); } return false; }
import {fetchCollectionsStart, fetchCollectionsSuccess, fetchCollectionsFail} from './shop.actions'; import {fireStore} from '../../config/firebase.config'; import {convertCollectionsSnapshotToMap} from '../../shared/services/Firebase.service'; export const fetchCollectionsStartAsync = () => { return dispatch => { const collectionRef = fireStore.collection('shop'); dispatch(fetchCollectionsStart()); collectionRef.get() .then((shapshot)=>{ const collectionsMap = convertCollectionsSnapshotToMap(shapshot); dispatch(fetchCollectionsSuccess(collectionsMap)); }) .catch((error) => { dispatch(fetchCollectionsFail(error)) }) } }
const mongoose = require('mongoose'); const request = require('supertest-as-promised'); const httpStatus = require('http-status'); const chai = require('chai'); // eslint-disable-line import/newline-after-import const expect = chai.expect; const app = require('../../index'); chai.config.includeStack = true; /** * root level hooks */ after((done) => { // required because https://github.com/Automattic/mongoose/issues/1251#issuecomment-65793092 mongoose.models = {}; mongoose.modelSchemas = {}; mongoose.connection.close(); done(); }); describe('## Document APIs', () => { let document = { name: 'markdown sample', contents: '# Markdown Title' + '## Markdown Subtitle' }; describe('# POST /api/documents', () => { it('should create a new document', (done) => { request(app) .post('/api/documents') .send(document) .expect(httpStatus.OK) .then((res) => { expect(res.body.name).to.equal(document.name); expect(res.body.contents).to.equal(document.contents); document = res.body; done(); }) .catch(done); }); }); describe('# GET /api/documents/:docId', () => { it('should get document details', (done) => { request(app) .get(`/api/documents/${document._id}`) .expect(httpStatus.OK) .then((res) => { expect(res.body.name).to.equal(document.name); expect(res.body.contents).to.equal(document.contents); done(); }) .catch(done); }); it('should report error with message - Not found, when document does not exist', (done) => { request(app) .get('/api/documents/56c787ccc67fc16ccc1a5e92') .expect(httpStatus.NOT_FOUND) .then((res) => { expect(res.body.message).to.equal('Not Found'); done(); }) .catch(done); }); }); describe('# PUT /api/documents/:docId', () => { it('should update document details', (done) => { document.name = 'KK'; request(app) .put(`/api/documents/${document._id}`) .send(document) .expect(httpStatus.OK) .then((res) => { expect(res.body.name).to.equal('KK'); expect(res.body.contents).to.equal(document.contents); done(); }) .catch(done); }); }); describe('# GET /api/documents/', () => { it('should get all documents', (done) => { request(app) .get('/api/documents') .expect(httpStatus.OK) .then((res) => { expect(res.body).to.be.an('array'); done(); }) .catch(done); }); it('should get all documents (with limit and skip)', (done) => { request(app) .get('/api/documents') .query({ limit: 10, skip: 1 }) .expect(httpStatus.OK) .then((res) => { expect(res.body).to.be.an('array'); done(); }) .catch(done); }); }); describe('# DELETE /api/documents/', () => { it('should delete document', (done) => { request(app) .delete(`/api/documents/${document._id}`) .expect(httpStatus.OK) .then((res) => { expect(res.body.name).to.equal('KK'); expect(res.body.contents).to.equal(document.contents); done(); }) .catch(done); }); }); });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class P2BodyEditor { constructor(tbody, config, projectClient, editConfig) { this.fields = {}; this.tbody = tbody; this.projectClient = projectClient; this.editConfig = editConfig; const massRow = SupClient.table.appendRow(this.tbody, SupClient.i18n.t("componentEditors:P2Body.mass")); this.fields["mass"] = SupClient.table.appendNumberField(massRow.valueCell, config.mass, { min: 0 }); this.fields["mass"].addEventListener("change", (event) => { this.editConfig("setProperty", "mass", parseFloat(event.target.value)); }); const fixedRotationRow = SupClient.table.appendRow(this.tbody, SupClient.i18n.t("componentEditors:P2Body.fixedRotation")); this.fields["fixedRotation"] = SupClient.table.appendBooleanField(fixedRotationRow.valueCell, config.fixedRotation); this.fields["fixedRotation"].addEventListener("click", (event) => { this.editConfig("setProperty", "fixedRotation", event.target.checked); }); const offsetRow = SupClient.table.appendRow(this.tbody, SupClient.i18n.t("componentEditors:P2Body.offset")); const offsetFields = SupClient.table.appendNumberFields(offsetRow.valueCell, [config.offsetX, config.offsetY]); this.fields["offsetX"] = offsetFields[0]; this.fields["offsetX"].addEventListener("change", (event) => { this.editConfig("setProperty", "offsetX", parseFloat(event.target.value)); }); this.fields["offsetY"] = offsetFields[1]; this.fields["offsetY"].addEventListener("change", (event) => { this.editConfig("setProperty", "offsetY", parseFloat(event.target.value)); }); const shapeRow = SupClient.table.appendRow(this.tbody, SupClient.i18n.t("componentEditors:P2Body.shape")); const shapeOptions = { "box": SupClient.i18n.t("componentEditors:P2Body.shapeOptions.box"), "circle": SupClient.i18n.t("componentEditors:P2Body.shapeOptions.circle") }; this.fields["shape"] = SupClient.table.appendSelectBox(shapeRow.valueCell, shapeOptions, config.shape); this.fields["shape"].addEventListener("change", (event) => { this.editConfig("setProperty", "shape", event.target.value); }); // Box this.sizeRow = SupClient.table.appendRow(this.tbody, SupClient.i18n.t("componentEditors:P2Body.size")); const sizeFields = SupClient.table.appendNumberFields(this.sizeRow.valueCell, [config.width, config.height], { min: 0 }); this.fields["width"] = sizeFields[0]; this.fields["width"].addEventListener("change", (event) => { this.editConfig("setProperty", "width", parseFloat(event.target.value)); }); this.fields["height"] = sizeFields[1]; this.fields["height"].addEventListener("change", (event) => { this.editConfig("setProperty", "height", parseFloat(event.target.value)); }); this.angleRow = SupClient.table.appendRow(this.tbody, SupClient.i18n.t("componentEditors:P2Body.angle")); this.fields["angle"] = SupClient.table.appendNumberField(this.angleRow.valueCell, config.angle, { min: -360, max: 360 }); this.fields["angle"].addEventListener("change", (event) => { this.editConfig("setProperty", "angle", parseFloat(event.target.value)); }); // Circle this.radiusRow = SupClient.table.appendRow(this.tbody, SupClient.i18n.t("componentEditors:P2Body.radius")); this.fields["radius"] = SupClient.table.appendNumberField(this.radiusRow.valueCell, config.radius, { min: 0 }); this.fields["radius"].addEventListener("change", (event) => { this.editConfig("setProperty", "radius", parseFloat(event.target.value)); }); this.updateShapeInput(config.shape); } updateShapeInput(shape) { switch (shape) { case "box": { this.sizeRow.row.hidden = false; this.radiusRow.row.hidden = true; this.angleRow.row.hidden = false; } break; case "circle": { this.sizeRow.row.hidden = true; this.radiusRow.row.hidden = false; this.angleRow.row.hidden = true; } break; } } destroy() { } config_setProperty(path, value) { if (path === "fixedRotation") this.fields["fixedRotation"].checked = value; else this.fields[path].value = value; if (path === "shape") this.updateShapeInput(value); } } exports.default = P2BodyEditor;
import React, { PropTypes } from 'react'; import { Link } from 'react-router-dom'; import '../style/__header.scss'; import {capitalize} from '../utils/strings'; const HeaderUI = ({pages, handleNavigate, currentPage}) => ( <header className="header"> <img src='./static/images/logo.png' width="48px" height="48px" /> <div className="menu"> {pages.map((page, i) => (<MenuItem page={page} currentPage={page.path === currentPage} handleNavigate={handleNavigate}/>))} </div> </header> ); HeaderUI.propTypes = { pages: PropTypes.array.isRequired, currentPage: PropTypes.string.isRequired, handleNavigate: PropTypes.func.isRequired }; export default HeaderUI; const MenuItem = ({page, handleNavigate, currentPage}) => { const classItem = (currentPage)?'menu-item active':'menu-item'; return ( <div className={classItem}> <Link to={page.path} onClick={() => handleNavigate(page.path)}>{capitalize(page.name)}</Link> </div> );}; MenuItem.propTypes = { page: PropTypes.object.isRequired };
/* / Centralizaded file for handle all fetch of the app. / It are using environments variable for the endpoint to / support multiple environments like dev, test, prod, sandsbox.. */ const getUsers = (limit=100) => { return fetch(`${process.env.REACT_APP_API_USERS}?inc=email,name&results=${limit}`) .then(async (res) => { let data = await res.json(); return data; }) .catch(async (err) => { console.error(`Fail in get the forecast weather.`, err) throw(err); }); } export { getUsers }
// Функция findMatches() принимает произвольное количество аргументов. // Первым аргументом всегда будет массив чисел, а остальные аргументы // будут просто числами. // Дополни код функции так, чтобы она возвращала новый массив matches, // в котором будут только те аргументы, начиная со второго, которые есть // в массиве первого аргумента. // Например, findMatches([1, 2, 3, 4, 5], 1, 8, 2, 7) должна вернуть // массив[1, 2], потому что только они есть в массиве первого аргумента. // Пиши код ниже этой строки function findMatches(array, ...args) { const matches = []; // Не изменяй эту строку for (const arr of array) { for (const arg of args) { if (arr === arg) { matches.push(arr); } } } // Пиши код выше этой строки return matches; } console.log(findMatches([1, 2, 3, 4, 5], 1, 8, 2, 7)); console.log(findMatches([4, 89, 17, 36, 2], 8, 17, 89, 27, 2)); console.log(findMatches([10, 24, 41, 6, 9, 19], 24, 11, 9, 23, 41)); console.log(findMatches([63, 11, 8, 29], 4, 7, 16));
$(document).ready(function () { var load = $('#load').hide(); $('body').removeClass('bg-primary'); $("#body").removeClass("d-none"); function getHour() { var data = new Date(); var horas = data.getHours(); var minutos = data.getMinutes(); var segundos = data.getSeconds(); if (horas < 10) { horas = '0' + horas; } if (minutos < 10) { minutos = '0' + minutos; } if (segundos < 10) { segundos = '0' + segundos; } var setdate = horas + " / " + minutos + " / " + segundos; document.getElementById('hours').innerHTML = setdate; } $("#btn-send").click(function (e) { e.preventDefault(); var btnSend = $("#btn-send"); btnSend.val("Sending..."); btnSend.removeClass("btn-outline-info").addClass("btn-outline-warning"); $.ajax({ url: 'http://localhost:8000/Get-Cars.PHP/add.php', type: 'post', data: { 'name': $("#name").val(), 'models': $("#models").val(), 'date1': $("#date1").val(), "date2": $("#date2").val(), "cost":$("#money").val() } }).done(function (DATE) { alert(DATE); btnSend.removeClass("btn-outline-warning").addClass("btn-outline-info").val("Send"); $("#name").val(''); $("#models").val(''); $("#date1").val(''); $("#date2").val(''); $("#money").val(''); }); }); $("#btn-search").click(function (event) { event.preventDefault(); var search = $("#searchInput").val(); var searchBTN = $("#btn-search"); var table = $("#table"); table.animate({ 'margin-left': '-900px' }); searchBTN.html("Searching...").removeClass("btn-outline-success").addClass("btn-outline-danger").click(false); $.ajax( { url: 'http://localhost:8000/Get-Cars.PHP/Search.php', type: 'post', data: { 'search': search } }).done(function (DATE) { var table = $("#table"); table.css({ 'margin-left': '900px' }); table.html(DATE).animate({ 'margin-left': '0' }, 1000); searchBTN.removeClass("btn-outline-danger").addClass("btn-outline-success").html("SEARCH"); // alert(DATE); }); }); $('.telefone').mask('(00) 0 0000-0000'); $('.dinheiro').mask('#.##0,00', {reverse: true}); $('.estado').mask('AA'); setInterval(getHour, 1000); }); var divdestiny = $('#divDestiny'); var setdestiny = $('#setDestiny'); function Destiny(id) { divdestiny.css({ 'top': '36%', 'left': '24%' }).removeClass("d-none"); var namedb = $('#nameDB' + id).html(); var modeldb = $("#modelDB" + id).html(); var date1db = $("#date1DB" + id).html(); var date2db = $('#date2DB' + id).html(); var costdb=$("#costDB"+id).html(); divdestiny.animate({ 'opacity': 1 }, 1500); setdestiny.html("<span class='btn btn-outline-primary' style='position: relative;left: 93%;cursor:pointer;' onclick=exit()>X</span><tr><td>Name: <span class=text-primary>" + namedb + "</span> </td></tr><tr><td>model: <span class=text-primary>" + modeldb + "</span> </td></tr> <tr><td>Sdate: <span class=text-primary>" + date1db + ' </td></tr> <tr><td>Edate: <span class=text-primary>' + date2db + "</span> </td></tr> <tr><td>Cost of veicule: <span class=text-primary>"+costdb+'</span>'); } function exit() { divdestiny.addClass('d-none'); }
require('dotenv').config(); const express = require('express'); const http = require('http'); const bodyParser = require('body-parser'); const graphQlHTTP = require('express-graphql'); const mongoose = require('mongoose'); const schema = require('./graphQL/schema'); const rootValue = require('./graphQL/resolvers'); const VerifyAuthentication = require('./middleware/verifyAuthentication'); const Uploaders = require('./uploaders/uploaderRoutes'); const APIRoutes = require('./APIRoutes/index'); const dev = process.env.NODE_ENV !== 'production'; const PORT = process.env.PORT || 8080; const mongoEnv = dev ? 'development' : 'production'; mongoose.connect(`mongodb+srv://${ process.env.MONGO_USER }:${ process.env.MONGO_PASSWORD }@coursecamp-qxarr.mongodb.net/${ mongoEnv }?retryWrites=true`, { useNewUrlParser: true }); const app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use((req, res, next) => { let allowedOrigins = ['http://localhost:5000', 'http://localhost:3000', 'https://teamcoursecamp.com', 'https://www.teamcoursecamp.com']; let origin = req.headers.origin; if (allowedOrigins.indexOf(origin) > -1){ res.setHeader('Access-Control-Allow-Origin', origin); } res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, currentsection'); res.header('Access-Control-Allow-Methods', 'DELETE, PUT, POST, PATCH, GET'); if (req.method === 'OPTIONS') { return res.status(200).json({}); } next(); }); app.use(VerifyAuthentication); app.use('/uploaders', Uploaders); app.use('/api-routes', APIRoutes); app.use('/graphql', graphQlHTTP({ schema, rootValue, graphiql: dev })); app.use(function(req, res) { res.status(200).json({ error: 'The requested url was not found' }) }); app.listen(PORT, () => console.log('---------- Course Camp API Running --------'));
/* Preloader Component */ // Package Imports // import { TimelineMax, Linear, Power1 } from "gsap"; // Export // export default function componentPreloader() { // Animation Timeline // const frameTop = document.querySelectorAll(".frame__top--border"); const logo = document.querySelector(".logo-link"); const preloaderLogo = document.querySelector(".preloader__logo"); const preloaderOverlay = document.querySelector(".preloader__overlay"); const preloader = document.querySelector(".preloader"); let tlPreloaderIn = new TimelineMax(); tlPreloaderIn.pause(); tlPreloaderIn.timeScale(1); tlPreloaderIn .to(preloaderOverlay, 0.6, {scaleX: 0, transformOrigin:"right", ease: Linear.easeNone }, 0) .to(preloaderLogo, 0.4, { y: 150, autoAlpha:0, ease: Power1.easeOut }, 0.5) .to(preloader, 0.6, { height: 0, ease: Linear.easeNone }, 0.9) .to(frameTop, 0.5, {width: "45%", ease: Power1.easeOut }, 1.4) .to(logo, 0.4, { marginLeft: 50, marginRight: 50, ease: Power1.easeOut }, 1.6) .fromTo(logo, 0.6, { autoAlpha:0, y: -30, ease: Power1.easeOut }, { autoAlpha:1, y: 0, display: "block", ease: Power1.easeOut }, 1.6); // Execute Animation // function preloaderAnimateIn() { tlPreloaderIn.restart(); tlPreloaderIn.play(); } window.addEventListener("load", preloaderAnimateIn); }
import * as React from 'react'; import { Text } from 'react-native' import Route from './Route.js'; export default function App() { return ( <Route/> ); }
const { canModifyQueue, LOCALE } = require("../util/svenbotUtil"); const i18n = require("i18n"); i18n.setLocale(LOCALE); module.exports = { name: "volume", aliases: ["v"], description: i18n.__("volume.description"), execute(message, args) { const queue = message.client.queue.get(message.guild.id); if (!queue) return message.reply(i18n.__("volume.errorNotQueue")).catch(console.error); if (!canModifyQueue(message.member)) return message.reply(i18n.__("volume.errorNotChannel")).catch(console.error); if (!args[0]) return message.reply(i18n.__mf("volume.currentVolume", { volume: queue.volume })).catch(console.error); if (isNaN(args[0])) return message.reply(i18n.__("volume.errorNotNumber")).catch(console.error); if (Number(args[0]) > 100 || Number(args[0]) < 0) return message.reply(i18n.__("volume.errorNotValid")).catch(console.error); queue.volume = args[0]; queue.connection.dispatcher.setVolumeLogarithmic(args[0] / 100); return queue.textChannel.send(i18n.__mf("volume.result", { arg: args[0] })).catch(console.error); } };
import React from 'react'; import { Button } from 'antd'; import './App.css'; import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom'; import RecipeGallery from './Pages/RecipeGallery'; import NewRecipe from './Pages/NewRecipe'; const App = () => ( <div className="App"> <Router> <Button type="primary"> <Link to="/new_recipe">New Recipe</Link> </Button> <Button type="primary"> <Link to="/recipe_gallery">gallery</Link> </Button> <Switch> <Route path="/recipe_gallery"> <RecipeGallery /> </Route> <Route path="/new_recipe"> <NewRecipe /> </Route> </Switch> </Router> </div> ); export default App;
"use strict"; let React = require("react-native"); let { AppRegistry, Component, StyleSheet, Text, View } = React; let Main = require("./App/containers/Root") class BrokenMixtape extends Component{ render() { return ( <Main /> ); } }; AppRegistry.registerComponent("BrokenMixtape", () => BrokenMixtape);
import { Person, Author } from './domain'; import { DATABASE_NAME, MONGO_URL } from './constants'; import connection from './storage'; console.log(` Welcome to the ODM example. This application will be loading data from a mongodb database (make sure you have it running locally) and printing it in the console. The enviromment should look like this: MONGO_URL: ${MONGO_URL} DATABASE_NAME: ${DATABASE_NAME} `); async function main() { const people = await Person.objects.find().toArray(); const authors = await Author.objects.find().toArray(); console.log(`* ${people.length} person(s) were found`); if (people.length) console.log(JSON.stringify(people, null, 2)); console.log(`* ${authors.length} author(s) were found`); if (authors.length) console.log(JSON.stringify(authors, null, 2)); console.log(` Please consider adding more data to your database, as follow, then run this script again: $ mongo ${MONGO_URL} db.${Person.collection}.insert({ firstName: 'John', lastName: 'Doe' }) db.${Author.collection}.insert({ firstName: 'George', lastName: 'Orwell' }) `); } connection .then(main) .then(() => { process.exit() }) .catch(e => setTimeout(() => { throw e; }));
export * from './containers/products'; export * from './store/products';
// src/app.js // alert('hello world');
var Firebase = require('firebase'); var fbRef = new Firebase('https://boiling-fire-3340.firebaseio.com/alexa/'); addItem('bake a pie'); addItem('clean the oven'); function readItems(){ fbRef.on("value", function(snapshot) { console.log("value: ",snapshot.val()); fb.off(); process.exit(0); }, function (e) { console.log("The read failed: " + e.code); fb.off(); process.exit(1); }); } function readItems2(){ fbRef.once("value", function(snapshot) { // The callback function will get called twice, once for "fred" and once for "barney" snapshot.forEach(function(childSnapshot) { // key will be "fred" the first time and "barney" the second time var key = childSnapshot.key(); console.log('key: ',key); // childData will be the actual contents of the child var childData = childSnapshot.val(); console.log('childData: ', childData); }); }); } function addItem(todo){ console.log('addItem: ', todo); fbRef.push().set({ 'item': todo}, function(e){ if(e) { console.log('The write failed: ', e.code); process.exit(1); } else { console.log(fbRef.key()); process.exit(0); } }); }
var HTTPError = require('http-errors') var parser = require('body-parser') var express = require('express') var logger = require('./logger') // ---------- // // Middleware // // ---------- // var app = express() // Parse JSON requests app.use(parser.json()) // Wrap jsonp responses in json API format and log app.use((req, res, next) => { var orig_jsonp = res.jsonp res.jsonp = function(obj){ if(obj instanceof Error){ res.status(obj.statusCode || 500) var body = {errors: [{status: res.statusCode, title: obj.message}]} }else{ var body = {data: obj} } orig_jsonp.call(this, body) logger.info({request: req.body, response: body}, `${res.statusCode} ${req.method} ${req.url}`) } next() }); // ------ // // Routes // // ------ // // Fetch and apply routes to app app = require('../routes')(app); // -------------- // // Error Handlers // // -------------- // // 404 app.use((req, res, next) => { res.jsonp(HTTPError.NotFound()) }) // 500 app.use((err, req, res, next) => { logger.error({error: err}, err.stack); switch(err.type || err.name){ case 'SequelizeValidationError': case 'SequelizeExclusionConstraintError': case 'SequelizeUniqueConstraintError': res.jsonp(HTTPError.BadRequest(err.message)); break; case 'SequelizeForeignKeyConstraintError': res.jsonp(HTTPError.NotFound()); break; default: res.jsonp(HTTPError.InternalServerError()); } }) module.exports = app
import axios from 'axios'; import apiKeys from '../apiKeys.json'; const baseUrl = apiKeys.firebaseKeys.databaseURL; const getEventFoodByEventId = (eventId) => new Promise((resolve, reject) => { axios.get(`${baseUrl}/eventFood.json?orderBy="eventId"&equalTo="${eventId}"`) .then((response) => { const eventFood = response.data; const food = []; Object.keys(eventFood).forEach((fbId) => { eventFood[fbId].id = fbId; food.push(eventFood[fbId]); }); resolve(food); }) .catch((err) => reject(err)); }); export default { getEventFoodByEventId };
const fs = require("fs"); const { alea } = require("seedrandom"); const events = JSON.parse(fs.readFileSync("./data/idle_events.json")); const listsize = 8; const index = []; for (let i = 0; i < events.length; i++) { index.push(i) }; module.exports = function(name) { // shuffle events let arng = new alea(name); let list = Array.from(index); for (let i = list.length; i > 0; i--) { let r = Math.floor(arng()*i); let _ = list[i-1]; list[i-1] = list[r]; list[r] = _; } // Take the first 8 events, each of them has 1/4 chance of happening. for (let i = 0; i < 8; i++) { if (Math.random() < 0.25) { return events[list[i]].replace("$NAME",name); } } return events[0].replace("$NAME",name); }
import { ADD_GAMER, REMOVE_GAMER } from '../constants' export const addGamer = (gamer) => ({ type: ADD_GAMER, payload: gamer }) export const removeGamer = (gamer) => ({ type: REMOVE_GAMER, payload: gamer })
const language = require('@google-cloud/language'); const path = require('path'); const enigmaConfig = require('./assets/js/config/enigma-config'); const enigma = require('enigma.js'); const enigmaMixin = require('./assets/js/halyard_dist/halyard-enigma-mixin.js'); const Halyard = require('./assets/js/halyard_dist/halyard.js'); const excelToJson = require('convert-excel-to-json'); enigmaConfig.mixins = enigmaMixin; const APP_NAME = `__newApp`; const FILE_PATH = path.join(__dirname, './assets/data/qsDays.xlsx'); const xlsFileStructure = { sourceFile: FILE_PATH, header:{rows: 1}, columnToKey: { 'A': '{{A1}}', 'B': '{{B1}}', 'C': '{{C1}}', 'D': '{{D1}}', } } let texts = excelToJson(xlsFileStructure); let fieldNames = Object.keys(texts.Feedback[0]) let textObj = texts.Feedback.map(text => ({textId: text[fieldNames[0]], textText: text[fieldNames[3]]})); async function SentimentAnalysis(textObj) { const client = new language.LanguageServiceClient(); let analysedTxt = textObj.map(async text => { let document = { content: text.textText, type: 'PLAIN_TEXT' }; let result = await client.analyzeSentiment({document: document}) let sentiment = result[0].documentSentiment; let sentences = result[0].sentences.map(sentence => { return { textId: text.textId, phrase: sentence.text.content, magnitude: sentence.sentiment.magnitude, sentiment: sentence.sentiment.magnitude, } }) return {textId: text.textId, magnitude: sentiment.magnitude, sentiment: sentiment.score, sentences: sentences} }) return await Promise.all(analysedTxt) }; SentimentAnalysis(textObj).then(async analysedTextJson => { // Create Qlik Sense APP const individualSentencesJson = analysedTextJson.map(analysedText => analysedText.sentences.map(sentence => sentence)[0]) const halyard = new Halyard() // create Master data table const feedbackTable = new Halyard.Table(FILE_PATH, { name:'userFeedback', fields: [ { src: fieldNames[0], name: '%FeedbackId'}, { src: fieldNames[1], name: '%Datum'}, { src: fieldNames[2], name: '%KundenId'}, { src: fieldNames[3], name: 'FeedbackText'} ], headerRowNr: 0 }) const textEval = new Halyard.Table(analysedTextJson, {name:'Text-Eval', fields: [{src:'textId', name:'%FeedbackId'},{src: 'magnitude', name:'magnitude_text'}, {src:'sentiment', name:'sentiment_text'}, {expr: 'if(sentiment < 0.4 and sentiment > -0.4 and magnitude < 1.5 , \'Neutral\', \'Emotional\' )', name: 'sentiment_Kat' }]}); const sentenceEval = new Halyard.Table(individualSentencesJson, {name:'Sentence-Eval', fields: [{src:'textId', name:'%FeedbackId'},{src: 'phrase'}, {src: 'magnitude', name:'magnitude_sentence'}, {src:'sentiment', name: 'sentiment_sentence'}]}); halyard.addTable(feedbackTable); halyard.addTable(textEval); halyard.addTable(sentenceEval); // open qlik sense const qix = await enigma.create(enigmaConfig).open() try { let result = await qix.reloadAppUsingHalyard(APP_NAME, halyard, true) console.log(`App created and reloaded - ${APP_NAME}.qvf`); process.exit(1); } catch(err) { console.log('could not create app') process.exit(1); } })
let clicked = false; function blurred() { let blur1 = document.querySelector("main"); let blur2 = document.querySelector("footer"); if (clicked) { blur1.setAttribute('class', null); blur2.setAttribute('class', null); } else { blur1.setAttribute('class', 'blur'); blur2.setAttribute('class', 'blur'); } clicked = !clicked; }
import Jsonp from 'js/jsonp.js'; import {ERR_OK,recommendParams} from './config.js' export const getSinger = () => { const url ='https://c.y.qq.com/v8/fcg-bin/v8.fcg'; const data = Object.assign({},recommendParams,{ g_tk: 1928093487, channel: 'singer', page: 'list', key: 'all_all_all', pagesize: 100, pagenum: 1, hostUin: 0, needNewCode: 0, platform: 'yqq' }); return Jsonp(url,data,{ param: 'jsonpCallback' }).then(res => { if(res.code === ERR_OK){ return res.data } throw new Error('没有获取到数据!'); }).catch(err => { if(err) { console.log('歌手列表获取错误' + err); } }) }
const courses = [{ _id: '58e62ec470528b2f6c86b9ba', status: 'draft', packageSequenceId: 'info:fedora/learning:5227', hoursOfVideo: 60, hoursPerWeek: 15, weeksDuration: 7, homeDescription: 'A full stack program focussing on the JavaScript stack. The core curriculum focuses on building complete Reactive apps. You build front-ends using AngularJS or React along with Bootstrap, HTMl5/CSS3 and Material or Semantic UI. You wire these front-end apps to microservice based backends built using technologies like NodeJS, Express, Seneca. You do a lot of async programming with message based models and NodeJS streams. You also work on databses like MongoDB, Cassandra and Neo4J. In addition, and perhaps more importantly, you learn what it takes to work in a truly automated project environment with test first thinking and small and distributed project teams. This is an extremely experiential course - your demonstration of competency is fundamentally in the code you write and the tech that you develop. Expect to build complete non-trivial applications as part of small, virtual project groups.', image: 'http://learn.stackroute.in/uploads/image/webdev2.png', pedagogyId: 'info:fedora/learning:240', description: '"A full stack program focussing on the JavaScript stack. The core curriculum focuses on building complete Reactive apps. You build front-ends using AngularJS or React along with Bootstrap, HTMl5/CSS3 and Material or Semantic UI. You wire these front-end apps to microservice based backends built using technologies like NodeJS, Express, Seneca. You do a lot of async programming with message based models and NodeJS streams. You also work on databses like MongoDB, Cassandra and Neo4J. In addition, and perhaps more importantly, you learn what it takes to work in a truly automated project environment with test first thinking and small and distributed project teams. This is an extremely experiential course - your demonstration of competency is fundamentally in the code you write and the tech that you develop. Expect to build complete non-trivial applications as part of small, virtual project groups."', name: 'Full Stack ME(A/R)N Programmer', nodeId: 'MEAN101W:1', identifier: 'info:fedora/learning:4693', community: { userId: 'course4693', coachGroup: { groupId: 'tsppt5wuTXmXBF3cpTwwdw', groupMembers: [] }, facultyGroup: { groupId: 'i7vw3W5OSq-t8gCvQbWyYg', groupMembers: [ 'saching', 'satishs' ] } }, is_deleted: false, outcomeSequence: [], packageSequence: [], packages: [], tutors: [{ name: 'Jayaprasad K', identifier: 'info:fedora/learning:780', description: '"JP loves programming. He is a problem solver, who has a simple and elegant answer to any programming problem that you may face. He has been part of multiple technology teams and startups, where he had an opportunity to create products from scratch, and go through high paced learning environments. He loves working with engineers and help them solve problems. "', image: 'http://learn.stackroute.in/uploads/image/JP.png', _id: '58e62ec670528b2f6c86bb22' }], order: 1, introduction: { videoMimeType: 'video/youtube', videoURL: 'https://youtu.be/PigAmso52kI', text: '"A full stack program focussing on the JavaScript stack. The core curriculum focuses on building complete Reactive apps. You build front-ends using AngularJS or React along with Bootstrap, HTMl5/CSS3 and Material or Semantic UI. You wire these front-end apps to microservice based backends built using technologies like NodeJS, Express, Seneca. You do a lot of async programming with message based models and NodeJS streams. You also work on databses like MongoDB, Cassandra and Neo4J. In addition, and perhaps more importantly, you learn what it takes to work in a truly automated project environment with test first thinking and small and distributed project teams. This is an extremely experiential course - your demonstration of competency is fundamentally in the code you write and the tech that you develop. Expect to build complete non-trivial applications as part of small, virtual project groups."' }, faculty: { image: 'http://learn.stackroute.in/uploads/image/sachin.png', description: '"Sachin is an experienced MEAN practitioner"', identifier: 'info:fedora/learning:6978', name: 'Sachin Grover' }, inboxEmailId: 'production_courses@app.ilimi.in' } ]; module.exports = courses;
/* A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. */ function findSolution(){ for (a=1;a<1000;a++){ for(b=2;b<1000;b++){ var c = Math.sqrt(a*a + b*b); if(a+b+c === 1000){ console.log("The solution is: " + a, b, c); console.log("The product, abc, is: " + a*b*c); return; } } } } findSolution();
import React, { PropTypes } from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import BuildTriggerLabel from './shared/BuildTriggerLabel.jsx'; import UsersForBuild from './shared/UsersForBuild.jsx'; import CancelBuildButton from '../shared/branch-build/CancelBuildButton.jsx'; import CommitsSummary from './shared/CommitsSummary.jsx'; import BranchBuildProgress from './shared/BranchBuildProgress.jsx'; import { isComplete } from '../../constants/BranchBuildStates'; const BranchBuildHeader = ({branchBuild, completedModuleBuildCount, totalNonSkippedModuleBuildCount, onCancelBuild}) => { const buildNumber = branchBuild.get('buildNumber'); const buildTrigger = branchBuild.get('buildTrigger'); const commitInfo = branchBuild.get('commitInfo'); const buildId = branchBuild.get('id'); const branchBuildState = branchBuild.get('state'); const isActiveBuild = !isComplete(branchBuildState); return ( <div className="branch-build-header"> <div className="branch-build-header__build-number"> {isActiveBuild && <span className="branch-build-header__active-build-icon" />} #{buildNumber} </div> <div className="branch-build-header__build-summary"> <BranchBuildProgress completedModuleBuildCount={completedModuleBuildCount} totalNonSkippedModuleBuildCount={totalNonSkippedModuleBuildCount} branchBuildState={branchBuildState} /> <div className="branch-build-header__build-summary-info"> <span className="branch-build-header__build-trigger-label-wrapper"> <BuildTriggerLabel buildTrigger={buildTrigger} /> </span> <span className="branch-build-header__users-for-build-wrapper"> <UsersForBuild branchBuild={branchBuild} /> </span> <span className="branch-build-header__commits-wrapper"> <CommitsSummary commitInfo={commitInfo} buildId={buildId} /> </span> {isActiveBuild && ( <span className="branch-build-header__module-builds-completed visible-lg-block"> Building … {completedModuleBuildCount}/{totalNonSkippedModuleBuildCount} modules complete </span> )} <span className="branch-build-header__action-items"> <CancelBuildButton onCancel={onCancelBuild} build={branchBuild.toJS()} btnStyle="link" btnClassName="cancel-build-button-link" /> </span> </div> </div> </div> ); }; BranchBuildHeader.propTypes = { branchBuild: ImmutablePropTypes.mapContains({ buildNumber: PropTypes.number.isRequired, buildTrigger: ImmutablePropTypes.map.isRequired, commitInfo: ImmutablePropTypes.map.isRequired }), completedModuleBuildCount: PropTypes.number.isRequired, totalNonSkippedModuleBuildCount: PropTypes.number.isRequired, onCancelBuild: PropTypes.func.isRequired }; export default BranchBuildHeader;
import 'leaflet/dist/leaflet.css'; import * as L from 'leaflet'; import shadow from '../assets/imgs/points/shadow.png'; // init map export function urlStyleMap(token) { const [user, mapId] = ['phqueiroz', 'cjraxr4jr2rok2ss1is4n357l']; return `https://api.mapbox.com/styles/v1/${user}/${mapId}/tiles/256/{z}/{x}/{y}?access_token=${token}`; } export function createMap({ mapId, latLong, zoomMap = 13, minZoom = 4, maxZoom = 20, }) { if (!mapId) return new Error('mapId argument is undefined'); const myMap = L.map(mapId).setView(latLong, zoomMap); L.tileLayer(urlStyleMap(LEAFLET_TOKEN), { minZoom, maxZoom, id: 'mapbox.streets', accessToken: LEAFLET_TOKEN, }).addTo(myMap); return myMap; } // marker icon init and functions export function DefaultIcon({ shadowUrl, iconSize, shadowSize, iconAnchor, shadowAnchor, popupAnchor, }) { return L.Icon.extend({ options: { shadowUrl, iconSize, shadowSize, iconAnchor, shadowAnchor, popupAnchor, }, }); } export function createIncludeIcon(iconUrl) { const IncludeDefaultIcon = DefaultIcon({ shadowUrl: shadow, iconSize: [40, 60], shadowSize: [60, 64], iconAnchor: [20, 59], shadowAnchor: [13, 62], popupAnchor: [-3, -76], }); return new IncludeDefaultIcon({ iconUrl }); } // think about this after // function createBusIcon(iconUrl) { // } export function createMarker(latLong, icon) { return L.marker(latLong, { icon }); } // export function createMarkers(arr) { // return arr.map(elem => L.marker(elem.latLong, { icon: elem.icon })); // } export function addMarkerInMap(marker, map) { if (marker.addTo(map)) { return true; } return false; } export function addMarkersInMap(markers, map) { if (!Array.isArray(markers)) return false; markers.forEach(elem => elem.addTo(map)); return true; } export function addPopupInMarkers(markers) { if (!Array.isArray(markers)) return false; markers.forEach(elem => elem.mkr.bindPopup(elem.description)); return true; } export function flyToPos(map, latLong, zoom = 19) { if (!Array.isArray(latLong)) return false; map.flyTo(latLong, zoom); return true; } export function isPopupOn(marker) { return marker.isPopupOpen(); } export function showPopup(marker) { marker.openPopup(); return isPopupOn(marker); } export function finishPopup(marker) { marker.closePopup(); return !isPopupOn(marker); }
layui.use(['element', 'table'], function(){ var $ = layui.jquery ,element = layui.element; table = layui.table; element.on('tab(test)', function(elem){ location.hash = 'test='+ $(this).attr('lay-id'); //点击当前不处理 if(searchCourse == $(this).attr("lay-id")) { return; } else { searchCourse = $(this).attr("lay-id"); searchCourseName = $(this).text(); $(".knowledge_content").empty(); $(".content_inner").empty(); $("#contentPage").empty(); $("#search_req").empty().append(searchCourseName); $(".totals").hide(); $(".res_types").hide(); $("table").hide(); $(".layui-table-view").hide(); selKnowledge = ""; selKnowledgeName = ""; selResType = "0"; } }); //Hash地址的定位 var layid = location.hash.replace(/^#test=/, ''); element.tabChange('test', layid); $(document).on("keyup", "input[name='keyWord']", function(e){ //回车搜索 if(e.keyCode == 13) { searchknowledge(); } }) }); //默认全部 var searchCourse = "0"; var searchCourseName = "全部学科"; var contentList = []; var searchingStr = ""; var knowledgeListAll = []; var selKnowledge; var selKnowledgeName; var selResType = "0"; var table; function searchknowledge() { $.ajax({ url: "template/searching/res/result.json", type: "GET" ,dataType: "json" ,contentType: 'application/json' ,success: function(res) { knowledgeListAll = res.knowledges; handelknowledge(res.knowledges); }, error: function(res) { layer.msg(res.data || "查询失败") } }) } function searchContent() { $.ajax({ url: "template/searching/res/result.json", type: "GET" ,dataType: "json" ,contentType: 'application/json' ,success: function(res) { contentList = res.data; handelContent(res.data); }, error: function(res) { layer.msg(res.data || "查询失败") } }) } function handelknowledge(data) { searchingStr = $.trim($("input[name='keyWord']").val()); var knowledgeList = []; $.each(data, function(index, e) { if((searchCourse == "0" ||e.course == searchCourse) && roundMatch(e.knowledgeName, searchingStr)) { knowledgeList.push(e); } }); $(".contentTotal").hide(); $(".knowledgeTotal").show(); $("#knowledgeNum").text(knowledgeList.length); $(".totals").show(); initknowledges(knowledgeList); } function initknowledges(data) { var knowledgeStr = "<div id='knowledgeContent'>"; $.each(data, function(index, e) { if(index % 9 == 0) { knowledgeStr += "<div class='knoledge_list'>"; } knowledgeStr += "<div class='knowledge_single' data-id='"+e.knowledgeId+"'' title='"+e.knowledgeName+"'>"+e.knowledgeName+"</div>"; if(index % 9 == 8) { knowledgeStr += "</div>"; } }); knowledgeStr += "</div>"; $(".knowledge_content").empty().append(knowledgeStr); $(".knowledge_single").unbind().bind("click", function(){ if($(this).data("id") == selKnowledge) { //// } else { $(".knowledge_single").removeClass("starc-this"); $(this).addClass("starc-this"); selKnowledge = $(this).data("id"); selKnowledgeName = $(this).text(); selResType = "0"; setKnowledgeReq(); } }); } function setKnowledgeReq() { $("#search_req").empty().append(searchCourseName+" > "+selKnowledgeName); $.each($(".res_types span"), function(index, e){ e.className = ""; }); $(".res_types").find("span")[0].className = "layui-this"; $(".res_types").show(); $(".res_types span").unbind().bind("click", function(){ if($(this).data("id") == selKnowledge) { //// } else { selResType = $(this).data("id"); $(".res_types span").removeClass("layui-this"); $(this).addClass("layui-this"); handelContent(contentList); } }); searchContent(); } function handelContent(data) { var selKnowledgeContentList = getFrom(knowledgeListAll, selKnowledge); var aimContentList = []; for(var i=0;i<selKnowledgeContentList.length;i++) { for(var j=0;j<data.length;j++) { if(selKnowledgeContentList[i] == data[j].resourceId) { aimContentList.push(data[j]); break; } } } $(".contentTotal").show(); $(".knowledgeTotal").hide(); $("#contentNum").text(aimContentList.length); $(".totals").show(); initTable(aimContentList); } function initTable(aimContentList) { $("table").show(); $(".layui-table-view").show(); table.render({ elem: '#resourseTable' //,height: 420 //,url: '/demo/table/user/' //数据接口 //,title: '用户表' ,page: true //开启分页 //,toolbar: 'default' //开启工具栏,此处显示默认图标,可以自定义模板,详见文档 ,cellMinWidth: 80 //,totalRow: true //开启合计行 ,cols: [[ //表头 //{type: 'checkbox', fixed: 'left'} //,{field: 'id', title: 'ID', width:80, sort: true, fixed: 'left', totalRowText: '合计:'}, {type:'numbers'}, {field: 'resourceName', title: '资源名称', //width:'50%', minWidth: 500, sort: true} ,{field: 'authorName', title: '作者', //width: '20%', minWidth: 120, sort: true} ,{field: 'type', title: '类型', //width:'20%', minWidth: 120, sort: true} //,{field: 'operation', title: '操作', width: '28%', template: '#operationBar'} //,{fixed: 'right', width: 165, align:'center', toolbar: '#barDemo'} ]] ,data: checkParam(aimContentList, selResType) }); //监听行单击事件(单击事件为:rowDouble) table.on('row(resTable)', function(obj){ /*var data = obj.data; layer.alert(JSON.stringify(data), { title: '当前行数据:' });*/ window.open(obj.data.url); //标注选中样式 obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click'); }); } function getFrom(arr, id) { var aimArr = []; for(var i=0;i<arr.length;i++) { if(arr[i].knowledgeId == id) { aimArr = arr[i].resources; break; } } return aimArr; } //处理状态 function checkParam(data, type) { var aimResList = []; $.each(data, function(index, e) { if(e.resourceType == "1") { e["type"] = "课件"; } else if(e.resourceType == "2") { e["type"] = "文本"; } else if(e.resourceType == "3") { e["type"] = "视频"; } else if(e.resourceType == "4") { e["type"] = "试题"; } else if(e.resourceType == "5") { e["type"] = "试卷"; } else if(e.resourceType == "6") { e["type"] = "图片"; } if(e.resourceType == type && type != "0") { aimResList.push(e); } else if(type == "0") { aimResList.push(e); } }) return aimResList; } //先全部去空格 //思路一,两个字符串转数组然后判定是否有相同元素 //思路二,两个字符先拼接,然后去重 //判定两个字符串是否模糊匹配 function roundMatch(str1, str2) { //若输入空则查全部 if(str2.length == 0) { return true; } else { //方案1,去除空格匹配 //方案2,按空格进行多条件匹配,即以空格分割条件,取所有条件都满足的情况 var arr2 = str2.split(" "); if(typeof(str1) == "string") { var arr1 = str1.split(" "); } else { //知识点的keywords列表 var arr1 = str1; } return arrMatch(arr1, arr2); } //去除所有空格 //str1 = str1.replace(/\s+/g, ""); //str2 = str2.replace(/\s+/g, ""); } //判定两个数组中是否匹配,2中每个在1中都有才算 function arrMatch(arr1, arr2) { var matchAll = false; for(var i=0;i<arr2.length;i++) { for(var j=0;j<arr1.length;j++) { if(arr1[j].indexOf(arr2[i]) >-1) { matchAll = true; break; } } } return matchAll; }
// npm install connect serve-static websocket var http_web_server_port = 8080 var websocket_signaling_port = 1234 var connect = require('connect'); var WebSocketServer = require("websocket").server; var HTTPStaticServer = require('serve-static'); var HTTPServer = require('http'); var webrtcClients = []; connect().use(HTTPStaticServer(__dirname)).listen(http_web_server_port, function(){ console.log("server listening (port "+http_web_server_port+")"); }); var signaling_http_server = HTTPServer.createServer(function(request, response) { // process HTTP request. Since we're writing just WebSockets // server we don't have to implement anything. console.log("signaling server listening (port "+websocket_signaling_port+")"); }); signaling_http_server.listen(websocket_signaling_port, function() { }); // create the server wsServer = new WebSocketServer({ httpServer: signaling_http_server }); wsServer.on('request', function(request) { var connection = request.accept(null, request.origin); ip = connection.remoteAddress.split(':'); ip = ip[ip.length - 1]; console.log("New connection (IP: " + ip + "): " + request.origin); connection.on('message', function(data) { var signal = JSON.parse(data.utf8Data); var answer; var room_found = false; req_str = `New message.\n Signal: ${signal.type}\n Token: ${signal.token}`; switch (signal.type) { case "join": if (signal.token != undefined) { if (webrtcClients.some(e => e.token == signal.token)) { req_str += "\n Answer:\n Type: 'error_room'\n Message: Token in use."; connection.send( JSON.stringify({ type: "error_room", message: "Token in use, try again with other", }) ); } else { webrtcClients.push({ token: signal.token, caller: connection, callee: "", }) req_str += "\n Answer: Create the room."; //console.log("Join signal with token: " + signal.token); } } break; case "check_room": try { for (var i = 0; i < webrtcClients.length; i++) { if (webrtcClients[i].token === signal.token && webrtcClients[i].callee === "") { room_found = true; webrtcClients[i].callee = connection; webrtcClients[i].callee.send( JSON.stringify({ type: "joinanswer", token: webrtcClients[i].token, callee: true, }) ); webrtcClients[i].caller.send( JSON.stringify({ type: "joinanswer", token: webrtcClients[i].token, callee: false, }) ); req_str += `\n Answer:\n Type: ${signal.type}\n Token: ${signal.token}\n Message: Join the room.`; } } if (!room_found) { req_str += "\n Answer:\n Type: 'error_room'\n Message: Token in use."; connection.send( JSON.stringify({ type: "error_room", message: "Token in use, try again with other", }) ); } } catch(e) { console.log(`error: ${e.toString()}`) } break; case "message": answer = JSON.stringify({ type: "message", message: signal.message, }) break; case "stream": answer = JSON.stringify({ type: "stream", offer: signal.offer, }) break; case "stream-set": answer = JSON.stringify({ type: "stream-set", answer: signal.answer, }) break; case "candidate": answer = JSON.stringify({ type: "candidate", candidate: signal.candidate, }) break; default: console.log("Message: " + message.uft8Data); } if (signal.type === "message" || signal.type === "stream" || signal.type === "stream-set" || signal.type === "candidate") { req_str += `\n Answer:\n type:${JSON.parse(answer).type}` for (var i = 0; i < webrtcClients.length; i++) { if (webrtcClients[i].token === signal.token) { if (webrtcClients[i].caller === connection) { webrtcClients[i].callee.send(answer); } else { webrtcClients[i].caller.send(answer); } } } } console.log(req_str); }); });
export default { label: 'Food and Hygiene', id: 'food-4', pdf: 'food-4.pdf', list: [ { label: 'Cooking - Reading', type: 'passage', id: '100', data: { title: 'Raw and Cooked Food', text: [ `Food is one of the basic needs of life. We get energy for all our activities from food. Food obtained from the nature provides all the nutrients to our body. But seeing the advertisement, we are attracted towards junk food.`, `In our daily life, we depend on plants and animals for our food. Food that we eat directly without cooking is called raw food. We eat fruits, some vegetables, tubers and nuts in the raw form. Some pulses and cereals are also eaten as raw food.`, `Food that needs to be processed using heat before it can be eaten is called cooked food. Why should we cook food?`, `1. Cooked food is digested easily.`, `2. Cooking softens the food materials.`, `3. Cooking kills germs.`, `4. Cooking adds taste and flavour to food.`, `# Cooking methods`, `Some of the commonly used cooking methods are given below.`, `# Boiling:`, `It is a method of cooking food by immersing it in boiling water. So that the food becomes soft. Example: Rice, Egg.`, `# Steaming: `, `It is a method of cooking food in steam by immersing the vessel in a container with boiling water. Example: Idli, Idiyappam.`, `# Pressure cooking: `, `It is a method of cooking food in a pressure cooker. Example: Rice, Dhal.`, `# Roasting: `, `It is a method of cooking food by heating on a tawa or frying pan without covering it. Example: Groundnuts, Cashewnut.`, `# Frying:`, `It is a method of cooking food in hot oil. Example: Chips, Poori.`, `Boiling, steaming and pressure cooking uses moist heat. Roasting, frying and baking uses dry heat. There are other cooking methods like microwave cooking and solar cooking.` ] } }, { label: 'Food from Plants vs Animals', type: 'group', id: '200', data: { title: 'We get the below food items from plants and animals. Classify.', types: [ { name: 'Plants', text: 'Carrot, Potato, Brinjal, Onion, Mushroom, Corn' }, { name: 'Animals', text: 'Egg, Milk, Meat, Curd,Fish,Butter,Ghee' } ] } }, { label: 'Raw food', type: 'group', id: '300', data: { title: 'We can eat some food items raw, without cooking. Classify', types: [ { name: 'Raw', text: "cashewnut, carrot, lady's finger, tomato, cucumber, apple" }, { name: 'Only Cooked', text: 'fish, meat, brinjal, potato, dhal, spinach' } ] } }, { id: '400', label: 'Match the following', type: 'match', data: { text: `Idli, Steaming Rice, Pressure cooking Egg, Boiling Cashewnut, Roasting Chips, Frying`, title: 'Match the foods with their major nutrients.' } }, { label: 'Choose the best answer', type: 'mcq', id: '500', data: { title: 'Multiple Choice Questions', questions: [ { qText: 'Which of the following vegetable is not used while making salad?', options: 'potato, carrot, cucumber, cabbage' }, { qText: 'Pick the food items that are made from milk?', options: '* curd, * butter, mushroom, * ghee' }, { qText: 'Which cooking process needs a lot of oil?', options: 'Frying, Roasting, Boiling' }, { qText: 'Cakes are usually prepared by the process of ________.', options: 'baking, frying, roasting' }, { qText: 'What are the benefits of cooking food?', options: 'Easy to digest, kills germs, adds taste and flavour, * all of the above' } ] } }, { label: 'True or False', id: '600', type: 'classifySentence', data: { title: 'Classify the below sentences as true or false', types: [ { name: 'True', text: `Cooking kills germs. Honey is the only food that does not spoil. Idlis are made by the process of steaming.` }, { name: 'False', text: `We make salad by cooking vegetables. Cooked foods are difficult to digest. Chips are made by the process of boiling.` } ] } }, { label: 'Food Hygiene - Reading', type: 'passage', id: '700', data: { title: 'Food Hygiene', text: [ `We need to follow the below basic habits.`, `1. Wash your hands with soap before cooking.`, `2. Wash vegetables and fruits before cutting.`, `3. Wash cooking vessels and knives.`, `4. Don't cook food for a long time because it destroys the nutrients present in the food.`, `5. Don't use the same oil for cooking food many times.`, `6. Using the food items after their expiry date is not good for health.`, `# Utensils`, `Utensils are in different shapes and sizes. We use specific utensils for each cooking method. Clay pots were used earlier. Stainless steel and aluminum vessels are now generally used for cooking.`, `# Meal-time Hygiene`, `Meal-time hygiene includes ways to make sure that we do not get sick because of the way we eat or make food.`, `1. Always cover food to protect them from dust and insects.`, `2. Eat fresh food always.`, `3. Avoid taking food that is too cold or too hot.`, `4. Avoid fast food and fried food.`, `5. Always wash your hands before and after eating.`, `# Food During Illness`, `When we are sick, we should avoid food items that are fried in oil. We should take energy-giving, easily digestible food. Some of them are given below:`, `1. Porridge of rice or cereals.`, `2. Fruit juice, tender coconut.`, `3. Steamed foods like idli.`, `# Food Wastage`, `We should not waste food. Food that is not eaten is called leftover food. That is discarded as waste. Following are the simple ways to avoid food wastage.`, `1. Take what you'll eat and eat what you take.`, `2. Share the excess food.`, `3. Give the excess food to hungry animals.`, `One third of the food produced in the world is wasted. On the other hand, one section of people do not get enough food. 28th May is observed as world hunger day.`, `# Food Preservation`, `We can preserve the food for long time by using the following methods.`, `1. Pickling - Mixing fruits and vegetables with oil and salt.`, `2. Refrigerating - Keeping food in the fridge to preserve them for a short time.`, `3. Drying - Removing the water content of the food.`, `4. Canning - Storing food in air tight containers.` ] } }, { label: 'Multiple Choice Questions', type: 'mcq', id: '800', data: { title: 'Multiple Choice Questions', questions: [ { qText: 'We should avoid eating ____ food.', options: 'junk, fresh, raw' }, { qText: '_______ is an easily digested food.', options: 'Idli, Briyani, parotta' }, { qText: 'What type of food should we take when sick?', options: 'meat, * energy giving, * easily digestible, fried food' }, { qText: 'Which day is observed as world hunger day?', options: '28th May, 18th May, 28th June, 18th June' }, { qText: 'The preservation method of mixing vegetables with oil and salt is known as _______.', options: 'pickling, drying, canning' } ] } }, { label: 'True or False', id: '900', type: 'classifySentence', data: { title: 'Classify the below sentences as true or false', types: [ { name: 'True', text: `You should wash your hands before cooking. Solar cooker reduces the use of fuel. You should wash your hands before and after eating.` }, { name: 'False', text: `Vegetables and fruits should be washed after cutting. In olden days, people cooked their food in pressure cooker. Pressure cooker is not a cooking utensil. Junk food is good for health.` } ] } }, { label: 'Preservatives - Fill up', type: 'matchByDragDrop', id: '1000', data: { isPractice: false, title: 'Drag and drop the preservative methods at appropriate places.', styles: { fontSize: '1.3rem', dashWidth: 80 }, text: `The process of mixing fruits and vegetables with oil and salt is called *pickling*. Keeping food in the fridge to preserve them for a short time is called *refrigerating*. Removing the water content of the food is called *drying*. Storing food in air tight containers is called *canning*.` } }, { label: 'Choose the best answer', type: 'mcq', id: '1100', data: { title: 'Multiple Choice Questions', questions: [ { qText: 'Which one can be eaten as raw food?', options: 'Carrot, Meat, Fish, Potato' }, { qText: 'Uncooked food is called _______', options: 'raw food, junk food, hygienic food, cooked food' }, { qText: 'Solar cooker reduces___________ .', options: 'Air Pollution, Water Pollution, Land Pollution, Noise Pollution' }, { qText: 'Which one cannot be preserved by drying method?', options: 'Fruits, Rice, Fish, Cereals' }, { qText: 'We can avoid food wastage by', options: 'Giving to the needy, Eating more than we need, buying extra food, throwing in a dust bin' } ] } }, { id: '1200', label: 'Fill Up', type: 'fillupOptions', data: { title: 'Fill in the blanks with the given options.', text: `*Raw (Junk)* food gives us energy to work and play. Cooked food is easily *digested(undigested)*. Pressure cooker is one of the *modern(olden)* utensils. We need pure air, protected water and * hygenic (junk) *food for our healthy life. We make Idli by *steaming(boiling)* method.` } }, { label: 'Hygienic vs Junk food', id: '1300', type: 'group', data: { title: 'Classify the below as hygenic or junk food.', types: [ { name: 'Hygenic', text: 'fruits, nuts, salad, milk' }, { name: 'Junk', text: 'panipoori, samosa, chips' } ] } }, { type: 'match', label: 'Match the following', id: '1400', data: { fontSize: '1rem', title: 'Match the following', text: `Grapes,Raw food Mixture of vegetables,Salad Electric rice cooker,Modern utensil Earthen pot, Olden utensil Less fatty food,Food during illness` } }, { label: 'Say yes or No', type: 'classifySentence', id: '1500', data: { title: 'Say Yes or No', types: [ { name: 'Yes', text: `Frying is a method of cooking. Cooking in a solar oven needs sunlight. Consuming too much oily food is bad for our health.` }, { name: 'No ', text: `Briyani is a raw food. We can cook rice on a tawa.` } ] } } ] };
import {getRef, setPath, reorderArray} from '../../../utils' export const AddRepeaterRowAtIndex = (state, path) => { const parts = path.split('.') const index = parts.pop() let pointer = getRef(state.data, parts.join('.')) pointer.splice(index, 0, getClearedCopy(pointer[0])); return {...state} } export const RemoveRepeaterRow = (state, path) => { const parts = path.split('.') const index = parts.pop() let pointer = getRef(state.data, parts.join('.')) pointer.splice(index, 1); return {...state} } export const OnDragStart = (state, index, ev) => { ev.dataTransfer.setData('text', index); } export const OnDragOver = (state, index, ev) => { ev.preventDefault() } export const OnDrop = (state, path, ev) => { ev.preventDefault() // console.log('dragged from ' + ev.dataTransfer.getData('text') + ' to ' + index) const parts = path.split('.') const index = parts.pop() const parentPath = parts.join('.') const repeater = getRef(state.data, parentPath) const originIndex = parseInt(ev.dataTransfer.getData('text')) return { ...state, data: setPath( state.data, parentPath, reorderArray(originIndex, index, repeater) ) } }
app.beginUndoGroup("Invert order"); var thisComp = app.project.activeItem; var sel = thisComp.selectedLayers; sel = sel.reverse(); if (sel.length > 0) { for (i=0; i<sel.length; i++) { sel[i].moveToBeginning(); } } else alert("Selecciona al menos 1 layer"); app.endUndoGroup();