text
stringlengths
7
3.69M
import React from 'react' import {Checkbox as Muicheckbox, FormControl, FormControlLabel} from "@material-ui/core"; export default function checkbox(props) { const {label,name,onChange,value} = props; const convertTodefaultEventPara = (name, value)=>({ target:{ name,value } }) return ( <FormControl> <FormControlLabel control={ <Muicheckbox checked={value} onChange={e=>onChange(convertTodefaultEventPara(name,e.target.checked))} name={name} color="primary" /> }label={label}> </FormControlLabel> </FormControl> ) }
import React, {useReducer} from 'react' import { BrowserRouter as Router,Route,Switch} from 'react-router-dom'; import Statspage from './components/Statspage.js'; import App from './App'; import {AnimatePresence} from 'framer-motion' import photos from './components/images/game1.jpg' import {StateContext} from './context' function reducer(state, action) { switch (action.type) { case 'game': return {currentGame: action.payload}; default: return state; } } const initialState = {currentGame: { url: photos, title: 'Cyberpunk 2077', timePlayed: '20h 44m', progress: '78%', production:'CD Projekt', diamond:'15', gold:'6', silver:'7', bronze:'7', size:'70 GB', lastTropy: 'The Wandering Fool', lastTropyInfo:'Find all the tarot graffiti for the job Fool on the Hill' }}; export default function Main() { const [state, dispatch] = useReducer(reducer, initialState); return ( <div className="overflow-hidden"> <Router > <StateContext.Provider value={{state, dispatch}} > <AnimatePresence exitBeforeEnter > <Switch> <Route path="/" exact component={App} /> <Route className='overflow-hidden' path="/Statspage" exact component={Statspage} /> </Switch> </AnimatePresence> </StateContext.Provider> </Router> </div> ) }
var quad = [-1.0,-1.0, 1.0,-1.0, -1.0,1.0, -1.0,1.0, 1.0,-1.0, 1.0,1.0]; function createShader(gl,type,source){ var shader = gl.createShader(type); gl.shaderSource(shader,source); gl.compileShader(shader); sucess = gl.getShaderParameter(shader,gl.COMPILE_STATUS); if(sucess){ return shader; } throw gl.getShaderInfoLog(shader); console.log(gl.getShaderInfoLog(shader)); gl.deleteShader(shader); } function createProgram(gl,vertexShader,fragmentShader){ var program = gl.createProgram(); gl.attachShader(program,vertexShader); gl.attachShader(program, fragmentShader); gl.linkProgram(program); var sucess = gl.getProgramParameter(program,gl.LINK_STATUS); if(sucess){ return program; } console.log(gl.getProgramInfoLog(program)); gl.deleteProgram(program); } class Renderer{ constructor(){ this.updateResolution(); this._initGLData(); } updateResolution(){ this.resolution = [canvas.width,canvas.height]; this.aspect_ratio = canvas.width/canvas.height; gl.viewport(0,0,gl.canvas.width,gl.canvas.height); } render() { if (scene == null) { return; } //gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.clearColor(scene.bgColor[0],scene.bgColor[1],scene.bgColor[2], 1.0); gl.clear(gl.COLOR_BUFFER_BIT); this._board_render(scene); this._robots_goal_render(scene); } _initGLData(){ this._initBoard(); this._initTextured(); gl.disable(gl.DEPTH_TEST); gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); } _board_render(scene){ gl.useProgram(this.programs.board); gl.bindVertexArray(this.vaos.board); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D,scene.texture); gl.uniform1i(this.uniformLoc.board.wallTexture, 0); gl.uniform1f(this.uniformLoc.board.board_size, scene.board_size); gl.uniform1f(this.uniformLoc.board.grid_width, scene.grid_width); gl.uniform1f(this.uniformLoc.board.v_zoom, scene.v_zoom); gl.uniform1f(this.uniformLoc.board.aspect_ratio, this.aspect_ratio); //TODO CHECK BUGS gl.uniform2f(this.uniformLoc.board.center, scene.center[1],scene.board_size-scene.center[0]); gl.uniform3fv(this.uniformLoc.board.wall_color, scene.wall_color); gl.uniform3fv(this.uniformLoc.board.grid_color, scene.grid_color); gl.uniform3fv(this.uniformLoc.board.board_color, scene.board_color); var primitiveType = gl.TRIANGLES; var offset = 0; var count = 6; gl.drawArrays(primitiveType, offset, count); } _robots_goal_render(scene){ gl.useProgram(this.programs.textured); gl.bindVertexArray(this.vaos.board); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D,scene.goal.texture); gl.uniform1i(this.uniformLoc.textured.image, 0); gl.uniform1f(this.uniformLoc.textured.v_zoom, scene.v_zoom); gl.uniform1f(this.uniformLoc.textured.aspect_ratio, this.aspect_ratio); gl.uniform1f(this.uniformLoc.textured.size, scene.goal.size); gl.uniform2f(this.uniformLoc.textured.center, scene.center[1],scene.board_size-scene.center[0]); let avgcol = scene.goal.color[0] + scene.goal.color[1] + scene.goal.color[2]; avgcol/=3; avgcol = 0.95; let param = 0.4; let scale = 1; let col = [ (scene.goal.color[0]*(1-param) + avgcol*param)*scale, (scene.goal.color[1]*(1-param) + avgcol*param)*scale, (scene.goal.color[2]*(1-param) + avgcol*param)*scale ] gl.uniform3fv(this.uniformLoc.textured.color, col); gl.uniform2f(this.uniformLoc.textured.pos, scene.goal.y,scene.board_size-scene.goal.x); var primitiveType = gl.TRIANGLES; var offset = 0; var count = 6; gl.drawArrays(primitiveType, offset, count); for(let robot in scene.robots){ gl.bindTexture(gl.TEXTURE_2D,scene.robots[robot].texture); gl.uniform1i(this.uniformLoc.textured.image, 0); gl.uniform1f(this.uniformLoc.textured.v_zoom, scene.v_zoom); gl.uniform1f(this.uniformLoc.textured.aspect_ratio, this.aspect_ratio); gl.uniform1f(this.uniformLoc.textured.size, scene.robots[robot].size); gl.uniform2f(this.uniformLoc.textured.center, scene.center[1],scene.board_size-scene.center[0]); gl.uniform3fv(this.uniformLoc.textured.color, scene.robots[robot].color); gl.uniform2f(this.uniformLoc.textured.pos, scene.robots[robot].y,scene.board_size-scene.robots[robot].x); var primitiveType = gl.TRIANGLES; var offset = 0; var count = 6; gl.drawArrays(primitiveType, offset, count); } } _initBoard(){ this.programs = {} this.uniformLoc = {} this.attributeLoc = {} this.vaos = {} let vs = `#version 300 es // an attribute will receive data from a buffer in vec4 a_position; uniform float board_size; uniform float grid_width; uniform float v_zoom; uniform float aspect_ratio; uniform vec2 center; out vec2 pos; out float grid_w; out float bs; // all shaders have a main function void main() { // gl_Position is a special variable a vertex shader // is responsible for setting vec2 tmp = (a_position.xy*0.5*(board_size+2.0*grid_width) + board_size*0.5) ; gl_Position = vec4( (tmp - center)*v_zoom + vec2(0.5), a_position.z, 1.0); gl_Position = vec4((tmp-center)*v_zoom, a_position.z, 1.0); //gl_Position = a_position; //gl_Position.xy = gl_Position.xy*0.4; gl_Position.x = gl_Position.x/aspect_ratio; grid_w = grid_width; bs = board_size; pos=tmp; } `; let fs = `#version 300 es precision mediump float; in vec2 pos; in float grid_w; in float bs; out vec4 frag_color; uniform sampler2D wallTexture; uniform vec3 wall_color; uniform vec3 grid_color; uniform vec3 board_color; void main() { // gl_FragColor is a special variable a fragment shader // is responsible for setting float x_thick = grid_w*0.5; if(pos.x>0.0 && pos.y > 0.0f) frag_color = vec4(board_color, 1.0); // return reddish-purple else frag_color = vec4(wall_color,1.0f); if(fract(pos.x)>=(1. - grid_w) || fract(pos.y)>=(1.-grid_w) || fract(pos.x) <=grid_w || fract(pos.y) <=grid_w ){ frag_color = vec4(grid_color,1.0); } if(pos.x<grid_w+x_thick || pos.y<grid_w+x_thick || pos.x>=bs - grid_w -x_thick || pos.y>= bs - grid_w-x_thick){ frag_color =vec4(wall_color,1.0); } vec2 help = pos-vec2(grid_w+x_thick,-grid_w-x_thick); ivec2 tile = ivec2(floor(help)) + ivec2(0,0); vec2 xy = texelFetch(wallTexture,tile,0).rg; if(fract(help).x >=(1.0-2.0*(grid_w+x_thick)) && fract(help).y>2.0*grid_w){ if(xy.x>0.5) frag_color =vec4(wall_color,1.0); } if(fract(help).y <=(2.0*(grid_w+x_thick)) && fract(help).x<1.0-2.0*grid_w){ if(xy.y>0.5) frag_color =vec4(wall_color,1.0); } //frag_color = vec4(texelFetch(wallTexture,ivec2(floor(pos)),0).rgb,1.0); } `; let vertexShader = createShader(gl,gl.VERTEX_SHADER, vs); let fragmentShader = createShader(gl,gl.FRAGMENT_SHADER, fs); this.programs.board = createProgram(gl,vertexShader,fragmentShader); this.attributeLoc.board = { position: gl.getAttribLocation(this.programs.board, "a_position") } this.uniformLoc.board = { board_size: gl.getUniformLocation(this.programs.board, "board_size"), grid_width: gl.getUniformLocation(this.programs.board, "grid_width"), v_zoom: gl.getUniformLocation(this.programs.board, "v_zoom"), aspect_ratio: gl.getUniformLocation(this.programs.board, "aspect_ratio"), center: gl.getUniformLocation(this.programs.board, "center"), wallTexture: gl.getUniformLocation(this.programs.board, "wallTexture"), board_color: gl.getUniformLocation(this.programs.board, "board_color"), grid_color: gl.getUniformLocation(this.programs.board, "grid_color"), wall_color: gl.getUniformLocation(this.programs.board, "wall_color"), } this.vaos.board = gl.createVertexArray(); gl.bindVertexArray(this.vaos.board); gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer()); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(quad),gl.STATIC_DRAW); gl.enableVertexAttribArray(this.attributeLoc.board.position); var size=2; var type=gl.FLOAT; var normalize = false; var stride = 0; var offset = 0; gl.vertexAttribPointer(this.attributeLoc.board.position,size,type,normalize,stride,offset); } _initTextured(){ let vs = `#version 300 es // an attribute will receive data from a buffer in vec4 a_position; uniform float size; uniform float v_zoom; uniform float aspect_ratio; uniform vec2 center; uniform vec2 pos; out vec2 uv; // all shaders have a main function void main() { // gl_Position is a special variable a vertex shader // is responsible for setting uv = a_position.xy*0.5+0.5; vec2 tmp = (a_position.xy*size*0.5 + pos) ; gl_Position = vec4( (tmp - center)*v_zoom + vec2(0.5), a_position.z, 1.0); gl_Position = vec4((tmp-center)*v_zoom, a_position.z, 1.0); gl_Position.x = gl_Position.x/aspect_ratio; } `; let fs = `#version 300 es precision mediump float; in vec2 uv; out vec4 frag_color; uniform sampler2D image; uniform vec3 color; const int SAMPLES = 4; void main() { // gl_FragColor is a special variable a fragment shader // is responsible for setting float alpha = texture(image,vec2(uv.x,1.0-uv.y)).r; vec2 p = (uv-0.5)*2.0; float f = -dot(p,p)*80./255. + 20./255.; //frag_color = vec4(f,f,f,1.0f); //return; frag_color = vec4((color+f)*alpha,alpha); //frag_color = vec4(texture(image,uv)); } `; let vertexShader = createShader(gl,gl.VERTEX_SHADER, vs); let fragmentShader = createShader(gl,gl.FRAGMENT_SHADER, fs); this.programs.textured = createProgram(gl,vertexShader,fragmentShader); this.attributeLoc.textured = { position: gl.getAttribLocation(this.programs.textured, "a_position") } this.uniformLoc.textured = { size: gl.getUniformLocation(this.programs.textured, "size"), v_zoom: gl.getUniformLocation(this.programs.textured, "v_zoom"), pos: gl.getUniformLocation(this.programs.textured, "pos"), aspect_ratio: gl.getUniformLocation(this.programs.textured, "aspect_ratio"), center: gl.getUniformLocation(this.programs.textured, "center"), image: gl.getUniformLocation(this.programs.textured, "image"), color: gl.getUniformLocation(this.programs.textured, "color") } this.vaos.board = gl.createVertexArray(); gl.bindVertexArray(this.vaos.board); gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer()); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(quad),gl.STATIC_DRAW); gl.enableVertexAttribArray(this.attributeLoc.board.position); var size=2; var type=gl.FLOAT; var normalize = false; var stride = 0; var offset = 0; gl.vertexAttribPointer(this.attributeLoc.board.position,size,type,normalize,stride,offset); } }
let building1; let building2; let building3; let building4; let building5; let zoomOutX = 0; let zoomOutY = 0; let zoomOutW = 150; let zoomOutH = 300; let moveCloudsX = 0; let moveCloudsY = 0; let cloudSize = 0; let starSize = 0; let earthSize = 0; let earthX = 0; let earthY = 0; let angle = 0; let sunAngle = 0; let sunSize = 0; function setup() { createCanvas(1200, 600, WEBGL); } function draw() { translate(-200, -200); building1 = new Building(40 - zoomOutX, 110 - zoomOutY, 150, 300); building2 = new Building(200 - zoomOutX, 100 - zoomOutY, 150, 300); building3 = new Building(100 - zoomOutX, 140 - zoomOutY, 150, 300); building4 = new Building(10 - zoomOutX, 200 - zoomOutY, 150, 300); building5 = new Building(270 - zoomOutX, 250 - zoomOutY, 150, 250); building6 = new Building(145 - zoomOutX, 290 - zoomOutY, 150, 210); timeOfDay(); } function timeOfDay() { if (mouseY > 200) { // NIGHT TIME background(30); //stars (); stars() building1.buildings(fill(200)); building1.windows(253, 185, 19); building2.buildings(fill(30)); building2.windows(253, 185, 19); building3.buildings(fill(130)); building3.windows(253, 185, 19); building4.buildings(fill(100)); building4.windows(253, 185, 19); building5.buildings(fill(150)); building5.windows(253, 185, 19); building6.buildings(fill(60)); building6.windows(253, 185, 19); clouds(); } else { // DAY TIME background(253, 185, 100); building1.buildings(fill(200)); building1.windows(10, 10, 10); building2.buildings(fill(30)); building2.windows(10, 10, 10); building3.buildings(fill(130)); building3.windows(10, 10, 10); building4.buildings(fill(100)); building4.windows(10, 10, 10); building5.buildings(fill(150)); building5.windows(10, 10, 10); building6.buildings(fill(60)); building6.windows(10, 10, 10); clouds(); //directionalLight(249,215,2, -200, -100, -1) } zoomOut(); earth(); } function stars() { push(); translate(-400, 0); noStroke(); fill(250); ellipse(random(windowWidth), random(windowHeight), 5 + starSize); pop(); } function sun(){ push(); sunAngle += 0.001; translate(200,200); rotateZ(sunAngle); strokeWeight(1); stroke(200, 170, 0); fill(227,38,54); // sphere(radiusx, radiusy, radius z); directionalLight(255,200, 0, -1, -1, -1); sphere(0 + sunSize); pop(); } function earth() { push(); //ambientLight(0,100,100, 40); angle += 0.004; translate(400 - earthX, 500 - earthY) rotateX(angle); rotateZ(angle); strokeWeight(5); stroke(0, 255, 170); noFill(); // sphere(radiusx, radiusy, radius z); sphere(1400 - earthSize); pop(); if (earthX >= 34){ sun(); } } function clouds() { // making clouds move moveCloudsX = moveCloudsX + 0.1 noStroke(); fill(255); circle(0 + moveCloudsX, 65 + moveCloudsY, 90 + cloudSize); circle(60 + moveCloudsX, 72 + moveCloudsY, 80 + cloudSize); circle(-20 + moveCloudsX, 80 + moveCloudsY, 60 + cloudSize); circle(100 + moveCloudsX, 83 + moveCloudsY, 60 + cloudSize); circle(220 + moveCloudsX, 95 + moveCloudsY, 90 + cloudSize); circle(250 + moveCloudsX, 102 + moveCloudsY, 80 + cloudSize); circle(170 + moveCloudsX, 110 + moveCloudsY, 60 + cloudSize); circle(290 + moveCloudsX, 113 + moveCloudsY, 60 + cloudSize); } function zoomOut() { if (mouseIsPressed) { if (mouseButton === LEFT) { zoomOutX -= 1; zoomOutY -= 3; moveCloudsX += 1; moveCloudsY += 3; cloudSize += 3; starSize += 0.01; earthSize -= 10; earthX += 0.1; earthY += 0.5; sunSize += 0.3; } if (mouseButton === RIGHT) { zoomOutX += 1; zoomOutY += 3; moveCloudsX -= 1; moveCloudsY -= 3; cloudSize -= 3; starSize -= 0.0003; earthSize += 10; earthX -= 0.1; earthY -= 0.5; sunSize -= 0.6; } } }
import React from 'react'; export const Medium = () => ( <svg xmlns="http://www.w3.org/2000/svg" height="24" width="24" viewBox="0 0 24 24" > <path d="M16 19.1l-5.2-8.5-.8-1.3v6.8l6 3m1.2-2L23.9 6l-7.2-3.6c-.4-.2-.8 0-1.1.3l-3.7 6 5.3 8.4zm.6 2.9l4.9 2.4c.7.4 1.3.1 1.3-.6V9.7L17.8 20zM8 6.1s0-.1 0 0c0-.1 0-.1 0 0L3.3 3.7 1.1 2.6l-.2-.1c-.5-.2-.9 0-.9.5v15.3c0 .4.3.9.7 1.1l6.2 3.1c.6.3 1.1 0 1.1-.7V6.1z" /> </svg> );
//@ts-check /** * @template StateType * @typedef {import("./createReducer").InitStateType<StateType>} InitStateType */ /** * @template StateType * @template ActionType * @typedef {import("./createReducer").ReducerType<StateType, ActionType>} ReducerType */ /** * @template StateType * @template ActionType * @typedef {import("./createReducer").DispatchType<StateType, ActionType>} DispatchType */ export { default as createReducer, refineAction } from "./createReducer"; export { StoreObject, ActionObject } from "./type"; export { default as SimpleMap } from "./SimpleMap";
define('app/exts/erobot/erobot', [ 'jquery', 'underscore', 'magix', 'brix/base', 'brix/event', 'app/exts/erobot/erobot.tpl', 'css!app/exts/erobot/erobot.css' ], function ($, _, Magix, Brick, EventManager, template) { var pathmap = { 'default': 464, '/': 463, '/promo/search/index.htm': 472, '/manage/zhaoshang/list.htm': 465 } function getSourceId(path) { var sourceId = pathmap[path] if (!sourceId) { sourceId = pathmap['default'] } return sourceId } return Brick.extend({ render: function() { var me = this var $el = $(me.element) var sourceId = getSourceId(Magix.Router.parse().path) $el.html(_.template(template)({ sourceId: sourceId })) var manager = new EventManager() manager.delegate($el, me) var awRendered = false // 全局的anywhere只需要初始化一次 if (window.AW && !window.AW.inited) { window.AW && window.AW.init({ sourceId: getSourceId(), bizCode: 'PCMaMaAnyWhereWindow', logoWidth: 30, onRendered: function () { // 只有每次点击链接的时候才显示浮层 if (awRendered) { window.AW.openDialog({ isFirstAnswer: true }) } awRendered = true } }) window.AW.inited = true } Magix.Router.on('changed', function (e) { if (e.isPath) { me._refresh(e.location.path) } }) }, _refresh: function (pathName) { var me = this var $el = $(me.element) var sourceId = getSourceId(pathName) $el.find('.erobot-trigger').attr('sourceId', sourceId) }, show: function (e) { e.preventDefault() var me = this var curNode = $(e.currentTarget) var sourceId = curNode.attr('sourceId') window.AW && window.AW.refresh({ sourceId: sourceId }) } }) })
'use strict'; module.exports = { name: 'smoothscroll' };
export { Table } from './Table' export { TableHead } from './TableHead' export { TableBody } from './TableBody' export { TableRow } from './TableRow' export { TableCell } from './TableCell' export { TableHeader } from './TableHeader'
const schoty = (frame) => +frame.map((x) => x.split('---')[0].replace(/^O*/g, (y) => y.length)).join(''); const result = schoty([ 'OO---OOOOOOOO', 'O---OOOOOOOOO', 'OOOOO---OOOOO', '---OOOOOOOOOO', '---OOOOOOOOOO', '---OOOOOOOOOO', '---OOOOOOOOOO', ]); console.log(result); // const schoty = frame => Number(frame.map(wire => wire.indexOf('-')).join('')); // const schoty = frame => // +frame.reduce((a, b) => a + b.replace(/-+|O+$/g, '').length, '') // ; // const schoty = f => +f.reduce((r, s) => r + s.indexOf('-'), '');
// while (условие) { // // код, тело цикла // } let i = 0; while (i < 150) { if (i % 2 == 0) console.log("Hello World"); else console.log("Hello everybody"); i += 1; } // Удобен тем, что дает гибкость условию
// These are the pages you can go to. // They are all wrapped in the App component, which should contain the navbar etc // See http://blog.mxstbr.com/2016/01/react-apps-with-pages for more information // about the code splitting business import {getAsyncInjectors} from './utils/asyncInjectors'; const errorLoading = (error) => { console.error('Dynamic page loading failed', error); // eslint-disable-line no-console }; const loadModule = (cb) => (componentModule) => { cb(null, componentModule.default); }; export default function createRoutes(store) { // create reusable async injectors using getAsyncInjectors factory const {injectReducer, injectSagas} = getAsyncInjectors(store); return [ { path: '/', name: 'forum', getComponent(nextState, cb) { const importModules = Promise.all([ System.import('containers/forum/forum.saga'), System.import('containers/forum/ForumPage.container') ]); const renderRoute = loadModule(cb); importModules.then(([saga, component]) => { injectSagas('forum.saga', saga.default); renderRoute(component); }); importModules.catch(errorLoading); } }, { path: '/albums/:albumId/:photoId', name: 'photo', getComponent(nextState, cb) { const importModules = Promise.all([ System.import('containers/photos/album.saga'), System.import('containers/photos/PhotoPage.container') ]); const renderRoute = loadModule(cb); importModules.then(([saga, component]) => { injectSagas('album.saga:photo', saga.default); renderRoute(component); }); importModules.catch(errorLoading); } }, { path: '/albums/:albumId', name: 'album', getComponent(nextState, cb) { const importModules = Promise.all([ System.import('containers/photos/album.saga'), System.import('containers/photos/AlbumPage.container') ]); const renderRoute = loadModule(cb); importModules.then(([saga, component]) => { injectSagas('album.saga:album', saga.default); renderRoute(component); }); importModules.catch(errorLoading); } }, { path: '/albums', name: 'albums', getComponent(nextState, cb) { const importModules = Promise.all([ System.import('containers/photos/album.saga'), System.import('containers/photos/AlbumsPage.container') ]); const renderRoute = loadModule(cb); importModules.then(([saga, component]) => { injectSagas('album.saga', saga.default); renderRoute(component); }); importModules.catch(errorLoading); } }, { path: '/authentication', name: 'authentication', getComponent(nextState, cb) { const importModules = Promise.all([ System.import('containers/authentication/authentication.saga'), System.import('containers/authentication/AuthenticationPage.container'), ]); const renderRoute = loadModule(cb); importModules.then(([saga, component]) => { injectSagas('authentication.saga', saga.default); renderRoute(component); }); importModules.catch(errorLoading); } }, { path: '/forum', name: 'forum', getComponent(nextState, cb) { const importModules = Promise.all([ System.import('containers/forum/forum.saga'), System.import('containers/forum/ForumPage.container') ]); const renderRoute = loadModule(cb); importModules.then(([saga, component]) => { injectSagas('forum.saga', saga.default); renderRoute(component); }); importModules.catch(errorLoading); } }, { path: '/users', name: 'users', getComponent(nextState, cb) { const importModules = Promise.all([ System.import('containers/users/user.saga'), System.import('containers/users/UsersPage.container'), ]); const renderRoute = loadModule(cb); importModules.then(([saga, component]) => { injectSagas('user.saga', saga.default); renderRoute(component); }); importModules.catch(errorLoading); } }, { path: '*', name: 'notfound', getComponent(nextState, cb) { System.import('containers/core/NotFoundPage.container') .then(loadModule(cb)) .catch(errorLoading); } } ]; }
require("../common/vendor.js"), (global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/personal_package/feedback/main" ], { "11c2": function(t, e, n) { n.r(e); var r = n("d866"), o = n.n(r); for (var a in r) [ "default" ].indexOf(a) < 0 && function(t) { n.d(e, t, function() { return r[t]; }); }(a); e.default = o.a; }, "15b1": function(t, e, n) { (function(t) { function e(t) { return t && t.__esModule ? t : { default: t }; } n("6cdc"), e(n("66fd")), t(e(n("d5a6")).default); }).call(this, n("543d").createPage); }, "81ac": function(t, e, n) { n.d(e, "b", function() { return r; }), n.d(e, "c", function() { return o; }), n.d(e, "a", function() {}); var r = function() { var t = this; t.$createElement; t._self._c; }, o = []; }, "96d2": function(t, e, n) {}, d5a6: function(t, e, n) { n.r(e); var r = n("81ac"), o = n("11c2"); for (var a in o) [ "default" ].indexOf(a) < 0 && function(t) { n.d(e, t, function() { return o[t]; }); }(a); n("d69f"); var i = n("f0c5"), u = Object(i.a)(o.default, r.b, r.c, !1, null, "2e2e7d1a", null, !1, r.a, void 0); e.default = u.exports; }, d69f: function(t, e, n) { var r = n("96d2"); n.n(r).a; }, d866: function(t, e, n) { function r(t) { return t && t.__esModule ? t : { default: t }; } function o(t, e) { var n = Object.keys(t); if (Object.getOwnPropertySymbols) { var r = Object.getOwnPropertySymbols(t); e && (r = r.filter(function(e) { return Object.getOwnPropertyDescriptor(t, e).enumerable; })), n.push.apply(n, r); } return n; } function a(t) { for (var e = 1; e < arguments.length; e++) { var n = null != arguments[e] ? arguments[e] : {}; e % 2 ? o(Object(n), !0).forEach(function(e) { i(t, e, n[e]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(t, Object.getOwnPropertyDescriptors(n)) : o(Object(n)).forEach(function(e) { Object.defineProperty(t, e, Object.getOwnPropertyDescriptor(n, e)); }); } return t; } function i(t, e, n) { return e in t ? Object.defineProperty(t, e, { value: n, enumerable: !0, configurable: !0, writable: !0 }) : t[e] = n, t; } function u(t) { return l(t) || f(t) || s(t) || c(); } function c() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function s(t, e) { if (t) { if ("string" == typeof t) return p(t, e); var n = Object.prototype.toString.call(t).slice(8, -1); return "Object" === n && t.constructor && (n = t.constructor.name), "Map" === n || "Set" === n ? Array.from(t) : "Arguments" === n || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n) ? p(t, e) : void 0; } } function f(t) { if ("undefined" != typeof Symbol && Symbol.iterator in Object(t)) return Array.from(t); } function l(t) { if (Array.isArray(t)) return p(t); } function p(t, e) { (null == e || e > t.length) && (e = t.length); for (var n = 0, r = new Array(e); n < e; n++) r[n] = t[n]; return r; } Object.defineProperty(e, "__esModule", { value: !0 }), e.default = void 0; var d = r(n("80d6")), m = r(n("b4fa")), g = function(t) { var e = function(t) { return "string" == typeof t && Boolean(t.trim()); }, n = { category: { check: e, text: "请选择反馈类型" }, content: { check: e, text: "请填写问题描述" } }; return Object.keys(n).every(function(e) { var r = n[e]; return !!r.check(t[e], t) || (wx.showToast({ title: r.text, duration: 2e3, icon: "none" }), !1); }); }, h = { UPLOADING: "uploading", FAIL: "fail", SUCCESS: "success" }, b = { data: function() { return { params: { category: "", content: "", contact: "", photos_urls: [] }, img_count: 3, temp_imgs: [] }; }, components: { TagFilter: function() { n.e("pages/personal_package/feedback/_tag_filter").then(function() { return resolve(n("e950")); }.bind(null, n)).catch(n.oe); } }, onShareAppMessage: function() { var t = encodeURIComponent("/pages/personal_package/feedback/main"), e = { title: "点这提交反馈哦,欢迎您对购房通提出建议和意见~", path: "/pages/index/main?sub_page=".concat(t) }; return this.getShareInfo(e); }, methods: { changeStatus: function(t) { this.params.category = t; }, handleUploadStatus: function(t, e, n) { this.temp_imgs[t].status = n ? h.SUCCESS : h.FAIL, this.temp_imgs[t].uploaded_url = e, this.temp_imgs.every(function(t) { return t.status != h.UPLOADING; }) && wx.hideLoading(); }, uploadImg: function(t) { var e = this, n = (t.currentTarget.dataset.mediatype, this.temp_imgs.length), r = this.img_count - n; d.default.chooseImage({ count: r, sourceType: [ "album" ] }).then(function(t) { var n, r = t.map(function(t) { return { url: t, status: h.UPLOADING, uploaded_url: "" }; }), o = e.temp_imgs.length; (n = e.temp_imgs).push.apply(n, u(r)), wx.showLoading({ title: "上传中", mask: !0 }), t.forEach(function(t, n) { d.default.uploadImg({ filePath: t }).then(function(t) { e.handleUploadStatus(o + n, t, !0); }).catch(function(t) { e.handleUploadStatus(o + n, "", !1); }); }); }); }, previewImg: function(t) { wx.previewImage({ current: this.temp_imgs[t].url, urls: this.temp_imgs.map(function(t) { return t.url; }) }); }, removeImg: function(t) { this.temp_imgs.splice(t, 1); }, submit: function() { var t = a(a({}, this.params), {}, { photos_urls: this.temp_imgs.filter(function(t) { return t.status === h.SUCCESS; }).map(function(t) { return t.uploaded_url; }) }); g(t) && m.default.setFeedbacks(t).then(function(t) { 422 !== t.code ? (wx.showToast({ title: "提交成功" }), setTimeout(function() { wx.switchTab({ url: "/pages/personal_center/main" }); }, 1500)) : wx.showToast({ title: t.error_message, icon: "none" }); }); } } }; e.default = b; } }, [ [ "15b1", "common/runtime", "common/vendor", "pages/personal_package/common/vendor" ] ] ]);
export const IS_REGISTER_OR_LOGIN = "IS_REGISTER_OR_LOGIN"; export const REGISTRATION = "REGISTRATION"; export const LOGIN = "LOGIN"; export const LOGOUT = "LOGOUT"; export const DELETE_ERR_MESSGE = "DELETE_ERR_MESSGE";
angular.module('ExternalDataServices', []) .factory('ParseAbstractService', ['ParseQueryAngular', function(ParseQueryAngular) { /******** This service provides an enhanced Parse.Object and Parse.Collection So we can call load and saveParse from any extending Class and have that wrapped within ParseQueryAngular **********/ var object = function(originalClass) { originalClass.prototype = _.extend(originalClass.prototype, { load: function() { return ParseQueryAngular(this, { functionToCall: "fetch" }); }, saveParse: function(data) { if (data && typeof data == "object") this.set(data); return ParseQueryAngular(this, { functionToCall: "save", params: [null] }); } }); return originalClass; }; var collection = function(originalClass) { originalClass.prototype = _.extend(originalClass.prototype, { load: function() { return ParseQueryAngular(this, { functionToCall: "fetch" }); } }); return originalClass; }; return { EnhanceObject: object, EnhanceCollection: collection }; } ]);
import React from 'react'; import fakeData from '../fakeData/fakeData'; import { useState } from 'react'; import './Courses.css'; import Enrollments from '../Enrollments/Enrollments'; import Cart from '../Cart/Cart'; import SelectedCourses from '../ SelectedCourses/SelectedCourses'; import { addToDatabaseCart, getDatabaseCart } from '../Utilities/DatabaseManager'; import { useEffect } from 'react'; const Courses = () => { const [course, setCourse] = useState(fakeData); const [cart, setCart] = useState([]); const [enroll, setEnroll] = useState([]); const handleAddCourse = (course) => { const newCart = ([...cart, course]); setCart(newCart); const sameItem = newCart.filter(crs => crs.id === course.id) const count = sameItem.length; addToDatabaseCart (course.id, count); } useEffect(() => { const savedCart = getDatabaseCart(); const courseIds = Object.keys(savedCart); const cartCourses = courseIds.map(id => { const course = fakeData.find(crs => crs.id === id); course.quantity = savedCart[id]; return course; }); setCart(cartCourses); },[]) return ( <div className="class-container"> <div className="row"> { course.map(course => <Enrollments key={course.id} handleAddCourse = {handleAddCourse} course={course}> </Enrollments>) } </div> <div className="enroll-container"> <Cart cart={cart} ></Cart> { cart.map(crs=><SelectedCourses course={crs}> </SelectedCourses>) } </div> </div> ); }; export default Courses;
/*global alert: true, console: true, ODSA */ // Written by Bailey Spell and Jesse Terrazas $(document).ready(function() { "use strict"; function setMessage() { localStorage.secretMsg = $("#inputSecretMsg").val(); } $("#inputSecretMsg").keyup(setMessage); });
const assert = require('assert'); function foo() { return { bar() { let a = 7; return 2*a; } }; } assert.equal(foo().bar(), 14);
(function(swiperContainer){ if(!swiperContainer.length) { return; } Array.prototype.forEach.call(swiperContainer, function(swipe){ var mySwipe, resizeTimeout = null, windowWidthOLd = null, toggleSwipe = null, resetSwipe = null, swipeNav = document.createElement('div'), swipeNext = document.createElement('button'), swipePrev = document.createElement('button'), count = swipe.querySelectorAll('.swiper-slide').length, md = swipe.classList.contains('swiper-container--md'), review = swipe.classList.contains('swiper-container--review'); swipeNav.className = 'swiper-pagination'; swipe.appendChild(swipeNav); swipePrev.className = 'swiper-button-prev button hide'; swipeNext.className = 'swiper-button-next button hide'; swipePrev.innerHTML = '<svg width="6" height="10" viewBox="0 0 6 10"><path d="M6 .788L5.183 0 0 5l5.183 5L6 9.212 1.633 5z"/></svg>'; swipeNext.innerHTML = '<svg width="6" height="10" viewBox="0 0 6 10"><path d="M0 .788L.817 0 6 5 .817 10 0 9.212 4.367 5z"/></svg>'; swipe.parentNode.appendChild(swipeNext); swipe.parentNode.appendChild(swipePrev); resetSwipe = function(){ if(mySwipe) { mySwipe.destroy(false,true); mySwipe = undefined; } if (APPLICA.width < 1199) { swipeNav.classList.remove('hide'); } else { swipeNav.classList.add('hide'); } } if (md) { toggleSwipe = function() { resetSwipe(); if (APPLICA.width < 1199) { mySwipe = new Swiper(swipe, { loop: true, autoHeight: true, pagination: { el: swipeNav } }); } } } if (review) { toggleSwipe = function() { if(!mySwipe) { swipePrev.classList.remove('hide'); swipeNext.classList.remove('hide'); mySwipe = new Swiper(swipe, { loop: true, autoHeight: false, slidesPerView: 2, pagination: { el: swipeNav, clickable: true }, navigation: { nextEl: swipeNext, prevEl: swipePrev }, breakpoints: { 1199: { autoHeight: true, slidesPerView: 1 } } }); } } } window.addEventListener("resize", function(){ window.requestAnimationFrame(function(){ if (!resizeTimeout) { resizeTimeout = setTimeout(function() { resizeTimeout = null; if(APPLICA.width != windowWidthOLd){ windowWidthOLd = APPLICA.width; if(toggleSwipe){ toggleSwipe(); } } }, 1000); } }); }); window.addEventListener("load", function(){ if(mySwipe){ mySwipe.update(); } }); if(toggleSwipe){ toggleSwipe(); } }); })(document.querySelectorAll('.swiper-container'));
import { Meteor } from 'meteor/meteor'; import { Mongo } from 'meteor/mongo'; import { check } from 'meteor/check'; /* * 1. We able to get collection module from here. */ export const Warehouses = new Mongo.Collection('warehouses'); /* * 2. Publication of collection will be declared overhere. */ if (Meteor.isServer) { Meteor.publish('warehouses', function warehousesPublication() { return Warehouses.find({}); }); } var getModel = function(){ var warehouse = { id:"", name:"", description:"", //zones:[], createdAt: new Date(), }; return warehouse; }; var checkModel = function(warehouse){ check(warehouse, { id:String, name:String, description:String, //zones:[String], createdAt: Date, }); return true; } /* * 3. Create all database adapter (method) of this collection here. */ Meteor.methods({ /* * Method to find max id from collection. [basic operation] */ 'warehouses.getMaxId' (){ const data = Warehouses.findOne({}, {sort:{id:-1}}); if(data == undefined){ return 0; }else{ return data['id']; } }, /* * Method to insert document into collection. [basic operation] * @param document BSON which need to insert into collection */ 'warehouses.insert' (warehouse) { if(checkModel(warehouse)){ Warehouses.insert(warehouse); } }, /* * Method to remove document from collection. [basic operation] * @param id of document which need to remove from collection */ 'warehouses.remove' (id) { check(id, String); Warehouses.remove({ id:id, }); }, /*'warehouses.addZone' (id, zoneId) { check(id, String); Warehouses.update( { "id" : id }, { $push: { zones: zoneId } } ); }, 'warehouses.removeZone' (id, zoneId) { check(id, String); Warehouses.update( { "id" : id }, { $pop: { zones: zoneId } } ); },*/ /* * Method to check valid document within collection. [basic operation] * @param id of document which need to validate */ 'warehouses.isValid' (id) { check(id, String); if(Warehouses.find({id:id}).count() > 0){ return true; }else{ return false; } }, });
import React from 'react'; import {languageHelper} from '../../../../tool/language-helper'; import {withRouter} from 'react-router-dom'; import PropTypes from 'prop-types'; import { MDBBtn, MDBRow, MDBCol, MDBView, MDBMask, MDBIcon } from 'mdbreact'; import ArticleEditInit from '../articleEditInit'; import classes from './edit.module.css'; import Camera from '../../public/camera.svg'; const basicFont = { fontFamily: 'IBM Plex Sans', fontStyle: 'normal', fontWeight: '600', lineHeight: 'normal', }; class ArticleCreate extends React.Component { constructor(props) { super(props); /* * */ this.state = { backend: null, showPic: false, title:'空标题', write:null, submit:null }; this.text = ArticleCreate.i18n[languageHelper()]; this.handleInputClick = this.handleInputClick.bind(this); this.handleInputChange = this.handleInputChange.bind(this); this.getObjectURL = this.getObjectURL.bind(this); this.deletePic = this.deletePic.bind(this); this.handleSetInput = this.handleSetInput.bind(this); } componentWillMount() { let mockData = { id: 0, status: { code: 2000 } }; const write = this.props.match.params.id !== undefined ? '编辑文章' : '写文章'; const submit = this.props.match.params.id !== undefined ? '提交' : '发布'; this.setState(() => { return { backend: mockData, write, submit }; }); } //todo,和服务器的链接 handleInputChange(e) { // if(e.target.files.length > 1){ // e.target.value = null // e.target.files.unshift() // } // 利用自带方法制造url let imgSrcI = this.getObjectURL(e.target.files[0]); this.setState({ showPic: true }); this.imgUrl.src = imgSrcI; } // 富文本提交 handleInputClick() { //todo,通过refs调用的方法 this.answerText.submitContent(); // this.refs.answerText.submitContent(); } // 删除图片 deletePic(){ this.imgUrl.src = ''; // 避免重复照片不能上传 this.input.value = null; this.setState({ showPic: false }); } // 转化上传文件到url getObjectURL(file) { let url = null; if (window.createObjectURL !== undefined) { // basic url = window.createObjectURL(file); } else if (window.URL !== undefined) { // mozilla(firefox) url = window.URL.createObjectURL(file); } else if (window.webkitURL !== undefined) { // webkit or chrome url = window.webkitURL.createObjectURL(file); } return url; } handleSetInput(e){ // console.log(this.input.current.value) let value = e.target.value; setTimeout(()=>( this.setState({ title:value }) ),100); } render() { return (this.state.backend && this.state.backend.status && this.state.backend.status.code === 2000) ? ( <div> <MDBRow style={{margin: '3.67vw 0'}}> <MDBCol size="1"></MDBCol> <MDBCol size="10" style={{height: '100%'}}> <MDBRow style={{margin: '1.71vw 0px'}}> <MDBCol size="4" style={{paddingLeft:'0',fontSize: '1.87vw',color:'#8D9AAF',verticalAlign: 'middle', ...basicFont}}> {this.state.write} </MDBCol> <MDBCol size="4"> </MDBCol> <MDBCol size="4" style={{paddingRight: '0'}}> <MDBBtn color="indigo" style={{ fontSize: '1.25vw', padding: '0.78vw 2.65vw', margin: '-.39vw 0', float: 'right', ...basicFont }}>{this.state.submit} </MDBBtn> </MDBCol> </MDBRow> <MDBRow> <MDBCol size="12"> <MDBView hover> <div style={this.state.showPic === false ? {display:'none'} : null}> <img ref={(imgInput) => this.imgUrl = imgInput} width="100%" height="auto" src="https://mdbootstrap.com/img/Others/documentation/forest-sm-mini.jpg" className="img-fluid" alt='' /> <MDBMask overlay="grey-light"> <MDBBtn style={{position:'absolute',right:'0',bottom:'0',padding:'.78vw'}} flat onClick={this.deletePic}> <MDBIcon icon="trash" />删除</MDBBtn> </MDBMask> </div> <div style={Object.assign({backgroundColor:'#F2F2F2'},this.state.showPic === true ? {display:'none'} : null)}> <img src={Camera} alt="" style={{fontSize:'1.95vw',width:'3.75vw',height:'3.12vw',position:'absolute',top:'45%',left:'45%',zIndex:'0',}} /> <input ref={(fileInput)=>this.input=fileInput} style={{width:'80vmax',height:'20vmax',opacity:'0'}} type="file" accept="image/*" onChange={(e) => this.handleInputChange(e)} /> </div> </MDBView> </MDBCol> </MDBRow> <MDBRow style={{marginTop:'20px'}}> <MDBCol> <input className={classes.inputStyle} style={{height:'50px'}} onChange={(e)=>this.handleSetInput(e)} placeholder={this.text.title}/> </MDBCol> </MDBRow> <br/> <ArticleEditInit inputData={this.state.title} ref={(answerText) => this.answerText = answerText} /> </MDBCol> <MDBCol size="1"> </MDBCol> </MDBRow> </div> ) : null; } } ArticleCreate.propTypes = { match: PropTypes.object.isRequired, }; ArticleCreate.i18n = [ { title: '请输入文章标题(限50字以内)', submitBtn: '提交文章', write: '写文章' }, { title: 'Title', submitBtn: 'submit article', write: 'write article' }, ]; export default withRouter(ArticleCreate);
const Discord = require("discord.js"); module.exports.run = async (bot, message, args) => { let msg = await message.channel.send("Me he cargado el bot jeje..."); let target = message.mentions.users.first() || message.author; //await message.channel.send("There is " + message.mentions.users.first() + " avatar!"); await message.channel.send({files: [ { attachment: target.displayAvatarURL, name: "wima.png" } ]}); msg.delete(); } module.exports.help = { name: "wima" }
import { Meteor } from 'meteor/meteor'; import { Products } from '../Collections/Products.js'; import { Carts } from '../Collections/Carts.js'; Meteor.startup(() => { // code to run on server at startup }); Meteor.publish('products', function() { return Products.find(); }); Meteor.publish('carts', function() { return Carts.find(); });
/* File that contains help functions for passport interaction. */ var mongoose = require('mongoose'); var user = mongoose.model('User'); var userCtrl = require("../controllers/user"); var passport = require('passport'); exports.localHandler = function(username, password, done){ //console.log(username, password); user.findOne({_id: username}, function(err, user){ //console.log(user); if (err) { return done(err); } //console.log("no err"); if(!user) { console.log("nouser"); return done(null, false, { code: 404, message: 'Incorrect username.'}); } if (!userCtrl.checkCredentials(user, password)){ console.log("bad pass"); return done(null, false, { code: 401, message: 'Incorrect password.' }); } return done(null, user); }); }; passport.serializeUser(function(user, done) { //console.log("serialize"); done(null, user._id); }); passport.deserializeUser(function(id, done) { //console.log("deserialize"); user.findById(id, function(err, user) { //console.log(user); done(err, user); }); });
var IndexPager=require('../views/indexPager'); var database=require('../database'); module.exports=function(req,res){ res.end(new IndexPager(database.list,req.session.isLogined).render()); };
import React from "react"; import AuthSystemWrapp from "../index"; import AuthSystemFormWrapp from "components/Forms/AuthSystemForms/index"; import SignInForm from "components/Forms/AuthSystemForms/SignIn"; const SignUp = (props) => { return ( <AuthSystemWrapp> <AuthSystemFormWrapp title="sign in" subtitle="Since we use many of the same online services" {...props} > <SignInForm {...props} /> </AuthSystemFormWrapp> </AuthSystemWrapp> ); }; export default SignUp;
import BrowserLink from '../widget/browser-link.jsx' import config from '../../app/config' import Persistence from '../../util/persistence.jsx' import React, {PureComponent} from 'react' import {Grid, Image, Icon} from 'semantic-ui-react' export default class Footer extends PureComponent { name = 'Footer' persist = ['visible'] constructor() { super() this.state = Persistence.register(this, { visible: true }) } logotype() { switch (config.vendor) { case 'club-leader': return <Image src="images/logo-leader.png"/> case 'lsproject': return <Image src="images/logo-lsproject.png"/> } } right() { switch (config.vendor) { case 'club-leader': return <p> MLBot Skype разработан для поддержки участников&nbsp; <BrowserLink href="https://club-leader.com/">«CLUB LEADER»</BrowserLink> &nbsp;от компании «BEST CHOICE» </p> case 'inbisoft': return <div> <div>Разрабатываем МЛМ-проекты, программы и сервисы.</div> <BrowserLink href="http://inbisoft.com/magazin/"> <Icon name="shop"/> Магазин </BrowserLink>&nbsp; <BrowserLink href="http://inbisoft.com/kontakty/"> <Icon name="chat"/> Связаться с Inbisoft </BrowserLink> </div> } } render() { const className = (this.state.visible ? 'expanded' : 'collapsed') + ' widget footer' return <footer className={className}> <Grid className="advertise"> <Grid.Row columns={2}> <Grid.Column> {this.logotype()} <Image src="images/logo-inbisoft.png"/> </Grid.Column> <Grid.Column className="logos"> <div className="copyright">&copy; 2017 Все права защищены.</div> <div className="inbisoft"> MLBot принадлежит IT-компании&nbsp; <BrowserLink href="http://inbisoft.com/">«INBISOFT»</BrowserLink>. </div> {this.right()} <BrowserLink href="https://join.skype.com/osF3PAzKHnc9"> <Icon name="skype" size="big"/> Чат Skype-поддержки </BrowserLink> </Grid.Column> </Grid.Row> </Grid> <div className="control"> <Icon name="chevron up" size="large" onClick={() => this.setState({visible: true})}/> <Icon name="close" size="large" onClick={() => this.setState({visible: false})}/> </div> </footer> } }
/** * JSONP request. */ var Promise = require('./promise'); module.exports = function (_, options) { var callback = '_jsonp' + Math.random().toString(36).substr(2), response = {}, script, body; options.params[options.jsonp] = callback; if (_.isFunction(options.beforeSend)) { _.warn('beforeSend has been deprecated in ^0.1.17. ' + 'Use transformRequest instead.' ); options.beforeSend.call(this, {}, options); } return new Promise(function (resolve) { script = document.createElement('script'); script.src = _.url(options); script.type = 'text/javascript'; script.async = true; window[callback] = function (data) { body = data; }; var handler = function (event) { if (event.type === 'load') { delete window[callback]; document.body.removeChild(script); } if (event.type === 'load' && !body) { event.type = 'error'; } switch (event.type) { case 'load': response.status = 200; break; case 'error': response.status = 404; break; default: response.status = 0; } response.ok = event.type === 'load'; response.reject = !response.ok; response.responseText = body ? body : ''; response.header = function () {return null}; resolve(response); }; if (options.timeout) { setTimeout(function () { handler({type: 'timeout'}); }, options.timeout); } script.onload = handler; script.onerror = handler; document.body.appendChild(script); }); };
/* eslint-env mocha */ const extendedEuclidean = require('../../../src').algorithms.math.extendedEuclidean; const assert = require('assert'); describe('Extended Euclidean', () => { it('should check for numbers as 0', () => { assert.deepStrictEqual(extendedEuclidean(35, 0), { gcd: 35, x: 1, y: 0 }); assert.deepStrictEqual(extendedEuclidean(0, 15), { gcd: 15, x: 0, y: 1 }); assert.deepStrictEqual(extendedEuclidean(0, 0), { gcd: 0, x: 0, y: 1 }); }); it('should check extended euclidean values for positive values of a and b', () => { assert.deepStrictEqual(extendedEuclidean(35, 15), { gcd: 5, x: 1, y: -2 }); assert.deepStrictEqual(extendedEuclidean(32, 1), { gcd: 1, x: 0, y: 1 }); assert.deepStrictEqual(extendedEuclidean(1, 32), { gcd: 1, x: 1, y: 0 }); assert.deepStrictEqual(extendedEuclidean(15, 35), { gcd: 5, x: -2, y: 1 }); assert.deepStrictEqual(extendedEuclidean(3, 11), { gcd: 1, x: 4, y: -1 }); }); it('should check extended euclidean values for negative values of a and b', () => { assert.deepStrictEqual(extendedEuclidean(35, -15), { gcd: 5, x: 1, y: 2 }); assert.deepStrictEqual(extendedEuclidean(-35, 15), { gcd: -5, x: 1, y: 2 }); assert.deepStrictEqual(extendedEuclidean(-35, -15), { gcd: -5, x: 1, y: -2 }); }); });
const express = require('express'); const router = express.Router(); const celebritiesController = require('../controllers/celebrities.controller'); router.get('/', celebritiesController.list) router.get('/new', celebritiesController.create) router.post('/new', celebritiesController.doCreate) router.get('/:id', celebritiesController.get) router.post('/:id/delete', celebritiesController.delete) router.get('/:id/edit', celebritiesController.edit) router.post('/:id/edit', celebritiesController.doEdit) module.exports = router;
const mongoose = require('mongoose'); mongoose.Promise = Promise; const dbUri = process.env.DB_URI || 'mongodb://localhost:27017/dbSimsPDX'; module.exports = mongoose.connect(dbUri); mongoose.connection.on('connected', () => { console.log('connected to mongodb !!!'); });
import "./App.css"; import React from "react"; import { SearchTerm } from "../features/searchTerm/SearchTerm"; import { FavoriteRecipes } from "../features/favoriteRecipes/FavoriteRecipes"; import { AllRecipes } from "../features/allRecipes/AllRecipes"; const App = ({ state, dispatch }) => { // Search recipes matching a term const getFilteredRecipes = (recipes, searchTerm) => { return recipes.filter((recipe) => recipe.name.toLowerCase().includes(searchTerm.toLowerCase()) ); }; const visibleAllRecipes = getFilteredRecipes( state.allRecipes, state.searchTerm ); const visibleFavoriteRecipes = getFilteredRecipes( state.favoriteRecipes, state.searchTerm ); return ( <main> <div className="header-container"> <img className="logo" src="img/logo.jpg" alt="" /> <h1> Choose your recipes </h1> </div> <section> <SearchTerm searchTerm={state.searchTerm} dispatch={dispatch} /> </section> <section> <h2>Favorite Recipes</h2> <FavoriteRecipes favoriteRecipes={visibleFavoriteRecipes} dispatch={dispatch} /> </section> <hr /> <section> <h2>All Recipes</h2> <AllRecipes allRecipes={visibleAllRecipes} dispatch={dispatch} /> </section> </main> ); }; export default App;
import magic from '@kuba/magic' function render (node, element) { node.append(element[render.flow]()) } Object.assign(render, { flow: magic.render_flow }) export default render
function Data() { this.comments = [ { id: "1", text: "Great welcoming experience to the Dominican. We used Otium for the airport transport- we were to the resort in 20 minutes. Ralphy has been our concierge for the first half of the stay, he been very helpful- always able to pull through for anything we request", username: "Jake W", imageurl: "https://media-cdn.tripadvisor.com/media/photo-l/01/2e/70/9e/avatar069.jpg", date: "January 2020", point: 11, }, { id: "2", text: "We travelled as a group of 13 ages 18 to 80 and this resort was enjoyed by all. We’ve been fortunate to travel to many resorts in Punta Cana but the Grand was by far the best", username: "Andrea C", imageurl: "https://media-cdn.tripadvisor.com/media/photo-l/01/2e/70/55/avatar028.jpg", date: "Jan 2020", point: 14, }, { id: "3", text: "The Hotel opened 1-1,5 hs ago. Everything is new and very clean. Even the cheapest rooms are very spacious (77square meters and room and dinning area with sofa bed are diivided by a sliding door).", username: "sergiogiaco", imageurl: "https://media-cdn.tripadvisor.com/media/photo-l/01/2e/70/74/avatar056.jpg", date: "Dec 2020", point: 11, }, ]; this.like=(id)=>{ const elIndex = this.comments.findIndex(c=> c.id === id); if (id >= 0){ this.comments[elIndex].point++; } } this.dislike=(id)=>{ const elIndex = this.comments.findIndex(c=> c.id === id); if (id >= 0){ this.comments[elIndex].point--; } } } function Painter(rootElement) { const data = new Data(); const getBuilder = function (tag) { return new ElementBuilder(tag); }; this.render = function () { // const container = document.createElement('div'); // container.style.maxWidth = "800px"; rootElement.innerHTML=""; const container = getBuilder("div") .style("maxWidth", "800px") .appendTo(rootElement) .build(); const createComment=function (comment, index) { const child = getBuilder("div") .style("border", "1px solid blue") .style("width", "100%") .style("height", "100px") .style("tableLayout", "fixed") .style("display", "table") .build(); //create add and delete button const buttonDiv = getBuilder("div").style("float", "right").style("margin", "10px 10px").build(); buttonDiv.display = "table-cell"; //add button const addButton = getBuilder("i").appendTo(buttonDiv).build(); addButton.className="fa fa-thumbs-up"; addButton.addEventListener("click",()=>{ data.like(comment.id); this.render(); }); //point const pointSpan = getBuilder("span").text(comment.point).style("padding", "0px 10px 0px 10px").appendTo(buttonDiv).build(); pointSpan.id = index; //delete button const deleteButton = getBuilder("i").appendTo(buttonDiv).build(); deleteButton.className="fa fa-thumbs-down"; deleteButton.addEventListener("click", () => { data.like(comment.id); this.render(); }); child.appendChild(buttonDiv); //create image const imgDiv = getBuilder("div").style("margin", "25px 25px 25px 25px").build(); imgDiv.display = "table-cell"; const img = document.createElement("img"); img.src = comment.imageurl; imgDiv.appendChild(img); child.appendChild(imgDiv); //create text const span = getBuilder("span").build(); span.display = "table-cell"; span.textContent = comment.text; child.appendChild(span); container.appendChild(child); } data.comments.forEach(createComment.bind(this)); //rootElement.appendChild(container); }; } function ElementBuilder(tag) { this.element = document.createElement(tag); this.text = function (text) { this.element.innerText = text; return this; }; this.style = function (name, value) { this.element.style[name] = value; return this; }; this.appendTo = function (container) { container.appendChild(this.element); return this; }; this.build = function () { return this.element; }; } const container = document.getElementById("root"); const app = new Painter(container); app.render();
// module: services/file-contact-service.js const fs = require('fs'); const path = require('path'); const filename = path.join(__dirname, 'contacts.json'); const requiredFields = ['firstname', 'email', 'phone', 'city']; let data = []; if (fs.existsSync(filename)) { data = JSON.parse(fs.readFileSync(filename, 'utf-8')); } class ContactService { constructor() { } getContactById(id, callbackFn) { if (!callbackFn || typeof callbackFn !== 'function') { throw new Error('callbackFn was not supplied or was not a function'); } setTimeout(() => { // console.log(id); let index = data.findIndex(c => c.id === id); console.log(index); if (index === -1) { let err = { code: 1005, message: 'index does not exist for entered id' }; callbackFn(err); return; } else { callbackFn(null, { ...data[index] }); return; } }, 0); } deleteContact(id, callbackFn) { if (!callbackFn || typeof callbackFn !== 'function') { throw new Error('callbackFn was not supplied or was not a function'); } setTimeout(() => { let index = data.findIndex(c => c.id === id); console.log('index = ', index); if (index === -1) { let err = { code: 1005, message: 'index does not exist for entered id' }; callbackFn(err); return; } else { let cont = data.splice(index, 1); callbackFn(null, cont); return; } }, 0); } updateContact(contact, callbackFn) { //required fields and id field as well if (!callbackFn || typeof callbackFn !== 'function') { throw new Error('callbackFn was not supplied or was not a function'); } setTimeout(()=>{ // console.log(contact.id); if (!contact || typeof contact !== 'object') { let err = { code: 1001, message: 'Contact was not supplied or was not an object!' }; callbackFn(err); // first arg to the callback is an error return; } const missingFields = []; requiredFields.forEach(f => { if (!(f in contact)) { missingFields.push(f); } }); if (missingFields.length) { let err = { code: 1002, message: 'required Fields ' + missingFields.join(', ') + ' missing' }; callbackFn(err); return; } let id = contact.id; let index = data.findIndex(c=> c.id === id); data[index]=contact; // console.log(tempData); callbackFn(null,{...data[index]}); // console.log(tempData); return; },0); } //Patching as in actual update and not replacement // let index = data.findIndex(c=> c.id ===contact.id); // if(index!==-1){ // let tempContact = data[index]; // data[index]={...tempContact,...contact}; // } // Asynchronous getAllContacts(options, callbackFn) { if (!callbackFn || typeof callbackFn !== 'function') { throw new Error('callbackFn was not supplied or was not a function'); } setTimeout(() => { let { pageNum = 1, pageSize = 10, sortBy = 'id', sortOrder = 'asc' } = options; let begin = (pageNum - 1) * pageSize; let end = begin + pageSize; let newData = data.slice(begin, end); callbackFn(null, newData); return; }, 0); } // Synchronous addNewContact(contact, callbackFn) { if (!callbackFn || typeof callbackFn !== 'function') { throw new Error('callbackFn was not supplied or was not a function'); } // to make out function as asynchronous from this point forward, // we use the setTimeout, builtin asynchronopus function with a // delay of 0 setTimeout(() => { if (!contact || typeof contact !== 'object') { let err = { code: 1001, message: 'Contact was not supplied or was not an object!' }; callbackFn(err); // first arg to the callback is an error return; } const missingFields = []; requiredFields.forEach(f => { if (!(f in contact)) { missingFields.push(f); } }); if (missingFields.length) { let err = { code: 1002, message: 'required Fields ' + missingFields.join(', ') + ' missing' }; callbackFn(err); return; } // generate the id if (data.length === 0) { contact.id = 1; } else { contact.id = Math.max(...data.map(c => c.id)) + 1; } // push the data data.push(contact); // write data to the file fs.writeFile(filename, JSON.stringify(data), (err) => { // if (err) throw err; if (err) { callbackFn(err); return; } callbackFn(null, { ...contact }); }); }, 0); } } module.exports = new ContactService();
$(document).ready(function() { $('.tooltip').css('display', 'none') // End-Hide $('#span').click(function() { $('.tooltip').fadeToggle(350) //End fade }) $('#span').mouseenter(function() { $('.tooltip').fadeIn(350) //End fade }) // mouseenter $('.tooltip').mouseleave(function() { $(this).fadeOut(350) //end fade }) //end mouseleave }) //End-Ready
'use strict'; const rootPath = process.cwd(); const multer = require('multer'); var upload = multer(); module.exports = function(app){ app.route('/').get(function(req, res){ res.sendFile(rootPath+'/public/index.html'); }); app.post('/getfilesize', upload.single('file'), function (req, res, next){ if(!req.file) return res.send('No file submitted! Submit a file to view its file size.'); res.json({'fileSize': req.file.size}); }); }
import React from "react"; const Section1 = () => { return ( <div className="container text-center"> <h2 className="text-muted pb-3 nothingCall">Proficiencies</h2> <div className="row"> <div className="col-md-4"> <img src="https://santhisrikh.github.io/images/react.png" alt="" /> <h3 className="text-muted">React App</h3> <p>React JS & Redux</p> </div> <div className="col-md-4"> <img src="https://santhisrikh.github.io/images/data.png" alt="" /> <h3 className="text-muted">Algo & Data Structures</h3> <p>Arrays,Stacks and Queues,Algorithms</p> </div> <div className="col-md-4 mt-2"> <img src="https://santhisrikh.github.io/images/back.png" alt="" /> <h3 className="text-muted">Backend</h3> <p>Node.js, Express, MongoDB</p> </div> </div> </div> ); }; export default Section1;
'use strict'; /** * @ngdoc function * @name cop21App.controller:UpdateCtrl * @description * # UpdateCtrl * Controller of the cop21App */ angular.module('cop21App') .controller('UpdateCtrl', function ($scope) { $scope.awesomeThings = [ 'HTML5 Boilerplate', 'AngularJS', 'Karma' ]; });
$(function() { // getUser(); initButtons(); getPayPeriods("#pp_select"); initAddPayDetails(); initLoadPayrollBtn(); initFunctionBtns(); /* Admin Functions */ initAdminAddUser(); initAdminUpdateUser(); initAddPayPeriod(); initPayrollTabs(); initPendingApprovals(); initAddProject(); var amount = $("#amount_in"); amount.blur(function(e) { var x = $(this).val(); $(this).val(x.replace(",", "")); }); $("#txtRemarks").on('change keyup paste', function() { var txtRemarks = $("#txtRemarks"); var remarksLength = txtRemarks.val().length; var maxLength = 250; if (remarksLength > maxLength) { txtRemarks.val(txtRemarks.val().substring(0, maxLength)); } $("#availableChar").html(250 - txtRemarks.val().length); }); $(document).ajaxStart($.blockUI).ajaxStop($.unblockUI); initDropdownHandlers(); }); jQuery.extend(jQuery.fn, { projects : function(data) { var input = $(this); input.find('option').remove().end(); input.append($('<option>', { value : "", text : "" })) $.each(data, function(i, data) { input.append($('<option>', { value : data.id, text : data.code, "data-manager": data.manager })); }); } }); var format = function(val) { return val.replace('\d+(\.\d{1,2})?') } var initPayrollTabs = function() { $("#tabs").tabs({ activate : function(event, ui) { switch (ui.newPanel.selector) { case "#tabs-4": initLoadPayperiodsAdmin(); initGenerateExcelBtn(); break; case "#tabs-3": loadOpenPeriods(); break; case "#tabs-1": getPayPeriods("#pp_select"); break; case "#tabs-5": getPayPeriods("#pa_select_admin"); break; case "#tabs-6": getAdmins("#project_admin"); getProjects("#project_upd"); getAdmins("#proj_approver"); initUpdateProject(); onChangeUpdateProj(); break; default: $("#updateUser_form")[0].reset(); $("#populate-div").hide(); // tab2 getProjects("#user_project"); getProjects("#user_project_upd"); initDeleteUser(); loadAllUsernames(); } } }); } var onChangeUpdateProj = function(){ $("#project_upd").on("change", function(){ var selected = $(this).find('option:selected'); var curr = selected.data('manager'); $("#curr_approver").val(curr); }) } var loadUserInfo = function(username) { if (username != "-21") { $.ajax({ url : contextPath + "/getUserInfo", type : "POST", data : { 'username' : username }, accept : 'application/json', success : function(data) { $("#empID_user_upd").val(data.empID); $("#lastname_user_upd").val(data.lastName); $("#firstname_user_upd").val(data.firstName); $("#role_user_upd").val(data.roleType.id); $("#user_project_upd").val(data.project.id); $("#populate-div").show(); }, error : function(e) { // //console.log(e); } }); } } var initUpdateProject = function() { // $("#update_project").on("click", function(){ if ($("#project_form_upd").valid()) { $.ajax({ url : contextPath + "/updateProject", type : "POST", accept : 'application/json', data : { 'projectID' : $("#project_upd").val(), 'projectName':$("#project_upd option:selected").text(), 'manager' : $("#proj_approver").val() }, success : function() { showNotify("Project has been updated.") $("#project_form_upd")[0].reset(); }, error : function(e) { showNotify("Update is unsuccessful."); } }); } }) } var loadAllUsernames = function() { $.ajax({ url : contextPath + "/getAllUsernames", type : "POST", accept : 'application/json', success : function(data) { console.log(data) $('#user-autocomplete').typeahead({ source : data, onSelect : function(item) { loadUserInfo(item.value); } }); }, error : function(e) { // //console.log(e); } }); } var getProjects = function(id) { // var select = $(id); $.ajax({ url : contextPath + "/getProjects", type : "POST", accept : 'application/json', success : function(data) { select.projects(data); }, error : function(e) { // console.log(e); } }); } var initDeleteUser = function(){ $("#deleteUser_btn").click(function(){ if (confirm("Delete selected user?")) { $.ajax({ url : contextPath + "/deleteUser", type : "POST", accept : 'application/json', data : { 'ntID' : $("#user-autocomplete").val() }, success : function(data) { showNotify("User has been deleted.") }, error : function(e) { showNotify("Delete is not successful.") // console.log(e); } }); } }); } var initAddProject = function() { $("#add_project_btn").click(function(event) { if ($("#project_form").valid()) { $.ajax({ url : contextPath + "/addProject", type : "POST", accept : 'application/json', data : { 'projectName' : $("#project_name").val(), 'admin' : $("#project_admin").val(), 'process' : $("#process").val() }, success : function(data) { showNotify("Project has been added.") }, error : function(e) { showNotify("The project already exists.") // console.log(e); } }); } }) } var initPendingApprovals = function() { $('#load_pa_admin').click(function(event) { var selectedOption = $('#pa_select_admin option:selected').text(); if (selectedOption == "") { showNotify("Please select a period.") // showNotify("Please select a period."); return; } loadIncomePeriodDetails(2, '#pa_grid'); $('#selectAll_btn').show(); $('#unSelectAll_btn').show(); $('#approve_btn').show(); $('#reject_btn').show(); }); } var loadOpenPeriods = function() { $.ajax({ url : contextPath + "/getOpenPayrolls", type : "POST", accept : 'application/json', success : function(data) { // console.log(data) loadToPayrollGrid(data, "#openPayrollGrid"); }, error : function(e) { // console.log(e); } }); } var loadToPayrollGrid = function(data, tableID) { if ($.fn.dataTable.isDataTable(tableID)) { var table = $(tableID).DataTable(); table.clear(); table.rows.add(data); table.draw(); } else { var table = $(tableID).dataTable({ "data" : data, "columns" : [ { "title" : "Payroll Period", "data" : "period", "class" : "dt-left" }, { "title" : "Status", "class" : "dt-left", "data" : "status" } ] }); $(tableID + ' tbody').on('click', 'tr', function() { if ($(this).hasClass('selected')) { $(this).removeClass('selected'); } else { table.$('tr.selected').removeClass('selected'); $(this).addClass('selected'); } }); $('#close_pperiod_btn').click(function() { var newInstance = $("#openPayrollGrid").DataTable(); var closeMe = newInstance.rows('.selected').data(); if (closeMe.length == 0) { showNotify("Please select a period to close.") } else { if (confirm("Close selected period?")) { var period = closeMe[0].period; $.ajax({ url : contextPath + "/closePayrollPeriod", type : "GET", data : { 'payPeriod' : period }, accept : 'application/json', success : function(data) { newInstance.row('.selected').remove().draw(); }, error : function(e) { // console.log(e); } }); } } }); } } var initGenerateExcelBtn = function() { var payperiod = $("#pp_select_admin"); var generateBtn = $('#generate_btn'); generateBtn.on('click', function() { var dataGrid = $("#report_grid").DataTable(); var size = dataGrid.rows()[0].length; if (size > 0) { window.location = contextPath + "/download.do?payPeriod=" + payperiod.val(); } else { showNotify("No data to generate.") } }); } var initLoadPayrollBtn = function() { var payrollBtn = $('#load_payroll'); payrollBtn.click(function(event) { // add button event onclick for load// $.ajax({ url : contextPath + "/getIncomeTypes", type : "POST", accept : 'application/json', success : function(data) { var incomeTypeInput = $('#income_type'); incomeTypeInput.empty(); incomeTypeInput.append($('<option>', { text : "" })); $.each(data, function(i, data) { incomeTypeInput.append($('<option>', { value : data, text : data })); }); }, error : function(e) { // console.log(e); } }); if (typeof String.prototype.trim !== 'function') { String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); } } loadIncomePeriodDetails(0, '#resultGrid'); var selected = $("#pp_select option:selected").text(); var status = selected.indexOf('Closed'); if (status > 0) { showNotify("Payroll period is already closed.") enableIncomeDetailForm(false); showHideButtonDelete(false); } else { enableIncomeDetailForm(true); showHideButtonDelete(true); } }); $('#income_type').change(function(event) { loadIncomeCodesByType(this.value); changeInputByIncomeType(this.value); $("#full-desc").html(""); }) } var showNotify = function(msg) { $.notify({ // options message : msg }, { // settings type : 'warning', offset : 50, delay : 7000, placement : { from : "top", align : "center" } }); } var enableIncomeDetailForm = function(boolean) { var ids = [ "#income_type", "#income_code", "#amount_in", "#createDt_in", "#txtRemarks" ] $.each(ids, function(i, ids) { $(ids).prop("disabled", !boolean) }); var btnid = [ "#addPay_btn", "#resetPay_btn" ] $.each(btnid, function(i, btnid) { $(btnid).button("option", "disabled", !boolean); }); } var loadIncomePeriodDetails = function(detailLevel, tableID) { var payperiod; switch (detailLevel) { case 0: // regular user payperiod = $("#pp_select").val(); break; case 1: // admin report generate payperiod = $("#pp_select_admin").val(); break; case 2: // admin pending approvals payperiod = $("#pa_select_admin").val(); break; default: } $.ajax({ url : contextPath + "/getIncomeDetails", type : "POST", data : { 'payPeriod' : payperiod, 'detailLevel' : detailLevel }, accept : 'application/json', success : function(data) { paintTable(data, tableID); }, error : function(e) { // console.log(e); } }); } var initAddPayDetails = function() { jQuery.validator.setDefaults({ debug : true, success : "valid" }); $("#addPay_btn").click( function(event) { var incomeDetailsIds = [ "#income_type", "#income_code", "#amount_in", "#txtRemarks", "#createDt_in" ]; var incomeForm = $("#income-form") incomeForm.validate({ rules : { amount_in : { required : true, number : true } } }); if (incomeForm.valid()) { var payperiod = $("#pp_select").val(); var incomeType = $("#income_type").val(); var incomeCode = $("#income_code").val(); var detailValue = isDateEntry == true ? $("#createDt_in") .val() : $("#amount_in").val(); var remarks = $("#txtRemarks").val(); $.ajax({ url : contextPath + "/addPayrollDetails", type : "POST", data : { 'payPeriod' : payperiod, 'incomeType' : incomeType, 'incomeCode' : incomeCode, 'detailValue' : detailValue, 'remarks' : remarks }, accept : 'application/json', success : function(data) { // console.log(data); showNotify("Income detail is saved.") $("#income-form")[0].reset(); loadIncomePeriodDetails(0, '#resultGrid'); }, error : function(e) { showNotify("Income detail was not saved. Please refresh browser.") } }); } event.preventDefault(); }); } var initAddPayPeriod = function() { $("#add_pperiod_btn").click(function(event) { var payPeriodForm = $('#payperiod_form'); payPeriodForm.validate(); if (payPeriodForm.valid()) { var payperiod = $("#payperiod_add").val(); var status = $("#pp_status").val(); $.ajax({ url : contextPath + "/addPayPeriod", type : "POST", data : { 'payPeriod' : payperiod, 'status' : status }, accept : 'application/json', success : function(data) { showNotify("Pay period was added.") $("#payperiod_form")[0].reset(); loadOpenPeriods(); }, error : function(e) { } }); } event.preventDefault(); }); } var initLoadPayperiodsAdmin = function() { getPayPeriods("#pp_select_admin"); $('#load_payroll_admin').click(function(event) { var selectedOption = $('#pp_select_admin option:selected').text(); if (selectedOption == "") { showNotify("Please select a period."); return; } loadIncomePeriodDetails(1, '#report_grid'); $('#generate_btn').show(); }); } var initAdminUpdateUser = function() { $("#updateUser_btn").click(function(event) { var addUserForm = $('#updateUser_form'); addUserForm.validate(); if (addUserForm.valid()) { var username = $("#user-autocomplete").val(); var empID = $("#empID_user_upd").val(); var firstname = $("#firstname_user_upd").val(); var lastname = $("#lastname_user_upd").val(); var role = $("#role_user_upd").val(); var project = $("#user_project_upd").val(); $.ajax({ url : contextPath + "/updateUser", type : "POST", accept : 'application/json', data : { 'ntID' : username, 'empID' : empID, 'firstName' : firstname, 'lastName' : lastname, 'roleId' : role, 'project' : project }, success : function(data) { showNotify("The user is updated.") addUserForm[0].reset(); }, error : function(e) { showNotify("The user update is unsuccessful."); } }); } }); } var initAdminAddUser = function() { $("#addUser_btn").click(function(event) { var addUserForm = $('#addUser_form'); addUserForm.validate(); if (addUserForm.valid()) { var username = $("#uname_user").val(); var empID = $("#empID_user").val(); var firstname = $("#firstname_user").val(); var lastname = $("#lastname_user").val(); var role = $("#role_user").val(); var project = $("#user_project").val(); $.ajax({ url : contextPath + "/addUser", type : "POST", accept : 'application/json', data : { 'ntID' : username, 'empID' : empID, 'firstName' : firstname, 'lastName' : lastname, 'roleId' : role, 'project' : project }, success : function(data) { showNotify("The user is added.") $('#addUser_form')[0].reset(); }, error : function(e) { showNotify("The username is already on the record"); } }); } }); } var getAdmins = function(id) { $.ajax({ url : contextPath + "/getAdmins", type : "POST", accept : 'application/json', success : function(data) { console.log(data); $(id).empty(); $(id).append($('<option>', { value : "", text : "" })) $.each(data, function(i, data) { $(id).append($('<option>', { value : data.networkID, text : data.firstName + " " + data.lastName })); }); }, error : function(e) { // console.log(e); } }); } var getPayPeriods = function(id) { $.ajax({ url : contextPath + "/getPayPeriods", type : "POST", accept : 'application/json', success : function(data) { $(id).empty(); $.each(data, function(i, data) { if (id == "#pp_select") { // if (data.status == "Open") $(id).append($('<option>', { value : data.period, text : data.period + " (" + data.status + ") " })); } else { $(id).append($('<option>', { value : data.period, text : data.period + " (" + data.status + ") " })); } }); }, error : function(e) { // console.log(e); } }); } var isDateEntry; var changeInputByIncomeType = function(incomeType) { if (incomeType == "LWOP") { hideDetailInput("dateSpan"); isDateEntry = true; } else { hideDetailInput("amountSpan"); isDateEntry = false; var amtHrLbl = document.getElementById("amtHrLbl"); if (incomeType == "OT_ND") { amtHrLbl.innerHTML = "Hours"; } else { amtHrLbl.innerHTML = "Amount"; } } } var hideDetailInput = function(id) { if (id == "dateSpan") { $('#amountSpan').hide(); $('#amountSpan').css("display", "none"); $('#dateSpan').show(); $('#dateSpan').css("display", "inline"); } else { $('#dateSpan').hide(); $('#dateSpan').css("display", "none"); $('#amountSpan').show(); $('#amountSpan').css("display", "inline"); } } var loadIncomeCodesByType = function(incomeType) { $.ajax({ url : contextPath + "/getCodesByType", type : "POST", accept : 'application/json', data : { 'incomeType' : incomeType }, success : function(data) { var codeInput = $('#income_code'); codeInput.empty(); codeInput.append($('<option>', { text : "" })); $.each(data, function(i, data) { $('#income_code').append($('<option>', { value : data.id, text : data.desc })); }); $('#income_code').change( function() { var val = this.value; var result = $.grep(data, function(e) { return e.id == val; }); if (val != "" || null != val) { if (result.length != 0) { var fullDesc = null == result[0].fullDesc ? "" : result[0].fullDesc; $("#full-desc").html(fullDesc); } } }); }, error : function(e) { // console.log(e); } }); } var getUser = function() { var network = new ActiveXObject("WScript.Network"); var networkId = network.UserName; var networkId = "asanju3"; $ .ajax({ url : contextPath + "/getUser", type : "POST", accept : 'application/json', data : { "empID" : networkId }, success : function(emp) { // console.log(emp) // $("#fullname").html(emp.firstName + " " + emp.lastName); // $("#empID").html(emp.empID); // $("#ntid").html(emp.networkID); // $("#manager").html(emp.manager); // $("#project").html(emp.project); // $('#load_payroll').button("option", "disabled", false); }, error : function(e) { showNotify("The user is not yet in the database. Please contact administrator."); $('#load_payroll').button("option", "disabled", true); } }); } var initButtons = function() { // $( "#tabs" ).tabs(); $(":button").button(); $(":reset").button(); $('#createDt_in').datepicker({ maxDate : '0' }); $('#payperiod_add').datepicker(); $("#tabs").tabs(); showHideButtonDelete(false); hideDetailInput("amountSpan"); $('#generate_btn').hide(); $('#approve_btn').hide(); $('#reject_btn').hide(); $('#selectAll_btn').hide(); $('#unSelectAll_btn').hide(); } var showHideButtonDelete = function(show) { if (show) { $('#delete_btn').show(); } else { $('#delete_btn').hide(); } } var paintTable = function(oData, tableID) { // console.log(oData) if ($.fn.dataTable.isDataTable(tableID)) { var table = $(tableID).DataTable(); table.clear(); table.rows.add(oData); table.draw(); } else { var table = $(tableID).dataTable( { "data" : oData, "columns" : [ { "title" : "Pay Period", "data" : "payrollPeriod", "class" : "dt-left", "render" : function(obj) { return '<span>' + obj.period.monthOfYear + '/' + obj.period.dayOfMonth + '/' + obj.period.year + '</span>' } }, { "title" : "Type", "class" : "dt-left", "data" : "incomeType.id" }, { "title" : "Description", "class" : "dt-left", "data" : "incomeType.desc" }, { "title" : "Remarks", "class" : "dt-longer", "data" : "remarks", }, { "title" : "Hours/Amount/Date", "class" : "dt-left", "data" : "prodHrsAmt" }, { "title" : "Employee", "class" : "dt-left", "data" : "empId", "render" : function(data){ return data.firstName +" "+data.lastName; } }, { "title" : "Team", "class" : "dt-left", "data" : "empId.project.code" }, { "title" : "Create Date", "class" : "dt-left", "data" : "createDate", "render" : function(obj) { return '<span>' + obj.monthOfYear + '/' + obj.dayOfMonth + '/' + obj.year + '</span>' } }, { "title" : "Approval Status", "class" : "dt-left", "data" : "status" }, { "title" : "Approver", "class" : "dt-left", "data" : "approver" } ] }); $(tableID + ' tbody').on('click', 'tr', function() { if ($(this).hasClass('selected')) { $(this).removeClass('selected'); } else { // table.$('tr.selected').removeClass('selected'); $(this).addClass('selected'); } }); } }; var initFunctionBtns = function() { $('#delete_btn').click(function() { var newInstance = $("#resultGrid").DataTable(); var deletePayIds = newInstance.rows('.selected').data(); if (deletePayIds.length == 0) { showNotify("Please select a row to delete.") } else { if (confirm("Delete selected item?")) { $.each(deletePayIds, function(key, value) { deletePayrollDetail(value["id"]); newInstance.row('.selected').remove().draw(); }); } } }); $('#approve_btn').click(function() { approvePayroll(true); }); $('#reject_btn').click(function() { approvePayroll(false); }); $('#selectAll_btn').click(function() { $('#pa_grid tbody tr').addClass('selected'); }); $('#unSelectAll_btn').click(function() { $('#pa_grid tbody tr').removeClass('selected'); }); } var approvePayroll = function(isApproved) { var newInstance = $("#pa_grid").DataTable(); var approveIDs = newInstance.rows('.selected').data(); var message = ''; if (approveIDs.length != 0) { if (isApproved) { message = "Approve selected item?"; } else { message = "Reject selected item?"; } if (confirm(message)) { $.each(approveIDs, function(key, value) { approvePayrollDetail(value["id"], isApproved); newInstance.row('.selected').remove().draw(); }); } } else { var alertMsg; if (isApproved) { alertMsg = "approve"; } else { alertMsg = "reject"; } showNotify("Please select a row to " + alertMsg + "."); } } var approvePayrollDetail = function(incomeId, isApproved) { $.ajax({ url : contextPath + "/approveIncomeDetail", type : "POST", data : { "incomeID" : incomeId, "isApproved" : isApproved }, accept : 'application/json', success : function(msg) { // console.log(msg) }, error : function(e) { showNotify("Error encountered during detail approval."); } }); } var deletePayrollDetail = function(incomeId) { $.ajax({ url : contextPath + "/deleteIncomeDetail", type : "POST", data : { "incomeID" : incomeId }, accept : 'application/json', success : function(msg) { }, error : function(e) { showNotify("Error encountered. Please refresh browser."); } }); } var initDropdownHandlers = function(){ $("#pp_select").mousedown(onMouseDownHandler); $("#pa_select_admin").mousedown(onMouseDownHandler); $("#pp_select_admin").mousedown(onMouseDownHandler); $("#pa_select_admin").click(onClickHandler); $("#pp_select_admin").click(onClickHandler); $("#pp_select").click(onClickHandler); } function onMouseDownHandler(e){ var el = e.currentTarget; if(el.hasAttribute('size') && el.getAttribute('size') == '1'){ e.preventDefault(); } } function onClickHandler(e) { var el = e.currentTarget; if (el.getAttribute('size') == '1') { el.className += " selectOpen"; el.setAttribute('size', '5'); } else { el.className = ''; el.setAttribute('size', '1'); } }
import { useHistory } from "react-router-dom"; export const GetHistory = () => useHistory();
function setupcharts() { var charts = {} charts.internalline = c3.generate({ bindto: ".internal-line", data: { columns: [ ['rx'].concat(new Array(100).fill(0)), ['tx'].concat(new Array(100).fill(0)), ] }, point: { show: false }, axis: { y: { show: false }, x: { show: false } }, legend: { hide: true }, interaction: {enabled: false}, transition: { duration: 0 }, }); charts.externalline = c3.generate({ bindto: ".external-line", data: { columns: [ ['rx'].concat(new Array(100).fill(0)), ['tx'].concat(new Array(100).fill(0)), ] }, point: { show: false }, axis: { y: { show: false }, x: { show: false } }, legend: { hide: true }, interaction: {enabled: false}, transition: { duration: 0 }, }); return charts; } var ws; function init() { var charts = setupcharts(); websocketuri= "ws://" + window.location.hostname + ":8080/ifstatus"; ws = new WebSocket(websocketuri, "SUPERNET"); ws.onopen = function (event) { console.log("ws connected"); }; ws.onmessage = function (event) { netdata = JSON.parse(event.data); if(!netdata['interfaces'] ||!netdata['interfaces'].length) return; charts.eth1line.load({ columns: [ ['rx'].concat(netdata[eth1]["rx"]), ['tx'].concat(netdata[eth1]["tx"]) ] }); } }
import React from 'react'; import Header from "./Header"; import * as axios from "axios"; import { setUsersDataAC } from "../reducer"; import {connect} from "react-redux"; class HeaderContainer extends React.Component { componentDidMount() { axios.get(`https://social-network.samuraijs.com/api/1.0/auth/me`, {withCredentials: true}) .then(response => { debugger let {id, login, email} = response.data.data if(response.data.resultCode === 0) { this.props.setUsersData(id, login, email) } }) } render() { return ( <Header {...this.props} /> ) } } const mapStateToProps = (state) => { return { isAuth: state.isAuth, login: state.login } } const mapDispatchToProps = (dispatch) => { return { setUsersData: (id, login, email) => { dispatch(setUsersDataAC(id, login, email)) }, } } const AuthHeaderContainer = connect(mapStateToProps, mapDispatchToProps)(HeaderContainer) export default AuthHeaderContainer
const appKey="877057fae069a92c77cd2eeb169c6d46"; var map; var position={ lat:19.0760, // Mumbai: lng:72.8777 //Lat Lng by default. } if(navigator.geolocation){ navigator.geolocation.getCurrentPosition((res)=>{ const pos=res.coords; setPosition(pos); }); } function initMap(){ const box=document.getElementById('map'); map=new google.maps.Map(box,{center:position,zoom:12}); google.maps.event.addListener(map,'click',(event)=>{ var pos=event.latLng.toJSON(); console.log(pos); const wet=new Weather(); wet.getWeatherByLatLng(pos); }) } function setPosition(data){ position.lat=data.latitude; position.lng=data.longitude; const wet=new Weather(); wet.text=`<h1>You are Here.!!!</h1>`; wet.getWeatherByLatLng(position); } function getWeather(){ var inp=document.getElementById("city").value; const wet=new Weather(); wet.getWeatherByCity(inp); } class Weather{ constructor(){ this.city,this.data; this.text=""; this.position={ lat:"", lng:"" } } getWeatherByCity(city){ this.city=city; const url=`https://api.openweathermap.org/data/2.5/weather?&q=${this.city}&units=metric&appid=${appKey}`; fetch(url).then((response)=>{ const data=response.json(); return data; }).then((data)=>{ this.data=data; var {main,weather,name,sys,coord}=this.data; this.position.lat=coord.lat; this.position.lng=coord.lon; var{temp,humidity,pressure}=main; var Des=weather[0].description; const Text=`<h2 style="border-bottom:solid; border-color:grey;">${name}&nbsp,&nbsp${sys.country}</h2> <p style="color:red"><i class="fas fa-temperature-low"></i>&nbspTemperature&nbsp:&nbsp${temp}&degC</p> <p style="color:blue"><i class="fas fa-tint"></i>&nbspHumidity&nbsp:&nbsp${humidity}%</p> <p style="color:#00acee"><i class="fas fa-cloud"></i>&nbspWeather&nbsp:&nbsp${Des}</p> <p style="color:green"><img src="https://cdn1.iconfinder.com/data/icons/power-and-energy-35/64/20-512.png" style="display:inline-block;width:20px;"> Pressure&nbsp:&nbsp${pressure}&nbspmillibar </p>`; this.info=new google.maps.InfoWindow({ content:this.text+Text }) this.mark=new google.maps.Marker({ map:map, position:this.position, draggable:true, animation:google.maps.Animation.DROP }); this.mark.addListener('click',()=>{ if(this.mark.getAnimation()!==null){ this.info.close(map,this.mark); this.mark.setAnimation(null); }else{ this.info.open(map,this.mark); this.mark.setAnimation(google.maps.Animation.BOUNCE); } }); map.panTo(this.position); }).catch((err)=>{ alert(`Something went wrong\n${err}`); }) } getWeatherByLatLng(pos){ this.position=pos; const url=`https://api.openweathermap.org/data/2.5/weather?lat=${this.position.lat}&lon=${this.position.lng}&units=metric&appid=${appKey}`; fetch(url).then((response)=>{ const data=response.json(); return data; }).then((data)=>{ this.data=data; var {main,weather,name,sys}=this.data; var{temp,humidity,pressure}=main; var Des=weather[0].description; const Text=`<h2 style="border-bottom:solid; border-color:grey; padding:2px;">${name}&nbsp,&nbsp${sys.country}</h2> <p style="color:red"><i class="fas fa-temperature-low"></i>&nbspTemperature&nbsp:&nbsp${temp}&degC</p> <p style="color:blue"><i class="fas fa-tint"></i>&nbspHumidity&nbsp:&nbsp${humidity}%</p> <p style="color:#00acee"><i class="fas fa-cloud"></i>&nbspWeather&nbsp:&nbsp${Des}</p> <p style="color:green"><img src="https://cdn1.iconfinder.com/data/icons/power-and-energy-35/64/20-512.png" style="display:inline-block;width:20px;"> Pressure&nbsp:&nbsp${pressure}&nbspmillibar </p>`; this.info=new google.maps.InfoWindow({ content:this.text+Text }) this.mark=new google.maps.Marker({ map:map, position:this.position, draggable:true, animation:google.maps.Animation.DROP }); this.mark.addListener('click',()=>{ if(this.mark.getAnimation()!==null){ this.info.close(map,this.mark); this.mark.setAnimation(null); }else{ this.info.open(map,this.mark); this.mark.setAnimation(google.maps.Animation.BOUNCE); } }); map.panTo(this.position); }).catch((err)=>{ alert(`Something went wrong.\n${err}`); }) } }
var Game = { Char: {}, Equipment: {}, Units: {}, Map: { Data: {} }, ShowingThrobber: 0, rendering: false, Player: {}, Character: {}, DIRECTIONS: { NONE: -1, NORTH: 0, WEST: 1, SOUTH: 2, EAST: 3 }, MAP: { TILES: { SIZE: { X: 64, Y: 64 } }, BUFFER: 12, SCALE: 64 }, LAYERS: { DEEP_BACKGROUND: 0, BACKGROUND: 1, ITEM_SHADOWS: 2, ITEMS: 3, EFFECTS: 4, MONSTER_SHADOWS: 5, MONSTERS: 6, PLAYER_SHADOWS: 7, PLAYERS: 8, WALLS: 9, CEILING: 10 }, Init: function Init(engine){ Game.Engine = engine; setInterval(Game.Tick, 10); Game.showThrobber(); Game.socket.onopen = function(evt){ Game.initGame(); } Game.socket.onclose = Game.disconnected; Game.socket.onmessage = Game.data; Game.socket.onerror = Game.error; $("body").keydown(Game.KeyDown); $("body").keyup(Game.KeyUp); }, disconnected: function(evt){ }, error: function(evt){ }, data: function(evt){ var command = JSON.parse(evt.data); console.log(command); switch (command.task){ case "init": var scene = new Engine.Render.scene(); Engine.renderer.setScene(scene); var camera = new Engine.Render.Camera(new Engine.Utilities.Position()); Engine.renderer.getScene().setCamera(camera); Game.character = Game.createNewCharacter(); Game.character.isPlayer = true; Game.otherCharacters = {}; Game.character.setAction("stand"); Game.character.setMovementSpeed(command.data.player.moveSpeed * Game.MAP.SCALE); Game.character.teleport(command.data.player.pos, Game.MAP.SCALE); Engine.renderer.getScene().addRenderItem(Game.character, Game.LAYERS.PLAYERS); Game.updateMap(command.data.map, Engine.renderer.getScene(), Game.character.pos); Game.hideThrobber(); Game.rendering = true; Game.DoRender(); break; case "move": Game.character.destination.setPos(command.player.destination, Game.MAP.SCALE); console.log(Game.character.destination); Game.character.setMovementSpeed(command.player.moveSpeed * Game.MAP.SCALE); Game.character.action = command.player.action; console.log(Game.character.action); break; case "syncPlayer": Game.character.teleport(command.player.pos, Game.MAP.SCALE); Game.character.setMovementSpeed(command.player.moveSpeed * Game.MAP.SCALE); Game.character.action = command.player.action; Game.resyncMap(); break; case "updateOther": var otherPlayer = command.data.player; console.log(otherPlayer.action); if(otherPlayer.action !== "disconnect" && Game.character.pos.distance(otherPlayer.pos, Game.MAP.SCALE) < Game.MAP.BUFFER * Game.MAP.SCALE){ if(Game.otherCharacters[otherPlayer.id] == null) { Game.otherCharacters[otherPlayer.id] = Game.createCharacter(); Engine.renderer.getScene().addRenderItem(Game.otherCharacters[otherPlayer.id], Game.LAYERS.PLAYERS); } Game.otherCharacters[otherPlayer.id].pos.setPos(otherPlayer.pos, Game.MAP.SCALE); Game.otherCharacters[otherPlayer.id].destination.setPos(otherPlayer.destination, Game.MAP.SCALE); Game.otherCharacters[otherPlayer.id].action = otherPlayer.action; Game.otherCharacters[otherPlayer.id].setMovementSpeed(otherPlayer.moveSpeed * Game.MAP.SCALE); } else { if(Game.otherCharacters[otherPlayer.id] != null) { Engine.renderer.getScene().removeRenderItem(Game.otherCharacters[otherPlayer.id]); delete Game.otherCharacters[otherPlayer.id]; } } break; case "resyncMap": Game.updateMap(command.data.map, Engine.renderer.getScene(), Game.character.pos); break; } }, initGame: function initGame(){ Game.socket.send(JSON.stringify({"task":"init","data":{}})); }, move: function move(direction){ Game.socket.send(JSON.stringify({"task":"move","data": {"direction": direction}})); }, resyncMap: function resyncMap(){ Game.socket.send(JSON.stringify({"task":"resyncMap", "data": {}})); }, Tick: function Tick(){ }, KeyDown: function KeyDown(event){ switch (event.keyCode){ case 87: case 38: Game.move(Game.DIRECTIONS.NORTH); break; case 83: case 40: Game.move(Game.DIRECTIONS.SOUTH); break; case 65: case 37: Game.move(Game.DIRECTIONS.WEST); break; case 68: case 39: Game.move(Game.DIRECTIONS.EAST); break; case 32: Game.character.attack(); break; } }, KeyUp: function KeyUp(event){ }, DoRender: function DoRender(){ if( Game.rendering === true ) { Engine.renderer.render(); requestAnimationFrame(Game.DoRender); } }, showThrobber: function showThrobber() { Game.ShowingThrobber = true; if ( $("#throbber").length === 0 ) { Game.loadTemplate("throbber", function (data) { //in case it loaded too slow, check we still need it if(Game.ShowingThrobber === true) { $('body').append(data); } }); } }, hideThrobber: function hideThrobber() { Game.ShowingThrobber = false; if ( $("#throbber").length > 0 ) { $("#throbber").remove(); } }, loadLogin: function loadLogin() { Game.loadTemplate("login-dialogue", function(data) { $('body').append(data); Game.hideThrobber(); $("#login-form").on('submit', Game.loginSubmit); }); }, loginSubmit: function loginSubmit(event){ var username = $("#username").val(); event.preventDefault(); var playerData = localStorage.getItem("char_" + username); if( playerData !== null ){ Game.Player = JSON.parse(charData); } $("#login-dialogue").remove(); Game.loadCharScreen(); }, createCharacter: function CreateCharacter() { var char = new Game.Character(); char.gear = Game.Char.GearSet.CreateGearSet(); return char; }, createNewCharacter: function CreateNewCharacter() { char = Game.createCharacter(); char.gear.addToGearSet(Game.Equipment.Equipment.CreateEquipment("male_body")); char.gear.addToGearSet(Game.Equipment.Equipment.CreateEquipment("noob_shoes")); char.gear.addToGearSet(Game.Equipment.Equipment.CreateEquipment("noob_pants")); char.gear.addToGearSet(Game.Equipment.Equipment.CreateEquipment("noob_vest")); char.setMovementSpeed(140); return char; }, generateStartingPosition: function generateStartingPosition(){ Game.updateMap(Engine.renderer.getScene(), {x: 0, y:0, z: 0}); return new Engine.Utilities.Position(0, 0); }, updateMap: function updateMap(data){ Engine.renderer.getScene().clearLayer(Game.LAYERS.BACKGROUND); var tiles = []; for(var x in data){ if(typeof tiles[x] === 'undefined'){ tiles[x] = {}; } for(var y in data[x]){ tiles[x][y] = Game.Map.Generator.createTile({ x: x * Game.MAP.TILES.SIZE.X, y: y * Game.MAP.TILES.SIZE.Y }); Engine.renderer.getScene().addRenderItem(tiles[x][y], Game.LAYERS.BACKGROUND); } } Game.Map.Data = tiles; }, characterCreateSubmit: function characterCreateSubmit(event){ }, loadTemplate: function(template, callback){ $.get("/templates/" + template + ".template.html", callback); } };
$.get('data/page2/2-4.csv', function(csv) { $('#container2-4').highcharts({ chart:{ type:'bubble', /* グラフの種類を指定します。bubbleはバブルチャートです。。 */ backgroundColor:'#f5f5f5' }, data:{ csv:csv }, title:{ text:'グラフ2−4' }, xAxis:{ title:{ text : 'A' } }, yAxis:{ title:{ text : 'B' } }, plotOptions:{ bubble:{ tooltip: { headerFormat: '<b>{series.name}</b><br>', pointFormat: 'A:{point.x}, B:{point.y},C:{point.z}' } } }, legend:{ borderWidth:1, borderRadius:1, backgroundColor:'#ffffff' }, credits:{ enabled:false } }); });
import React, { useEffect } from "react"; import { connect } from "react-redux"; import { authorize } from "../store/actions"; import MyProfile from "./MyProfile/MyProfile"; const mapStateToProps = state => ({ login: state.login, passw: state.passw }); const mapDispatchToProps = { authorize }; let MyProfileContainer = props => { const { authorize, login, passw } = { ...props }; useEffect(() => { authorize(login.subscriber.subsIdent, passw); }, [authorize, login.subscriber.subsIdent, passw]); return ( <div> {props.login && <MyProfile login={props.login} path={props.match.path} />} </div> ); }; export default connect(mapStateToProps, mapDispatchToProps)(MyProfileContainer);
import React from 'react'; import s from './SearchPeople.module.css'; import User from '../User/User'; import { getPeople } from '../../../api/peopleApi'; let firstVisit = true; // StrictMode * 2 function onShoWMoreButtonClick(token, showMore, page=1, firstName="", lastName="", country="", city="") { if(page === -1) return; // no more getPeople(token, page, firstName, lastName, country, city) .then((response) => showMore(response.data)); } function SearchPeople(props) { if (props.users.length === 0 && firstVisit) { // TODO - remove, side effects firstVisit = false; onShoWMoreButtonClick(props.token, props.showMore); } let users = props.users.map((user, index) => <User key={index} token={props.token} user={user} addFriend={props.addFriend} removeFriend={props.removeFriend} />); return ( <div className={s.searchPeopleWrapper}> <h2>Search people</h2> { users } <button className={s.showMoreButton} onClick={() => onShoWMoreButtonClick(props.token, props.showMore, props.page)}>Show More</button> </div> ); } export default SearchPeople;
import React from 'react'; import { Field, reduxForm, clearFields } from 'redux-form'; import { validate, validators } from 'validate-redux-form'; import { api } from "api"; import { renderField, renderNumber, AsyncSelectField } from '../Utils/renderField'; import CreateModal from '../Utils/renderField/createModal'; import Modal from '../Utils/Modal/ReactModal'; import CreateForm from '../Fabrica/CreateForm'; import { phone } from '../../../utility/validation'; const ArticuloForm = (props) => { const { handleSubmit, ver, getFabricas } = props; const { stateModal, openModal, closeModal } = props; return ( <form onSubmit={handleSubmit} className="uk-card uk-card-default uk-padding uk-margin-auto"> <div className="uk-child-width-1-2@s uk-grid"> <div> <label>Nombre</label> <Field name="nombre" type="text" component={renderField} className="uk-input uk-border-rounded" disabled={ver} /> </div> <div> <label>Descripcion</label> <Field name="descripcion" type="text" component={renderField} className="uk-input uk-border-rounded" disabled={ver} /> </div> </div> <div className="uk-child-width-1-2@s uk-grid"> <div> <label>Fabrica</label> <div> <Field name="fabrica" type="text" placeholder="Seleccionar..." loadOptions={getFabricas} /* component={CreateModal} */ component={AsyncSelectField} /* className="uk-input uk-border-rounded" */ disabled={ver} /> </div> <div> <button disabled={ver} className="uk-button uk-button-link uk-align-right uk-margin-remove-bottom " onClick={() => openModal()} > + Fabrica </button> </div> </div> <div> <label>Existencia</label> <Field name="existencia" type="text" component={renderField} className="uk-input uk-border-rounded" disabled={ver} /> </div> </div> <br /> <div className="uk-flex uk-flex-center"> <a className="uk-button uk-button-secondary uk-border-rounded uk-button-small uk-flex" href="/#/articulo" etapas={null} > Cancelar <i style={{ marginLeft: "2px" }} className="material-icons">cancel</i> </a> { !ver && ( <button type="submit" className="uk-button uk-button-primary uk-border-rounded uk-button-small uk-margin-small-left uk-flex" > Guardar <i style={{ marginLeft: "2px" }} className="material-icons">save</i> </button> ) } </div> <Modal showModal={stateModal}> <CreateForm isNested closeModal={closeModal} onSubmit={props.funcionRegistro} /> </Modal> </form> ); }; export default reduxForm({ form: 'articuloForm', // a unique identifier for this form validate: (data) => { return validate(data, { nombre: validators.exists()('Este campo es requerido'), existencia: validators.exists()('Este campo es requerido'), descripcion: validators.exists()('Este campo es requerido'), fabrica: validators.exists()('Este campo es requerido'), /* business_lines: validators.exists()('Este campo es requerido'), sales_channel: validators.exists()('Este campo es requerido'), */ }); }, })(ArticuloForm);
const NotFound = () => { return <div> 404 Not Found</div>; }; export default NotFound;
var searchData= [ ['can_5fmsg_5fbuffer_5flist_5ft_88',['can_msg_buffer_list_t',['../structcan__msg__buffer__list__t.html',1,'']]], ['can_5frx_5fmsg_89',['Can_rx_msg',['../structCan__rx__msg.html',1,'']]], ['can_5ftx_5fmsg_90',['Can_tx_msg',['../structCan__tx__msg.html',1,'Can_tx_msg'],['../structcan__tx__msg.html',1,'can_tx_msg']]] ];
import React from 'react'; import { Row, Col, Icon } from 'react-materialize'; import { contactInfoStyles } from './../styles/styles.js'; function ContactInfo(){ return ( <Row> <style jsx>{contactInfoStyles}</style> <Row id="contactspy" className="center"> <Col s={4} m={4} l={4}> <a href="https://www.github.com/LinaShadrach"><img className="contact-icon" src='https://image.flaticon.com/icons/svg/25/25231.svg'></img></a> </Col> <Col s={4} m={4} l={4}> <a href='mailto:lina@epicodus.com'><Icon medium>email</Icon></a> </Col> <Col s={4} m={4} l={4}> <a href="https://www.linkedin.com/in/lina-shadrach/" ><img className="contact-icon" src='https://cdn3.iconfinder.com/data/icons/free-social-icons/67/linkedin_circle_black-512.png'></img></a> </Col> </Row> </Row> ); } export default ContactInfo;
import { Schema } from 'mongoose'; const role = new Schema({ name: String, }); export default role;
"use strict"; var Hapi = require('hapi'); var spark = require('../spark'); /** * Spark.io functions */ module.exports = function(server) { function getLightColor(req, reply) { var lightId = req.params.id; spark.getLightColor(lightId).then(function(data) { reply(data); }, function(error) { server.log(["error", "getLightColor"], error); reply(Hapi.error.internal()); }); } function changeLight(req, reply) { var lightId = req.params.id; var color = req.payload; spark.changeLight(lightId, color).then(function(data) { reply(data); }, function(error) { server.log(["error", "changeLight"], error); reply(Hapi.error.internal()); }); } function randomLight(req, reply) { var lightId = req.params.id; spark.randomLight(lightId).then(function(data) { reply(data); }, function(error) { server.log(["error", "changeLight"], error); reply(Hapi.error.internal()); }); } return [ { method: 'GET', path: '/lights/{id}', config: { handler: getLightColor } }, { method: 'POST', path: '/lights/{id}', config: { handler: changeLight } }, { method: 'POST', path: '/lights/{id}/random', config: { handler: randomLight } } ]; };
import React from 'react'; const GroceryItem = (props) => ( <div className={props.completed ? 'strike groceryItem ' : 'groceryItem'} onClick={props.completeCallback} > <span className = 'col'>{props.groceryItem}</span> <span className = 'col'>{props.groceryQuantity}</span></div> ) export default GroceryItem;
/* CLRS Section 23.3, p. 634 */ class PrimMinPQ { constructor(G, Q = [], length = 0) { this.Q = Q; this.length = length; this.buildMinPQ(G); } // Min PQ Operations // N.B. These approximate the behavior of a min PQ, as by // perfoming a sort with respect to key, the minimum-value key // is always extracted by extractMin(), as in a min PQ. A more // rigorous implementation would involve modifying the class // MinPQ to work with GraphVertexPrim.key values rather than // simple primitive number values. buildMinPQ = (G) => { for (let vertex in G.V) { this.length++; this.Q.push(G.V[vertex]); } this.Q.sort((a, b) => a.key - b.key); } extractMin = () => { this.length--; const u = this.Q.shift(0); this.Q.sort((a, b) => a.key - b.key); return u; } decreaseKey = (v, w) => { const vIndexInQ = this.Q.findIndex(vertex => vertex === v); this.Q[vIndexInQ].key = w; this.Q.sort((a, b) => a.key - b.key); } } // Minor deviation from textbook version, using coloring instead // -- cf. https://home.cse.ust.hk/~dekai/271/notes/L07/L07.pdf // -- cf. https://cs.stackexchange.com/questions/50964/confusion-in-clrss-version-of-prims-algorithm const PrimMST = (G, r) => { for (let u in G.V) { G.V[u].key = Number.POSITIVE_INFINITY; G.V[u].pi = null; G.V[u].color = 'WHITE' } r.key = 0; const Q = new PrimMinPQ(G); while (Q.length !== 0) { const u = Q.extractMin(); const adj = u.adjacentVertices; for (let vertex in adj) { const v = G.V[vertex]; const w = adj[vertex].edge.weight; if((v.color === 'WHITE') && (w < v.key)) { v.pi = u; Q.decreaseKey(v, w) } u.color = 'BLACK' } } } module.exports = { PrimMST }
import React, {Component} from 'react'; import { Provider } from 'react-redux'; import store from './src/store'; import SearchTvShowsView from './src/components/views/SearchTvShowsView'; import TrailerView from './src/components/views/TrailerView'; function WrappedComponent (Component) { return function inject (props) { const EnhancedComponent = () => ( <Provider store={store}> <Component {...props} /> </Provider> ); return <EnhancedComponent />; }; } export const WrappedSearchShows = WrappedComponent(SearchTvShowsView); export const WrappedTrailerView = WrappedComponent(TrailerView);
import React, { Component } from "react"; import { View, Button, Text, Alert } from "react-native"; import TextBox from "./TextBox"; import { TouchableOpacity } from "react-native-gesture-handler"; import { global } from "../style/global"; export default class User extends Component { constructor(props) { super(props); this.state = { noiDungCauHoi: [], valid: false, cauhoi: [ { name: "HoTen", IDCauHoi: 0, TieuDe: "Họ và tên", BatBuoc: true, valid: true, }, { name: "MSNV", IDCauHoi: 1, TieuDe: "Mã số nhân viên", BatBuoc: true, valid: true, }, { name: "Email", IDCauHoi: 2, TieuDe: "Địa chỉ Email", BatBuoc: true, valid: true, }, ], }; } renderUser = () => { return this.state.cauhoi.map((item, index) => ( <TextBox key={index} datatext={this.text} data={item} valid={item.valid} /> )); }; text = (data) => { let noiDungCauHoiUpdate = this.state.noiDungCauHoi; let { cauhoi } = this.state; let i = cauhoi.findIndex((item) => { return item.IDCauHoi == data.IDCauHoi; }); if (i !== -1) { cauhoi[i] = data.CauTraLoi ? { ...cauhoi[i], valid: true } : { ...cauhoi[i], valid: false }; this.setState({ cauhoi }); } let index = this.state.noiDungCauHoi.findIndex((item) => { return item.IDCauHoi == data.IDCauHoi; }); if (index != -1) { noiDungCauHoiUpdate[index] = data; } else { // post noiDungCauHoiUpdate = [...this.state.noiDungCauHoi, data]; } this.setState( { noiDungCauHoi: noiDungCauHoiUpdate, }, () => { this.checktext(); } ); }; checktext = () => { let index = this.state.noiDungCauHoi.findIndex((item) => { return item.CauTraLoi === ""; }); this.setState({ valid: this.state.cauhoi.length === this.state.noiDungCauHoi.length && index === -1, }); }; checkData = () => { let { cauhoi, noiDungCauHoi } = this.state; cauhoi = cauhoi.map((item) => { let index = noiDungCauHoi.findIndex( (i) => item.IDCauHoi == i.IDCauHoi && i.CauTraLoi ); return index !== -1 ? { ...item, valid: true } : { ...item, valid: false }; }); this.setState({ cauhoi, }); }; render() { return ( <View> {this.renderUser()} <View style={global.flex}> <View style={{ width: "45%" }}> <View style={global.btn}> <TouchableOpacity onPress={() => { this.props.navi.navigate("Template"); }} > <Text style={global.btnText}>Quay lại</Text> </TouchableOpacity> </View> </View> <View style={{ width: "45%" }}> {this.props.endpage === 1 ? ( <View style={global.btn}> <TouchableOpacity onPress={() => { if (this.state.valid) { this.props.submitUser(this.state.noiDungCauHoi); this.props.submitData(); } else { Alert.alert("Vui lòng kiểm tra thông tin"); } }} > <Text style={global.btnText}>Hoàn tất</Text> </TouchableOpacity> </View> ) : ( <View style={global.btn}> <TouchableOpacity onPress={() => { if (this.state.valid) { this.props.changePage(2); this.props.submitUser(this.state.noiDungCauHoi); } else { this.checkData(); } }} > <Text style={global.btnText}>Tiếp</Text> </TouchableOpacity> </View> )} </View> </View> </View> ); } }
export default function(app) { console.log(456, app) }
import './calendar.css'; import React, { useState, useEffect, useRef } from 'react' import { connect } from "react-redux" import { Calendar, momentLocalizer } from 'react-big-calendar' import Timer from 'react-compound-timer' import moment from 'moment' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' //import myEventsList from './eventsList' import 'react-big-calendar/lib/css/react-big-calendar.css'; import io from "socket.io-client" import {GetCalendarEvents} from '../use-cases/getEvents' import {AddCalendarEvent} from '../use-cases/addEvent' import {DeleteCalendarEvent} from '../use-cases/deleteEvent' export const MainPage = ({getCalendarEvents, addCalendarEvent, deleteCalendarEvent, event}) => { const localizer = momentLocalizer(moment) const [events, setEvents] = useState([]) const [showModal, setShowModal] = useState(false) const [select, setSelect] = useState(true) const [newEvent, setNewEvent] = useState(false) const [fields, setFields] = useState({}) const [modalContent, setModalContent] = useState({}) const [timer, setTimer] = useState(false) const [yourId, setYourId] = useState(); const [messages, setMessages] = useState([]) const [messageBody, setMessageBody] = useState("") const calendarId = 2 useEffect(() => { getCalendarEvents(calendarId) },[]) //const socket = io.connect('http://localhost:8000') //const socketServer = "http://localhost:8000" /* useEffect(() => { socketRef.current = socketIOClient(socketServer) socketRef.current.on("your Id", id => { setYourId(id) }) socketRef.current.on("message", (message) => { receivedMessage(message) }) }, []) const receivedMessage = (message) => { setMessages(oldMessages => [...oldMessages, message]) } const sendMessage = (e) => { e.preventDefault() const messageObject = { body: messageBody, id: yourId } setMessageBody("") socketRef.current.emit("send message", messageObject) } */ const setField = (evt) => { setFields({ ...fields, [evt.target.name]: evt.target.value }) } console.log(fields) console.log(event) const DisplayEvent = (event) => { setSelect(false) setShowModal(true) setModalContent({ id: event.id, title: event.title, description: event.description }) } const handleSelect = ({ fields, start, end }) => { setNewEvent(true) setFields({ ...fields, "start": start, "end": end }) } return ( <div className="App"> <div> <div className = "timer-container"> <div>Study Timer</div> <Timer initialTime={3600000} direction="backward" startImmediately = {false} > {({ start, pause, reset, getTimerState, getTime }) => ( <div> <div> <Timer.Hours /> hours {" "} <Timer.Minutes /> minutes{" "} <Timer.Seconds /> seconds </div> <br /> <div> <button onClick={start}>Start</button> <button onClick={pause}>Pause</button> <button onClick={reset}>Reset</button> </div> </div> )} </Timer> </div> <div className = "content-container"> {(events.events === null) ? <button type="button" class="bg-rose-600 ..." disabled> <svg class="animate-spin h-5 w-5 mr-3 ..." viewBox="0 0 24 24"> </svg> Processing </button> : <div className="calendar-members-container"> <Calendar className="calendar" selectable={select} defaultView={'week'} localizer={localizer} events={event.events} step={60} onSelectEvent={event => { DisplayEvent(event) console.log(event) }} onSelectSlot={handleSelect} /> <div className = "members-container"> <div className = "members"></div> </div> </div> } <div className = "chatroom-container"> <div className = "room-title"> BIOCHEM STUDY GROUP</div> <div className = "chatlogs"></div> <div className = "message-container"> <input className = "message-body"></input> <div className = "button-container"> <button className = "button-all">Send</button> </div> </div> </div> </div> </div> {newEvent === true ? ( <div className="modal"> <div className="input-content"> <button className = "close-button"onClick={() => { setNewEvent(false) }}>Close</button> <h2>Event Window</h2> <label>Title:</label> <input className="form-inputs" name="title" type="text" value={fields.title} onChange={setField}> </input> <label>Description: </label> <textarea className = "form-textbox" name="description" type="text" rows="5" cols="50" value={fields.description} onChange={setField}> </textarea> <button onClick={() => { {addCalendarEvent(fields)} setNewEvent(false) setFields({}) }}>Add To Calendar</button> </div> <div className="actions"> </div> </div> ) : ( <div></div> )} {showModal === true ? ( <div className="modal"> <div className="content"> <button onClick={() => { {setShowModal(false)} setSelect(true) }}>Close </button> <button onClick = {()=>{ {deleteCalendarEvent(calendarId, modalContent.id)} setShowModal(false) setSelect(true) }}>X</button> <div className = "modal-title">{modalContent.title}</div> Description: {modalContent.description} </div> <div className="actions"> <button className="toggle-button">OK</button> </div> </div> ) : ( <div></div> )} </div> ) } const mapStateToProps = (state, { }) => ({ //user: state.user event: state.events }) const mapDispatchToProps = (dispatch) => ({ getCalendarEvents: GetCalendarEvents(dispatch), addCalendarEvent: AddCalendarEvent(dispatch), deleteCalendarEvent: DeleteCalendarEvent(dispatch) }) export default connect(mapStateToProps, mapDispatchToProps)(MainPage);
/** * Make the following POST request with either axios or node-fetch: POST url: http://ambush-api.inyourarea.co.uk/ambush/intercept BODY: { "url": "https://api.npms.io/v2/search/suggestions?q=react", "method": "GET", "return_payload": true axios.get('https://api.npms.io/v2/search/suggestions?q=react').then(response => response.data).filter(obj => { return obj.b === 6 }); Object.values().filter(function (el) { return el.version == "17.0.2"; }); } ******* The results should have this structure: { "status": 200.0, "location": [ ... ], "from": "CACHE", "content": [ ... ] } ** * With the results from this request, inside "content", count * the number of packages that have a MAJOR semver version * greater than 10.x.x */ var a = -1 var b = 1 var pack = [] var packageCount = 0 var responseObject = {} const axios = require('axios') function CreatePostRequest() { const POST = { method: 'post', url: 'http://ambush-api.inyourarea.co.uk/ambush/intercept', headers: { // Overwrite Axios's automatically set Content-Type 'Content-Type': 'application/json' }, data: { "url": "https://api.npms.io/v2/search/suggestions?q=react", "method": "GET", "return_payload": true } }; const Count = axios(POST).then(function (response) { const Value = response.data.content}); responseObject = axios(POST).then(function (response) { for(let step = 0; step < response.data.content.length - 1; step++){a = a + 1 if (parseInt(response.data.content[a].package.version) > 10) {packageCount = packageCount + 1 }} return packageCount}); return responseObject }; module.exports = async function countMajorVersionsAbove10() { // TODO const count = await CreatePostRequest() return count };
var path = require('path'), webpack = require('webpack'), root = path.resolve(__dirname, './sayll_void'); // 项目目录 var user_config = { entry : { 'main' : path.join(root, './index'), 'common': [],// 公共模块 } , script : ['common', 'main',],// 按顺序引入JS.PS:common公共文件必须放置最前 alias : { // 调用模块使用别名 avalon: 'avalon2', } , externals: { // 文件内部快速调用 //avalon: alias.avalon, }, devServer: { proxy: { // 用于转发api数据 '/api/*': { target: 'http://localhost:8080', secure: false, bypass: function (req, res, proxyOptions) {} } } }, root : root, app_path : { src : path.join(root, './src'), // 引用的资源文件入口 bin : path.join(root, './bin'), // 资源文件入口,生成静态文件的地址 view: path.join(root, './bin'), // 资源文件入口 } , output : { // 输出地址 dist : path.join(root, './build'), css : 'public/css', js : 'public/js', img : 'public/img', font : 'public/fonts', asyn : 'public/asyn_file',// 异步加载文件 link_path: '/', // 输出文件域名:绝对路径!!!http://localhost:8080 } } module.exports = user_config;
import * as React from 'react'; import './index.scss'; const Cell = (props) => { const { cellInfo, flagCell, lostGame, revealAdjacent, revealCell } = props; const getCellValue = () => { if (cellInfo.revealed) { if (cellInfo.isHitMine || cellInfo.value === 'X') { return <span>&#128163;</span> } if (cellInfo.value > 0) { return <span className="number">{cellInfo.value}</span>; } } if (cellInfo.flagged) { return <span className="board-cell__flagged">&#128681;</span> } return ''; } return ( <div className={`board-cell ${cellInfo.revealed && 'board-cell__revealed'} ${cellInfo.isHitMine && 'board-cell__hit-mine'}`} onClick={() => !lostGame && revealCell(cellInfo.x, cellInfo.y)} onDoubleClick={(e) => revealAdjacent(e, cellInfo.x, cellInfo.y)} onContextMenu={(e) => flagCell(e, cellInfo.x, cellInfo.y)} > {getCellValue()} </div> ) } export default Cell;
$(document).ready(function() { var modal3 = $("#myModal3"); var btn3 = document.getElementById('myBtn3'); var span3 = document.getElementsByClassName("close3")[0]; btn3.onclick = function() { modal3.show(); }; span3.onclick = function() { modal3.hide(); }; $(".modal").click(function () { modal3.hide(); }); });
import { shallowMount } from '@vue/test-utils' import PageForm from '@/components/PageForm.vue' import {TestHelper, AjaxHelper, StateHelper} from './../helpers/Helpers.js' let stateHelper = new StateHelper(); let localVue = stateHelper.localVue; describe('PageForm.vue', () => { let wrapper; let ui; let ajaxHelper; let store; beforeEach(() => { store = stateHelper.freshStore(); ajaxHelper = new AjaxHelper(); ajaxHelper.install(); }) afterEach(() => { ajaxHelper.uninstall(); }) it('displays an empty form', () => { bootstrapWrapper({id: '', title: '', body: ''}); ui.seeForm('#pageForm'); ui.see('New page'); ui.seeInput('input[name="title"]', ''); ui.seeInput('textarea[name="body"]', ''); }) it ('displays a filled form if page is provided', () => { bootstrapWrapper(); ui.seeForm('#pageForm'); ui.see('Edit page'); ui.seeInput('input[name="title"]', 'Foo'); ui.seeInput('textarea[name="body"]', 'Bar'); }) it('calls the api when the save button is clicked', (done) => { bootstrapWrapper(); ui.type('input[name="title"]', 'Foobar'); ui.type('textarea[name="body"]', 'Barbaz'); mockSuccessfullRequest(); ui.click('$save'); ajaxHelper.expectAfterRequest(() => { ajaxHelper.expectRequest('/pages/1', { type: '', component: '', title:'Foobar', body: 'Barbaz' }); }, done); }) it ('displays feedback after successful api call', (done) => { bootstrapWrapper(); mockSuccessfullRequest(); ui.notSeeBusFeedback(); ui.click('$save'); ajaxHelper.expectAfterRequest(() => { ui.seeBusFeedback(); }, done); }) it('displays validation errors', (done) => { bootstrapWrapper(); mockRequestWithValidationErrors(); ui.click('$save'); ajaxHelper.expectAfterRequest(() => { ui.see('Title is required'); ui.see('Body is required'); }, done); }) it('triggers an event when the form is submitted', (done) => { bootstrapWrapper(); mockSuccessfullRequest(); ui.notExpectEvent('success'); ui.click('$save'); ajaxHelper.expectAfterRequest(() => { ui.expectEvent('success'); ui.expectEventData('success', [{ id: 12, title: 'Barfoo', body: 'Bazbar' }]); }, done); }) it('does not trigger an event if validation errors are present', (done) => { bootstrapWrapper(); mockRequestWithValidationErrors(); ui.click('$save'); ajaxHelper.expectAfterRequest(() => { ui.notExpectEvent('success'); }, done); }) it('triggers an event when the cancel button is clicked', () => { bootstrapWrapper(); ui.click('$cancel'); ui.expectEvent('cancel'); }) it ('resets the form when the save button is clicked', (done) => { bootstrapWrapper(); mockSuccessfullRequest(); ui.seeInput('input[name="title"]', 'Foo'); ui.seeInput('textarea[name="body"]', 'Bar'); ui.click('$save'); ajaxHelper.expectAfterRequest(() => { ui.seeInput('input[name="title"]', 'Barfoo'); ui.seeInput('textarea[name="body"]', 'Bazbar'); }, done); }) it ('resets the form when the cancel button is clicked', () => { bootstrapWrapper(); ui.seeInput('input[name="title"]', 'Foo'); ui.seeInput('textarea[name="body"]', 'Bar'); ui.type('input[name="title"]', 'Foobar'); ui.type('textarea[name="body"]', 'Barbaz'); ui.seeInput('input[name="title"]', 'Foobar'); ui.seeInput('textarea[name="body"]', 'Barbaz'); ui.click('$cancel'); ui.seeInput('input[name="title"]', 'Foo'); ui.seeInput('textarea[name="body"]', 'Bar'); }) let bootstrapWrapper = (page) => { page = page ? page : {id: '1', title:'Foo', body: 'Bar'}; wrapper = shallowMount(PageForm, { localVue, store, propsData: { dataPage: page, dataEndpoint: '/pages' } }); ui = new TestHelper(wrapper); stateHelper.propagateFeedback(wrapper); } let mockSuccessfullRequest = (record, override) => { record = record ? record : { id: 12, title: 'Barfoo', body: 'Bazbar' }; ajaxHelper.stubRequest( /pages\/\d+/, ajaxHelper.getSuccessfulResponse(record, override) ); } let mockRequestWithValidationErrors = () => { ajaxHelper.stubRequest( /pages\/\d+/, ajaxHelper.getResponseWithValidationErrors({ title: ['Title is required'], body: ['Body is required'] }) ); } })
const {mysql} = require('../qcloud'); module.exports = async ctx => { const {bookid, openid} = ctx.request.query; const mysqlSelect = mysql('comments').select('comments.*', 'cSessionInfo.user_info').join('cSessionInfo', 'comments.openid', 'cSessionInfo.open_id'); let commentList = []; if (bookid) { commentList = await mysqlSelect.where('bookid', bookid); } else if (openid) { commentList = await mysqlSelect.where('openid', openid); } ctx.state.data = { list: commentList.map(v => { v.user_info = JSON.parse(v.user_info); return Object.assign({}, v); }) } };
exports.up = function(knex, Promise) { return knex.schema.table('models', function (table) { table.decimal('ordersFrom'); table.decimal('ordersTo'); table.decimal('conversionRateFrom'); table.decimal('conversionRateTo'); }); }; exports.down = function(knex, Promise) { return knex.schema.table('models', function (table) { table.dropColumn('ordersFrom'); table.dropColumn('ordersTo'); table.dropColumn('conversionRateFrom'); table.dropColumn('conversionRateTo'); }); };
//Ripples js $(home).ripples({ resolution: 512, dropRadius: 15, perturbance: 0.01, });
function Person(name,age) { this.name = name this.age = age } Person.prototype = { constructor:Person, sayName:function () { console.log(this.name) } } var person1 = new Person('yang',20) var person2 = new Person('he',23)
// CANVAS // var canvas; var ctx; // METRICS // var width = 0; var height = 0; var ratio = 1; var scale = 1; var TAU = 2 * Math.PI; //INTERACTION var mouseX = 0; var mouseY = 0; var mousePosition; var mouseIsDown = false; // ECO SYSTEM // var visuals = []; var spores = []; var org1 = []; var org2 = []; var org3 = []; var cull = [1,3,5,7,9,11,13,15,17,19,21,23,25]; //------------------------------------------------------------------------------------------- // INITIALISE //------------------------------------------------------------------------------------------- // this function is called when the page loads function init() { // SETUP CANVAS // canvas = document.getElementById("canvas"); ctx = canvas.getContext("2d"); // SET CANVAS & DRAWING POSITIONS // metrics(); // add canvas event listener // canvas.addEventListener("mousemove", function(event) { // mousePosition.x = event.clientX; // mousePosition.y = event.clientY; // }); setupInteraction(); // INITIALISE AUDIO // setupAudio(); // GENERATE ORGANISMS // // so that generate functions are called when the page loads and organisms and spores are created // generateSpores(55, 0, 0, width, height); generateOrganism1(7, 0, 0, width, height); generateOrganism2(4, 0, 0, width, height); generateOrganism3(3, 0, 0, width, height); // BEGIN // loop(); } //------------------------------------------------------------------------------------------- // GENERATE //------------------------------------------------------------------------------------------- // for loops generate bunch of instances of spores/organisms within the given coordinates, saving them to an array // function generateSpores(n, x1, y1, x2, y2) { for (var i=0; i<n; i++) { spores.push( new Spore(x1, y1, x2, y2) ); } } function generateOrganism1(n, x1, y1, x2, y2) { for (var i=0; i<n; i++) { org1.push( new Organism1(x1, y1, x2, y2) ); } } function generateOrganism2(n, x1, y1, x2, y2) { for (var i=0; i<n; i++) { org2.push( new Organism2(x1, y1, x2, y2) ); } } function generateOrganism3(n, x1, y1, x2, y2) { for (var i=0; i<n; i++) { org3.push( new Organism3(x1, y1, x2, y2) ); } } // create an instance generate function for visual, (update and draw on its instances called below) function generateVisual(position, size) { visuals.push( new Visual(position.x, position.y, size * 2) ); } //------------------------------------------------------------------------------------------- // MAIN LOOP //------------------------------------------------------------------------------------------- function loop() { update(); draw(); requestAnimationFrame(loop); } //------------------------------------------------------------------------------------------- // UPDATE //------------------------------------------------------------------------------------------- function update() { // LOOP THROUGH ALL SPORES AND UPDATE THEIR POSITIONS // // updates the position of every instance of spore before they are drawn for (var i=0; i<spores.length; i++) { spores[i].update(); } // LOOP THROUGH ALL ORGANISM1 AND UPDATE THEIR POSITIONS // for (var i=0; i<org1.length; i++) { org1[i].update(); } // LOOP THROUGH ALL ORGANISM2 AND UPDATE THEIR POSITIONS // for (var i=0; i<org2.length; i++) { org2[i].update(); } // LOOP THROUGH ALL ORGANISM3 AND UPDATE THEIR POSITIONS // for (var i=0; i<org3.length; i++) { org3[i].update(); } // LOOP THROUGH ALL VISUALS AND ANIMATE THEM // for (var i=0; i<visuals.length; i++) { visuals[i].update(); } } //------------------------------------------------------------------------------------------- // DRAW //------------------------------------------------------------------------------------------- function draw() { // FILL BACKGROUND COLOR // ctx.fillStyle = '#111133'; ctx.fillRect(0, 0, width, height); // LOOP THROUGH ALL SPORES AND DRAW THEM // // so once have created instances of spores in an array we want to draw them. draw loop gets called 60 times per second // for (var i=0; i<spores.length; i++) { spores[i].draw(); } // LOOP THROUGH ALL ORGANISM1 AND DRAW THEM // for (var i=0; i<org1.length; i++) { org1[i].draw(); } // LOOP THROUGH ALL ORGANISM2 AND DRAW THEM // for (var i=0; i<org2.length; i++) { org2[i].draw(); } // LOOP THROUGH ALL ORGANISM3 AND DRAW THEM // for (var i=0; i<org3.length; i++) { org3[i].draw(); } // LOOP THROUGH ALL VISUALS AND DRAW THEM // for (var i=0; i<visuals.length; i++) { visuals[i].draw(); } // DRAW TITLE // ctx.fillStyle = 'snow'; ctx.textAlign = 'center'; ctx.font = '400 ' + (35 * scale) + 'px Open Sans'; ctx.fillText('S O N I S P O R E', width/2, height - (70 * scale)); } //------------------------------------------------------------------------------------------- // SCREEN WRAP ORGANISMS //------------------------------------------------------------------------------------------- function screenWrap(instance) { var margin = 50; if (instance.position.x > (width + margin)) { instance.position.x = -margin; instance.wrap(); } if (instance.position.x < -margin) { instance.position.x = width + margin; instance.wrap(); } if (instance.position.y > (height + margin)) { instance.position.y = -margin; instance.wrap(); } if (instance.position.y < -margin) { instance.position.y = height + margin; instance.wrap(); } }
$(document).ready(function() { var mylib = MyLibrary(); var text = $("#someitemtext"); var butt = $(":button"); var prior = $("#priority"); butt.on("click", function() { var txtinput = text.val(); var txt = document.createElement('p'); txt.innerHTML = txtinput; var txt2 = $(txt); var p = prior.val(); if (p == "High") { $('.high').append('<div style="color:red" class="input"><input type="checkbox" name="item" class="item" value="' + txtinput + '" /> '+ txtinput +'</div>'); } if (p == "Medium") { $('.medium').append('<div style="color:orange" class="input"><input type="checkbox" name="item" class="item" value="' + txtinput + '" /> '+ txtinput +'</div>'); } if (p == "Low") { $('.low').append('<div style="color:black" class="input"><input type="checkbox" name="item" class="item" value="' + txtinput + '" /> '+ txtinput +'</div>'); } txt2.css("opacity", 0.0); txt2.animate({ opacity: 1.0 }, 1000, function() {}); text.val(""); }); $(document).on('change', '.item', function() { if( $(this).is(':checked') ){ var parentElem = $(this).parent(); parentElem.remove(); } }); });
export const highlightsDefault = [ { _id:"hl-1503413757154", betweenArray:[], color:"pink", colorCode:"#FF4081", colorHighlight: "#FF80AB", endId:"pr-4", endPos:323, note:"Wow! What a tug!", selectedText:"The strap broke with the single tug", startId:"pr-4", startPos:288, time:"Tue Aug 22 2017 09:55:57 GMT-0500 (CDT)" }, { _id:"hl-1503414638133", betweenArray:["pr-13"], color:"purple", colorCode:"#E040FB", colorHighlight: "#EA80FC", endId:"pr-14", endPos:36, note:"This highlight was auto-generated by a fake data file. Cool huh?", selectedText:"She said, “You a lie!”\nBy that time two or three people passed, stopped, turned to look, and some stood watching.\n“If I turn you loose, will you run?”", startId:"pr-12", startPos:0, time:"Tue Aug 22 2017 10:10:38 GMT-0500 (CDT)" } ]
import { CardData } from "../classes/CardData"; const allCards = [ "C01", "C02", "C03", "C04", "C05", "C06", "C07", "C11", "C12", "C13", "B01", "B02", "B03", "B04", "B05", "B06", "B07", "B11", "B12", "B13", "S01", "S02", "S03", "S04", "S05", "S06", "S07", "S11", "S12", "S13", "D01", "D02", "D03", "D04", "D05", "D06", "D07", "D11", "D12", "D13", ]; function shuffleDeck() { let shuffledDeck = new Array(...allCards); shuffledDeck.sort(() => Math.random() - 0.5); return shuffledDeck; } function dealCards(deck) { let playerHands = new Array(4); for (let i = 0; i < 4; i++) { playerHands[i] = deck.splice(0, 10); } return playerHands; } export const dealNewCards = () => { return dealCards(shuffleDeck()).map((playerHand, index) => { return { name: `Player ${index + 1}`, cards: playerHand.map((card) => CardData.deserialize(card)), }; }); }; function getCalcValue(value) { return value <= 3 ? value : value - 13; } export const getWinnerIndex = (playedCards) => { const ledSuit = playedCards[0].suit; let highestValue = getCalcValue(playedCards[0].value); let winnerIndex = 0; for (let i = 1; i < 4; i++) { if ( playedCards[i].suit == ledSuit && getCalcValue(playedCards[i].value) > highestValue ) { highestValue = getCalcValue(playedCards[i].value); winnerIndex = i; } } return winnerIndex; }; export const calculatePoints = (playedCards) => { let points = 0; for (let i = 0; i < 4; i++) { const value = playedCards[i].value; if (value == 1) points += 3; else if (value <= 3) points += 1; else if (value >= 11) points += 1; } return (points * 1.0) / 3; }; export const chooseCard = (playerHand, playedCards) => { const ledSuit = playedCards[0].suit; if (playerHand.filter((card) => card.suit == ledSuit).length > 0) { const strongestCard = playerHand .filter((card) => card.suit == ledSuit) .sort((a, b) => getCalcValue(a.value) > getCalcValue(b.value)) .pop(); return strongestCard; } else { playerHand = playerHand.sort( (a, b) => getCalcValue(a.value) < getCalcValue(b.value) ); return playerHand.pop(); } };
import React, { useState, useEffect } from "react"; import { useParams } from "react-router-dom"; import Button from '@material-ui/core/Button'; import CardContent from '@material-ui/core/CardContent'; import { Card } from '@material-ui/core'; import ISPIRITHALEI from "../../../assets/2.png"; import { Link } from "react-router-dom"; import "./doctor.css" import PrescriptionDataService from "../../../services/doctorPrescriptionService"; import Pdf from "react-to-pdf"; const ref = React.createRef(); function DoctorPrintPrescription() { const { id } = useParams(); //console.log(id); const [prescription, setPrescription] = useState([]); //get employee details by id const getPrescription = (id) => { PrescriptionDataService .getOnePrescription(id) .then((response) => { setPrescription(response.data); //console.log(response.data); }) .catch((e) => { console.log(e); }); //console.log("name print", employee.firstName); }; useEffect(() => { getPrescription(id); }, [id]); var today = new Date(); var dd = String(today.getDate()).padStart(2, '0'); var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0! var yyyy = today.getFullYear(); today = dd + '/' + mm + '/' + yyyy; return ( <div style={{ marginBottom: 10 }}> <Card> <CardContent> <> <Card style={{ width: "70%", margin: "auto" }}> <div ref={ref}> <CardContent> <div style={{ textAlign: "center" }}> <img src={ISPIRITHALEI} alt="Ispirithalei Logo" /> <p style={{ fontSize: 15 }} >647, Utuwakanda, Mawanella.<br />TEL : +9411 2696 696 / +9411 269 696 <br />FAX : +9411 2696 969<br />EMAIL : reception@ispirithalei.lk</p> </div> <br /> <p style={{ float: "right", fontSize: 15 }}><strong>Issued Doctor ID : </strong>{prescription.dId}</p> <p style={{ fontSize: 15 }}><strong>Date of issue : </strong>{today}</p> <hr /> <br /> <p style={{ textAlign: "center" }}><strong>Patient Name : </strong>{prescription.dPName} &emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; <strong>Diagnosis : </strong>{prescription.dPDignosis}</p> <br /> <hr style={{ width: "80%", margin: "auto" }} /> <br /> <p style={{ textAlign: "center" }}><strong>Medicine 1 : </strong>{prescription.dMed1} &emsp;&emsp;&emsp; <strong>Dose : </strong>{prescription.dDose1}</p> <br /> <p style={{ textAlign: "center" }}><strong>Medicine 2 : </strong>{prescription.dMed2} &emsp;&emsp;&emsp; <strong>Dose : </strong>{prescription.dDose2}</p> <br /> </CardContent> </div> </Card> <div className="buttonAlignMiddle" style={{ marginTop: 10 }}> <Link to={"/staff/doctor/viewprescription/" + prescription.dId}> <Button size="large" variant="contained" style={{ marginRight: 8 }}>Cancel</Button> </Link> <Pdf targetRef={ref} filename={prescription.dPName}> {({ toPdf }) => <Button size="large" variant="contained" color="primary" type="submit" onClick={toPdf}>Generate PDF</Button>} </Pdf> </div> </> </CardContent> </Card> </div> ); } export default DoctorPrintPrescription;
import React from 'react'; import ReactDOM from 'react-dom'; import Enzyme, {mount} from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; Enzyme.configure({ adapter: new Adapter() }); import App from './App'; import InstantPiCamera from './components/InstantPiCamera'; import TempAndHumidity from './components/TempAndHumidity'; it('renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render(<App />, div); ReactDOM.unmountComponentAtNode(div); }); it('is composed with instantPicture component', () => { const mountedApp = mount(<App />); expect(mountedApp.containsMatchingElement(<InstantPiCamera />)).toBe(true); }); it('is composed with TempAndHumidity component', () => { const mountedApp = mount(<App />); expect(mountedApp.containsMatchingElement(<TempAndHumidity />)).toBe(true); });
import React from 'react'; import { shallow, mount } from 'enzyme'; import { Link } from "react-router-dom"; import MockAdapter from 'axios-mock-adapter'; import Login from '../../components/Auth/Login'; describe( "Login Component", () => { const wrapper = shallow(<Login />); it("renders without crashing", () => { shallow(<Login />); }); it("should render login form", () =>{ const title = <h3 className="text-dark text-center font-weight-bold">Login</h3> expect(wrapper.contains(title)).toEqual(true); }); it("should render heading", () =>{ const title_1 = <h2 className="text-light">WeConnect</h2> expect(wrapper.contains(title_1)).toEqual(true); }); it("should render submit", () =>{ const title_1 = <button type="submit" name="submit" id="submit" value="submit" className="btn btn-secondary">Login</button> expect(wrapper.contains(title_1)).toEqual(true); }); it("should render login form text", () =>{ const title_1 = <p className="text-dark text-center" >Have no account? <Link className="btn btn-sm btn-outline-secondary" to="/signup" >SignUp</Link></p> expect(wrapper.contains(title_1)).toEqual(true); }); it("renders email input", () =>{ expect(shallow(<Login />).find("#email").length).toEqual(1); }); it("renders password input", () =>{ expect(shallow(<Login />).find("#password").length).toEqual(1); }); }) // test change on getting input and logs in user describe("Email and password input", () =>{ const wrapper = (shallow (<Login />)); const mock = new MockAdapter(wrapper.instance().xhr); it("should respond to change event ", () =>{ wrapper.find("#email").simulate("change", {target:{name:"email", value:"john@john.com"}}); expect(wrapper.state("email")).toEqual("john@john.com"); }); it("should respond to change event ", () =>{ wrapper.find("#password").simulate("change", {target:{name:"password", value:"john"}}); expect(wrapper.state("password")).toEqual("john"); }); it('login user', () => { mock.onPost('/auth/login').reply(200, {}); wrapper.find("#submit").simulate('submit', { preventDefault: () => {} }); }); })
const User = require('../models/user') const verify = async (req, res, next)=>{ try { const user = await User.findOne({name:req.body.name, designation:req.body.designation}) if(user){ return res.send(user._id) } next() } catch (error) { res.status(400).send() } } module.exports = verify
// pages/report/2020/steps/main.js Page({data: {}})
export default function debug (strings, ...values) { return strings .reduce((memo, string, index) => { memo.push(string); memo.push((values[index] || '').toString()); return memo; }, []) .join(''); }
const path = require('path') const webpack = require('webpack') const HtmlWebpackPlugin = require('html-webpack-plugin') const UglifyJsPlugin = require('uglifyjs-webpack-plugin') const TerserPlugin = require('terser-webpack-plugin') const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer') const fs = require('fs') // I need to find out if the electron app makes some sort of npm install in order to function const externals = fs.readdirSync(path.resolve(__dirname, 'node_modules')) .reduce((externals, mod) => { externals[mod] = `commonjs ${mod}` return externals }, {}) const webpackConfig = { externals, mode: 'production', target: 'electron-renderer', node: { __dirname: false, __filename: false }, entry: { bundle: [ 'react-hot-loader/patch', path.join(__dirname, 'src') ] }, output: { filename: '[name].[hash].js' }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader' } } ] }, optimization: { minimizer: [ new TerserPlugin({ terserOptions: { compress: { warnings: false, comparisons: false }, output: { comments: false, ascii_only: true }, paralell: true, cache: true, sourceMap: true } }) ] }, plugins: [ new HtmlWebpackPlugin({ template: path.join(__dirname, 'template.html') }), new webpack.EnvironmentPlugin({ NODE_ENV: 'production' }) ] } if (process.env.ANALYZE) { webpackConfig.plugins.push(new BundleAnalyzerPlugin({ analyzerHo7st: '7001' })) } module.exports = webpackConfig
var chatView = (function($){ var addMessage = function(data){ var content = $('.messages'); var template = '<li data-id="' + data.id + '"><div class="msg">' + data.message + '</div><div class="tick"></div><div class="doubletick"></div></li>'; content.append(template); }; var receiveMessage = function(data){ var content = $('.messages'); var template = '<li class="other" data-id="' + data.id + '"><div class="msg">' + data.message + '</div></li>'; content.append(template); }; var addWelcomeMessage = function(data) { var content = $('.messages'); var template = '<li class="welcome">' + data.message + '</li>'; content.append(template); }; var getInputValue = function(data){ return $('#message').val(); }; var cleanInput = function(){ $('#message').val(''); }; var markAsSent = function(id){ $('li[data-id="' + id + '"] .tick').css('display', 'inline-block'); }; return { addMessage : addMessage, receiveMessage : receiveMessage, addWelcomeMessage : addWelcomeMessage, getInputValue : getInputValue, cleanInput : cleanInput, markAsSent: markAsSent } })($);
import React from "react"; import MovieCards from "./MovieCards"; import Moviecards2 from "./Moviecards2"; import { useState } from "react"; const Barre = (props) => { const [film, setFilm] = useState(""); return ( <div> <input onChange={(e) => { setFilm(e.target.value); }} /> <button onClick={(e) => {}}>recherche</button> </div> ); }; export default Barre;
import React, { useEffect, useState, useCallback } from "react"; import { useAppState } from "../AppState"; import uniq from "lodash/uniq"; import debounce from "lodash/debounce"; let currentNotes = []; let midiInputs; const ProvideMidi = ({ children }) => { const { midi } = useAppState("config"); const { setSelectedNotes } = useAppState("keyboard"); const [alreadyInitialised, setAlreadyInitialised] = useState(false); const throttleSetSelectedNotes = debounce(n => { setSelectedNotes(n); }, 400); const addNote = useCallback( noteId => { const t = new Date().getTime(); currentNotes = currentNotes.filter(v => { return t - v.t < 400; }); currentNotes.push({ t, noteId }); const sortedNotes = currentNotes.map(x => x.noteId); const uniqueNotes = uniq(sortedNotes); throttleSetSelectedNotes(uniqueNotes.sort()); }, [throttleSetSelectedNotes] ); const midiHandler = useCallback( m => { const command = m.data[0]; const note = m.data[1]; const velocity = m.data.length > 2 ? m.data[2] : 0; // a velocity value might not be included with a noteOff command if (velocity > 0 && command > 0) { addNote(note); } }, [addNote] ); useEffect(() => { if (midi === true) { if (alreadyInitialised === false) { navigator.requestMIDIAccess().then(function(access) { midiInputs = access.inputs; for (const input of midiInputs.values()) { input.onmidimessage = midiHandler; } setAlreadyInitialised(true); }); } } else { // turn off everything if (alreadyInitialised) { for (const input of midiInputs.values()) { input.onmidimessage = () => {}; } setAlreadyInitialised(false); } } }, [midi, midiHandler, alreadyInitialised]); return <>{children}</>; }; export default ProvideMidi;
import axios from 'axios' export function fetchProjects(){ return function(dispatch){ axios.get('http://localhost:8080/api/getprojects').then((response)=>{ dispatch({type:"FETCH_PROJECTS",payload:response.data.data}) }) } } export function closeModal(item){ return function(dispatch){ dispatch({type:"CLOSE_MODAL",payload:item}) } } export function openModal(item){ return function(dispatch){ dispatch({type:"OPEN_MODAL",payload:item}) } } export function editOpenModal(item){ return function(dispatch){ dispatch({type:"EDIT_OPEN_MODAL",payload:item}) } } export function updateProject(item){ return function(dispatch){ axios.put('http://localhost:8080/api/updateproject/'+item._id,item).then((response)=>{ dispatch({type:"UPDATE_PROJECT",payload:item}) }) } } export function addProject(item){ return function(dispatch){ axios.post('http://localhost:8080/api/addproject/',item).then((response)=>{ dispatch({type:"ADD_PROJECT",payload:response.data.data}) }) } } export function deleteProject(item){ return function(dispatch){ axios.delete('http://localhost:8080/api/removeproject/'+item).then((response)=>{ dispatch({type:"DELETE_PROJECT",payload:item}) }) } }
var express = require('express'), app = express(), socket = require('socket.io'), path = require('path'), hbs = require('express-handlebars'), bodyparser = require('body-parser'), pg = require('pg'), Handlebars = require('handlebars'), expressValidator = require('express-validator'), expressSession = require('express-session'), cookieParser = require('cookie-parser'), passport = require('passport'), pool = require('./controllers/db_connection'); localStrategy = require('passport-local').Strategy, PostgreSqlStore = require('connect-pg-simple')(expressSession); //server var server = app.listen(8080,function(){ console.log("server on port 8080" ); }); //Set public folder app.use(express.static('routes')); app.use(express.static(path.join(__dirname,'assets'))); app.use('/assetsFiles',express.static(__dirname + '/assets')); //Body parser Middleware app.use(bodyparser.json()); app.use(bodyparser.urlencoded({extended: false})); //session app.use(expressValidator()); app.use(cookieParser()); app.use(expressSession({ secret:'dolores', saveUninitialized: true, resave:false, store: new PostgreSqlStore({ pool : pool, // Connection pool tableName : 'session' // Use another table-name than the default "session" one }), })); //passport app.use(passport.initialize()); app.use(passport.session()); //Active menu app.use(function (req, res, next) { switch (req.path) { case '/': res.locals.active_home = 'active'; break; case '/home': res.locals.active_home = 'active'; break; default: res.locals.active_home = ''; } switch (req.path) { case '/wall/': res.locals.active_wall= 'active'; break; default: res.locals.active_wall = ''; } switch (req.path) { case '/forum': res.locals.active_forum= 'active'; break; default: res.locals.active_forum = ''; } switch (req.path) { case '/gallery': res.locals.active_gallery= 'active'; break; default: res.locals.active_gallery = ''; } switch (req.path) { case '/sign-in': res.locals.active_login= 'active'; break; default: res.locals.active_login = ''; } next(); }); app.set('views',path.join(__dirname,"views")); app.engine('handlebars',hbs({defaultLayout:'main'})); app.set('view engine','handlebars'); app.use('/assetsFiles',express.static(__dirname + '/assets')); var io = socket(server); app.set('socketio', io); //routes var users = require('./routes/users'); var register = require('./routes/register'); var wall = require('./routes/wall/wall'); var home = require('./routes/home'); var forum = require('./routes/forum/forum'); var gallery = require('./routes/gallery/gallery'); var login = require('./routes/login/login'); //routes admin var admin_wall = require('./routes/admin/admin_wall/admin_wall'); //exports functions // var wall = require('./controllers/wall'); //app js ext. app.use('/sign-up',register); app.use('/users',users); app.use('/wall',wall); app.use('/',home); app.use('/forum',forum); app.use('/gallery',gallery); app.use('/sign-in',login); //app js ext. for admin app.use('/admin/wall',admin_wall); passport.use(new localStrategy( function(username,password,done){ pool.connect(function(err,client,done_query){ if(err){ console.error("Error :",err); }else{ client.query( "Select id FROM users Where username = '"+username+"' AND password = '"+password+"'", function(err,result){ if(err){ return console.error('error running query',err); }else{ var user_id = result.rows[0]['id']; done_query(); return done(null,{user_id:user_id,logged:true}); } }); } }); } )); passport.serializeUser(function(user_id,done){ done(null,user_id); }); passport.deserializeUser(function(user_id,done){ done(null,user_id) }); /* //my socket io var io = socket(server); var socket_connections = []; io.sockets.on('connection',function(socket){ socket_connections.push(socket); // console.log("socket connect success !",socket_connections.length); //disconnect socket socket.on('disconnect',function(data){ socket_connections.splice(socket_connections.indexOf(socket),1); // console.log("socket connect success !",socket_connections.length); }); socket.on("send message",function(data){ // console.log(data); pool.connect(function(err,client,done) { if (err) { return console.error('error', err); } else { client.query("Select * from posts where id = '34'",function(err,result){ done(); if(err){ console.log("error in posts_images",err); }else{ console.log(result.rows); // res.redirect('/admin/wall'); } }); } }); // io.sockets.emit("new message",{msg:data}); }); });*/
// no rigid, only soft bodies!!! class Collider2D { // hollow colliders as cavity points??? like points[point[x,y]] then cavities[cavity[points[point[x,y]]]] constructor(pts = f.geometry.shape.square(),circles = [], rigidbody = null) { this.rigidbody = rigidbody; // points can either be outer points as in pts[point[x,y]] or shapes[pts[point[x,y]] , ... cavities] if(!Array.isArray( pts[0][0] )){ this.pts = pts; this.cavities = []; } else { this.pts = pts[0]; this.pts.splice(0,1); this.cavities = pts; } this.circles = circles; this.nextVx = vx; this.nextVy = vy; this.area = this.setArea(); this.volume = this.setVolume(); this.maxColliderDist = this.calculateMaxColliderDist(); this.relativeCenterOfMass = this.calculateRelativeCenterOfMass(); this.integralDistanceSquared = this.calculateIntegralDistanceSquared(); this._electricCenterOfMass = null; } get electricCenterOfMass(){ return (_electricCenterOfMass == null)? this.com:this._electricCenterOfMass; } set electricCenterOfMass(v){ this._electricCenterOfMass = v;} get rcom(){ return this.relativeCenterOfMass;} get com(){ return this.centerOfMass;} get centerOfMass(){ return f.subtract(f.rotate(this.relativeCenterOfMass, this.transform.theta) ,this.transform.pos); } calculateRelativeCenterOfMass(){ // Unfinished return [0,0]; } setArea () { this.area = ? return 5; } get vol(){return this.volume()} setVolume () { this.volume = ? return 5; } collide(obj){ if(this.contains(obj)){ // elasticCollision // or inelastic collision with heat & friction incorporated into it // change nextVelocity & not current velocity } } calculateRelativeCenterOfMass(){ // and apply to whole class } calculateCenterOfMass(){ } calculateIntegralDistanceSquared(){ // inertia = mass * IntegralDistanceSquared // from com } claculateMaxColliderDist(){ let maxColliderDist = 0; for (circle in this.circles){ if(f.v.mag(circle) + circle[2] > maxColliderDist){ maxColliderDist = f.v.mag(circle) + circle[2]; } } for (point in this.points){ if(f.v.mag(point) > maxColliderDist){ maxColliderDist = f.v.mag(point); } } this.maxColliderDist = maxColliderDist; return maxColliderDist; } quickContains(obj){ return (this.maxColliderDist + obj.maxColliderDist > f.v.mag(f.v.subtract(obj.pos, this.pos))); } // contains for cavities as well containsPoint(pos){ for (circle in this.circles){ if (f.v.mag(f.v.difference(f.v.add(this.pos,[circle[0], circle[1]]), pos)) < circle[2]){ return true; } } // check if in poly let intersections = 0; for (let i = 0; i < this.points.length; i++){ let pt1 = f.v.rotate(this.points[i],this.theta); let pt2 = f.v.rotate(this.points[(i < this.points.length - 1)? i + 1: pts - this.points.length],this.theta); if(f.geometry.lineContainsPoint(pt1,pt2,pos,true)){ intersections++; } } if(intersections >= 1){ intersections = 0; for (let i = 0; i < this.points.length; i++){ let pt1 = f.v.rotate(this.points[i],this.theta); let pt2 = f.v.rotate(this.points[(i < this.points.length - 1)? i + 1: pts - this.points.length],this.theta); if(f.geometry.lineContainsPoint(pt1,pt2,pos,false)){ intersections++; } } } else return false; return intersections >= 1; // 1 for strict edge inclusion, 2 for not included } inside(obj){ return this.containsPoint(obj.pos) || obj.containsPoint(this.pos); // checks if obj is completely inside this } contains(obj, mode = false){ // need to check for circle collisions if(!this.quickContains(obj)){ // optimization return false; } /* cheater method: don't use if(this.inside(obj) || obj.inside(this)){ return true; }*/ // check line:line if(mode){ // by checking point enclosure for(let i = 0; i < obj.points.length; i++){ if(this.containsPoint(obj.worldPoint(obj.points[i]))){ return true; } } if(!bool){ for(let i = 0; i < this.points.length; i++){ if(obj.containsPoint(this.worldPoint(this.points[i]))){ return true; } } } } else { // by checking line intersections for(let i = 0; i < this.points.length; i++){ let i2 = (i < this.points.length - 1)? i + 1: i - this.points.length; for(let e = 0; i < this.points.length; e++){ let e2 = (i < obj.points.length - 1)? e + 1: e - obj.points.length; if(f.geometry.lineIntersects(this.worldPoint(this.points[i]), this.worldPoint(this.points[i2]), obj.worldPoint(obj.points[e]),obj.worldPoint(obj.points[e2]))){ return true; } } } } // check circle:circle for(let i = 0; i < this.circles.length; i++){ for(let c = 0; c < obj.circles.length; c++){ if(f.geometry.circleIntersectsCircle(obj.worldCircle(i), this.worldCircle(c))){ return true; } } } for(let i = 0; i < obj.circles.length; i++){ for(let c = 0; c < this.circles.length; c++){ if(f.geometry.circleIntersectsCircle(this.worldCircle(i), obj.worldCircle(c))){ return true; } } } // check circle:line for(let i = 0; i < this.points.length; i++){ let i2 = (i < this.points.length - 1)? i + 1: i - this.points.length; for(let c = 0; c < obj.circles.length; c++){ if(f.geometry.circleIntersectsLine(this.worldPoint[i],this.worldPoint[i2],obj.worldCircle[c])){ return true; } } } for(let i = 0; i < obj.points.length; i++){ let i2 = (i < obj.points.length - 1)? i + 1: i - obj.points.length; for(let c = 0; c < this.circles.length; c++){ if(f.geometry.circleIntersectsLine(obj.worldPoint[i],obj.worldPoint[i2],this.worldCircle[c])){ return true; } } } return false; } get area(){ return 5; // area of points - area of cavities inside points } worldCircle(c){ if(typeof pt == Number){ // pt not defined c = this.circles[c]; } let tmp = this.worldPoint(c); return [tmp[0],tmp[1],c[2]]; } toWorldCircle(c){ return this.worldCircle(c); } get volume(){ return Math.PI * (4/3) * Math.power(this.r, 3);} get r(){ return Math.sqrt(this.area / Math.PI);} // imaginary + auxiliary radius formation get radius(){ return Math.sqrt(this.area / Math.PI);} get A(){ return this.area;} get sa(){ return this.A; } get surfaceArea(){ return this.sa;} get frontSurfaceArea(){ return this.sa;} // for wind resistenc f(v) get m(){ return this.density * this.volume;} update(){ this.vx = this.nextVx; this.vy = this.nextVy; super.update(); } postUpdate(gw = null,gh=null){ // polish super.update(); // standard discrete updates if(gh != null && gw != null){ f.setInBox(this,w,h); } } draw (display) { // draw // let ctx = display.ctx; display.drawCircle(this.x + (.5 * this.r),this.y + (.5 * this.r),this.r); } } class SmoothBodyCollider extends Collider2D { // elasticity between 2 connected points (angle and dist) constructor(x = 0, y = 0, vx = 0, vy = 0, theta = 0, av = 0, pts = f.geometry.shape.square(), circles = [], density = 1, springConstant = .5, rotationalSpringConstant = springConstant) { super(x, y, vx, vy, theta, av, pts, circles, density); } //points are rigidbodies with spring joints } class JointedBodyCollider extends Collider2D { // elasticity between 2 connected points (angles only) dist is approx. constant constructor(x = 0, y = 0, vx = 0, vy = 0, theta = 0, av = 0, pts = f.geometry.shape.square(), circles = [], density = 1, springConstant = .5, rotationalSpringConstant = springConstant) { super(x, y, vx, vy, theta, av, pts, circles, density); } //points are rigidbodies with spring joints } // pressure on edge distributed to surrounding points class SoftBodyCollider extends Collider2D { // elasticity between point & pos constructor(x = 0, y = 0, vx = 0, vy = 0, theta = 0, av = 0, pts = f.geometry.shape.square(), circles = [], density = 1, springConstant = .5) { super(x, y, vx, vy, theta, av, pts, circles, density); } //points are rigidbodies with spring joints } class RigidBodyCollider extends Collider2D { // adds material properties: ex: bounciness via// inelastic collisions constructor(x = 0, y = 0, vx = 0, vy = 0, theta = 0, av = 0, pts = f.geometry.shape.square(), circles = [], density = 1, bounciness = 0) { super(x, y, vx, vy, theta, av, pts, circles, density); } // add collision bounciness }
../../../../../shared/src/App/Home/actions.js
//Controle das abas de Cadastro $('#inserir_transportadora').click(function () { $("#tabs_transportadora").tabs(); });
import React from 'react'; import createAbsoluteGrid from 'react-absolute-grid'; import Card from './Card'; import './Gallery.css' // Pass your display component to create a new grid const AbsoluteGrid = createAbsoluteGrid(Card); class Gallery extends React.Component { constructor(props) { super(props); } render(){ const {data} = this.props return ( <div className="gallery"> <AbsoluteGrid items={data} dragEnabled={false} responsive={true} verticalMargin={42} itemWidth={400} itemHeight={200}/> </div> ) } } export default Gallery
const express = require("express"); const db = require("../../models/index"); const { countries,userLanguages } = require("../../constants"); const mail = require('../../utils/mail'); var auth = require('../../utils/authentication'); var moment = require('moment-timezone'); const router = express.Router(); const User = db.user; const Company = db.company; const Login = db.login; const Department = db.department; const DepartmentUserAccess = db.department_user_access; // Update Detail router.post("/companyMoveUp", async (req, res) => { try { console.log("===================================="); console.log("req.body:", req.body); console.log("===================================="); let response_arr = []; const {companyId, oldCompanyId, userId} = req.body; if (!userId || !companyId) { let errorMsg = !userId ? 'User required!' : 'Company required!'; return res .status(200) .json({ success: false, msg: errorMsg }); } // Replace Company Id await User.update({companyId}, { where: { id:userId, companyId:oldCompanyId }, }); // Fetch Old Company's Department Connected With User let getDepartmentList = await db.sequelize.query( `SELECT * FROM (SELECT department_user_access.userId AS dua_userId, department_user_access.departmentId AS dua_departmentId, department.id AS departmentId,department.name AS departmentName, company.id AS companyId FROM department_user_access INNER JOIN department ON department.id = department_user_access.departmentId INNER JOIN company ON company.id = department.companyId) AS TEMP WHERE companyId = '${oldCompanyId}' AND dua_userId = '${userId}'`, { type: db.sequelize.QueryTypes.SELECT } ); // Add Department to New Company and Connect Dept with User for (const dept of getDepartmentList) { const {departmentId} = dept; await Department.update({companyId}, { where: { id:departmentId, companyId:oldCompanyId }, }); } return res .status(200) .json({ success: true, msg: "Data update done.", response_arr }); } catch (error) { return res.status(400).json({ success: false, msg: error.message }); } }); module.exports = router;
/** * Created by chrisgregory on 6/13/17. */
const DirectoryMapper = require("./SequelizeDirectoryMapper"); const fs = require("fs"); const path = require("path"); class SequelizeDirectoriesRepository { constructor({ DirectoryModel }) { this.DirectoryModel = DirectoryModel; } async findOne(...args) { const data = await this.DirectoryModel.findOne(...args); let entity = null; if (data) { entity = DirectoryMapper.toEntity(data); } return entity; } async getAll(...args) { const list = await this.DirectoryModel.findAll({ ...args }); const listEntity = list.map(DirectoryMapper.toEntity); return listEntity; } async getById(id) { const data = await this._getById(id); return DirectoryMapper.toEntity(data); } async add(data) { const { valid, errors } = data.validate(); if (!valid) { const error = new Error("ValidationError"); error.details = errors; throw error; } let newItem = null; try { const { name, parent } = data; let dir = null; let srcPath = null; if (parent) { await this.getById(parent).then(parentDirectory => { srcPath = parentDirectory.path + "/" + name; dir = path.resolve(srcPath); }); } else { srcPath = "uploads/" + name; dir = path.resolve(srcPath); } newItem = await this.DirectoryModel.create({ ...DirectoryMapper.toDatabase(data), path: srcPath }); if (!fs.existsSync(dir)) { fs.mkdirSync(dir); } } catch (err) { throw err; } return DirectoryMapper.toEntity(newItem); } async remove(id) { const data = await this._getById(id); await data.destroy(); return; } async update(id, newData) { const data = await this._getById(id); const transaction = await this.DirectoryModel.sequelize.transaction(); try { const updatedData = await data.update(newData, { transaction }); const entity = DirectoryMapper.toEntity(updatedData); const { valid, errors } = entity.validate(); if (!valid) { const error = new Error("ValidationError"); error.details = errors; throw error; } await transaction.commit(); return entity; } catch (error) { await transaction.rollback(); throw error; } } validate(directory) { const { valid, errors } = directory.validate(); if (!valid) { const error = new Error("ValidationError"); error.details = errors; throw error; } } async count() { return await this.DirectoryModel.count(); } // Private async _getById(id) { try { return await this.DirectoryModel.findById(id, { rejectOnEmpty: true }); } catch (error) { if (error.name === "SequelizeEmptyResultError") { const notFoundError = new Error("NotFoundError"); notFoundError.details = `User with id ${id} can't be found.`; throw notFoundError; } throw error; } } } module.exports = SequelizeDirectoriesRepository;
import { ArcSlider, Img, Txt } from 'rendition'; import React from 'react'; import styled from 'styled-components'; const Brightness = styled.h1` color: white; span { font-size: 50%; } `; const ImgContainer = styled.div` text-align: center; img { width: 24px; display: inline-block; } `; export const Arcslider = props => { const { active, brightness, name } = props.device; const brightnessLevel = active ? brightness : 0; return ( <div className='c-arc-slider__container'> <div className='c-arc-slider__header'> <span>{name}</span> <span className='close' onClick={props.close}> X </span> </div> <ArcSlider mx='auto' value={(brightnessLevel / 100).toFixed(2)} onValueChange={props.handleChange} className='c-arc-slider__root' > <ImgContainer> <Img src='assets/icons/icon-bright-light.png' alt='brightness' /> </ImgContainer> <Brightness> {Math.round(brightnessLevel)} <span>%</span> </Brightness> <Txt color='white'>Brightness</Txt> </ArcSlider> </div> ); };
var util = require('util'); var fs = require('fs'); var yeoman = require('yeoman-generator'); var _ = require('lodash-node'); var _s = require('underscore.string'); _.mixin(_s.exports()); var ModuleGenerator = module.exports = function ModuleGenerator(args, options, config) { // By calling `NamedBase` here, we get the argument to the subgenerator call // as `this.name`. yeoman.generators.NamedBase.apply(this, arguments); var parts = this.name.split('/'); if (parts.length == 1) { parts.push('index'); } this.moduleName = parts[parts.length - 1]; parts.pop(); this.moduleBase = parts.join('/'); }; util.inherits(ModuleGenerator, yeoman.generators.NamedBase); ModuleGenerator.prototype.files = function files() { this.mkdir('lib/' + this.moduleBase); this.template('_module.js', 'lib/' + this.moduleBase + '/' + this.moduleName + '.js'); if (fs.existsSync('index.js')) { fs.appendFileSync('index.js', 'exports.' + _(this.name).classify() + ' = require(\'./lib/' + this.moduleBase + '/' + this.moduleName + '.js\');\n'); } this.mkdir('test/' + this.moduleBase); this.template('_test.js', 'test/' + this.moduleBase + '/' + this.moduleName + '.js'); };
import { add, differenceInDays, eachDayOfInterval } from 'date-fns' export const state = () => ({ current_level: 1, current_missing: 0, act: [], total_xp: 0, total_days: 0, }) export const getters = { daysLeft: state => differenceInDays(new Date(), new Date(state.act.start)), myXp: state => { const level = state.current_level const done = state.act.levels[level - 1].needed - parseInt(state.current_missing) return state.act.levels.slice(0, level - 1).reduce((sum, level) => sum + level.needed, 0) + done }, myPercent: (state, getters) => getters.myXp / state.total_xp * 100, myAverage: (state, getters) => getters.myXp / getters.daysLeft, myEnd: (state, getters) => { return add(new Date(), { days: Math.ceil((state.total_xp - getters.myXp) / (getters.myAverage || 1)) })}, myFinish: (state, getters) => differenceInDays(getters.myEnd, new Date(state.act.end)), missingXp: (state, getters) => state.total_xp - getters.myXp, } export const mutations = { SET_ACT(state, act) { state.act = act state.total_xp = act.levels.reduce((sum, level) => sum + level.needed, 0) state.total_days = eachDayOfInterval({ start: new Date(act.start), end: new Date(act.end) }, { weekStartsOn: 1 }) state.current_missing = parseInt(act.levels[0].needed) }, SET_CURRENT_LEVEL(state, level) { state.current_level = parseInt(level) }, SET_CURRENT_MISSING(state, missing) { state.current_missing = parseInt(missing) }, }
const escola = "Cod3r" // O indece inicia apartir do 0, entaõ o Indice(4) vai ser o "R" console.log(escola.charAt(4)) // Ele traz a letra que esta no indice informado console.log(escola.charAt(5)) // Retorna um valor vazio, pois não não existe um char // Serve para busca o valor ASC ou UNICODE do valor console.log(escola.charCodeAt(3)) // Ele informa a posição de Indice, onde você passa o valor do indice console.log(escola.indexOf('d')) // Signifca que ele vai imprimir apartir do indice informado para frente console.log(escola.substring(1)) // Ele vai ate ultimo indice informado e se imprime o que esta entre ele console.log(escola.substring(0,3)) // Concatenação console.log('Escola '.concat(escola).concat("!")) console.log(`Escola ${escola} ! - Melhor`) // Faz um replace - substitui o valor de um char console.log(escola.replace(3, 'e')) // Expresão regular - Subistitui todos os DIGITOS(Numeros) dentro TEXTO pela letra passada entre aspas simples '' console.log(escola.replace(/\d/, 'e')) // Expressão regular - Subistitui todos letras e digitos pelo valor passado entre aspas simples '' console.log(escola.replace(/\w/g, 'e')) // Converter uma string separada por virgula e converte isso em um Array console.log('Ana,Maria,Pedro,Jefferson'.split(',')) console.log('3' + 2) // String tem preferencia então ele vai concatenar e não somar
$(function(){ var page=0; var start=true; function Tab(){ // if(start){ $(".silde").animate({ "left":-840*page+'px' },300,function(){ if($(".silde").position().left==-4*840+'px'){ $(".silde").css('left',-840) } }); $(".list li").removeClass('active'); $(".list li").eq(page).addClass('active'); page++; if(page>2){ page=0; } // } setTimeout(Tab,2000); } Tab(); $("dl div").css("display","none"); $(".expansion").toggle(function(){ $("dl div").css("display","block"); $(".expansion").html("收起<i class='top'></i>"); },function(){ $("dl div").css("display","none"); $(".expansion").html("展开<i></i>"); }) })
(function() { return function() { if (!this._is_form) return; var obj = null; this.on_create = function() { this.set_name("insertStudent"); this.set_titletext("New Form"); if (Form == this.constructor) { this._setFormPosition(300,500); } // Object(Dataset, ExcelExportObject) Initialize obj = new Dataset("ds_students_copy", this); obj._setContents("<ColumnInfo><Column id=\"chk\" type=\"STRING\" size=\"256\"/><Column id=\"s_seq\" type=\"STRING\" size=\"256\"/><Column id=\"gender\" type=\"STRING\" size=\"256\"/><Column id=\"name\" type=\"STRING\" size=\"256\"/><Column id=\"age\" type=\"STRING\" size=\"256\"/><Column id=\"email\" type=\"STRING\" size=\"256\"/><Column id=\"contact\" type=\"STRING\" size=\"256\"/><Column id=\"address\" type=\"STRING\" size=\"256\"/><Column id=\"scholarship\" type=\"STRING\" size=\"256\"/><Column id=\"rest\" type=\"STRING\" size=\"256\"/><Column id=\"grade\" type=\"STRING\" size=\"256\"/><Column id=\"birth\" type=\"DATE\" size=\"256\"/><Column id=\"pw\" type=\"STRING\" size=\"256\"/></ColumnInfo>"); this.addChild(obj.name, obj); // UI Components Initialize obj = new Edit("edt_s_seq","85","20","175","30",null,null,null,null,null,null,this); obj.set_taborder("0"); this.addChild(obj.name, obj); obj = new Static("Static00","10","20","50","30",null,null,null,null,null,null,this); obj.set_taborder("1"); obj.set_text("학번"); this.addChild(obj.name, obj); obj = new Static("Static00_00","10","55","50","30",null,null,null,null,null,null,this); obj.set_taborder("2"); obj.set_text("이름"); this.addChild(obj.name, obj); obj = new Static("Static00_01","10","90","50","30",null,null,null,null,null,null,this); obj.set_taborder("3"); obj.set_text("나이"); this.addChild(obj.name, obj); obj = new Static("Static00_02","10","125","50","30",null,null,null,null,null,null,this); obj.set_taborder("4"); obj.set_text("이메일"); this.addChild(obj.name, obj); obj = new Static("Static00_03","10","160","50","30",null,null,null,null,null,null,this); obj.set_taborder("5"); obj.set_text("전화번호"); this.addChild(obj.name, obj); obj = new Static("Static00_04","10","195","50","30",null,null,null,null,null,null,this); obj.set_taborder("6"); obj.set_text("주소"); this.addChild(obj.name, obj); obj = new Static("Static00_05","10","230","50","30",null,null,null,null,null,null,this); obj.set_taborder("7"); obj.set_text("장학금"); this.addChild(obj.name, obj); obj = new Static("Static00_06","10","265","50","30",null,null,null,null,null,null,this); obj.set_taborder("8"); obj.set_text("휴학"); this.addChild(obj.name, obj); obj = new Static("Static00_07","10","300","50","30",null,null,null,null,null,null,this); obj.set_taborder("9"); obj.set_text("성적"); this.addChild(obj.name, obj); obj = new Static("Static00_08","10","335","50","30",null,null,null,null,null,null,this); obj.set_taborder("10"); obj.set_text("생일"); this.addChild(obj.name, obj); obj = new Static("Static00_09","10","370","75","30",null,null,null,null,null,null,this); obj.set_taborder("11"); obj.set_text("초기비밀번호"); this.addChild(obj.name, obj); obj = new Static("Static00_10","10","405","50","30",null,null,null,null,null,null,this); obj.set_taborder("12"); obj.set_text("성별"); this.addChild(obj.name, obj); obj = new Edit("edt_name","85","55","175","30",null,null,null,null,null,null,this); obj.set_taborder("13"); this.addChild(obj.name, obj); obj = new Edit("edt_age","85","90","175","30",null,null,null,null,null,null,this); obj.set_taborder("14"); this.addChild(obj.name, obj); obj = new Edit("edt_email","85","125","175","30",null,null,null,null,null,null,this); obj.set_taborder("15"); this.addChild(obj.name, obj); obj = new Edit("edt_contact","85","160","175","30",null,null,null,null,null,null,this); obj.set_taborder("16"); this.addChild(obj.name, obj); obj = new Edit("edt_address","85","195","175","30",null,null,null,null,null,null,this); obj.set_taborder("17"); this.addChild(obj.name, obj); obj = new Edit("edt_scholarship","85","230","175","30",null,null,null,null,null,null,this); obj.set_taborder("18"); this.addChild(obj.name, obj); obj = new Edit("edt_rest","85","265","175","30",null,null,null,null,null,null,this); obj.set_taborder("19"); this.addChild(obj.name, obj); obj = new Edit("edt_grade","85","300","175","30",null,null,null,null,null,null,this); obj.set_taborder("20"); this.addChild(obj.name, obj); obj = new Edit("edt_pw","85","370","175","30",null,null,null,null,null,null,this); obj.set_taborder("21"); this.addChild(obj.name, obj); obj = new Edit("edt_gender","85","405","175","30",null,null,null,null,null,null,this); obj.set_taborder("22"); this.addChild(obj.name, obj); obj = new Button("btn_insert","85","455","50","30",null,null,null,null,null,null,this); obj.set_taborder("23"); obj.set_text("입력"); this.addChild(obj.name, obj); obj = new Button("btn_cancel","210","455","50","30",null,null,null,null,null,null,this); obj.set_taborder("24"); obj.set_text("취소"); this.addChild(obj.name, obj); obj = new Calendar("cal_birth","85","335","175","30",null,null,null,null,null,null,this); obj.set_taborder("25"); obj.set_dateformat("yyyy-MM-dd"); this.addChild(obj.name, obj); // Layout Functions //-- Default Layout : this obj = new Layout("default","",300,500,this,function(p){}); obj.set_mobileorientation("landscape"); this.addLayout(obj.name, obj); // BindItem Information }; this.loadPreloadList = function() { }; // User Script this.registerScript("insertStudent.xfdl", function() { this.fn_update_students = function(id,url){ //업데이트 따로 뺀것 this.transaction( id ,url ,"in_ds=ds_students:U" ,"" ,"" ,"fn_callback" ) } this.fn_callback = function(id,ErrorCode,ErrorMsg){ //콜백함수 trace(id); trace(ErrorMsg); trace(ErrorCode); } this.btn_insert_onclick = function(obj,e) { var s_seq = this.edt_s_seq.value; var name = this.edt_name.value; var age = this.edt_age.value; var email = this.edt_email.value; var contact = this.edt_contact.value; var address = this.edt_address.value; var scholarship = this.edt_scholarship.value; var rest = this.edt_rest.value; var grade = this.edt_grade.value; var birth = this.cal_birth.value; var pw = this.edt_pw.value; var gender = this.edt_gender.value; var addRow = this.ds_students_copy.addRow(); this.ds_students_copy.setColumn(addRow,"s_seq",s_seq); this.ds_students_copy.setColumn(addRow,"name",name); this.ds_students_copy.setColumn(addRow,"age",age); this.ds_students_copy.setColumn(addRow,"email",email); this.ds_students_copy.setColumn(addRow,"contact",contact); this.ds_students_copy.setColumn(addRow,"address",address); this.ds_students_copy.setColumn(addRow,"scholarship",scholarship); this.ds_students_copy.setColumn(addRow,"rest",rest); this.ds_students_copy.setColumn(addRow,"grade",grade); this.ds_students_copy.setColumn(addRow,"birth",birth); this.ds_students_copy.setColumn(addRow,"pw",pw); this.ds_students_copy.setColumn(addRow,"gender",gender); this.transaction( "ds_insert" //1. strSvcID ,"/insertStudent.nex" //2. strURL ,"in_ds=ds_students_copy:U" //3.strInDatasets - I,U,D Sds=Fds:U 변경된값만보내겟다, :A, :N ,"" //4.strOutDatasets -select Fds=Sds ,"" //5.strArgument text값 ,"fn_callback" //6.strCallbackFunc ); this.close(""); }; this.btn_cancel_onclick = function(obj,e) { this.close(""); }; }); // Regist UI Components Event this.on_initEvent = function() { this.Static00_09.addEventHandler("onclick",this.Static00_09_onclick,this); this.btn_insert.addEventHandler("onclick",this.btn_insert_onclick,this); this.btn_cancel.addEventHandler("onclick",this.btn_cancel_onclick,this); }; this.loadIncludeScript("insertStudent.xfdl"); this.loadPreloadList(); // Remove Reference obj = null; }; } )();
(function(){ angular.module('openmuc.channelaccesstool', []); })();
const path = require('path'); // server const port = 8000; var express = require('express'); const app = express(); // bodyParser const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); // view engine app.set('views', path.join(__dirname, './views')); app.set('view engine', 'ejs'); // static files app.use(express.static(path.join(__dirname, './static'))); // require mongoose var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/newOne'); // create a new Schema var UserSchema = new mongoose.Schema({ fname: { type: String } }, {timestamps: true}) // create collection mongoose.model('User', UserSchema); var User = mongoose.model('User'); // ROUTING // show all users app.get('/', function(req, res){ User.find({}, function(err, allUsers){ if(err){ console.log(err); res.json({message: "Error", error: err}); } else{ console.log("-------------------"); console.log(allUsers); res.json({message: "Success", data: allUsers}); } }) }) // create new user app.get('/new/:fname', function(req, res){ User.create({}, function(err, newUser){ if(err){ console.log("Something went wrong", err); res.json({message: "Error", error: err}); } else{ console.log("Added new User"); newUser = new User({fname: req.params.fname}); newUser.save(); console.log(newUser.fname); res.json({message: "Successfully added a new User", newUser}); } }) }) // remove one user app.get('/remove/:fname', function(req, res){ console.log("I'm here--------------"); User.remove({fname: req.params.fname}, function(err, removeUser){ if(err){ console.log("Im inside the delete but not deleting anything"); res.json({message: "Error", error: err}); } else{ console.log(removeUser); console.log('User is deleted'); res.json({message: "User is deleted"}); } }) }) // show specific user app.get('/:fname', function(req, res){ console.log("I show you the User after I find one"); User.findOne({fname: req.params.fname}, function(err, specUser){ console.log(specUser); // console.log(fname); console.log(req.params.fname); if(err){ res.json({message: "Error", error: err}); } else{ console.log("Thats your user"); res.json({message: "That the specific User, you're looking for", user: specUser}); } }) }) const server = app.listen(port)