text
stringlengths
7
3.69M
module.exports = async function(arg) { await require(arg.__rootDir + '/core/setup.js')(arg); log('version: ' + pkg.version); const gyroServer = require('./gyroServer.js'); const { Mouse, Keyboard, Gamepad, or, and } = require('./contro.js'); let gamepad = new Gamepad(); const http = require("http"); const WebSocket = require("ws"); let btnNames = [ 'lt', 'rt' ]; let btns = {}; for (let i of btnNames) { btns[i] = gamepad.button(i); } let btnStates = {}; let speedShift = true; let gyaxises = ['x', 'y', 'z']; let acaxises = ['x', 'y', 'z']; let invert = { x: 1, y: 1, z: 1 }; let gamepadConnected = false; let inNuetralPos = { x: true, y: true, z: true }; let stickDeadZone = 0.0; // Gyro conversion: float (+-1) => *16b (+-32767) unit => * 250/32767 deg/sec let gySens = -1.0 * 250; // Accel conversion: float (+-1) => *16b (+-32767) unit => * 2/32767 g let acSens = -1.0 * 2 * 1; let files = await klaw(path.join(__rootDir, '/views/md')); for (let file of files) { let html = await fs.readFile(file, 'utf8'); html = '<div class="md">' + md(html) + '</div>'; file = path.parse(file); $('#' + file.name).prepend(html); } $(document).on('click', 'a[href^="http"]', function(event) { event.preventDefault(); opn(this.href); }); function toggleAxis() { let $btn = $(this); $btn.toggleClass('enabled'); gyaxises = []; acaxises = []; if ($('#gyroX').hasClass('enabled')) { gyaxises.push('x'); } if ($('#gyroY').hasClass('enabled')) { gyaxises.push('y'); } if ($('#gyroZ').hasClass('enabled')) { gyaxises.push('z'); } if ($('#accelX').hasClass('enabled')) { acaxises.push('x'); } if ($('#accelY').hasClass('enabled')) { acaxises.push('y'); } if ($('#accelZ').hasClass('enabled')) { acaxises.push('z'); } } $('#gyroX').click(toggleAxis); $('#gyroY').click(toggleAxis); $('#gyroZ').click(toggleAxis); $('#accelX').click(toggleAxis); $('#accelY').click(toggleAxis); $('#accelZ').click(toggleAxis); function toggleControls() { let $btn = $(this); let axis = $btn.attr('id')[6].toLowerCase(); $btn.toggleClass('enabled'); if ($btn.hasClass('enabled')) { invert[axis] = 1; $btn.text(axis.toUpperCase() + ' normal'); } else { invert[axis] = -1; $btn.text(axis.toUpperCase() + ' inverted'); } log(invert); } $('#invertX').click(toggleControls); $('#invertY').click(toggleControls); $('#invertZ').click(toggleControls); function toggleSpeedShifters() { let $btn = $(this); $btn.toggleClass('enabled'); speedShift = $btn.hasClass('enabled'); } $('#speedShift').click(toggleSpeedShifters); async function loop() { if (gamepadConnected || gamepad.isConnected()) { let multi = 1; for (let i in btns) { let btn = btns[i]; let query = btn.query(); // if button is not pressed, query is false and unchanged if (!btnStates[i] && !query) { continue; } // if button is held, query is true and unchanged if (btnStates[i] && query) { // log(i + ' button press held'); if (i == 'lt') { multi = .5; } else if (i == 'rt') { multi = 5; } continue; } // save button state change btnStates[i] = query; // if button press ended query is false if (!query) { // log(i + ' button press end'); continue; } // if button press just started, query is true if (arg.v) { log(i + ' button press start'); } } let stickR = gamepad.stick('right').query(); let stickL = gamepad.stick('left').query(); let gyro = { z: ((gyaxises.includes('x')) ? stickR.x : 0), x: ((gyaxises.includes('y')) ? -stickR.y : 0), y: ((gyaxises.includes('z')) ? -stickR.z : 0) }; let accel = { x: ((acaxises.includes('x')) ? stickL.x : 0), z: ((acaxises.includes('y')) ? stickL.y : 0), // Y <-> Z in Cemuhook y: ((acaxises.includes('z')) ? -stickL.z : 0) }; for (axis of gyaxises) { if (gyro[axis] > stickDeadZone) { gyro[axis] = gySens * gyro[axis]; inNuetralPos[axis] = false; } else if (gyro[axis] < -stickDeadZone) { gyro[axis] = gySens * gyro[axis]; inNuetralPos[axis] = false; } gyro[axis] *= invert[axis]; if (speedShift) { gyro[axis] *= multi; } } for (axis of acaxises) { if (accel[axis] > stickDeadZone) { accel[axis] = acSens * accel[axis]; inNuetralPos[axis] = false; } else if (accel[axis] < -stickDeadZone) { accel[axis] = acSens * accel[axis]; inNuetralPos[axis] = false; } // accel[axis] *= invert[axis]; if (speedShift) { accel[axis] *= multi; } } // gyro.y *= -1; log(gyro, accel); gyroServer.sendMotionData(gyro, accel); if (!gamepadConnected) { log('gamepad connected!'); $('#gamepadIndicator').text('Gamepad Connected!'); gamepadConnected = true; } } requestAnimationFrame(loop); } loop(); };
import express from 'express'; import businessApi from './business'; import sendMessageByShortMes from './sendMessageByShortMes'; import sendMessageByEmail from './sendMessageByEmail'; import messageSubscribe from './messageSubscribe'; let api = express.Router(); api.use('/business',businessApi); api.use('/sendMessageByShortMes',sendMessageByShortMes); api.use('/sendMessageByEmail',sendMessageByEmail); api.use('/messageSubscribe', messageSubscribe); export default api;
module.exports = function(grunt) { grunt.config('browserify', { dist: { files: { './bundle.js': ['app.js'] } } }); grunt.loadNpmTasks('grunt-browserify'); grunt.registerTask('default', ['browserify']); };
export default function () { return { load: ({ resources, Progress }) => { const totSize = resources.map(it => it.size).reduce((itA, itB) => itA + itB); const progress = Progress(totSize, resources.map((it) => { return { size: it.size }; })); progress.startSimulate(); return Promise.all(resources.map((resource) => { return new Promise(function (resolve) { Promise.all([ new Promise(function (resolve) { var img = new Image(); img.addEventListener('load', function () { resource.sprite = img; resolve(); }); img.src = resource.url + '.png'; }), new Promise(function (resolve) { return fetch(resource.url + '.xml') .then(response => response.text()) .then(res => { var lines = res.split('\n'); lines.splice(0, 1); lines.splice(lines.length - 1, 1); resource.json = { filename: '', frames: lines.map(function (line) { return { filename: line.match(/ref="([^"]*)"/)[1] + '.png', frame: { x: line.match(/x="([^"]*)"/)[1], y: line.match(/y="([^"]*)"/)[1], w: line.match(/width="([^"]*)"/)[1], h: line.match(/height="([^"]*)"/)[1] } }; }) }; resolve(); }) }) ]).then(function () { resolve(resource); }) }); })) } } }
describe('BarChart', function() { var chart; afterEach(function() { if (chart) { chart.destroy(); chart = null; } }); describe('chartConfig', function() { it('should configure for stacking', function() { chart = Ext.create('BarChart', { enableStacking: true, chartData: {}, loadMask: false }); expect(chart.chartConfig.plotOptions.bar.showInLegend).toBe(true); expect(chart.chartConfig.plotOptions.bar.colorByPoint).toBe(false); expect(chart.chartConfig.tooltip).not.toBeDefined(); expect(chart.chartConfig.yAxis.reversedStacks).toBe(false); }); it('should configure for no stacking', function() { chart = Ext.create('BarChart', { enableStacking: false, chartData: {}, loadMask: false }); expect(chart.chartConfig.plotOptions.bar.showInLegend).toBe(false); expect(chart.chartConfig.plotOptions.bar.colorByPoint).toBe(true); expect(chart.chartConfig.tooltip).toEqual({ headerFormat: '', pointFormat: '{point.name}: <b>{point.y}</b>' }); }); }); describe('#_isData', function() { beforeEach(function() { chart = Ext.create('BarChart', { enableStacking: true, chartData: {}, loadMask: false }); }); it('should return true for a value', function() { expect(chart._isData(5)).toBe(true); }); it('should return true for a nested value', function() { expect(chart._isData({ y: 5 })).toBe(true); }); it('should return false for an empty value', function() { expect(chart._isData()).toBe(false); }); it('should return false for a 0 value', function() { expect(chart._isData(0)).toBe(false); }); it('should return false for a nested 0 value', function() { expect(chart._isData({ y: 0 })).toBe(false); }); }); });
import { PATHNAME_TEMPLATE } from '../constants'; import { getPathname } from './getPathname'; describe(`${PATHNAME_TEMPLATE} getPathname`, () => { const websiteId = 1234; it('should return the right string', () => { const actual = getPathname(websiteId); expect(actual).toBe(`/v2/websites/locations/website/${websiteId}`); }); });
let myRequest = new Request("./beerlist.json"); fetch(myRequest) .then(function(resp){ return resp.json(); }) .then(function(data){ const locConverter = (ind) =>{ if (ind === 1){ return 'Itaewon'; } else if (ind === 2){ return 'Hannam'; } else{ return 'Gyeongridan'; } } for (let i = 1; i<22; i++){ document.getElementById(`_${i}`).addEventListener('click', ()=>{ var thisSpot = data.spots[i-1]; var thisRating = thisSpot.rating.toFixed(1); console.log(data.spots[i-1]); document.getElementById('Header').textContent = `${thisSpot.name}`; document.getElementById('Beer').textContent = `#${thisSpot.beer}`; document.getElementById('Genre').textContent = `#${thisSpot.genre}`; document.getElementById('Atmosphere').textContent = `#${thisSpot.atmosphere}`; //Ratting: Bottle of Beer roundedRate = Math.round(thisSpot.rating*2); for (let k = 1; k < roundedRate+1; k++){ document.getElementById(`B${k}`).style.opacity = 1; } if (roundedRate!= 10){ for (let j = roundedRate+1; j<11; j++){ document.getElementById(`B${j}`).style.opacity = 0; } } document.getElementById('Rating').textContent = `${thisSpot.rating.toFixed(1)}/5.0`; document.getElementById('Location').textContent = locConverter(thisSpot.location); //Search in Google document.getElementById('SearchA').setAttribute('href', `https://www.google.com/search?q=${thisSpot.name}+itaewon`); }) } console.log(data.spots); console.log(document.getElementById('Header').textContent); })
/* global it expect describe */ import Immutable from 'immutable'; import * as Reducers from '../../../src/reducers/nodes'; import {clusterUpdate, addNodes, removeNodes} from '../../../src/actions'; describe('reducers - nodes', () => { const initialState = [ { pid: 'TEST_ID_1', hostname: 'mesos', resources: { cpus: 1, disk: 13483, mem: 498, ports: '[12000-12999]', }, used_resources: { cpus: 0.2, disk: 10, mem: 32, ports: '[12103-12103, 12723-12723]', }, }, { pid: 'TEST_ID_2', hostname: 'mesos', resources: { cpus: 1, disk: 13483, mem: 498, ports: '[12000-12999]', }, used_resources: { cpus: 0.2, disk: 10, mem: 32, ports: '[12103-12103, 12723-12723]', }, }, ]; describe('#CLUSTER_NODE_UPDATE', () => { it('should update all matching nodes', () => { const state = initialState; const message = [ { pid: 'TEST_ID_1', hostname: 'mesos', resources: { cpus: 1, disk: 13483, mem: 498, ports: '[12000-12999]', }, used_resources: { cpus: 0.4, disk: 20, mem: 34, ports: '[12103-12103, 12723-12723]', }, }, ]; let result = Reducers.nodes( Immutable.fromJS(state), clusterUpdate(Immutable.fromJS(message)) ); result = result.toJS(); expect(result[0].used_resources.cpus).to.equal(0.4); expect(result[0].used_resources.disk).to.equal(20); expect(result[0].used_resources.mem).to.equal(34); expect(result[1].used_resources.cpus).to.equal(0.2); expect(result[1].used_resources.disk).to.equal(10); expect(result[1].used_resources.mem).to.equal(32); }); }); describe('#CLUSTER_NODE_ADDED', () => { it('should add new nodes', () => { const state = initialState; const message = [ { pid: 'TEST_ID_3', hostname: 'mesos', resources: { cpus: 1, disk: 13483, mem: 498, ports: '[12000-12999]', }, used_resources: { cpus: 0.4, disk: 20, mem: 34, ports: '[12103-12103, 12723-12723]', }, }, ]; let result = Reducers.nodes( Immutable.fromJS(state), addNodes(Immutable.fromJS(message)) ); result = result.toJS(); expect(result[0].pid).to.equal(initialState[0].pid); expect(result[1].pid).to.equal(initialState[1].pid); expect(result[2].pid).to.equal(message[0].pid); }); }); it('should not add existing nodes', () => { const state = initialState; const message = [ { pid: 'TEST_ID_2', hostname: 'mesos', resources: { cpus: 1, disk: 13483, mem: 498, ports: '[12000-12999]', }, used_resources: { cpus: 0.4, disk: 20, mem: 34, ports: '[12103-12103, 12723-12723]', }, }, ]; let result = Reducers.nodes( Immutable.fromJS(state), addNodes(Immutable.fromJS(message)) ); result = result.toJS(); expect(result.length).to.equal(initialState.length); expect(result[0].pid).to.equal(initialState[0].pid); expect(result[1].pid).to.equal(initialState[1].pid); expect(result[1].used_resources.cpus).to.equal(initialState[1].used_resources.cpus); }); describe('#CLUSTER_NODE_REMOVED', () => { it('should remove all matching nodes', () => { const state = initialState; const message = [ { pid: 'TEST_ID_1', }, ]; let result = Reducers.nodes( Immutable.fromJS(state), removeNodes(Immutable.fromJS(message)) ); result = result.toJS(); expect(result.length).to.equal(1); expect(result[0].pid).to.equal(initialState[1].pid); }); }); });
import {useEffect, useState} from 'react'; async function getRepos() { const repos = await fetch('/api/getPrivateRepos') .then(resp => resp.json()); return repos; } export default function Repos() { const [reposList, setRepoList] = useState([]); useEffect(() => { getRepos().then(data => setRepoList(data)); }, []); return ( <ul> {reposList.map(repo => <li key={repo.name}>{repo.name}</li>)} </ul> ); }
import mockNaja from './setup/mockNaja'; import fakeXhr from './setup/fakeXhr'; import cleanPopstateListener from "./setup/cleanPopstateListener"; import {assert} from 'chai'; import sinon from 'sinon'; describe('makeRequest()', function () { fakeXhr(); it('should call success event if the request succeeds', function (done) { const naja = mockNaja(); naja.initialize(); cleanPopstateListener(naja.historyHandler); sinon.stub(naja.historyHandler.historyAdapter); const loadCallback = sinon.spy(); const beforeCallback = sinon.spy(); const startCallback = sinon.spy(); const successCallback = sinon.spy(); const errorCallback = sinon.spy(); const completeCallback = sinon.spy(); naja.addEventListener('load', loadCallback); naja.addEventListener('before', beforeCallback); naja.addEventListener('start', startCallback); naja.addEventListener('success', successCallback); naja.addEventListener('error', errorCallback); naja.addEventListener('complete', completeCallback); const request = naja.makeRequest('GET', '/makeRequest/success/events'); assert.equal(1, this.requests.length); request.then(() => { assert.isTrue(beforeCallback.called); assert.isTrue(beforeCallback.calledBefore(startCallback)); assert.isTrue(beforeCallback.calledWith(sinon.match.object .and(sinon.match.has('xhr', sinon.match.instanceOf(window.XMLHttpRequest))) .and(sinon.match.has('method', sinon.match.string)) .and(sinon.match.has('url', sinon.match.string)) .and(sinon.match.has('data')) .and(sinon.match.has('options', sinon.match.object)) )); assert.isTrue(startCallback.called); assert.isTrue(startCallback.calledBefore(successCallback)); assert.isTrue(startCallback.calledWith(sinon.match.object .and(sinon.match.has('request')) .and(sinon.match.has('xhr', sinon.match.instanceOf(window.XMLHttpRequest))) )); assert.isTrue(successCallback.called); assert.isTrue(successCallback.calledBefore(completeCallback)); assert.isTrue(successCallback.calledWith(sinon.match.object .and(sinon.match.has('response')) .and(sinon.match.has('xhr', sinon.match.instanceOf(window.XMLHttpRequest))) .and(sinon.match.has('options', sinon.match.object)) )); assert.isTrue(completeCallback.called); assert.isTrue(completeCallback.calledBefore(loadCallback)); assert.isTrue(completeCallback.calledWith(sinon.match.object .and(sinon.match.has('error', null)) .and(sinon.match.has('response')) .and(sinon.match.has('xhr', sinon.match.instanceOf(window.XMLHttpRequest))) .and(sinon.match.has('options', sinon.match.object)) )); assert.isTrue(loadCallback.called); assert.isFalse(errorCallback.called); done(); }); this.requests.pop().respond(200, {'Content-Type': 'application/json'}, JSON.stringify({answer: 42})); }); it('should resolve with the response if the request succeeds', function (done) { const naja = mockNaja(); naja.initialize(); const request = naja.makeRequest('GET', '/makeRequest/success/resolve'); assert.equal(1, this.requests.length); request.then((response) => { assert.deepEqual(response, {answer: 42}); done(); }); this.requests.pop().respond(200, {'Content-Type': 'application/json'}, JSON.stringify({answer: 42})); }); it('should call error event if the request fails', function (done) { const naja = mockNaja(); naja.initialize(); cleanPopstateListener(naja.historyHandler); const loadCallback = sinon.spy(); const beforeCallback = sinon.spy(); const startCallback = sinon.spy(); const successCallback = sinon.spy(); const errorCallback = sinon.spy(); const completeCallback = sinon.spy(); naja.addEventListener('load', loadCallback); naja.addEventListener('before', beforeCallback); naja.addEventListener('start', startCallback); naja.addEventListener('success', successCallback); naja.addEventListener('error', errorCallback); naja.addEventListener('complete', completeCallback); const request = naja.makeRequest('GET', '/makeRequest/error/events'); assert.equal(1, this.requests.length); request.catch(() => { assert.isTrue(beforeCallback.calledWith(sinon.match.object .and(sinon.match.has('xhr', sinon.match.instanceOf(window.XMLHttpRequest))) .and(sinon.match.has('method', sinon.match.string)) .and(sinon.match.has('url', sinon.match.string)) .and(sinon.match.has('data')) .and(sinon.match.has('options', sinon.match.object)) )); assert.isTrue(startCallback.called); assert.isTrue(startCallback.calledBefore(successCallback)); assert.isTrue(startCallback.calledWith(sinon.match.object .and(sinon.match.has('request')) .and(sinon.match.has('xhr', sinon.match.instanceOf(window.XMLHttpRequest))) )); assert.isTrue(errorCallback.called); assert.isTrue(errorCallback.calledBefore(completeCallback)); assert.isTrue(errorCallback.calledWith(sinon.match.object .and(sinon.match.has('error', sinon.match.truthy)) .and(sinon.match.has('response')) .and(sinon.match.has('xhr', sinon.match.instanceOf(window.XMLHttpRequest))) .and(sinon.match.has('options', sinon.match.object)) )); assert.isTrue(completeCallback.called); assert.isTrue(completeCallback.calledBefore(loadCallback)); assert.isTrue(completeCallback.calledWith(sinon.match.object .and(sinon.match.has('error', sinon.match.truthy)) .and(sinon.match.has('response')) .and(sinon.match.has('xhr', sinon.match.instanceOf(window.XMLHttpRequest))) .and(sinon.match.has('options', sinon.match.object)) )); assert.isTrue(loadCallback.called); assert.isFalse(successCallback.called); done(); }); this.requests.pop().respond(500, {'Content-Type': 'application/json'}, JSON.stringify({error: 'Internal Server Error'})); }); it('should reject with the error if the request fails', function (done) { const naja = mockNaja(); naja.initialize(); cleanPopstateListener(naja.historyHandler); sinon.stub(naja.historyHandler.historyAdapter); const request = naja.makeRequest('GET', '/makeRequest/error/reject'); assert.equal(1, this.requests.length); request.catch((error) => { assert.isOk(error); // isOk = truthy done(); }); this.requests.pop().respond(500, {'Content-Type': 'application/json'}, JSON.stringify({error: 'Internal Server Error'})); }); it('should call abort event if the request is aborted', function () { const naja = mockNaja(); naja.initialize(); const abortCallback = sinon.spy(); const successCallback = sinon.spy(); const errorCallback = sinon.spy(); const completeCallback = sinon.spy(); naja.addEventListener('abort', abortCallback); naja.addEventListener('success', successCallback); naja.addEventListener('error', errorCallback); naja.addEventListener('complete', completeCallback); naja.makeRequest('GET', '/makeRequest/abort'); this.requests.pop().abort(); assert.isTrue(abortCallback.called); assert.isFalse(successCallback.called); assert.isFalse(errorCallback.called); assert.isTrue(completeCallback.called); assert.isTrue(completeCallback.calledWith(sinon.match.object .and(sinon.match.has('error', sinon.match.instanceOf(Error))) .and(sinon.match.has('response', null)) .and(sinon.match.has('xhr', sinon.match.instanceOf(window.XMLHttpRequest))) .and(sinon.match.has('options', sinon.match.object)) )); }); it('should not send the request if before event is aborted', function () { const naja = mockNaja(); naja.initialize(); cleanPopstateListener(naja.historyHandler); const completeCallback = sinon.spy(); naja.addEventListener('complete', completeCallback); naja.addEventListener('before', (evt) => evt.preventDefault()); let thrown = false; try { naja.makeRequest('GET', '/makeRequest/abortedBefore'); } catch (e) { // sinon's fake XHR throws error if readyState is not OPENED if (e.message === "INVALID_STATE_ERR") { thrown = true; } } assert.isTrue(thrown); assert.isFalse(completeCallback.called); }); describe('options', function () { it('should be set to default options', function (done) { const naja = mockNaja(); naja.initialize(); cleanPopstateListener(naja.historyHandler); const beforeCallback = sinon.spy(); naja.addEventListener('before', beforeCallback); const request = naja.makeRequest('GET', '/makeRequest/options/defaultOptions'); assert.equal(1, this.requests.length); request.then(() => { assert.isTrue(beforeCallback.called); assert.isTrue(beforeCallback.calledWith(sinon.match.object .and(sinon.match.has('options', sinon.match.object .and(sinon.match.has('dataType', 'post')) .and(sinon.match.has('responseType', 'auto')) )) )); done(); }); this.requests.pop().respond(200, {'Content-Type': 'application/json'}, JSON.stringify({answer: 42})); }); it('should be overridden by defaultOptions', function (done) { const naja = mockNaja(); naja.initialize(); cleanPopstateListener(naja.historyHandler); const beforeCallback = sinon.spy(); naja.addEventListener('before', beforeCallback); naja.defaultOptions = { 'dataType': 'json', 'customOption': 42, }; const request = naja.makeRequest('GET', '/makeRequest/options/defaultOptions'); assert.equal(1, this.requests.length); request.then(() => { assert.isTrue(beforeCallback.called); assert.isTrue(beforeCallback.calledWith(sinon.match.object .and(sinon.match.has('options', sinon.match.object .and(sinon.match.has('dataType', 'json')) .and(sinon.match.has('responseType', 'auto')) .and(sinon.match.has('customOption', 42)) )) )); done(); }); this.requests.pop().respond(200, {'Content-Type': 'application/json'}, JSON.stringify({answer: 42})); }); it('should be overridden by ad-hoc options', function (done) { const naja = mockNaja(); naja.initialize(); cleanPopstateListener(naja.historyHandler); const beforeCallback = sinon.spy(); naja.addEventListener('before', beforeCallback); naja.defaultOptions = { 'customOption': 42, }; const request = naja.makeRequest('GET', '/makeRequest/options/defaultOptions', null, {'customOption': 24, 'anotherOption': 42}); assert.equal(1, this.requests.length); request.then(() => { assert.isTrue(beforeCallback.called); assert.isTrue(beforeCallback.calledWith(sinon.match.object .and(sinon.match.has('options', sinon.match.object .and(sinon.match.has('dataType', 'post')) .and(sinon.match.has('responseType', 'auto')) .and(sinon.match.has('customOption', 24)) .and(sinon.match.has('anotherOption', 42)) )) )); done(); }); this.requests.pop().respond(200, {'Content-Type': 'application/json'}, JSON.stringify({answer: 42})); }); }); });
; var check=new Array(); //每正确填写一个输入框则添加一个元素,添加八个元素之后恢复submit按钮 $(function () { //判断isbn的输入框是否为空,为空则提示错误,并将submit按钮置为灰色 var text=document.getElementById("isbn_alert"); var auto=document.getElementById("autofill"); var manual=document.getElementById("manualfill"); var reg = /^[9][7][8,9]\d{10}$/; //正则表达式,判断是否满足isbn的13位标准 $('#isbn').blur(function(event) { var value=$(this).val(); if (!(reg.test(value))) { text.innerHTML="Invalid ISBN! Ensure to input only numbers[13 digits]."; $("#isbn").css('borderColor','red'); auto.disabled=true; manual.disabled=false; if(check.includes('1')) check.remove('1'); document.getElementById("submit").disabled=true; }else{ text.innerHTML=""; $("#isbn").css('borderColor','green'); if(!check.includes('1'))check.push('1'); if(check.length>=8) document.getElementById("submit").disabled=false; auto.disabled=false; manual.disabled=true; } }); }) $(function () { //判断booktitle的输入框是否为空,为空则提示错误,并将submit按钮置为灰色 var text=document.getElementById("title_alert"); $('#title').blur(function(event) { if ($(this).val()=='') { text.innerHTML="Title Could't be Null"; $("#title").css('borderColor','red'); if(check.includes('2')) check.remove('2'); document.getElementById("submit").disabled=true; }else{ text.innerHTML=""; $("#title").css('borderColor','green'); if(!check.includes('2'))check.push('2'); if(check.length>=8) document.getElementById("submit").disabled=false; } }); }) $(function () { //判断bookauthor的输入框是否为空,为空则提示错误,并将submit按钮置为灰色 var text=document.getElementById("author_alert"); $('#author').blur(function(event) { if ($(this).val()=='') { text.innerHTML="Author Could't be Null"; $("#author").css('borderColor','red'); if(check.includes('3')) check.remove('3'); document.getElementById("submit").disabled=true; }else{ text.innerHTML=""; $("#author").css('borderColor','green'); if(!check.includes('3'))check.push('3'); if(check.length>=8) document.getElementById("submit").disabled=false; } }); }) $(function () { //判断publisher的输入框是否为空,为空则提示错误,并将submit按钮置为灰色 var text=document.getElementById("publisher_alert"); $('#publisher').blur(function(event) { if ($(this).val()=='') { text.innerHTML="Publisher Could't be Null"; $("#publisher").css('borderColor','red'); if(check.includes('4')) check.remove('4'); document.getElementById("submit").disabled=true; }else{ text.innerHTML=""; $("#publisher").css('borderColor','green'); if(!check.includes('4'))check.push('4'); if(check.length>=8) document.getElementById("submit").disabled=false; } }); }) $(function () { //判断shelflocation的输入框是否为空,为空则提示错误,并将submit按钮置为灰色 var text=document.getElementById("shelflocation_alert"); $('#shelflocation').blur(function(event) { if ($(this).val()=='') { text.innerHTML="Shelflocation Could't be Null"; $("#shelflocation").css('borderColor','red'); if(check.includes('5')) check.remove('5'); document.getElementById("submit").disabled=true; }else{ text.innerHTML=""; $("#shelflocation").css('borderColor','green'); if(!check.includes('5'))check.push('5'); if(check.length>=8) document.getElementById("submit").disabled=false; } }); }) $(function () { //判断price的输入框是否为空,为空则提示错误,并将submit按钮置为灰色 var text=document.getElementById("price_alert"); var reg = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/; $('#price').blur(function(event) { var value = ($(this).val()); if (!(reg.test(value))) { text.innerHTML="Invalid price! Ensure to input only numbers and dot.\nOnly three decimal digits are allowed after the decimal point"; $("#price").css('borderColor','red'); if(check.includes('6')) check.remove('6'); document.getElementById("submit").disabled=true; }else{ text.innerHTML=""; $("#price").css('borderColor','green'); if(!check.includes('6'))check.push('6'); if(check.length>=8) document.getElementById("submit").disabled=false; } }); }) $(function () { //判断copies的输入框是否为空,为空则提示错误,并将submit按钮置为灰色 var text=document.getElementById("copies_alert"); $('#copies').blur(function(event) { if ($(this).val()=='') { text.innerHTML="Invalid Copies! Ensure to input only positive integer."; $("#copies").css('borderColor','red'); if(check.includes('7')) check.remove('7'); document.getElementById("submit").disabled=true; }else{ text.innerHTML=""; $("#copies").css('borderColor','green'); if(!check.includes('7'))check.push('7'); if(check.length>=8) document.getElementById("submit").disabled=false; } }); }) function Literature(name){ //点击后在图书的分类显示处添加一个新的分类 var labelgroup = document.getElementById("labels"); var label_var = document.createElement("span"); label_var.className="label label-success"; label_var.innerHTML=name; labelgroup.appendChild(label_var); } Array.prototype.indexOf = function(val) { for (var i = 0; i < this.length; i++) { if (this[i] == val) return i; } return -1; }; Array.prototype.remove = function(val) { var index = this.indexOf(val); if (index > -1) { this.splice(index, 1); } }; $(function(){ var text=document.getElementById("category_alert"); $('#myDropdown').on('hidden.bs.dropdown', function () { if(document.getElementById("labels").hasChildNodes()) { text.innerHTML=""; if(!check.includes('8'))check.push('8'); if(check.length>=8) document.getElementById("submit").disabled=false; } else{ text.innerHTML="Category Could't be Null"; if(check.includes('8')) check.remove('8'); document.getElementById("submit").disabled=true; } }); }) function autofillfunc(){ var auto = document.getElementById("autofill"); var form1 = document.getElementById("form1") form1.action = "BookInfo/AutoFill"; form1.method = "post"; console.log(document.getElementById("form1").action); var buttonsubmit = document.getElementById("autofill"); buttonsubmit.type = "submit"; } $(function (){ if($('#isbn').val()!=null){ check.push('1'); } if($('#title').val()!=null){ check.push('2'); } if($('#author').val()!=null){ check.push('3'); } if($('#publisher').val()!=null){ check.push('4'); } if($('#price').val()!=null){ check.push('6'); } }) $(function (){ document.getElementById("description").value = document.getElementById("introduction").value; }) function finalSubmit(){ var form = document.createElement("form"); form.action = "BookInfo/AddBook"; form.method = "post"; var input_isbn = document.createElement("input"); input_isbn.type = "hidden"; input_isbn.name = "ISBN"; input_isbn.value = document.getElementById("isbn").value; form.appendChild(input_isbn); var input_title = document.createElement("input"); input_title.type = "hidden"; input_title.name = "name"; input_title.value = document.getElementById("title").value; form.appendChild(input_title); var input_author = document.createElement('input'); input_author.type = 'hidden'; input_author.name = 'author'; input_author.value = document.getElementById('author').value; form.appendChild(input_author); var input_publisher = document.createElement('input'); input_publisher.type = 'hidden'; input_publisher.name = 'publisher'; input_publisher.value = document.getElementById('publisher').value; form.appendChild(input_publisher); var input_location = document.createElement('input'); input_location.type = 'hidden'; input_location.name = 'location'; input_location.value = document.getElementById('shelflocation').value; form.appendChild(input_location); var input_description = document.createElement('input'); input_description.type = 'hidden'; input_description.name = 'introduction'; input_description.value = document.getElementById('description').value; form.appendChild(input_description); var input_price = document.createElement('input'); input_price.type = 'hidden'; input_price.name = 'price'; input_price.value = document.getElementById('price').value; form.appendChild(input_price); var input_copies = document.createElement('input'); input_copies.type = 'hidden'; input_copies.name = 'copies'; input_copies.value = document.getElementById('copies').value; form.appendChild(input_copies); console.log("(*╯3╰)Ready to submit!(*╯3╰)(*╯3╰)"); document.body.appendChild(form); form.submit(); }
window.onload = function (){ // 获得元素 var main_right = document.getElementById('main-right') var attention = document.getElementById('attention') var ic_weixin = document.getElementsByClassName('ic-weixin')[0] var ewm = attention.getElementsByClassName('ewm')[0] //给ic-weiixn 微信图标绑定一个鼠标进入onmouseenter事件 ic_weixin.onmouseenter = function (){ ewm.style.display = 'block' } //当鼠标移开后,变回none ic_weixin.onmouseout = function (){ ewm.style.display = 'none' } // 正在热映的轮播图 var icon_r = this.document.getElementsByClassName('icon-r')[0] var icon_l = this.document.getElementsByClassName('icon-l')[0] var now_main = this.document.getElementsByClassName('now-main')[0] var ul = now_main.getElementsByTagName('ul')[0] function banner_now_r(obj1,obj2){ obj1.onclick = function (){ // var time = setInterval(function (){ obj2.style.marginLeft = -700 + 'px' // },1000) page_index++ page.innerText = page_index + ' / 8' } } function banner_now_l(obj1,obj2){ obj1.onclick = function (){ // var time = setInterval(function (){ obj2.style.marginLeft = 0 + 'px' // },1000) page_index-- page.innerText = page_index + ' / 8' } } banner_now_r(icon_r,ul) banner_now_l(icon_l,ul) // clearInterval(time) //拿到页数的标签 var page_index = 1 var page = this.document.getElementsByClassName('page')[0] //最热门电影 //head的active var movie = this.document.getElementById('movie') var series = this.document.getElementById('series') var movie_head = movie.getElementsByClassName('movie-head')[0] var series_head = series.getElementsByClassName('movie-head')[0] var lis_movie_head = movie_head.querySelectorAll('li') var lis_series_head = series_head.querySelectorAll('li') //加类名的函数 function active(obj1){ obj1.onmouseover = function (){ obj1.classList.add('active') } obj1.onmouseout = function (){ obj1.classList.remove('active') } } for(var i= 0 ; i < lis_movie_head.length; i++){ var a = lis_movie_head[i].children[0] active(a) } //热门电视剧 //head的active for(var i= 0 ; i < lis_series_head.length; i++){ var b = lis_series_head[i].children[0] // console.log(b) active(b) } }
// Inside vue.config.js module.exports = { // ...other vue-cli plugin options... pwa: { name: 'Eagleglobal Markets', themeColor: '#0476F2', msTileColor: '#000000', appleMobileWebAppCapable: 'yes', appleMobileWebAppStatusBarStyle: 'black', iconsPath: { favicon32: 'img/icons/favicon-32x32.png', favicon16: 'img/icons/favicon-16x16.png', appleTouchIcon: 'img/icons/apple-touch-icon.png', maskIcon: 'img/icons/android-chrome-192x192.png', msTileImage: 'img/icons/android-chrome-512x512.png' }, // configure the workbox plugin workboxPluginMode: 'GenerateSW', // workboxOptions: { // swSrc is required in InjectManifest mode. // swSrc: 'dev/sw.js', // ...other Workbox options... // } } }
function User(userData) { if (userData) { // если указаны данные -- одна ветка if this.name = userData.name; this.age = userData.age; } else { // если не указаны -- другая this.name = 'Аноним'; } this.sayHi = function() { alert(this.name) }; // ... } // Использование var guest = new User(); guest.sayHi(); // Аноним var knownUser = new User({ name: 'Вася', age: 25 }); knownUser.sayHi(); // Вася
const tpl = require('./util/tpl'); const vfs = require('vinyl-fs'); const path = require('path'); const chalk = require('chalk'); const spawn = require('child_process').spawn; const through = require('through2'); const log = console.log; const cwd = process.cwd(); const info = text => log(chalk.green(`\n${text}`)); const remind = text => log(chalk.red(`\n${text}`)); const superman = require.resolve('@youzan/superman'); const babelCli = require.resolve('babel-cli/bin/babel.js'); const createDir = (cb) => { tpl.createDir(cwd, ['publish']); cb && cb(); }; const preBuild = (cb) => { info('Compile Client-side Js Files'); spawn(superman, ['prd'], { stdio: 'inherit' }) .on('close', () => { info('Compile Client-side Js Files Finish'); cb && cb(); }); }; const hash = (cb) => { info('Generate Client-side Js Files Hash Code'); spawn(superman, ['hash'], { stdio: 'inherit' }) .on('close', () => { info('Generate Client-side Js Files Hash Code Finish'); cb && cb(); }); }; const cdn = (cb) => { info('Upload Client-side Js Files to CDN'); spawn(superman, ['cdn'], { stdio: 'inherit' }) .on('close', () => { info('Upload Client-side Js Files to CDN Finish'); cb && cb(); }); }; const tplMiddleware = function(dest) { return through.obj(function(file, enc, cb) { if (!file.stat.isFile()) { return cb(); } log(chalk.green(`copy ${file.path.replace('server/', 'publish/server/')}`)); this.push(file); cb(); }); }; const copyExtraFiles = (cb) => { const dest = path.resolve(cwd, 'publish'); info('Copy Extra !.js Files...'); vfs.src(['./server/**/*.*', './package.json', '!./server/**/*.js'], { cwd, cwdbase: true, dot: true }) .pipe(tplMiddleware(dest)) .pipe(vfs.dest(dest)) .on('end', () => cb && cb()); }; const babel = (cb) => { info('Compile Server-side Js File'); spawn(babelCli, [ 'server', '--out-dir', 'publish/server', '-x', '.js' ], { stdio: 'inherit' }) .on('close', () => { info('Compile Server-side Js File Completed!'); cb && cb(); }); }; const run = (...tasks) => { const program = [() => {}]; while (tasks.length) { const task = tasks.pop(); const pos = program.length - 1; program.push(() => task(program[pos])); } program[program.length - 1](); }; run(createDir, preBuild, hash, cdn, babel, copyExtraFiles);
// This is a manifest file that'll be compiled into application.js. // // Any JavaScript file within this directory can be referenced here using a relative path. // // You're free to add application-wide JavaScript to this file, but it's generally better // to create separate JavaScript files as needed. // require_tree . // //= require jquery/jquery-2.2.0.min //= require bootstrap/bootstrap // //= require plugins/blockUI/blockUI.js // site: http://jquery.malsup.com/block/ //= require plugins/dialog/dialog.min // site: http://nakupanda.github.io/bootstrap3-dialog/ //= require plugins/growl/growl // site: https://github.com/ksylvest/jquery-growl //= require plugins/validation/jquery.validate.min // site: https://jqueryvalidation.org/validate ou https://jqueryvalidation.org/documentation/ //= require plugins/tooltipster/tooltipster.bundle.min // site: http://iamceege.github.io/tooltipster/#demos // //= require_self $(document).ready(function() { app.run(); }); var app = (function() { var _ajaxCount = 0; var _callbackFunction = null; var _url = 'http://localhost:8080/gas/'; var _run = function() { _loadMainMenu(); _growl('Bem Vindo!'); }; var _loadModule = function(strModule) { if ($('#divContent').get(0)) { $.ajax({ url: _url + strModule, type: 'POST', dataType: 'HTML', success: function(res) { $('#divContent').html(res); $('#divContent').find('input,select,textarea').tooltipster({ theme : 'tooltipster-error', timer : 2000, position : 'right' }); $('#divContent').find('form').each(function() { _initValidate(this); }); } }) } else { top.location.href = _url + strModule; } }; var _loadMainMenu = function() { if ($('#appDivMainMenu').get(0)) { $.ajax({ url: _url + 'app/menu', type: 'POST', dataType: 'HTML', success: function(res) { $('#appDivMainMenu').html(res); $(".btn-menu-toggle").click(function(e) { e.preventDefault(); $("#wrapper").toggleClass("toggled"); }); } }) } }; var _dialog = function(msg, title, seconds, type, btnLabel, size, callback, data, glyphicon) { // http://nakupanda.github.io/bootstrap3-dialog/#available-options title = title || 'Mensagem'; type = type || 'primary' // primary,info,success,warning,danger btnLabel = btnLabel || 'Fechar' size = size || 'normal' // small, large, wide, small glyphicon = glyphicon || ''; var timer = null; var modal = BootstrapDialog.show({ title: title, message: msg, description: title, closable: false, closeByBackdrop: false, closeByKeyboard: false, keyboard: false, animate: false, draggable: true, size: 'size-' + size, cssClass: 'app-dialog-' + type, type: 'type-' + type, data: data, buttons: [{ label: btnLabel, cssClass: 'btn-sm btn-' + type, icon: 'glyphicon ' + glyphicon, autospin: true, action: function(dialogRef) { dialogRef.enableButtons(false); dialogRef.setClosable(false); clearTimeout(timer); if (typeof callback == 'function') { window.setTimeout(function() { try { callback && callback(data); callback = null; } catch (e) {} }, 300) } dialogRef.close(); } }] }); if (seconds > 0) { timer = window.setTimeout(function() { callback && callback(data); modal.close() }, seconds * (seconds > 999 ? 1 : 1000)) } }; var _alert = function(msg, title, callback, data, seconds) { _dialog(msg, title, seconds, 'primary', 'Fechar', null, callback, data); }; var _alertError = function(msg, title, callback, data, seconds) { title = title || 'Erro'; _dialog(msg, title, seconds, 'danger', 'Fechar', null, callback, data); }; var _confirm = function(msg, callbackYes, callbackNo, data, title, type, labelYes, labelNo) { msg = msg || 'Confirma?'; labelYes = labelYes || 'Sim'; labelNo = labelNo || 'Não'; title = title || 'Confirmação' type = type || 'primary' // primary,info,success,warning,danger var callbackYesNo = null; BootstrapDialog.confirm({ title: title, animate: true, message: msg, closable: false, closeByBackdrop: false, closeByKeyboard: false, type: 'type-' + type, draggable: true, // <-- Default value is false btnCancelLabel: labelYes, // <-- Default value is 'Cancel', btnOKLabel: labelNo, // <-- Default value is 'OK', btnOKClass: 'btn-danger', // botoes invertidos para exibir o Sim primeiro btnCancelClass: 'btn-success', onshown: function(dialogRef) {}, callback: function(result) { result = !result; _callbackYesNo = null if (result) { callbackYesNo = callbackYes; } else { callbackYesNo = callbackNo; } if (typeof callbackYesNo === 'function') { // timeou para esperar o fechamento do dialog e depois executar o callback window.setTimeout(function() { try { callbackYesNo.call(null, result, data); } catch (e) {} }, 300) } } }); }; var _blockUI = function(msg, onBlock, onUnblock, seconds) { seconds = seconds || 0; $.msg({ content: msg, bgPath: 'assets/jquery/plugins/msg/', center: { against: 'parent' }, z: 5000, timeOut: seconds * (seconds > 999 ? 1 : 1000), fadeOut: 200, fadeIn: 200, clickUnblock: false, autoUnblock: (seconds > 0), beforeUnblock: function() { onUnblock && onUnblock(); }, afterBlock: function() { onBlock && onBlock(); } }); }; var _unblockUI = function(onUnblock) { $.msg('unblock'); }; var _growl = function(message, seconds, title, location, size, style, fixed, delayOnHover) { message = message || ''; seconds = seconds || 5; title = title || ''; location = location || 'tc'; size = size || 'medium'; style = style || 'warning'; fixed = (fixed === true ? true : false); delayOnHover = (delayOnHover === false ? false : true); if (message) { //$.growlUI(title, message, seconds * (seconds > 999 ? 1 : 1000)); $.growl({ message: message, title: title, duration: seconds * (seconds > 999 ? 1 : 1000), location: location, size: size, fixed: fixed, style: style, delayOnHover: delayOnHover }); }; }; var _initValidate = function(form, rules, messages, onSuccess, onError, focusCleanup, debug) { if (typeof(form) == 'object') { form = $(form).attr('id'); } if (!form) { return; } rules = rules || {}; messages = messages || {}; debug = (debug === true ? true : false); focusCleanup = (focusCleanup === true ? true : false); form = '#' + form.replace('#', ''); // o evento validate-successs deve ser utilizando quando for utilizado o metodo submit do form var formOnSuccess = $(form).data('validate-success'); if (formOnSuccess) { onSuccess = function(form) { _eval(formOnSuccess, form); } } var formOnError = $(form).data('validate-error'); if (formOnError) { onError = function(event, validator) { _eval(formOnError, event, validator); } } var formDebugMode = ($(form).data('validate-debug') === true) ? true : false; if (formDebugMode) { debug = true; } var formFocusCleanup = ($(form).data('validate-focus-cleanup') === true) ? true : false; if (formFocusCleanup) { focusCleanup = true; } $(form).validate({ debug: debug, focusCleanup: focusCleanup, errorClass: 'error', validClass: 'valid', success: function(label, element) { try { // http://iamceege.github.io/tooltipster/#demos $(element).tooltipster('hide'); } catch (e) {} label.addClass("valid"); }, errorPlacement: function(error, element) { if ($(error).text()) { try { $(element).tooltipster('content', $(error).text()); $(element).tooltipster('show'); } catch (e) {} } // var name = $element.attr("name"); // $("#error" + name).append($error); }, submitHandler: function(form) { onSuccess && onSuccess(form) }, invalidHandler: function(event, validator) { if (onError) { onError(event, validator); } else { // var errors = validator.numberOfInvalids(); // app.alertError('Existe(m) ' + errors + ' erro(s) no // formulário.'); } }, rules: rules, messages: messages }); } var _eval = function(f, p) { p = p || arguments; try { f = eval(f); if (typeof(f) === 'function') { // testar chamar com arguments do javascript ex: // f.apply({},arguments); if ($.isArray(p)) { f.apply(this, p); } else { f(p); } }; } catch (e) {}; } var _updateSelect = function(url, idSelect, optDefault, optValue, optText) { $.ajax({ url: url, type: 'POST', dataType: 'JSON', success: function(res) { $('#' + idSelect).empty(); $('#' + idSelect).append('<option value="">' + optDefault + '</option>'); $.each(res, function(key, value) { $('#' + idSelect).append('<option value="' + value[optValue] + '">' + value[optText] + '</option>'); }); } }); } return { url: _url, run: _run, loadModule: _loadModule, dialog: _dialog, alertError: _alertError, alert: _alert, confirm: _confirm, blockUI: _blockUI, unblockUI: _unblockUI, growl: _growl, initValidate: _initValidate, eval: _eval, updateSelect: _updateSelect, } })()
export function isVoucherProduct(product) { return product.sku.startsWith('--voucher--') } /* * We add to the non-voucher products the quantity (from the client-side state). */ export function withLocalState(localCart, item) { // Exclude voucher codes if (isVoucherProduct(item)) { return item; } const clientBasketCartItem = localCart.find( (c) => c.sku === item.sku ); /** * Don't show the cart item if it is not in * the client cache. **/ if (!clientBasketCartItem) { return null; } return { ...item, quantity: clientBasketCartItem.quantity }; } export function clientCartItemForAPI({ sku, path, quantity, priceVariantIdentifier }) { return { sku, path, quantity, priceVariantIdentifier }; }
const { User } = require('../models'); const validator = require('validator'); const { to, TE } = require('../services/util.service'); const Sequelize = require('sequelize'); const bcrypt = require('bcrypt'); const bcrypt_p = require('bcrypt-promise'); const crypto = require('crypto'); const CONFIG = require('../config/config'); const createUser = async (userInfo) => { //console.log("++++++++createUser1"); let err; //if(!validator.isEmail(userInfo.email)) TE('A valid email was not entered.'); /* User.build(userInfo).validate().then(function(model) { console.log("++++++++createUser2"); }).catch(Sequelize.ValidationError, function(err) { console.log("++++++++createUser3", err.errors[0].message); }).catch(function(err) { console.log("++++++++createUser4"); }); */ let user = User.build(userInfo); let salt; [err, salt] = await to(bcrypt.genSalt(10)); if(err) TE(err.message, true); const hash = crypto.createHmac('sha256', CONFIG.salt) .update(user.password + salt) .digest('hex'); user.password = hash; user.salt = salt; user.username = ''; [err, user] = await to(user.validate()); if(err) { TE(err.message); } else { [err, user] = await to(user.save()); if(err) TE(err.message); } /* [err, user] = await to(User.create(userInfo)); if(err) { console.log("++++++++createUser4", err); TE('user already exists with that email'); } */ return user; } module.exports.createUser = createUser; const authUser = async function(userInfo){//returns token let auth_info = {}; auth_info.status = 'login'; if(!userInfo.email) TE('Please enter an email to login'); if(!userInfo.password) TE('Please enter a password to login'); let user; if(validator.isEmail(userInfo.email)){ auth_info.method='email'; [err, user] = await to(User.findOne({where:{email:userInfo.email}})); if(err) TE(err.message); }else{ TE('A valid email was not entered'); } if(!user) TE('Not registered'); [err, user] = await to(user.comparePassword(userInfo.password)); if(err) TE(err.message); return user; } module.exports.authUser = authUser;
import React, { useState } from "react"; import TaskChart from "./TaskChart"; import Profile from "./TaskData"; import { Table, TableHead, Checkbox, TableHeaderCell, Pane, Button, Avatar, } from "evergreen-ui"; function UniTable() { const [checkAll, setCheckAll] = useState(false); const [check, setCheck] = useState(false); let one = (e) => { onchange = (e) => setCheck(); }; return ( <div className="table-head"> <Table> <div className="table-head"> <Table.Head height={"50px"}> <Table.HeaderCell flexBasis={10} flexShrink={0} flexGrow={0}> <Checkbox checked={checkAll} onChange={(e) => setCheckAll(e.target.checked)} /> </Table.HeaderCell> <Table.TextHeaderCell flexBasis={100} flexShrink={0} flexGrow={0}> Status </Table.TextHeaderCell> <Table.TextHeaderCell flexBasis={250} flexShrink={0} flexGrow={1}> Title </Table.TextHeaderCell> <Table.TextHeaderCell flexBasis={150} flexShrink={0} flexGrow={0}> Type </Table.TextHeaderCell> <Table.TextHeaderCell flexBasis={200} flexShrink={0} flexGrow={0}> Associated with </Table.TextHeaderCell> <Table.TextHeaderCell flexBasis={100} flexShrink={0} flexGrow={0}> Due date </Table.TextHeaderCell> </Table.Head> </div> <div> <Table.VirtualBody height={"70vh"}> {Profile.map((profile) => ( <Table.Row key={profile.id} isSelectable hoverElevation={4} activeElevation={4} > <Table.TextCell flexBasis={40} flexShrink={0} flexGrow={0}> {/* {profile.id === "" ? ( <Checkbox checked={checkAll} onChange={(e) => setCheckAll(e.target.checked)} /> ) : ( <Checkbox checked={check} onChange={(e) => setCheck(e.target.checked)} /> )} */} </Table.TextCell> <Table.TextCell flexBasis={120} flexShrink={0} flexGrow={0}> {profile.status === "completed" ? ( <Button appearance="primary" intent="success"> compleated </Button> ) : ( <Button appearance="primary" intent="warning"> active </Button> )} </Table.TextCell> <Table.TextCell flexBasis={250} flexShrink={0} flexGrow={1}> {profile.title} </Table.TextCell> <Table.TextCell flexBasis={150} flexShrink={0} flexGrow={0}> {profile.associated} </Table.TextCell> <Table.TextCell isNumber flexBasis={200} flexShrink={0} flexGrow={0} > <Pane className="avatar"> <Avatar name={profile.associated} size={40} /> <h4>{profile.associated}</h4> </Pane> </Table.TextCell> <Table.TextCell isNumber flexBasis={100} flexShrink={0} flexGrow={0} > {profile.date} </Table.TextCell> </Table.Row> ))} </Table.VirtualBody> </div> </Table> </div> ); } export default UniTable;
var server = require('server.js'); var agents = []; var cur_time = 0; export.init = function (homeX,homeY,homeR,officeX,officeY,officeR,agentNums,clockin,clockout) { } var initAgent = function(agentNums) { for (var i = 1; i <= agentNums; i++) { agent = new Object(), agent.id = i, agent.x = i*10, agent.y = i*10, agent.r = 5, agents.push(agent) }; } var initBuilding = function() { building1 = new Object(), building1.id = 1, building1.x = 20, building1.y = 20, building1.r = 80, buildings.push(building1); building2 = new Object(), building2.id = 2, building2.x = 500, building2.y = 300, building2.r = 80, buildings.push(building2); map.width = 800; map.height = 500; return { buildings: buildings, map: map } var start = function() { } var pause = function() { } var stop = function() { } var interval = function() { cur_time++; window.setTimeout("Scroll()", 1000); } var Scroll = function() { }
const Augur = require("augurbot"); const request = require("request"); const u = require("../utils/utils"); const attempts = new Set(); function getStats(channel) { if (attempts.size == 0) return Promise.resolve(true); else return new Promise((fulfill, reject) => { request("https://stats.foldingathome.org/api/team/238415", async function(error, response, body) { try { if (!error && response.statusCode == 200) { body = JSON.parse(body); let embed = u.embed() .setTimestamp() .setImage(body.credit_cert + "?timestamp=" + Date.now()) .setTitle(`${body.name} Folding@home Stats`) .setURL("https://stats.foldingathome.org/team/238415") .setDescription(`The top ${Math.min(25, body.donors.length)} contributors to the LDSG Folding@home team:`); let contributors = body.donors.sort((a, b) => b.credit - a.credit); for (let i = 0; i < Math.min(25, contributors.length); i++) { let contrib = contributors[i]; embed.addField(contrib.name, `**Profile:** [[Link]](https://stats.foldingathome.org/donor/${contrib.name})\n**Work Units:** ${contrib.wus}\n**Credit:** ${contrib.credit}${(contrib.rank ? "\n**Rank:** " + contrib.rank : "")}`, true); } for (const channel of attempts) { Module.client.channels.cache.get(channel).send({embed}).catch(e => u.errorHandler(e, "F@H Post")); } attempts.clear(); fulfill(true); } else { fulfill(false); } } catch(error) { u.errorHandler(error, "F@H Posting"); } }); }); } const Module = new Augur.Module() .addCommand({name: "fah", aliases: ["foldingathome", "folding", "folding@home"], description: "LDSG Folding@home Stats", process: async (msg) => { try { attempts.add(msg.channel.id); let success = await getStats(msg.channel); if (!success) msg.channel.send("I'm having trouble connecting to the Folding @ Home website. I'll keep trying!"); } catch(e) { u.errorHandler(e, msg); } } }) .setClockwork(() => { try { return setInterval(getStats, 10 * 60000); } catch(error) { u.errorHandler(error, "F@H Clockwork"); } }) .setUnload(() => { attempts.clear(); }); module.exports = Module;
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import Paper from 'material-ui/Paper'; import Typography from 'material-ui/Typography'; import Divider from 'material-ui/Divider' import Grid from 'material-ui/Grid' const styles = theme => ({ root: theme.mixins.gutters({ paddingTop: 16, paddingBottom: 16, marginTop: theme.spacing.unit , }), }); function PaperSheet(props) { const { classes } = props; return ( <div> <Paper className={classes.root} elevation={4}> <Grid container> <Grid item xs={6}> <Typography gutterBottom type="subheading">全场通用</Typography> <Typography gutterBottom type="caption">有效期2018.02.01</Typography> </Grid> <Grid item xs={6}> <Typography align="right" color="accent" gutterBottom type="headline">¥8</Typography> <Typography align="right" gutterBottom type="caption">满10元可用</Typography> </Grid> </Grid> <Divider /> <Typography style={{marginTop:8}} type="caption">仅限苹果唱片使用</Typography> </Paper> </div> ); } PaperSheet.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(PaperSheet);
'use strict'; let clientScripts = require('../config/scripts.js'); let Award = require('../models/award.model.js'); let Grammy = require('../models/grammy.model.js'); let _ = require('lodash'); let chance = require('chance').Chance(); let async = require('async'); exports.editor = function(req, res){ let finalDataArray = []; let rawText = req.body.text; let rawTextArray = rawText.split("\n"); let finalArray = []; let tempArray = []; rawTextArray.forEach(function(i){ if(i !== "===") { tempArray.push(i); } else { finalArray.push(tempArray); tempArray = []; } }); finalArray.forEach(function(nominee){ let categoryObject = { name: req.body.name, year: req.body.year, }; categoryObject.category = nominee[0]; nominee.splice(0,1); categoryObject.winner = nominee[0]; categoryObject.nominees = nominee.map(function(i){ var t = {}; t.name = i; t.count = 0; return t; }); finalDataArray.push(categoryObject); }); process.nextTick(function(){ Award.create(finalDataArray, function(err, docs){ if (err) return res.status(400).json({ error: err, message: "Not saved in db." }); res.status(200).json({data: docs, message: "Saved in db."}); }); }); };
/* eslint-disable no-param-reassign */ import test from 'ava'; import WebId from '../dist/webid.cjs'; /** @todo import this from ./src/constants.js once ava updates @babel/core */ const DefaultOptions = { delimiter: '-', delimiterInShortid: false, lower: true, maxLength: 128, remove: null, strict: true, }; const testStr = '1. László Čapek ♥ déjà vu in the Åland Islands'; test.beforeEach('reset options to default', (t) => { t.context.webid = new WebId(); }); test('uses default options when none are provided', (t) => { t.deepEqual(t.context.webid.options, DefaultOptions); }); test('generates an id with defaults', (t) => { t.is(t.context.webid.generate(testStr), 'laszlo-capek-love-deja-vu-in-the-aland-islands'); }); test('#generate with no arguments', (t) => { const id = t.context.webid.generate(); t.true(typeof id === 'string'); t.true(id.length >= 7); t.true(id.length <= 14); }); test('#generate with options, but no string', (t) => { const id = t.context.webid.generate({ prefix: 'wid' }); t.true(typeof id === 'string'); t.true(id.startsWith('wid-')); t.true(id.length >= 11); }); test('#generateUnique with no arguments', (t) => { const id = t.context.webid.generateUnique(); t.true(typeof id === 'string'); t.true(id.length >= 7); t.true(id.length <= 14); t.false(id.includes(t.context.webid.delimiter)); }); test('#generateUnique with options, but no string', (t) => { const id = t.context.webid.generateUnique({ prefix: 'wid' }); t.true(typeof id === 'string'); t.true(id.startsWith('wid-')); t.true(id.length >= 11); }); test('#generate in non-strict mode', (t) => { t.is(t.context.webid.generate(testStr, { strict: false }), '1.-laszlo-capek-love-deja-vu-in-the-aland-islands'); }); test('sets a valid prefix in strict mode', (t) => { t.context.webid.prefix = 'wid'; t.is(t.context.webid.prefix, 'wid-'); t.is(t.context.webid.generate(testStr), 'wid-laszlo-capek-love-deja-vu-in-the-aland-islands'); }); test('errors on prefix that doesn\'t begin with a letter in strict mode', (t) => { const error = t.throws(() => { t.context.webid.prefix = '123'; }); t.is(error.message, 'prefix must begin with a letter (a-z).'); t.is(error.name, 'Error'); }); test('errors on non-string prefix', (t) => { const error = t.throws(() => { t.context.webid.prefix = 123; }); t.is(error.message, 'Expected a string. Received number.'); t.is(error.name, 'TypeError'); }); test('sets a valid suffix in strict mode', (t) => { t.context.webid.suffix = 'wid'; t.is(t.context.webid.suffix, '-wid'); t.is(t.context.webid.generate(testStr), 'laszlo-capek-love-deja-vu-in-the-aland-islands-wid'); }); test('sets a valid delimiter in strict mode', (t) => { t.context.webid.delimiter = '_'; t.is(t.context.webid.delimiter, '_'); t.is(t.context.webid.generate(testStr), 'laszlo_capek_love_deja_vu_in_the_aland_islands'); }); test('errors on an invalid delimiter in strict mode', (t) => { const error = t.throws(() => { t.context.webid.delimiter = '🕺🏽'; }); t.is(error.message, '🕺🏽 is not a safe delimiter.'); }); test('allows an invalid delimiter in non-strict mode', (t) => { t.context.webid.configure({ strict: false, delimiter: '🕺🏽', }); t.is(t.context.webid.delimiter, '🕺🏽'); t.is(t.context.webid.generate(testStr), '1.🕺🏽laszlo🕺🏽capek🕺🏽love🕺🏽deja🕺🏽vu🕺🏽in🕺🏽the🕺🏽aland🕺🏽islands'); }); test('sets an invalid delimiter in non-strict mode', (t) => { t.context.webid.configure({ strict: false }); const error = t.throws(() => { t.context.webid.delimiter = '\t'; }); t.is(error.message, 'The delimiter cannot be a space.'); }); test('adds a prefix and suffix via options', (t) => { const opts = { prefix: 'wid-pre', suffix: 'wid-suf', }; t.is(t.context.webid.generate(testStr, opts), 'wid-pre-laszlo-capek-love-deja-vu-in-the-aland-islands-wid-suf'); }); test('use alias options', (t) => { const opts = { pre: 'wid-pre', suf: 'wid-suf', delim: '_', }; t.is(t.context.webid.generate(testStr, opts), 'wid-pre_laszlo_capek_love_deja_vu_in_the_aland_islands_wid-suf'); }); test('generates a unique id every time', (t) => { const unique1 = t.context.webid.generateUnique(testStr); const unique2 = t.context.webid.generateUnique(testStr); t.not(unique1, unique2); }); test('generate# with string and options', (t) => { const unique = t.context.webid.generateUnique(testStr, { delimiter: '_', }); const underscores = unique.match(/_/g); t.true(underscores.length >= 9); }); test('id and shortid are the same when no string is given', (t) => { const webidObj = t.context.webid.parse(); t.is(webidObj.id, webidObj.shortid); }); test('shortid does not contain the delimiter character', (t) => { const webidObj = t.context.webid.parse(); t.false(webidObj.shortid.includes(t.context.webid.delimiter)); });
PIXI.VideoTexture = function( source, scaleMode ) { if( !source ){ throw new Error( 'No video source element specified.' ); } // hook in here to check if video is already available. // PIXI.BaseTexture looks for a source.complete boolean, plus width & height. if( (source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA ) && source.width && source.height ) { source.complete = true; } PIXI.BaseTexture.call( this, source, scaleMode ); this.autoUpdate = false; this.updateBound = this._onUpdate.bind(this); if( !source.complete ) { this._onCanPlay = this.onCanPlay.bind(this); source.addEventListener( 'canplay', this._onCanPlay ); source.addEventListener( 'canplaythrough', this._onCanPlay ); // started playing.. source.addEventListener( 'play', this.onPlayStart.bind(this) ); source.addEventListener( 'pause', this.onPlayStop.bind(this) ); } }; PIXI.VideoTexture.prototype = Object.create( PIXI.BaseTexture.prototype ); PIXI.VideoTexture.constructor = PIXI.VideoTexture; PIXI.VideoTexture.prototype._onUpdate = function() { if(this.autoUpdate) { window.requestAnimationFrame(this.updateBound); this.dirty(); } }; PIXI.VideoTexture.prototype.onPlayStart = function() { if(!this.autoUpdate) { window.requestAnimationFrame(this.updateBound); this.autoUpdate = true; } }; PIXI.VideoTexture.prototype.onPlayStop = function() { this.autoUpdate = false; }; PIXI.VideoTexture.prototype.onCanPlay = function() { if( event.type === 'canplaythrough' ) { this.hasLoaded = true; if( this.source ) { this.source.removeEventListener( 'canplay', this._onCanPlay ); this.source.removeEventListener( 'canplaythrough', this._onCanPlay ); this.width = this.source.videoWidth; this.height = this.source.videoHeight; // prevent multiple loaded dispatches.. if( !this.__loaded ){ this.__loaded = true; this.dispatchEvent( { type: 'loaded', content: this } ); } } } }; /** * Mimic Pixi BaseTexture.from.... method. * @param video * @param scaleMode * @returns {PIXI.VideoTexture} */ PIXI.VideoTexture.baseTextureFromVideo = function( video, scaleMode ) { if( !video._pixiId ) { video._pixiId = 'video_' + PIXI.TextureCacheIdGenerator++; } var baseTexture = PIXI.BaseTextureCache[ video._pixiId ]; if( !baseTexture ) { baseTexture = new PIXI.VideoTexture( video, scaleMode ); PIXI.BaseTextureCache[ video._pixiId ] = baseTexture; } return baseTexture; }; PIXI.VideoTexture.prototype.destroy = function() { if( this.source && this.source._pixiId ) { PIXI.BaseTextureCache[ this.source._pixiId ] = null; delete PIXI.BaseTextureCache[ this.source._pixiId ]; this.source._pixiId = null; delete this.source._pixiId; } PIXI.BaseTexture.prototype.destroy.call( this ); }; /** * Mimic PIXI Texture.from... method. * @param video * @param scaleMode * @returns {PIXI.Texture} */ PIXI.VideoTexture.textureFromVideo = function( video, scaleMode ) { var baseTexture = PIXI.VideoTexture.baseTextureFromVideo( video, scaleMode ); return new PIXI.Texture( baseTexture ); }; PIXI.VideoTexture.fromUrl = function( videoSrc, scaleMode ) { var video = document.createElement('video'); video.src = videoSrc; video.autoPlay = true; video.play(); return PIXI.VideoTexture.textureFromVideo( video, scaleMode); };
function Animal(name, weight) { this.name = name; this.weight = weight; this.getName = function() { return this.name; }; this.getWeight = function() { return this.weight; }; this.setWeight = function(weight) { this.weight = weight; }; } function Bear(name, weight) { Animal.call(this, name, weight); this.maxWeight = 200; this.eatWolf = function(animal) { this.setWeight(this.getWeight() - this.getWeight() * 0.1); this.setWeight(this.getWeight() + animal.getWeight() / 2); }; this.eatAnimal = function(animal) { if (animal.getName() !== "Wolf") { this.setWeight(this.getWeight() + animal.getWeight() * 0.3); } else { this.eatWolf(animal); } console.log( `The bear caught ${animal.getName()} and will gain weight` ); }; this.canBearMove = function() { return this.weight < this.maxWeight; }; this.loseWeight = function() { console.log("The bear is losing 20% weight"); this.weight = this.weight - this.weight * 0.2; }; } Bear.prototype = new Animal(); function Rabbit(name, weight) { Animal.call(this, name, weight); } Rabbit.prototype = new Animal(); function Wolf(name, weight) { Animal.call(this, name, weight); } Wolf.prototype = new Animal(); function Deer(name, weight) { Animal.call(this, name, weight); } Deer.prototype = new Animal();
import React, { Component } from "reactn"; import { View, Button, Text, TouchableOpacity, StyleSheet, Animated, FlatList } from "react-native"; import InventoryListItem from "./InventoryListItem"; import firebase from "../../Firebase"; import * as data from "../shared/data"; const db = firebase.firestore(); class InventoryComponent extends Component { constructor(props) { super(props); } render() { return ( <View> <FlatList style={styles.listContainer} data={this.global.inventory} renderItem={info => ( <InventoryListItem productId={info.item.ProductId} description={info.item.Description} qty={info.item.Qty} comment={info.item.Comment} style={{ backgroundColor: "white" }} //onItemPressed={() => props.onItemSelected(info.item.key)} /> )} /> </View> ); } } const styles = StyleSheet.create({ listContainer: { width: "100%" } }); export default InventoryComponent;
var pull = require('pull-stream'); var test = require('tape'); var black_box = require('./index.js'); var blackbox = new black_box(); test('should work as composed through stream', function (t) { t.plan(5); blackbox.add('demo'); blackbox.add('split', 'demo'); blackbox.on('demo', function (data) { t.ok(typeof data === 'object'); t.ok(data.demo === true); }); blackbox.on('split', function (data) { t.ok(typeof data === 'object'); t.ok(data.demo === true); }); pull( blackbox.tap('demo'), pull.drain(function (data) { t.ok(data.demo); }) ) pull ( pull.values([ { demo: true } ]), blackbox.pull(), pull.drain() ); }); test('should handle large json events', function (t) { t.plan(12); var long_string = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; blackbox.add('big'); blackbox.on('big', function (_data) { var data = Object.assign({}, _data); t.ok(typeof data === 'object'); t.ok(data.big.b[0] === 'with'); t.ok(data.big.b[1] === 'nested'); t.ok(data.big.b[2].c === 'data'); }); var _big = { big: { a: 'really long json event', b: [ 'with', 'nested', { c: 'data' } ], c: long_string, d: long_string, e: long_string, f: long_string }}; pull ( pull.values([ _big, _big, _big ]), blackbox.pull(), pull.drain() ); });
export default theme => ({ root: { padding: theme.spacing.unit * 2, overflow: 'hidden' }, inputs: { ...theme.flexColumnCenter }, buttons: { ...theme.flexColumnCenter }, scrollbar: { width: 500, height: 573, display: 'flex', flexDirection: 'row', fontSize: 20, color: '#7487a3', marginBottom: 20 }, titleContainer: { display: 'flex' }, titleText: { margin: '0 auto' }, switchButton: { float: 'right' } })
angular.module('timelineApp.controllers').controller('RegisterCtrl', ['$scope', '$http', 'AuthService', function($scope, $http, AuthService) { $scope.submit = function() { var payload = ('username=' + $scope.register.username + '&password=' + $scope.register.password + '&first_name=' + $scope.register.firstname + '&last_name=' + $scope.register.lastname + '&email=' + $scope.register.email); var config = { headers: {'Content-Type':'application/x-www-form-urlencoded;; charset=UTF-8'} } $http.post(AuthService.yii + '/site/register', payload, config).success(function(data) { return true; }).error(function(data) { return false; }); }; $scope.unique = function(name) { if (!(typeof(name) === 'string')) { return false; } var url = AuthService.yii + "/site/namecheck"; var config = { headers: {'Content-Type':'application/x-www-form-urlencoded;; charset=UTF-8'} } var payload = ('username=' + name); $http.post(AuthService.yii + "/site/namecheck", payload, config).success(function(data) { $scope.registerForm.username.$setValidity("unique", true); }).error(function(data) { $scope.registerForm.username.$setValidity("unique", false); }); return true; }; }]);
const mongoose = require('mongoose'); let TournmentSchema = require('./tournment-schema'); TournmentSchema.statics = { createTournment } let TournmentModel = mongoose.model('tournment', TournmentSchema); module.exports = TournmentModel; async function createTournment(body, requestUser) { let tournment = new TournmentModel(body); tournment.createdBy = requestUser; return await tournment.save(); }
import Layout from "../components/Layout"; import axios from "axios"; import {env} from "../next.config"; import Link from "next/link"; import {useState, useEffect} from "react"; import moment from "moment"; const Home = ({ categories}) => { const [setTrending, setTrendingState] = useState([]); useEffect(() => { loadTrending(); }, []); const loadTrending = async () => { const response = await axios.get(`${env.API}/link/popular`); setTrendingState(response.data); }; const handleClick = async (link_Id) => { // send link id to backend in order to increase views const response = await axios.put(`${env.API}/view-count`, {link_Id}); loadTrending(); } const displayLinks = () => { return ( setTrending.map((link, index) => { return ( <div className="row alert alert-secondary"> <div className="col-md-6" onClick={() => handleClick(link._id)}> <a href={link.url} target="_blank" className="custom text-secondary">{link.title}</a> </div> <div className="col-md-6"> <span className="badge text-dark">{moment(link.createdAt).fromNow()} added by {link.postedBy.name} </span> </div> <div className="colmd-12"> <span className="badge text-dark">{link.type} {link.medium}</span> <span className="badge text-dark">{link.views} views</span> {link.categories.map((category, index) => { return ( <span className="badge text-dark">{category.name}</span> ) })} </div> </div> ) }) ) } const listCategories = () => categories.map((element, index) => ( <Link href={`/links/${element.slug}`}> <a className="bg-light col-md-4 custom"> <div className="row" style={{"marginLeft": "0"}}> <div className="col-md-4 pb-3"> <img src={element.image && element.image.url} alt={element.name} style={{ width: '100px', height: 'auto' }} className="pr-3" /> </div> <div className="col-md-8" style={{"paddingLeft": "0"}}> <h3>{element.name}</h3> </div> </div> </a> </Link> )); return ( <Layout> <div className="row"> <div className="col-md-12"> <h1 className="font-weight-bold text-center">Category</h1> <br /> </div> </div> <div className="row"> <div className="col-md-5"> <h3>Top trending</h3> <br/> {displayLinks()} </div> <div className="col-md-7"> {listCategories()} </div> </div> </Layout> ); }; // server side render Home.getInitialProps = async () => { const response = await axios.get(`${env.API}/categories`); return {categories: response.data}; }; export default Home;
import React, {Component} from 'react'; class Index extends Component { render() { return ( <div className={`container`}> <h1>Welcome!</h1> <div> This site is designed for sharing KC ship lists and equip(work in progress) info. </div> <div> <h3>Instructions</h3> <h4>KC3</h4> <div>Note: Right now the only way would be manual. Later the would be buttons in SR#showcase.</div> <div>Open Strategy Room. Open devtools(F12 or Ctrl+Shift+I). CopyPaste code from <a target="_blank" href={`https://gist.github.com/DynamicSTOP/e68c68e6de4d5464aeafcdfa92dae1cd`}>here</a> into console. New tab should open with your ship list. </div> <h4>Other</h4> <div> Other viewers should be able to export using url hash. See <strong>datapacker.v1.js</strong>. </div> </div> <div> <h3>Github links</h3> <div><a href={`https://github.com/DynamicSTOP/kcexport`}>Website</a> for reporting issues</div> <div><a href={`https://github.com/KC3Kai/KC3Kai`}>KC3</a></div> <div><a href={`https://github.com/TeamFleet/WhoCallsTheFleet`}>WhoCallsTheFleet DB</a></div> </div> </div> ); } } export default Index;
const test = require('./testHelper')('kevm'); const assert = require('assert'); const mallet = test.mallet // import key let res = mallet.importPrivateKey(test.prvKeyA, 'passw0rd'); assert.strictEqual(res, test.accA); // new key const accB = mallet.newAccount('passw0rd'); res = mallet.listAccounts().filter(a => a != test.accA)[0] assert.strictEqual(res, accB); res = mallet.getBalance(accB); assert.strictEqual(res, '0'); // selecting account mallet.selectAccount(test.accA); res = mallet.currentAccount(); assert.strictEqual(res, test.accA); // requesting funds const balA1 = mallet.getBalance(); res = mallet.requestFunds(); test.awaitReceipt(res); const balA2 = mallet.getBalance(); console.log(balA1, '<', balA2); assert.ok(parseInt(balA2) > parseInt(balA1)); // sending TX let tx = {to: accB, gas: 100000, value: 1000} res = mallet.sendTransaction(tx, 'passw0rd'); test.awaitReceipt(res); assert.strictEqual(mallet.getBalance(accB), '1000') console.log('SUCCESS!');
import styled from "styled-components"; import stylers from "@paprika/stylers"; export const Content = styled.div` &:focus { ${stylers.focusRing.subtle(true)} } `;
/* * This is the model representation of the Users table. It represents a single * user. */ var Bookshelf = require('bookshelf').DB; /* So this model is a little more complicated. Recall from our DB schema that * we've got a join/bridge table for followers. * * The problem is, Bookshelf wants us to tell it what the end model will be. * Both sides of the join table point to User models (albeit different users). * But we can't import the User model into the User model, that would be circular. * Nor can we use a this/self reference in the User model because it would still * be undefined. * * The solution is to create a temporary bridge model called FollowerUser that * contains just a tableName attribute and nothing else. This is, in reality, * just a second copy of the User model with a different name and extra * relations. Check out /app/models/user-follow.js to see the implementation. * */ var FollowerUser = require("./user-follow").model; /* The tweets() attribute is the other side of the one-to-many relationship * between users and tweets. It will return all the tweet a user has posted. * * The followers() and following() attributes use the belongsToMany() method. * The first argument is the model type that will be on the other side of the * bridge table (see above for my explanation about why we couln't just use User). * The second argument is the name of the join table, followed by the key presenting * the current user and the key representing the other user. */ exports.model = Bookshelf.Model.extend({ tableName: "Users", tweets: function() { var Tweet = require("./tweet").model; return this.hasMany(Tweet, "user_id"); }, followers: function() { return this.belongsToMany(FollowerUser, "Followers", "followee", "follower"); }, following: function() { return this.belongsToMany(FollowerUser, "Followers", "follower", "followee"); } });
import React from 'react'; import { Link } from 'react-router'; import RaisedButton from 'material-ui/RaisedButton'; const styles = { base: { width: '600px' }, button: { margin: '0 10px' } }; const ButtonCenter = () => ( <div style={styles.base} className="boxItemCenter"> <div style={styles.button}> <RaisedButton label="Find a Job" primary={true} /> </div> <div style={styles.button}> <Link to={'post-job'}><RaisedButton label="Post a Job" /></Link> </div> </div> ); export default ButtonCenter;
var tokki = angular.module("tokkiApp"); tokki.config(["$stateProvider", "$urlRouterProvider", function($stateProvider, $urlRouterProvider){ $stateProvider .state('system.sii.recibidos', { url: "/recibidos", templateUrl: "pages/sii/xmlrecibidos/recibidos.html", controller: "XmlRecibidos", resolve: { tokkiData: ["$q", "tokkiApi", function($q, tokkiApi){ var deferred = $q.defer(); var dtes = tokkiApi.query({action: 'recibidos'}); $q.all([dtes.$promise]). then(function(response) { deferred.resolve(response); }); return deferred.promise; } ] }, }) } ]); tokki.controller('XmlRecibidos', ['$scope', '$rootScope', '$state', '$stateParams', 'tokkiData', 'tokkiApi', 'xmlFilter', 'xmlParser', 'Notification', function($scope, $rootScope, $state, $stateParams, tokkiData, tokkiApi, xmlFilter, xmlParser, Notification) { $scope.recibidos = tokkiData[0]; $scope.dtes = []; $scope.dteDetalle; $scope.search = {}; $scope.setDoc = function(docXml){ $scope.currentDoc = null; $scope.currentDoc = docXml; var x2js = new X2JS(); var decoded = window.atob(docXml.xml.replace(/-/g, '+').replace(/_/g, '/')) var doc = x2js.xml_str2json(decoded); var caratula = doc.EnvioDTE.SetDTE.Caratula; var dte = doc.EnvioDTE.SetDTE.DTE; var envioId = doc.EnvioDTE.SetDTE._ID; $scope.respuesta = {}; $scope.respuesta.rutReceptor = caratula.RutReceptor; $scope.respuesta.rutEmisor = caratula.RutEmisor; $scope.respuesta.envioid = envioId; if($scope.respuesta.rutReceptor != $rootScope.info.rut) Notification.warning('el archivo XML parece estar dirijido a un <strong>rut diferente</strong> a la suya, verifique que el rut antes de responder'); if(dte.constructor !== Array) dte = [dte]; $scope.respuesta.fecha = dte[0].Documento.Encabezado.IdDoc.FchEmis; $scope.respuesta.razon = dte[0].Documento.Encabezado.Emisor.RznSoc; $scope.respuesta.nroDetalles = dte.length; $scope.dtes = []; for(var x=0; x<dte.length; x++){ var detalles = []; if(dte[x].Documento.Detalle.constructor !== Array){ dte[x].Documento.Detalle = [dte[x].Documento.Detalle]; } for(var y=0; y<dte[x].Documento.Detalle.length;y++){ var UnmdItem = ''; var exe = ''; if(dte[x].Documento.Detalle[y].UnmdItem) UnmdItem = dte[x].Documento.Detalle[y].UnmdItem; if(dte[x].Documento.Detalle[y].IndExe) UnmdItem = dte[x].Documento.Detalle[y].IndExe; detalles.push({ 'dte': dte[x].Documento.Encabezado.IdDoc.TipoDTE, 'id': dte[x].Documento.Encabezado.IdDoc.Folio, 'producto': dte[x].Documento.Detalle[y].NmbItem, 'unidad': UnmdItem, 'exe': exe, 'cantidad': dte[x].Documento.Detalle[y].QtyItem, 'precio': dte[x].Documento.Detalle[y].PrcItem }) } if(dte[x].Documento.Encabezado.Receptor.RUTRecep != $rootScope.info.rut) Notification.warning('hay un <strong>rut diferente</strong> a la suya en el detalle, verifique que el rut antes de responder'); $scope.dtes.push({ 'dte': dte[x].Documento.Encabezado.IdDoc.TipoDTE, 'id': dte[x].Documento.Encabezado.IdDoc.Folio, 'fecha': dte[x].Documento.Encabezado.IdDoc.FchEmis, 'rutEmisor': dte[x].Documento.Encabezado.Emisor.RUTEmisor, 'rutReceptor': dte[x].Documento.Encabezado.Receptor.RUTRecep, 'razon': dte[x].Documento.Encabezado.Emisor.RznSoc, 'giro': dte[x].Documento.Encabezado.Emisor.GiroEmis, 'direccion': dte[x].Documento.Encabezado.Emisor.DirOrigen, 'comuna': dte[x].Documento.Encabezado.Emisor.CiudadOrigen, 'ciudad': dte[x].Documento.Encabezado.Emisor.RznSoc, 'exento': dte[x].Documento.Encabezado.Totales.MntExe, 'neto': dte[x].Documento.Encabezado.Totales.MntNeto, 'iva': dte[x].Documento.Encabezado.Totales.IVA, 'total': dte[x].Documento.Encabezado.Totales.MntTotal, 'rechazado': false, 'rechazo': '', 'detalles': detalles, 'dtexml': x2js.json2xml_str(dte[x]) }); } } $scope.saveRecepcion = function(){ $scope.sending = true; recepcion = tokkiApi.save({ action: 'acuse', control: 'recibomail', respuesta: $scope.respuesta, dtes: $scope.dtes, user_id: $scope.currentUserId }).$promise.then(function(response){ swal("success", "enviado", "success"); location.reload(); /* var pom = document.createElement('a'); pom.setAttribute('href', 'data:text/plain;charset=iso-8859-1;base64,' + response.xml); pom.setAttribute('download', 'acuse_recibo.xml'); pom.style.display = 'none'; document.body.appendChild(pom); pom.click(); document.body.removeChild(pom); */ $scope.sending = false; }, function(response){ Notification.error(response.data); $scope.sending = false; }) } $scope.saveMercaderia = function(){ mercaderia = tokkiApi.save({ action: 'acuse', control: 'mercaderia', respuesta: $scope.respuesta, dtes: $scope.dtes, user_id: $scope.currentUserId }).$promise.then(function(response){ var pom = document.createElement('a'); pom.setAttribute('href', 'data:text/plain;charset=iso-8859-1;base64,' + response.xml); pom.setAttribute('download', 'acuse_mercaderia.xml'); pom.style.display = 'none'; document.body.appendChild(pom); pom.click(); document.body.removeChild(pom); $scope.sending = false; }, function(response){ Notification.error(response.data); $scope.sending = false; }) } $scope.saveResultado = function(){ resultado = tokkiApi.save({ action: 'acuse', control: 'comercial', respuesta: $scope.respuesta, dtes: $scope.dtes, user_id: $scope.currentUserId }).$promise.then(function(response){ var pom = document.createElement('a'); pom.setAttribute('href', 'data:text/plain;charset=iso-8859-1;base64,' + response.xml); pom.setAttribute('download', 'acuse_comercial.xml'); pom.style.display = 'none'; document.body.appendChild(pom); pom.click(); document.body.removeChild(pom); $scope.sending = false; }, function(response){ Notification.error(response.data); $scope.sending = false; }) } } ]);
import React, {useState , useEffect} from "react"; import "./geradorPosts.css"; import api from "../../Connection/Api"; export default function GeradorPosts() { const [logado , setLogado] = useState([]); const [mensagem, setMensagem] = useState(""); let numero = localStorage.getItem("nome"); useEffect(() => { api .get("/usuarios/listar/" + numero) .then((response) => setLogado(response.data.resposta)) .catch((err) => console.log("deu erro" + err)) }, [numero] ) function enviarPostagem() { if(!!mensagem) { api.post("/usuarios/postar", { nome: logado.login, mensagem: mensagem, }) .then(() => console.log("ok")) .catch((err) => console.log("deu ruim" + err)) window.location.reload(); }else{ console.log("mensagem vazia") } } return ( <div className="post-ger"> <div className="ger"> <div className="img"></div> <form onSubmit={(event) => {event.preventDefault(); enviarPostagem();}}> <input type="text" placeholder="Digite o seu pensamento" value={mensagem} onChange={(event) => setMensagem(event.target.value)} /> <button className="btn-post" type="submit">Postar</button> </form> </div> </div> ); }
import Siembra from '@/models/ModeloSiembra'; export default { namespaced: true, state: { siembra: new Siembra('', '', '', '', '', '', '', ''), // Modelo siembra formSiembraValido: false, // Indica si el formulario de siembra es valido }, actions: { }, mutations: { // Coloca un nuevo siembra setSiembra(state, nuevaSiembra) { state.siembra = nuevaSiembra }, // Vacia el modelo siembra vaciarSiembra(state) { state.siembra = new Siembra('', '', '', '', '', '', '', '') }, cambiarEstadoFormSiembraValido(state, nuevoEstado) { state.formSiembraValido = nuevoEstado }, }, getters: { formSiembraValido: (state) => state.formSiembraValido, // Devuelve la variable formSiembraValido }, }
var app = angular.module('myApp.filters.defaultValueFilter', []); app.filter('defaultValue', function () { return function (input, params) { //console.log(input); //console.log(params); if (!input) { return params; } return input; }; });
chrome.browserAction.onClicked.addListener(function(tab) { chrome.tabs.executeScript({ code: "[...document.getElementsByTagName('button')].forEach(button => button.innerHTML = '<span>🥚</span>')" }); });
var hooksObject = { // Called every time an update or typeless form // is revalidated, which can be often if keyup // validation is used. formToModifier: function(modifier) { // console.log('formToModifier'); // console.log(modifier); var _set = modifier.$set if(_set && _set.securityDepositInCents) modifier.$set.securityDepositInCents = parseInt(_set.securityDepositInCents * 100); return modifier; }, // Called whenever `doc` attribute reactively changes, before values // are set in the form fields. docToForm: function(doc, ss) { // console.log('docToForm'); // console.log(doc); if(doc.securityDepositInCents) doc.securityDepositInCents = parseFloat(doc.securityDepositInCents) / 100; return doc; }, }; AutoForm.addHooks(['updateSpaceForm'], hooksObject);
/** * 类型扩展支持 * @desc 用于导入数据类型扩展 * @author wangxin */ 'use strict'; // javascript 严格说明 /** * 模块引用 * @private */ let { logger, fsh } = require('../framework'); const DIR_TYPE_EXTEND = "../extends"; let sysRoot = undefined; /** * 执行数据类型扩展导入。 * @param {string} catalog 扩展文件(.js)所在的目录 */ var extendImpoter = (catalog) => { var paths = fsh.scan(catalog); paths.forEach((_path) => { var name = _path.replace('.js', ''); _path = _path.replace(sysRoot, ''); try { require(name); logger.info("type-extend " + _path + " 导入成功."); } catch (err) { logger.error("type-extend ." + _path + " 导入失败.", err); } }); } /** * 模块内容定义 * @public */ module.exports.define = { "id": "type-extend-import", /** 模块名称 */ "name": "类型扩展引擎", /** 模块版本 */ "version": "1.0", /** 模块依赖 */ "dependencies": ["config"] } /** * 初始化 HttpHandler * @param {object} config 应用程序配置对象实例 */ module.exports.run = (config) => { if (!config) { throw new Error('config 不存在'); } sysRoot = config.rootPath; // 导入自定义目录的类型扩展 extendImpoter(fsh.join(__dirname, DIR_TYPE_EXTEND)); if (config && config.catalog && config.catalog.typeextend) { let rootPath = fsh.join(config.rootPath, config.catalog.typeextend); // 导入自定义目录的类型扩展 extendImpoter(rootPath); } };
function Controller() { function openMenu() { APP.openCloseMenu(); } function openOptions() { APP.openCloseOptions(); } function openNextWindow() { APP.openWindow(params); } function closeWindow() { APP.onClose && APP.onClose() && (APP.onClose = null); APP.closeWindow(); } function setCloseAction(callback) { APP.onClose = callback; return true; } function setLeftButton(_type, _boolean) { if (_type == APP.OPENMENU) $.openMenu.height = _boolean ? 36 : 0; else if (_type == APP.CLOSEWINDOW) $.closeWindow.height = _boolean ? 36 : 0; else { $.openMenu.height = _boolean ? 36 : 0; $.closeWindow.height = _boolean ? 36 : 0; } } function setRightButton(_type, _boolean, _params, _image) { if (_type == APP.OPENOPTIONS) { switch (_image) { case 1: $.openOptions.backgroundImage = "/images/ic_my_neighborhoods.png"; $.openOptions.backgroundSelectedImage = "/images/ic_my_neighborhoods_pressed.png"; } $.openOptions.height = _boolean ? 36 : 0; params = null; } else if (_type == APP.OPENWINDOW) { $.openNextWindow.height = _boolean ? 36 : 0; params = _params; } else { $.openOptions.height = _boolean ? 36 : 0; $.openNextWindow.height = _boolean ? 36 : 0; params = null; } } function addCustomView(_view) { $.container.add(_view); stackViews.push(_view); } function removeCustomView(_view) { $.container.remove(_view); _.each(stackViews, function(_value, _key) { if (_value == _view) { stackViews.splice(_key, 1); return; } }); } function removeAllCustomViews() { for (var i = stackViews.length; i > 0; i--) $.container.remove(stackViews.pop()); } function setTitle(_string) { $.title.text = _string; } require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments)); this.__controllerPath = "TopToolBar/TopToolBar"; arguments[0] ? arguments[0]["__parentSymbol"] : null; arguments[0] ? arguments[0]["$model"] : null; arguments[0] ? arguments[0]["__itemTemplate"] : null; var $ = this; var exports = {}; var __defers = {}; $.__views.container = Ti.UI.createView({ backgroundColor: "transparent", backgroundImage: "/images/bg_header_flex.png", left: 0, right: 0, height: 44, id: "container" }); $.__views.container && $.addTopLevelView($.__views.container); $.__views.title = Ti.UI.createLabel({ color: "white", font: { fontSize: 18 }, left: 50, id: "title" }); $.__views.container.add($.__views.title); $.__views.closeWindow = Ti.UI.createButton({ backgroundSelectedImage: "/images/ic_back_pressed.png", backgroundImage: "/images/ic_back.png", color: "#17B8E4", borderColor: "#18b2e0", borderWidth: 0, borderRadius: 1, style: Ti.UI.iPhone.SystemButtonStyle.PLAIN, font: { fontSize: 14 }, height: "0", width: 36, left: 10, id: "closeWindow" }); $.__views.container.add($.__views.closeWindow); closeWindow ? $.__views.closeWindow.addEventListener("click", closeWindow) : __defers["$.__views.closeWindow!click!closeWindow"] = true; $.__views.openMenu = Ti.UI.createButton({ backgroundSelectedImage: "/images/ic_dashboard_pressed.png", backgroundImage: "/images/ic_dashboard.png", color: "#17B8E4", borderColor: "#18b2e0", borderWidth: 0, borderRadius: 1, style: Ti.UI.iPhone.SystemButtonStyle.PLAIN, font: { fontSize: 14 }, height: 36, width: 36, left: 4, id: "openMenu" }); $.__views.container.add($.__views.openMenu); openMenu ? $.__views.openMenu.addEventListener("click", openMenu) : __defers["$.__views.openMenu!click!openMenu"] = true; $.__views.openOptions = Ti.UI.createButton({ backgroundSelectedImage: "/images/bgBlackOpacity39.png", backgroundImage: "/images/transparent.png", color: "#17B8E4", borderColor: "#18b2e0", borderWidth: 0, borderRadius: 1, style: Ti.UI.iPhone.SystemButtonStyle.PLAIN, font: { fontSize: 14 }, height: 36, width: 36, right: 4, id: "openOptions" }); $.__views.container.add($.__views.openOptions); openOptions ? $.__views.openOptions.addEventListener("click", openOptions) : __defers["$.__views.openOptions!click!openOptions"] = true; $.__views.openNextWindow = Ti.UI.createButton({ backgroundSelectedImage: "/images/bgBlackOpacity39.png", backgroundImage: "/images/transparent.png", color: "#17B8E4", borderColor: "#18b2e0", borderWidth: 0, borderRadius: 1, style: Ti.UI.iPhone.SystemButtonStyle.PLAIN, font: { fontSize: 14 }, height: "0", width: 36, right: 4, backgroundColor: "yellow", id: "openNextWindow" }); $.__views.container.add($.__views.openNextWindow); openNextWindow ? $.__views.openNextWindow.addEventListener("click", openNextWindow) : __defers["$.__views.openNextWindow!click!openNextWindow"] = true; $.__views.refresh_advice = Ti.UI.createLabel({ color: "#0066ff", font: { fontSize: 16 }, text: "Pulldown to update content", textAlign: "center", backgroundImage: "/images/bg_white_alpha90.png", top: 0, width: "100%", height: 0, id: "refresh_advice" }); $.__views.container.add($.__views.refresh_advice); $.__views.refresh_counter = Ti.UI.createView({ backgroundColor: "#0066ff", bottom: 2, height: 4, width: 0, borderRadius: 2, opacity: .8, id: "refresh_counter" }); $.__views.container.add($.__views.refresh_counter); exports.destroy = function() {}; _.extend($, $.__views); var APP = require("/core"); arguments[0] || {}; var params = null; var stackViews = []; exports.setCloseAction = setCloseAction; exports.setLeftButton = setLeftButton; exports.setRightButton = setRightButton; exports.addCustomView = addCustomView; exports.removeCustomView = removeCustomView; exports.removeAllCustomViews = removeAllCustomViews; exports.setTitle = setTitle; exports.refresh_advice = $.refresh_advice; exports.refresh_counter = $.refresh_counter; __defers["$.__views.closeWindow!click!closeWindow"] && $.__views.closeWindow.addEventListener("click", closeWindow); __defers["$.__views.openMenu!click!openMenu"] && $.__views.openMenu.addEventListener("click", openMenu); __defers["$.__views.openOptions!click!openOptions"] && $.__views.openOptions.addEventListener("click", openOptions); __defers["$.__views.openNextWindow!click!openNextWindow"] && $.__views.openNextWindow.addEventListener("click", openNextWindow); _.extend($, exports); } var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._; module.exports = Controller;
import { useState, useEffect } from 'react'; import { connect } from 'react-redux'; import { Link, useHistory } from 'react-router-dom'; import { useToasts } from 'react-toast-notifications'; import { fetchAllUser, deleteUser } from '../../redux/actions/userManageActionCreator'; import UserModalAdd from '../dashboard/UserModalAdd.component'; import UserModalDelete from '../dashboard/UserModalDelete.component'; const User = ({ users, dispatchGetAllUserAction, dispatchDeleteUserAction }) => { const history = useHistory(); const { addToast } = useToasts(); const [selected, setSelected] = useState(''); useEffect(() => dispatchGetAllUserAction(), [dispatchGetAllUserAction]) const showDeleteModal = (event, id) => { event.preventDefault(); setSelected(id); window.$('#modalDeleteUser').modal('show'); }; const handleOnDelete = () => { dispatchDeleteUserAction(selected, () => { window.$('#modalDeleteUser').modal('hide'); addToast('Delete User Successfully.', {appearance:'warning'}); }, (message) => { window.$('#modalDeleteUser').modal('hide'); addToast(`Error: ${message}`, {appearance:'error'}); }); }; const handleBack = () => { history.replace("/dashboard") }; return( <> <div className="con-dashboard-right"> <header className="px-3"> <button className="back my-auto px-2 py-1" onClick={handleBack}> <i className="fas fa-arrow-left mr-2"/> Back </button> <h4>User Management</h4> <button className="add my-auto px-2 py-1" data-bs-toggle="modal" data-bs-target="#modalAddUser"> <i className="fas fa-plus mr-2"/> User </button> </header> <div className="con-right"> <table className="user mb-5"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Username</th> <th>Role</th> <th className="detail">Detail</th> <th className="action">Action</th> </tr> </thead> <tbody> {users.map((user) => ( <tr key={user.id}> <td>{user.firstName}</td> <td>{user.lastName}</td> <td>{user.username}</td> <td>{user.role}</td> <td> <Link to={`/dashboard/user/${user.id}`} className="Link"> Detail </Link> </td> <td> <button onClick={(e) => showDeleteModal(e, user.id)}> Delete </button> </td> </tr> ))} </tbody> </table> </div> </div> <UserModalAdd/> <UserModalDelete handleOnDelete={handleOnDelete} /> </> ) } const mapStateToProps = state => ({ users: state.users }); const mapDispatchToProps = dispatch => ({ dispatchGetAllUserAction: () => dispatch(fetchAllUser()), dispatchDeleteUserAction: (id, onSuccess, onError) => dispatch(deleteUser(id, onSuccess, onError)) }); export default connect(mapStateToProps, mapDispatchToProps)(User); // const Data = [ // { // 'id': 1, // 'firstName': 'firstName', // 'lastName': 'LastName', // 'username': 'username', // 'role': 'User' // }, // { // 'id': 2, // 'firstName': 'firstName', // 'lastName': 'LastName', // 'username': 'username', // 'role': 'User' // }, // { // 'id': 3, // 'firstName': 'firstName', // 'lastName': 'LastName', // 'username': 'username', // 'role': 'User' // }, // { // 'id': 4, // 'firstName': 'firstName', // 'lastName': 'LastName', // 'username': 'username', // 'role': 'User' // }, // { // 'id': 5, // 'firstName': 'firstName', // 'lastName': 'LastName', // 'username': 'username', // 'role': 'User' // }, // { // 'id': 6, // 'firstName': 'firstName', // 'lastName': 'LastName', // 'username': 'username', // 'role': 'User' // }, // { // 'id': 7, // 'firstName': 'firstName', // 'lastName': 'LastName', // 'username': 'username', // 'role': 'User' // }, // { // 'id': 8, // 'firstName': 'firstName', // 'lastName': 'LastName', // 'username': 'username', // 'role': 'User' // }, // { // 'id': 9, // 'firstName': 'firstName', // 'lastName': 'LastName', // 'username': 'username', // 'role': 'User' // }, // { // 'id': 10, // 'firstName': 'firstName', // 'lastName': 'LastName', // 'username': 'username', // 'role': 'User' // }, // { // 'id': 11, // 'firstName': 'firstName', // 'lastName': 'LastName', // 'username': 'username', // 'role': 'User' // }, // { // 'id': 12, // 'firstName': 'firstName', // 'lastName': 'LastName', // 'username': 'username', // 'role': 'User' // }, // { // 'id': 13, // 'firstName': 'firstName', // 'lastName': 'LastName', // 'username': 'username', // 'role': 'User' // }, // { // 'id': 14, // 'firstName': 'firstName', // 'lastName': 'LastName', // 'username': 'username', // 'role': 'User' // }, // { // 'id': 15, // 'firstName': 'firstName', // 'lastName': 'LastName', // 'username': 'username', // 'role': 'User' // }, // ]
/** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow */ import React, { Component } from 'react'; import { StyleSheet, View, SafeAreaView, Text, ImageBackground } from 'react-native'; import PickerModal from 'react-native-picker-modal-view'; const data = require("./top20.json") console.disableYellowBox = true; export default class App extends Component { constructor(props) { super(props); this.state = { selectedItem: {}, intro: true }; } close() { console.log("close key pressed"); } selected(selected) { this.setState({ selectedItem: selected }); return selected; } onBackRequest() { console.log("back key pressed"); } componentDidMount() { // for intro :) setTimeout(() => { this.setState({ intro: false }); }, 2000); } render() { return ( <React.Fragment> {this.state.intro ? ( <ImageBackground style={styles.imgContainer} resizeMode={'contain'} source={require('./logo.png')}> </ImageBackground> ) : ( <SafeAreaView style={{ flex: 1, justifyContent: 'center', marginHorizontal: 20 }}> <PickerModal onSelected={(selected) => this.selected(selected)} // selected Item as IModalListInDto { // Id: string | number; // Name: string; // Value: string; // [key: string]: any; // CountryId?: ICity; // CityId?: ITown; // } onClosed={this.close.bind(this)} // close request onBackButtonPressed={this.onBackRequest.bind(this)} // back key press trigger items={data} sortingLanguage={'tr'} // default alphabet sorting is tr showToTopButton={true} // show top to up button while pass the screen half selected={this.state.selectedItem} // keyExtractor={(item, index) => item.Id.toString()} autoGenerateAlphabeticalIndex={true} // using first letter while auto generate alphabets array in data list selectPlaceholderText={'Choose one...'} onEndReached={() => console.log('list ended...')} // list end trigger searchPlaceholderText={'Search...'} // search box placeholder text // alphaBets={['A', 'E', 'O', 'M', 'N']} // if autoGenerateAlphabet variable is false, use custom alphabets requireSelection={false} // force select and user can not close modal, close button hidden autoSort={false} // generate sorting to use Name in data array // SearchInputProps={} // search input box props as React Native TextInputProps // ModalProps={} // modal props as React Native Modal ModalBaseProps | ModalPropsIOS | ModalPropsAndroid // FlatListProps={} // flatlist props as React Native FlatListProps<any> /> {this.state.selectedItem && <View style={{ padding: 10, alignItems: 'center', backgroundColor: '#ddd' }}> <Text>Chosen: </Text> <Text>{JSON.stringify(this.state.selectedItem)}</Text> </View>} </SafeAreaView> ) } </React.Fragment> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, imgContainer: { flex: 1, backgroundColor: '#F9D92D', top: 0, left: 0, justifyContent: 'center', alignItems: 'center', zIndex: 1 } });
import React , { Component } from 'react'; import {Link} from 'react-router-dom'; import {AboutDiv} from './aboutStyle'; import {CSSTransition} from 'react-transition-group'; import './style.css'; import Button from '@material-ui/core/Button'; import teal from '@material-ui/core/colors/teal'; import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles'; const theme = createMuiTheme ({ palette : { primary: teal } }) export default class About extends Component { constructor(props) { super(props); this.state = { flag: false } } handleClick = () => { this.setState ({ flag: !this.state.flag }) } render() { const {flag} = this.state; return ( <AboutDiv > <h3> Hello World. </h3> <p>Welcome to our</p> <MuiThemeProvider theme={theme}> <Button variant="contained" color='primary' onClick={this.handleClick}>click me!</Button> </MuiThemeProvider> {flag && <CSSTransition in = {flag} appear = {true} classNames="animate"> <Link to ='/'>online shop!</Link> </CSSTransition> } </AboutDiv> ) } }
//let lista = [1, 2, 3, 4, 5] let lista = ['Ovo', 'Sal', 'Leite', 'Massa'] //console.log(typeof lista) //console.log(Object.keys(lista)) let pessoa = { nome: 'Tilola', sobrenome: 'Naosei', idade: '120' } console.log(Object.values(pessoa))//retorna os valores do objeto console.log(Object.keys(pessoa))//retorna as chaves do objeto console.log(Object.entries(pessoa))//retorna arrays com chave e valor
const { Profile } = require('../../models/profile') module.exports = (req, res) => { const profile = new Profile({ firstname: req.query.firstname, lastname: req.query.lastname, address: req.query.address, email: req.query.email, password: req.query.password, phonenumber: req.query.phonenumber, birthday: req.query.birthday, type: req.query.type }) if(profile.type != "user" && profile.type != "owner" && profile.type != "admin"){ profile.type = "user"; } profile.save().then((result) => { res.send(result) }, (error) => { res.status(400).send(error) // 400 for bad request }) }
import { ADD_TODO, FILTER_TODO, GET_TODOS, TOGGLE_TODO } from '../actions/action-types' let initialState = { todos: [], filter: 'All' } export default function todoReducer(state = initialState, action) { let todosCopy = JSON.parse(JSON.stringify(state.todos)) switch (action.type) { case ADD_TODO: console.log(action.payload) todosCopy.push({...action.payload }) return { ...state, todos: todosCopy } case TOGGLE_TODO: todosCopy[action.payload].completed = !todosCopy[action.payload].completed return { ...state, todos: todosCopy } case FILTER_TODO: return { ...state, filter: action.payload } case GET_TODOS: todosCopy.push({ ...action.payload }) return { ...state, todos: todosCopy } default: return state } }
const koa = require('koa') const app = new koa() const port = 8422 app.context.renderToString = function() { console.log(`abc`) } app.use(async (ctx, next) => { ctx.renderToString() ctx.body = 'Hello, world' }) app.listen(port, function() { console.log(`✨ Server on: http://localhost:${port}`) })
import React, { useState, useEffect } from "react"; import { BrowserRouter } from "react-router-dom"; import Routes from "./Routes"; import NavBar from "./Navbar"; import UserContext from "./UserContext"; import './App.css'; import JoblyApi from "./api"; import jwt from "jsonwebtoken" /** * App: * - Makes API calls to get the current user, stores the user's token, and sets the current user. * - Current user is passed to other components via UserContext * * App -> [NavBar, Routes] * */ function App() { const initialToken = JSON.parse(localStorage.getItem("token")) || null; const [token, setToken] = useState(initialToken); const [currentUser, setCurrentUser] = useState("fetching"); // or could have a user, or an empty object, or set it to string like "waiting" or fetching /** * Makes API call to get the current user given a username and token. * Sets the currentUser. */ useEffect(function updateUserWithTokenChange() { async function fetchCurrentUser(token) { setCurrentUser("fetching"); let { username } = jwt.decode(token); let user = await JoblyApi.getCurrentUser(username, token); setCurrentUser(user); } if (token) fetchCurrentUser(token); if (!token) setCurrentUser({}); }, [token]); /** * Makes API call to log in the current user given a username and password. * Sets the token and gets the currentUser. */ async function logIn({ username, password }) { let newToken = await JoblyApi.login(username, password); setToken(() => newToken); return localStorage.setItem("token", JSON.stringify(newToken)); } /** * Makes API call to register a user given a username, password, firstName, * lastName and email. * Sets the token and gets the currentUser. */ async function register({ username, password, firstName, lastName, email }) { let newToken = await JoblyApi.register(username, password, firstName, lastName, email); setToken(() => newToken); return localStorage.setItem("token", JSON.stringify(newToken)); } /** * Logs the currentUser out by resetting the token and currentUser to null. */ function logOut() { setToken(null); return localStorage.setItem("token", JSON.stringify(null)); } return ( <div className="App"> <UserContext.Provider value={{currentUser, setCurrentUser }}> <BrowserRouter> {currentUser === "fetching" ? <i>loading...</i> : <div> <NavBar logOut={logOut} /> <Routes logIn={logIn} register={register} /> </div> } </BrowserRouter> </UserContext.Provider> </div> ); } export default App;
import * as React from 'react'; import debounce from 'lodash/debounce'; import { PropTypes } from 'prop-types'; import { Image, Text, View } from 'react-native'; import { Counter } from 'kitsu/components/Counter'; import { ProgressBar } from 'kitsu/components/ProgressBar'; import { Rating } from 'kitsu/components/Rating'; import { SelectMenu } from 'kitsu/components/SelectMenu'; import { MediaCard } from 'kitsu/components/MediaCard'; import Swipeable from 'react-native-swipeable'; import menuImage from 'kitsu/assets/img/menus/three-dot-horizontal-grey.png'; import { styles } from './styles'; const USER_LIBRARY_EDIT_SCREEN = 'UserLibraryEdit'; export const STATUS_SELECT_OPTIONS = [ { value: 'current', anime: 'Currently Watching', manga: 'Currently Reading' }, { value: 'planned', anime: 'Want To Watch', manga: 'Want To Read' }, { value: 'on_hold', anime: 'On Hold', manga: 'On Hold' }, { value: 'dropped', anime: 'Dropped', manga: 'Dropped' }, { value: 'completed', anime: 'Completed', manga: 'Completed' }, { value: 'remove', anime: 'Remove From Library', manga: 'Remove From Library' }, { value: 'cancel', anime: 'Nevermind', manga: 'Nevermind' }, ]; const HEADER_TEXT_MAPPING = { current: { anime: 'Watching', manga: 'Reading' }, planned: { anime: 'Want To Watch', manga: 'Want to Read' }, completed: { anime: 'Complete', manga: 'Complete' }, on_hold: { anime: 'On Hold', manga: 'On Hold' }, dropped: { anime: 'Dropped', manga: 'Dropped' }, }; export class UserLibraryListCard extends React.Component { static propTypes = { currentUser: PropTypes.object.isRequired, libraryEntry: PropTypes.object.isRequired, libraryStatus: PropTypes.string.isRequired, libraryType: PropTypes.string.isRequired, navigate: PropTypes.func.isRequired, onSwipingItem: PropTypes.func.isRequired, profile: PropTypes.object.isRequired, updateUserLibraryEntry: PropTypes.func.isRequired, } state = { isUpdating: false, libraryStatus: this.props.libraryEntry.status, progress: this.props.libraryEntry.progress, progressPercentage: Math.floor( (this.props.libraryEntry.progress / this.getMaxProgress()) * 100, ), ratingTwenty: this.props.libraryEntry.ratingTwenty, isSliderActive: false, } onProgressValueChanged = (newProgress) => { const maxProgress = this.getMaxProgress(); const progressPercentage = Math.floor((newProgress / maxProgress) * 100); this.setState({ progressPercentage, progress: newProgress, }, this.debounceSave); } onRatingChanged = (ratingTwenty) => { this.setState({ ratingTwenty }, this.debounceSave); } onRightActionActivate = () => { this.setState({ isSliderActive: true }); } onRightActionDeactivate = () => { this.setState({ isSliderActive: false }); } onStatusSelected = (libraryStatus) => { this.setState({ libraryStatus }, this.debounceSave); } onSwipeStart = () => this.props.onSwipingItem(true) onSwipeRelease = () => this.props.onSwipingItem(false) getMaxProgress() { const { libraryEntry, libraryType } = this.props; const mediaData = libraryEntry[libraryType]; if (mediaData.type === 'anime') { return mediaData.episodeCount; } return mediaData.chapterCount; } navigateToEditEntry = () => { if (this.state.isSliderActive) { const { currentUser, profile, libraryEntry, libraryStatus, libraryType, updateUserLibraryEntry, } = this.props; this.props.navigate(USER_LIBRARY_EDIT_SCREEN, { libraryEntry, libraryStatus, libraryType, profile, canEdit: profile.id === currentUser.id, ratingSystem: currentUser.ratingSystem, updateUserLibraryEntry, }); } } saveEntry = async () => { // send the status from props because that is the list we're looking // at not the status from state because that is what the value of the // card may have just been changed to const { libraryEntry, libraryType } = this.props; const { libraryStatus: newStatus, progress, ratingTwenty } = this.state; this.props.updateUserLibraryEntry(libraryType, libraryEntry.status, { id: this.props.libraryEntry.id, progress, ratingTwenty, status: newStatus, }); } debounceSave = debounce(this.saveEntry, 200); selectOptions = () => STATUS_SELECT_OPTIONS.map(option => ({ value: option.value, text: option[this.props.libraryType], })).filter(option => option.value !== this.props.libraryEntry.status); render() { const { libraryEntry, libraryType, currentUser } = this.props; const { progressPercentage, isSliderActive } = this.state; const mediaData = libraryEntry[libraryType]; const canEdit = this.props.profile.id === this.props.currentUser.id; const maxProgress = this.getMaxProgress(); return ( <Swipeable onRightActionActivate={this.onRightActionActivate} onRightActionDeactivate={this.onRightActionDeactivate} onRightActionComplete={this.navigateToEditEntry} onSwipeStart={this.onSwipeStart} onSwipeRelease={this.onSwipeRelease} rightActionActivationDistance={145} rightContent={[ <View key={0} style={[ styles.swipeButton, (isSliderActive ? styles.swipeButtonActive : styles.swipeButtonInactive), ]} > <Text style={styles.swipeButtonText}>{canEdit ? 'Edit Entry' : 'View Details'}</Text> </View>, ]} > <View style={styles.container}> { libraryEntry.status !== this.props.libraryStatus && <View style={styles.moved}> <View style={styles.horizontalRule} /> <Text style={styles.movedText}> Moved to <Text style={styles.movedToText}> {HEADER_TEXT_MAPPING[libraryEntry.status][libraryType]} </Text> </Text> <View style={styles.horizontalRule} /> </View> } <View style={styles.metaDataContainer}> <MediaCard cardDimensions={{ height: 75, width: 65 }} cardStyle={styles.posterImage} mediaData={mediaData} navigate={this.props.navigate} /> <View style={styles.content}> <View style={styles.titleSection}> <Text numberOfLines={1} style={styles.titleText} > {mediaData.canonicalTitle} </Text> {canEdit && ( <SelectMenu options={this.selectOptions()} onOptionSelected={this.onStatusSelected} style={styles.menuButtonContainer} > <Image source={menuImage} style={styles.menuButton} resizeMode="contain" /> </SelectMenu> )} </View> <View style={styles.progressContainer}> <ProgressBar height={6} fillPercentage={progressPercentage} backgroundStyle={styles.progressBarBackground} /> </View> <View style={styles.statusSection}> <Counter disabled={!canEdit} initialValue={libraryEntry.progress} maxValue={typeof maxProgress === 'number' ? maxProgress : undefined} progressCounter={typeof maxProgress === 'number'} onValueChanged={this.onProgressValueChanged} /> <Rating disabled={!canEdit} size="small" viewType="single" onRatingChanged={this.onRatingChanged} style={styles.ratingStyle} rating={libraryEntry.ratingTwenty} ratingSystem={currentUser.ratingSystem} /> </View> </View> </View> </View> </Swipeable> ); } }
'use strict'; var fs = require('fs'), path = require('path'); fs.exists('default.html', function(e){ if(e){ console.log("It there."); }else{ console.log('No there.'); } }); /* process.nextTick(function(){ console.log('Next tick callback.'); }); process.on('exit',function(code){ console.log('about to exit with code,'+code); }); console.log('nexttick was set!'); if (typeof(window) === 'undefined') { console.log('node.js,run...') } else{ console.log('browser.'); } */
"use strict"; var gulp = require('gulp'); var nodemon = require('gulp-nodemon'); var browserify = require('browserify'); var babelify = require('babelify'); var source = require('vinyl-source-stream'); var concat = require('gulp-concat'); var mocha = require('gulp-mocha'); var spawn = require('child_process').spawn; var config = { paths: { public: './public', js: ['./src/js/**/*.js', './src/js/**/*.jsx', './lib/*.js'], css: ['node_modules/bootstrap/dist/css/bootstrap.min.css', 'node_modules/font-awesome/css/font-awesome.min.css', './src/css/**/*.css'], tests: './test/**/*.js', mainJs: './src/js/main.js' } }; gulp.task('css', function() { gulp.src(config.paths.css) .pipe(concat('bundle.css')) .pipe(gulp.dest(config.paths.public + '/css')); }); gulp.task('js', function() { browserify(config.paths.mainJs) .transform("babelify", {presets: ["es2015", "react"]}) .bundle() .on('error', console.error.bind(console)) .pipe(source('bundle.js')) .pipe(gulp.dest(config.paths.public + '/scripts')); }); gulp.task('watch', function() { gulp.watch(config.paths.js, ['js']); gulp.watch(config.paths.css, ['css']); }); gulp.task('build', ['js', 'css']); gulp.task('test', function() { return gulp.src(config.paths.tests, {read: false}) .pipe(mocha({reporter: 'nyan'})); }); gulp.task('start', function () { nodemon({ script: 'index.js' , ext: 'js html' , env: { 'NODE_ENV': 'development' } }) }); gulp.task('startSimple', function (cb) { spawn('node', ['index.js'], { stdio: 'inherit' }); }); gulp.task('default', ['build', 'test', 'watch', 'start']); gulp.task('simple', ['build', 'test', 'watch', 'startSimple']);
(function () { 'use strict'; /** * @ngdoc object * @name activityForm.controller:ActivityFormCtrl * * @description * */ angular .module('activityForm') .controller('ActivityFormCtrl', ActivityFormCtrl); function ActivityFormCtrl($scope, $location, $stateParams, $state, Tags, ActivityForm) { $scope.activity = { Tags: [] }; $scope.tags = []; $scope.editMode = $state.current.name == 'activityFormUpdate'; $scope.save = function(valid) { if (!valid) return; showLoader(); ActivityForm.save($scope.activity).then(function(response) { hideLoader(); if (response.data) { $location.path("activity"); } }); } $scope.getActivity = function() { showLoader(); ActivityForm.getActivity($stateParams.activityId).then(function(response) { $scope.activity = response.data; hideLoader(); console.log($scope.activity); }); } $scope.getTags = function() { showLoader(); Tags.getAll().then(function(response) { $scope.tags = response.data; hideLoader(); }); } //Tags autocomplete $scope.searchText = ""; $scope.selectedItem = undefined; $scope.transformChip = function(chip) { // If it is an object, it's already a known chip if (angular.isObject(chip)) { return chip; } // Otherwise, create a new one // return { name: chip, type: 'new' } } $scope.querySearch = function(query) { var results = query ? $scope.tags.filter(createFilterFor(query)) : []; return results; } function createFilterFor(query) { var lowercaseQuery = angular.lowercase(query); return function filterFn(tag) { return (tag.TagName.indexOf(lowercaseQuery) === 0) || (tag.TagName.indexOf(lowercaseQuery) === 0); }; } //Start if ($scope.editMode) $scope.getActivity(); $scope.getTags(); } }());
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { emails: [] }, mutations: { SEND(state, email) { state.emails.push(email) } }, actions: { storeSend({commit}, {email}) { commit("SEND", email) } }, modules: { } })
console.log("Hoisting In Functions & Variables"); console.log(number); printNumber(); var number = 15; var printNumber2 = function () { console.log(`number : ${number}`); }; function printNumber() { console.log(`number : ${number}`); }
// global variables var signalServer = 'https://ec2-52-28-93-228.eu-central-1.compute.amazonaws.com:8888/'; /** * generates a random room name * @return {String} room name */ function randomRoomName() { var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; var length = 10; var result = ''; for (var i = length; i > 0; --i) { result += chars[Math.floor(Math.random() * chars.length)]; } return result; } /** * redirects to the specified room * @param {String} ID of the room */ function openRoom(roomId) { window.location.href = '/room/' + roomId; } /** * opens local streams and connects to signal server * @param {String} ID of the room */ function connect(roomId) { var webrtc = new SimpleWebRTC({ // the id/element dom element that will hold "our" video localVideoEl: 'localVideo', // the id/element dom element that will hold remote videos remoteVideosEl: 'remoteVideos', // immediately ask for camera access autoRequestMedia: true, url: signalServer, debug: true }); // we have to wait until it's ready webrtc.on('readyToCall', function () { // you can name it anything webrtc.joinRoom(roomId); }); }
function searchbox(){ return ` <div id="searchbox"> <input oninput="throttleFunction()" type="text" id="query" placeholder="Search By Receipe Name"> <div id="searchOptions"></div> </div>`; } export default searchbox;
import express from "express"; import config from "./config"; import load from "./loaders"; (async () => { try { const app = express(); const server = await load(app); server.listen(config.port, () => { console.log(`Server is starting on port ${config.port}`); }); } catch (err) { console.log(err); } })();
(function () { 'use strict'; /** * @ngdoc service * @name article.factory:Article * * @description * */ angular .module('article') .factory('Article', Article); function Article($http,consts) { var ArticleBase = {}; ArticleBase.getAll = function () { return $http({ method: "GET", url: consts.serverUrl + "Article/GetArticles", }); }; ArticleBase.delete = function(articleId) { return $http({ method: "POST", url: consts.serverUrl + "Article/DeleteArticle", data: { articleId: articleId } }); }; return ArticleBase; } }());
app.factory('dataservice', function($http,$log,$q){ var factory = {}; const ROOT_URL = 'http://localhost:3090'; //Get all pokemon data factory.getPokemons = function(){ var deferred = $q.defer(); $http.get(ROOT_URL + '/pokemon') .then(function(data) { deferred.resolve(data); },function(msg, code) { deferred.reject(msg); $log.error(msg, code); }); return deferred.promise; }; //Get all pokemon types factory.getPokemonTypes = function(){ var deferred = $q.defer(); $http.get(ROOT_URL + '/types') .then(function(data) { deferred.resolve(data); },function(msg, code) { deferred.reject(msg); $log.error(msg, code); }); return deferred.promise; }; //Get skills based on id factory.getPokemonSkills = function(pokemonSkillId){ var deferred = $q.defer(); $http.get(ROOT_URL + '/skills?id='+pokemonSkillId) .then(function(data) { deferred.resolve(data); },function(msg, code) { deferred.reject(msg); $log.error(msg, code); }); return deferred.promise; }; return factory; });
import React from 'react'; import { render } from 'react-dom'; // import Counter from './Counter'; import Input from './Input'; import Child from './Child'; import Parent from './Parent'; import Demo from './Demo'; import Counter from './Counter'; import FetchUseEffect from './FetchUseEffect'; render(<FetchUseEffect />, document.getElementById('root'));
import { checkSelector } from '../../utils/util.js'; export default checkSelector(':fullscreen');
//IMPORTS //react import React, { useState, useEffect, useContext } from "react"; // eslint-disable-line no-unused-vars //styled-components import styled from "styled-components"; // router import { Link } from "react-router-dom"; // contexts import { UserContext } from "../../../contexts/UserContext"; import { UserMissionsContext } from "../../../contexts/UserMissionsContext"; // helpers import { flex } from "../../../styles/global/Mixins"; //axios with auth import { axiosWithAuth } from "../../../helpers/axiosWithAuth"; // eslint-disable-line no-unused-vars //images import waves from "../../../images/Onboarding/waves.svg"; // components import Calendar from "./Calendar.js"; const CreateTMission = props => { // contexts const activeUser = useContext(UserContext); const userMissions = useContext(UserMissionsContext); const [missionInfo, setMissionInfo] = useState({ name: "", date: "", desc: "" }); const [calendar, setCalendar] = useState({ isOpen: false }); const [selectedDay, setSelectedDay] = useState("mm/dd/yy"); console.log(selectedDay); const routeToTLView = e => { e.preventDefault(); props.history.push("/team-view"); }; const handleChanges = e => { setMissionInfo({ [e.target.name]: e.target.value }); }; const handleSubmit = e => { props.debug && console.log(missionInfo); props.history.push("/team-view"); }; const toggleCalendar = () => { setCalendar({ isOpen: !calendar.isOpen }); console.log("[checking calendar state]", calendar); }; return ( <TVContainer> <ButtonNoColor onClick={routeToTLView}>&lt;</ButtonNoColor> <User> <Link to="/coming-soon"> <i className="fas fa-bell"></i> </Link> <Link to="/profile-overview"> <Avatar> {activeUser.avatar && ( <img src={activeUser.avatar} alt="User avatar" /> )} </Avatar> </Link> </User> <Header>Create Team Mission</Header> <Form onSubmit={handleSubmit}> <FormHeader>Mission Name</FormHeader> <InputDiv> <Input type="text" name="name" placeholder="Create a name" onChange={handleChanges} value={missionInfo.name} width={100} border={"1px solid #3D3B91"} backgroundColor={"#3D3B91"} /> </InputDiv> <FormHeader>Due Date</FormHeader> <InputDiv onClick={toggleCalendar}> <Input type="text" name="date" placeholder={selectedDay} onChange={handleChanges} value={missionInfo.date} width={100} border={"1px solid #3D3B91"} backgroundColor={"#3D3B91"} /> <i className="fas fa-calendar-alt"></i> </InputDiv> <Calendar calendar={calendar} setCalendar={setCalendar} setTheDay={setSelectedDay} /> {!calendar.isOpen && ( <> {" "} <FormHeader>Mission Description</FormHeader> <InputDiv className="mission-desc"> <Input type="text" name="desc" placeholder="Add a description" onChange={handleChanges} value={missionInfo.desc} width={100} border={"1px solid #3D3B91"} backgroundColor={"#3D3B91"} className="missionInput" /> </InputDiv>{" "} </> )} <Button onClick={handleSubmit}>Share with your team</Button> </Form> </TVContainer> ); }; const TVContainer = styled.div` display: flex; flex-direction: column; align-items: center; font-family: "Catamaran", sans-serif; margin: auto; line-height: 1.5; background-color: #4742bc; background-image: url(${waves}); background-size: contain; color: #7f7cca; width: 100vw; height: 100vh; max-height: 100vh; padding: 8%; &:nth-child(*) { background-color: green; margin-bottom: 5%; } `; const Header = styled.h1` margin-right: 3rem; font-weight: bold; font-size: calc(110% + 2vw); line-height: 6.6rem; letter-spacing: 3.5px; color: #ffffff; `; const FormHeader = styled.p` font-size: calc(100% + 0.1vw); font-weight: bold; text-transform: uppercase; line-height: 2.6rem; letter-spacing: 2px; color: #b8b7e1; `; const Form = styled.form` display: flex; flex-direction: column; width: 89%; input { font-size: calc(100% + 0.2vw); ::-webkit-input-placeholder { font-family: "Catamaran", sans-serif; color: #a6a6a6; } } .disabledColor { opacity: 30%; } `; const InputDiv = styled.div` display: flex; justify-content: space-between; border: 1px solid #3d3b91; margin: 3% 0; padding: 5%; width: 100%; border-radius: 3px; box-shadow: 1px 1px 1px 1px #35347f; background: #3d3b91; color: #ffffff; i { color: rgba(204, 201, 255, 0.4); font-size: 4.5vw; } .missionInput { align-content: flex-start; height: 15rem; ::-webkit-input-placeholder { } } `; const Input = styled.input` border: 1px solid #3d3b91; background: #3d3b91; color: #ffffff; outline: none; font-size: calc(100%); ::-webkit-input-placeholder { font-family: "Catamaran", sans-serif; font-size: calc(100%); } `; const Button = styled.a` display: flex; justify-content: space-evenly; border-radius: 0.5rem; padding: 1.5rem 0.8rem; width:75%; text-align:center; margin: 13% auto auto; background: #E05CB3; color: white; font-size:calc(110% + 0.5vw); letter-spacing:0.1rem; } `; const ButtonNoColor = styled.a` margin-right: 89%; font-size: 2rem; font-style: medium; color: #ccc9ff; `; const User = styled.div` width: 10rem; height: 5rem; position: absolute; top: 3rem; right: 3rem; ${flex.flexRowNoWrapAround} i { font-size: 2rem; } a { color: #ccc9ff; } `; const Avatar = styled.div` width: 5rem; height: 5rem; border-radius: 50%; background-image: url("https://i1.wp.com/grueneroadpharmacy.com/wp-content/uploads/2017/02/user-placeholder-1.jpg?ssl=1"); background-size: cover; img { width: 100%; border-radius: 50%; } `; export default CreateTMission;
import React, { createContext, useContext } from "react"; // Context is used to share the data between different components // Context related code could be moved to separate file const defaultContextValue = { id: "1", name: "user1", }; const Context = createContext(defaultContextValue); // const Provider = Context.Provider; // const Consumer = Context.Consumer; const ChildComponent = () => { const cnt = useContext(Context); return <> test : {cnt.name}</>; }; const ContextApiExample = () => { return ( <h1> {/* If you have to pass small value through provider you can do it in following manner */} {/* <Context.Provider value = "test"> */} <ChildComponent /> {/* </Context.Provider> */} </h1> ); }; export default ContextApiExample;
import React, { Component } from 'react'; import { Card, CardBody, CardHeader, Col, Collapse, Fade, Form, FormGroup, Input, Label, Row, Button, } from 'reactstrap'; import crypto from 'crypto'; import axios from 'axios'; import { ToastContainer, toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; import { token, API_SERVER } from '../../../helper/variable'; export default class ConfigAPI extends Component { constructor(props) { super(props) this.state = { collapse: true, fadeIn: true, timeout: 300, secretKey: '', tokenAuth: '', showSecret: false, showSecretManual: false, showToken: false, showTokenManual: false }; } onClick = () => { const secret = crypto.randomBytes(10).toString('hex'); this.setState({ secretKey: secret, showSecret: true, showSecretManual: false }) } onClickInputSecretKey = () => { this.setState({ showSecret: false, showSecretManual: true, secretKey: ''}) } onClickToken = () => { const secret = crypto.randomBytes(20).toString('hex'); this.setState({ tokenAuth: secret, showToken: true}) } success = message => { toast.success(`${message}`, { onClose: () => window.location.href="/config-api", autoClose: 3000 }) } error =message => { toast.error(`${message}`,{ autoClose: 3000 }) } submitData = e => { e.preventDefault(); axios.put(`${API_SERVER}/config-api`,{ secret_key: this.state.secretKey, api_token: this.state.tokenAuth }, { headers: { Authorization: `Bearer ${token}` } }).then(result => { if(result.data.status === "OK"){ this.success('Config API berhasil diubah') } else { this.error('Config API gagal diubah') } }) .catch(error => { console.log(error) this.error('Terdapat kesalahan pada server') }) } render() { return ( <div> <Row> <ToastContainer position={toast.POSITION.TOP_CENTER}/> <Col xs="9"> <Fade timeout={this.state.timeout} in={this.state.fadeIn}> <Card> <CardHeader> <i className="fa fa-edit"></i>Config API </CardHeader> <Collapse isOpen={this.state.collapse} id="collapseExample"> <CardBody> <div> Anda harus mengetahui Secret Key dan Token Authentication anda untuk melakukan integrasi dengan Jazaa. Secret Key dan Token Authentication digunakan untuk berkomunikasi dengan API Jazaa dalam bertransaksi. </div> <Form onSubmit={this.submitData} className="form-horizontal"> <FormGroup style={{marginTop: 15}}> <Label htmlFor="appendedInput">Secret Key</Label> <div className="controls"> <Button onClick={this.onClickInputSecretKey} color="primary" style={{marginBottom: 10, marginRight: 10}}>Input Secret Key</Button> <Button style={{marginBottom:10}} onClick={this.onClick}>Generate key</Button> {this.state.showSecret && <Input style={{width: 350}} id="appendedInput" size="16" type="text" disabled value={this.state.secretKey} />} {this.state.showSecretManual && <Input style={{width: 350}} id="appendedInput" size="16" type="text" onChange={e => this.setState({ secretKey: e.target.value})} value={this.state.secretKey} /> } </div> </FormGroup> <FormGroup> <Label htmlFor="appendedPrependedInput">Token Authentication</Label> <div className="controls"> <Button style={{marginBottom:10}} onClick={this.onClickToken}>Generate Token Auth</Button> {this.state.showToken && <Input style={{width: 350}} id="appendedInput" size="16" type="text" disabled value={this.state.tokenAuth} />} </div> </FormGroup> <div className="form-actions"> <Button type="submit" size="sm" color="success" style={{marginRight: '10px'}}><i className="fa fa-dot-circle-o"></i>Submit</Button> </div> </Form> </CardBody> </Collapse> </Card> </Fade> </Col> </Row> </div> ) } }
import { cons, car, cdr } from 'hexlet-pairs'; import { getRandomInt } from '../utils'; import gameConstructor from '../index'; const makeExp = (operation, a, b) => cons(cons(operation, a), b); const getOperation = exp => car(car(exp)); const getA = exp => cdr(car(exp)); const getB = exp => cdr(exp); const getRandomOperation = () => { switch (getRandomInt(0, 2)) { case 1: return '-'; case 2: return '*'; default: return '+'; } }; const calc = (exp) => { const a = getA(exp); const b = getB(exp); switch (getOperation(exp)) { case '-': return a - b; case '*': return a * b; default: return a + b; } }; export default () => { const rules = 'What is the result of the exp?'; const makeQuestion = () => { const exp = makeExp(getRandomOperation(), getRandomInt(0, 20), getRandomInt(0, 20)); const expString = `${getA(exp)} ${getOperation(exp)} ${getB(exp)}`; const correct = calc(exp); return cons(expString, correct); }; gameConstructor(rules, makeQuestion); };
const mongoose = require('mongoose'); const URLSchema = mongoose.Schema({ shortURL: { type: String, required: true }, longURL: { type: String, required: true }, timeOfCreation: { type: Number, default: Math.floor(Date.now()/1000), required: true }, timeOfDeletion: { type: Number, required: true }, privateOrPublic: { type: String, required: true }, accessCounts: { type: Number, default: 0 } }); const URL = module.exports = mongoose.model('URL', URLSchema );
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(1); /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { var rocky = __webpack_require__(2); //initialize watchface var d = new Date(); var timeString = d.toLocaleTimeString() var hmsArray = timeString.split(":") var timeInSeconds = (parseInt(hmsArray[0]*3600) + parseInt(hmsArray[1]*60) + parseInt(hmsArray[2]*1)) var currentTimeInCentiDays = parseInt(timeInSeconds / 864) rocky.requestDraw(); rocky.on('draw', function(event) { var ctx = event.context; ctx.clearRect(0, 0, ctx.canvas.clientWidth, ctx.canvas.clientHeight); var offsetY = (ctx.canvas.clientHeight - ctx.canvas.unobstructedHeight) / 2; var centerX = ctx.canvas.unobstructedWidth / 2; ctx.fillStyle = 'white'; ctx.textAlign = 'center'; ctx.font = '26px bold Leco-numbers-am-pm'; ctx.fillText(currentTimeInCentiDays, centerX, (66 - offsetY)); }); rocky.on('secondchange', function(event) { var d = new Date(); var timeString = d.toLocaleTimeString(); var hmsArray = timeString.split(":"); var timeInSeconds = (parseInt(hmsArray[0]*3600) + parseInt(hmsArray[1]*60) + parseInt(hmsArray[2])); //console.log("currentTimeInCentiDays: " + currentTimeInCentiDays); if(timeInSeconds % 864 == 0) { currentTimeInCentiDays = timeInSeconds / 864 console.log("one centiDay has elapsed: " + currentTimeInCentiDays) rocky.requestDraw(); } }); /***/ }), /* 2 */ /***/ (function(module, exports) { module.exports = _rocky; /***/ }) /******/ ]);
import Axios from 'axios'; function CallUrl(updateItemsCallback, url) { console.log('CallUrl'); Axios.get(url) .then((response) => { console.log('Axios.response.data'); console.log(response.data); updateItemsCallback(response.data.items) }) .catch(function(error) { console.log('CallUrl', error); }); } export const AllLanguage = (updateItemsCallback) => { console.log('All call'); CallUrl(updateItemsCallback, 'https://api.github.com/search/repositories?q=stars:%3E1&sort=stars&order=desc&type=Repositories') } export const SingleLanguage = (updateItemsCallback, language) => { console.log('SingleLanguage call'); CallUrl(updateItemsCallback, `https://api.github.com/search/repositories?q=stars:>1+language:${language}&sort=stars&order=desc&type=Repositories`) } export const GetLogin = (loginCallback, login) => { console.log('SingleLanguage call'); Axios.get('http://api.github.com/users/' + login) .then((response) => { console.log('Axios.response.data'); console.log(response.data); loginCallback(response.data) }) .catch(function(error) { console.log('SingleLanguage', error); }); }
'use strict'; const YamlTree = require('../index'); const opts = { encoding: 'utf8' }; const Tree = new YamlTree('./test/test.raml', opts); Tree.buildTree(true) .then(success => { console.log(Tree.getJson()); }) .catch(err => { console.log('Something went horribly wrong...\n' + err); });
var tipo = document.getElementById('inputTipo') var precoValor = document.getElementById('inputPreco') var carros = document.getElementById('inputCarro') var nome = document.getElementById('inputNome') var telefone = document.getElementById('inputFone') var email = document.querySelector('#email'); var error = document.querySelector('#error-email'); function cadastrar() { if (nome.value == "") { alert('Preencha o campo nome!') return } if (email.value == "") { alert('preencha o campo Email') return } if (telefone.value == "") { alert('preencha o campo de telefone') } alert('Cadastrado com sucesso!!') $.ajax({ url: "http://localhost/projetos/Formulario-car/adiciona-dados.php", type: 'POST', data: $('#formulario').serialize(), success: function (data) { alert('Cadastrado com sucesso!') console.log(data); }, error: function (data) { alert('Erro ao chamar requisiçao') } }); return; } function tipoCar() { $.ajax({ url: "http://localhost/projetos/Formulario-car/tipo-carros.php/?tipo=" + tipo.value, type: 'GET', success: function (data) { tipos = data limpaResetCarros(); createCarros(tipos); getPreco(tipo.value); }, error: function (data) { alert('Erro ao chamar requisiçao') } }); } function limpaResetCarros() { while (carros.length) { carros.remove(0); } } //Validaçao do E-mail function validarEmail() { if (!email.checkValidity()) { error.innerHTML = "Email invalido"; error - email } } function redefinirMsg() { var error = document.querySelector('#error-email'); if (error.innerHTML == "Email invalido") { error.innerHTML = ""; } } //mascara no telefone function mascara(o, f) { v_obj = o v_fun = f setTimeout("execmascara()", 1) } function execmascara() { v_obj.value = v_fun(v_obj.value) } function mtel(v) { v = v.replace(/\D/g, ""); //Remove tudo o que não é dígito v = v.replace(/^(\d{2})(\d)/g, "($1) $2"); //Coloca parênteses em volta dos dois primeiros dígitos v = v.replace(/(\d)(\d{4})$/, "$1-$2"); //Coloca hífen entre o quarto e o quinto dígitos return v; } function id(el) { return document.getElementById(el); } window.onload = function () { id('inputFone').onkeyup = function () { mascara(this, mtel); } } function createTipos(tipos) { tipos.forEach(function (element, index, array) { var optionElement = document.createElement("option"); optionElement.value = element.tipo; optionElement.text = element.tipo; tipo.add(optionElement, tipo.options[0]); }) } function createCarros(carro) { carro.forEach(function (element, index, array) { var optionElement = document.createElement("option"); optionElement.value = element.nome; optionElement.text = element.nome; carros.add(optionElement, carros.options[0]); }) } function getPreco(preco) { console.log(preco); tipos.forEach(function (element, index, array) { if (preco == element.tipo) { valorTipo = element.preco; precoValor.value = element.preco } }) } var valorTipo = ""; var tipos = []; //preenche as informaçoes do select de tipo $.ajax({ url: "http://localhost/projetos/Formulario-car/carro.php", type: 'GET', success: function (data) { tipos = data createTipos(tipos); }, error: function (data) { alert('Erro ao chamar requisiçao') } });
angular.module('app.routes', ['ngRoute']) .config(function($routeProvider, $locationProvider) { $routeProvider // home route .when('/', { templateUrl: 'views/pages/login.html', controller: 'MainController', controllerAs: 'login' }) .when('/home', { templateUrl: 'views/pages/home.html' }); $locationProvider.html5Mode(true); });
class Controller { index(req,res,...args){ res.setHeader('content-type','text/html;charset="utf-8"'); res.end('<h1><a href="/Item/index">Go ToDoList</a></h1>') } } module.exports = new Controller();
const Sequelize = require('sequelize'); module.exports = function(sequelize, DataTypes) { return sequelize.define('SalesSequenceProfile', { profile_id: { autoIncrement: true, type: DataTypes.INTEGER.UNSIGNED, allowNull: false, primaryKey: true, comment: "ID" }, meta_id: { type: DataTypes.INTEGER.UNSIGNED, allowNull: false, comment: "Meta_id", references: { model: 'sales_sequence_meta', key: 'meta_id' } }, prefix: { type: DataTypes.STRING(32), allowNull: true, comment: "Prefix" }, suffix: { type: DataTypes.STRING(32), allowNull: true, comment: "Suffix" }, start_value: { type: DataTypes.INTEGER.UNSIGNED, allowNull: false, defaultValue: 1, comment: "Start value for sequence" }, step: { type: DataTypes.INTEGER.UNSIGNED, allowNull: false, defaultValue: 1, comment: "Step for sequence" }, max_value: { type: DataTypes.INTEGER.UNSIGNED, allowNull: false, comment: "MaxValue for sequence" }, warning_value: { type: DataTypes.INTEGER.UNSIGNED, allowNull: false, comment: "WarningValue for sequence" }, is_active: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: 0, comment: "isActive flag" } }, { sequelize, tableName: 'sales_sequence_profile', timestamps: false, indexes: [ { name: "PRIMARY", unique: true, using: "BTREE", fields: [ { name: "profile_id" }, ] }, { name: "SALES_SEQUENCE_PROFILE_META_ID_PREFIX_SUFFIX", unique: true, using: "BTREE", fields: [ { name: "meta_id" }, { name: "prefix" }, { name: "suffix" }, ] }, ] }); };
let price = +prompt('enter price'); let discount = +prompt('enter discount'); let pWd = price / 100 * (100 - discount); pWd = parseInt(pWd * 100) / 100; let saved = price - pWd; saved = parseInt(saved * 100) / 100; if (!price || !discount || price <= 0 || discount <= 0) { console.log('Invalid data'); } else { console.log(`Price without discount ${price}\nDiscount ${discount}%\nPrice with discount ${pWd}\nSaved ${saved}`); }
import { combineReducers } from "redux"; function getUser(state = [], action) { switch (action.type) { case "SET_USER": // console.log(action.payload, "Payload") return { ...state, user: action.payload } default: return state; } } function getAllUsers(state = [], action) { switch (action.type) { case "SET_ALL_USERS": return { ...state, users: action.payload } default: return state; } } const rootReducer = combineReducers({ getUser, getAllUsers }); export default rootReducer;
import Vue from 'vue'; let initializePageSlug = (state, page) => { if (state.dictionary[page.slug] === undefined) { Vue.set(state.dictionary, page.slug, []); } } export default { namespaced: true, state () { return { all: [], dictionary: {}, } }, mutations: { initialize (state, payload) { if (payload['_library'] !== undefined) { state.all = payload._library; } else { state.all = payload; } state.dictionary = payload; }, removeById (state, id) { state.all = state.all.filter((el) => { return el.id !== id; }); }, overrideById (state, payload) { state.all = state.all.map((el) => { return el.id == payload.id ? payload.record : el; }); }, add (state, record) { state.all.push(record); }, addToPage (state, payload) { initializePageSlug(state, payload.page); state.dictionary[payload.page.slug].push(payload.record); }, removeFromPage (state, payload) { initializePageSlug(state, payload.page); state.dictionary[payload.page.slug] = state.dictionary[payload.page.slug].filter((currentRecord) => { return currentRecord.id != payload.record.id; }); }, removeFromPageByIndex (state, payload) { initializePageSlug(state, payload.page); state.dictionary[payload.page.slug].splice(payload.index, 1); }, removeFromPageByIdAndPivot (state, payload) { initializePageSlug(state, payload.page); state.dictionary[payload.page.slug] = state.dictionary[payload.page.slug].filter((currentRecord) => { return ! (currentRecord.id == payload.record.id && currentRecord.pivot.preferences[payload.pivotProperty] == payload.record.pivot.preferences[payload.pivotProperty]); }); } }, getters: { all (state) { return state.all; }, allById: (state) => (id) => { return state.all.filter((el) => { return el.id == id; }); }, byId: (state) => (id) => { return state.all.filter((el) => { return el.id == id; })[0]; }, byPageSlug: (state) => (slug) => { return state.dictionary[slug] !== undefined ? state.dictionary[slug] : []; }, countByPageSlug: (state) => (slug) => { return state.dictionary[slug] !== undefined ? state.dictionary[slug].length : 0; }, pageHas: (state) => (payload) => { return state.dictionary[payload.page.slug].filter((currentRecord) => { return currentRecord.id == payload.record.id; }).length > 0; }, pageHasWithPivot: (state) => (payload) => { return state.dictionary[payload.page.slug].filter((currentRecord) => { return currentRecord.id == payload.record.id && currentRecord.pivot.preferences[payload.pivotProperty] == payload.record.pivot.preferences[payload.pivotProperty]; }).length > 0; }, idsForPage: (state) => (page) => { return state.dictionary[page.slug].map((record) => { return record.id; }); }, idsAndPivotForPage: (state) => (payload) => { return state.dictionary[payload.page.slug].map((record) => { let tmp = {}; tmp['id'] = record.id; tmp[payload.pivotProperty] = record.pivot.preferences[payload.pivotProperty]; return tmp; }); } }, actions: { initialize (context, payload) { context.commit('initialize', payload); }, removeById(context, id) { context.commit('removeById', id); }, overrideById(context, payload) { context.commit('overrideById', payload); }, add(context, record) { context.commit('add', record); }, addToPage(context, payload) { context.commit('addToPage', payload); }, removeFromPage(context, payload) { context.commit('removeFromPage', payload); }, removeFromPageByIndex(context, payload) { context.commit('removeFromPageByIndex', payload); }, removeFromPageByIdAndPivot(context, payload) { context.commit('removeFromPageByIdAndPivot', payload); } } }
import React, { useEffect, useState } from 'react'; import 'bootstrap/dist/css/bootstrap.min.css'; import { Container, Row, Col, Form, Button } from 'react-bootstrap'; import Autocomplete from '@material-ui/lab/Autocomplete'; import TextField from '@material-ui/core/TextField'; import AutoCompleteSearch from '../AutoCompleteSearch/AutoCompleteSearch'; const getAllStudents = async () => { console.log("async"); const url = "http://localhost:9090/api/student/students"; try { const response = await fetch(url); if (!response.ok) { return Promise.reject("Something Went wrong"); } return Promise.resolve(await response.json()); } catch (error) { return Promise.reject(error); } }; const AddGroup = (props) => { const [students, setStudents] = useState([]); const [members, setMembers] = useState([]); const [currentUser, setCurrentUser] = useState(""); const [currentUserID, setCurrentUserID] = useState(0); const [groupName, setGroupName] = useState(""); const [memberIsFocused, setMemberIsFocused] = useState(false); const [memberToBeRemoved, setMemberToBeRemoved] = useState(""); useEffect(() => { getAllStudents().then(data => { setStudents(data); console.log("data:", data); }); console.log(students); }, []); useEffect(() => { if (currentUserID !== 0) { alert("Changed! CurrentUserID is " + currentUserID + " - " + currentUser); setMembers([...members, { student_id: currentUserID, name: currentUser }]); setCurrentUser("") setCurrentUserID(0); } }, [currentUserID]) console.log("members:", members); console.log("Students:", students); //Rendering for chosen students for new group for select field // const listItems = members.map((m, index) => // <option key={m.student_id}>{m.name}</option> // ); //Loops through list of students from server, checks if student user wants to add exists function addMember() { let alreadyAdded = false; members.forEach(element => { if (element.name === currentUser) { alreadyAdded = true; } }); if (alreadyAdded) { alert("Studenten ligger allerede i den nye gruppa!") return; } console.log("This is current user ", currentUser); for(let element of students){ console.log("looping..."); let name = element.first_name + " " + element.last_name + " - " + element.student_number; console.log("Loop name: ", name); if (currentUser === name) { console.log("Found: ", element.student_id + " " + element.first_name) setCurrentUserID(element.student_id); break; } } console.log("Current user ", currentUser); console.log("CurrentUserID: ", currentUserID); console.log("Members: ", members); } function postGroup() { console.log(groupName); console.log("Posting group: ", groupName, " and members: ", members); fetch('http://localhost:9090/api/studygroup/studygroup', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ groupName: groupName, students: members, }) }) } //REMOVE? function handleFocusedMember(e) { console.log(e); console.log(e.target.value); setMemberToBeRemoved(e.target.value); } //#TODO CHANGE TO REMOVE AS NORMAL function handleRemoveMember() { console.log("MTBR: ", memberToBeRemoved); //members.map(option => option.map(c => console.log(c.name))); members.map(m => console.log(m.name)) setMembers(members.filter(item => item.name !== memberToBeRemoved)); } return ( <Container> <br></br> <br></br> <Row> <Col><h1>Opprett en ny gruppe</h1> <p>Navnet på gruppen</p><input onChange={(e) => setGroupName(e.target.value)}></input></Col> </Row> <Row> <Col> <h2>Legg til medlemmer</h2> </Col> <Col> <h2>Medlemmer</h2> </Col> </Row> <br /> <Row> <Col> <AutoCompleteSearch addMember={addMember} students={students} currentUserID={currentUserID} currentUser={currentUser} setCurrentUser={setCurrentUser}> </AutoCompleteSearch> <Button onClick={addMember} variant="primary" type="submit">Legg til</Button> </Col> <Col> <Form.Group controlId="exampleForm.ControlSelect2"> <Form.Control as="select" multiple onChange={e => handleFocusedMember(e)} > {members.map((m, index) => <option onClick={() => handleRemoveMember()} key={m.student_id}>{m.name}</option> )} </Form.Control> <p>Trykk på en student for å fjerne dem fra gruppen</p> </Form.Group> </Col> </Row> <Row> </Row> <br /> <br /> <br /> <Row> <Col> <Button variant="primary" type="submit" onClick={postGroup}> Opprett gruppe</Button> </Col> </Row> <br> </br> </Container> ); } //Hvis det trengs {memberIsFocused && <Button variant="secondary" onMouseDown={() => handleRemoveMember()}> Fjern medlem</Button>} export default AddGroup;
maskX = 0; maskY = 0; function preload() { mask = loadImage('https://i.postimg.cc/pLfgGM4w/Snake-removebg-preview.png') } function setup() { canvas = createCanvas(400, 400); canvas.position(400, 200); video = createCapture(VIDEO); video.size(300, 300); video.hide(); poseNet = ml5.poseNet(video, modelLoaded); poseNet.on('pose', gotPoses); } function modelLoaded() { console.log('PoseNet is Initialized'); } function draw() { image(video,0,0,400,400); image(mask, maskX-20, maskY-35, 150, 150) } function take_snapshot() { save('myFilterImage.png'); } function gotPoses(results) { if(results.length > 0) { console.log(results); maskX = results[0].pose.nose.x; maskY = results[0].pose.nose.y; console.log("mask x = " + maskX); console.log("mask y = " + maskY); } }
require('dotenv').config(); import app from './app'; app.listen(process.env.SERVER_PORT, () => { console.log(`Server running on port ${process.env.SERVER_PORT}`); });
#target Illustrator #targetengine main // ASSUMES PNG'S OF 500x500 PX IN SAME FOLDER AS .AI File // RENAMES ARTBOARDS TO NAME OF PNG FOUND // Written by Robert Moggach & Qwertyfly // Frankensteined together by Herman van Boeijen function getFolder() { // Frankensteined to just get the folder this file is in pathToFile = app.activeDocument.path; var selectedFolder = new Folder(pathToFile); return selectedFolder; } function newRect(x, y, width, height) { var l = 0; var t = 1; var r = 2; var b = 3; var rect = []; rect[l] = x; rect[t] = y; rect[r] = width + x; rect[b] = -(height - rect[t]); return rect; }; function importFolderAsLayers(selectedFolder) { // if a folder was selected continue with action, otherwise quit var doc; app.coordinateSystem = CoordinateSystem.DOCUMENTCOORDINATESYSTEM; if (selectedFolder) { doc = app.activeDocument; var firstImageLayer = true; var newLayer; var posX=0; var posY=0; var count=0; var prettyname = ""; var rectside = 512; var margin = 200; // create document list from files in selected folder var imageList = selectedFolder.getFiles(); for (var i = 0; i < imageList.length; i++) { if (imageList[i] instanceof File) { var fileName = imageList[i].name.toLowerCase(); if( (fileName.indexOf(".png") == -1) ) { continue; } else { var cutpoint = fileName.lastIndexOf("."); prettyname = fileName.substring(0, cutpoint ); if( firstImageLayer ) { newLayer = doc.layers[0]; firstImageLayer = false; var activeAB = doc.artboards[doc.artboards.getActiveArtboardIndex()]; activeAB.name = prettyname; } else { newLayer = doc.layers.add(); box = newRect(posX, posY, rectside, rectside) var AB = doc.artboards.add(box); AB.name = prettyname; } // Name the Layer after the image file newLayer.name = prettyname; // Place the image newGroup = newLayer.groupItems.createFromFile( imageList[i] ); newGroup.position = [ posX , posY ]; var activeAB = doc.artboards[doc.artboards.getActiveArtboardIndex()]; box = newRect(posX, posY, rectside, rectside) activeAB.artboardRect = box; } } posX += rectside + margin; if(posX >= (612*5)) { posX = 0; posY -= (rectside + margin); } } if( firstImageLayer ) { // alert("The action has been cancelled."); // display error message if no supported documents were found in the designated folder alert("Sorry, but the designated folder does not contain any recognized image formats.\n\nPlease choose another folder."); doc.close(); importFolderAsLayers(getFolder()); } } else { // alert("The action has been cancelled."); // display error message if no supported documents were found in the designated folder alert("Rerun the script and choose a folder with images."); //importFolderAsLayers(getFolder()); } } // Start the script off importFolderAsLayers( getFolder() ); app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; function ScaleToArtboard(){ var docw = doc.width; var doch = doc.height; var activeAB = doc.artboards[doc.artboards.getActiveArtboardIndex()]; // get active AB docLeft = activeAB.artboardRect[0]; docTop = activeAB.artboardRect[1]; // get selection bounds var sel = doc.selection[0]; var selVB = sel.visibleBounds; var selVw = selVB[2]-selVB[0]; var selVh = selVB[1]-selVB[3]; var selGB = sel.geometricBounds; var selGw = selGB[2]-selGB[0]; var selGh = selGB[1]-selGB[3]; // get the difference between Visible & Geometric Bounds var deltaX = selVw-selGw; var deltaY = selVh-selGh; sel.width = docw-deltaX; // width is Geometric width, so we need to make it smaller...to accomodate the visible portion. sel.height = doch-deltaY; sel.top = docTop; // Top is actually Visible top sel.left = docLeft; // dito for Left } function CenterEverythingToArtboards(doc){ //Get total amount of groups var TotalArtboards = doc.artboards.length; //iterate all Artboards for (var i = 0 ; i < TotalArtboards ; i++){ var CurrentArtboard = doc.artboards[i]; doc.artboards.setActiveArtboardIndex(i); //Select everything on artboard doc.selectObjectsOnActiveArtboard(i); ScaleToArtboard(); } } doc = app.activeDocument; CenterEverythingToArtboards(doc); // app.executeMenuCommand ('save'); // app.executeMenuCommand ('close');
(function (angular) { "use strict"; var module = angular.module("student", ['ngMaterial']); function config() { } config.$inject = []; module.config(config); })(window.angular);
export class Vector2 { constructor(x = 0.0, y = 0.0) { this.x = x; this.y = y; } setTo(x, y) { this.x = x; this.y = y; } copy(v) { this.x = v.x; this.y = v.y; } clone() { return new Vector2(this.x, this.y); } normalize() { var t = Math.sqrt(this.x * this.x + this.y * this.y) + Vector2.ZERO_TOLERANCE; this.x /= t; this.y /= t; return t; } length() { return Math.sqrt(this.x * this.x + this.y * this.y); } lengthSqrd() { return this.x * this.x + this.y * this.y; } clampScalar(max) { var l = this.length(); if (l > max) { this.multEquals(max / l); } } clampVector(v) { this.x = Math.min(Math.max(this.x, -v.x), v.x); this.y = Math.min(Math.max(this.y, -v.y), v.y); } plusEquals(v) { this.x += v.x; this.y += v.y; } minusEquals(v) { this.x -= v.x; this.y -= v.y; } multEquals(s) { this.x *= s; this.y *= s; } plusMultEquals(v, s) { this.x += v.x * s; this.y += v.y * s; } minusMultEquals(v, s) { this.x -= v.x * s; this.y -= v.y * s; } dot(v) { return this.x * v.x + this.y * v.y; } cross(v) { return this.x * v.y - this.y * v.x; } leftHandNormal() { return new Vector2(this.y, -this.x); } leftHandNormalEquals() { var t = this.x; this.x = this.y; this.y = -t; } rightHandNormal() { return new Vector2(-this.y, this.x); } rightHandNormalEquals() { var t = this.x; this.x = -this.y; this.y = t; } reflectEquals(normal) { var d = this.dot(normal); this.x -= 2 * d * normal.x; this.y -= 2 * d * normal.y; } interpolate(v1, v2, t) { this.copy(v1); this.multEquals(1 - t); this.plusMultEquals(v2, t); // return v1.mult(1 - t).plus(v2.mult(t)); } setAngle(angle) { var len = this.length(); this.x = Math.cos(angle) * len; this.y = Math.sin(angle) * len; } rotateEquals(angle) { var a = angle * (Math.PI / 180); var cos = Math.cos(a); var sin = Math.sin(a); this.x = cos * this.x - sin * this.y; this.y = cos * this.y + sin * this.x; } setUnitRotation(angle) { var a = angle * (Math.PI / 180); this.x = Math.cos(a); this.y = Math.sin(a); } heading() { return Math.atan2(this.y, this.x); } distSqrd(v) { var dX = this.x - v.x; var dY = this.y - v.y; return dX * dX + dY * dY; } roundDown(closest) { this.x = Math.floor(this.x / closest) * closest; this.y = Math.floor(this.y / closest) * closest; return this; } } Vector2.ZERO_TOLERANCE = 1e-8;
$(function(){ init_countdown(); init_dp_star(); $(".J_item_more").click(function(){ $(this).parent().find(".business_display").toggleClass("business_blank"); }); }); /** * 初始化倒计时 */ function init_countdown() { var endtime = $("#countdown").attr("endtime"); var nowtime = $("#countdown").attr("nowtime"); var timespan = 1000; $.show_countdown = function(dom){ var showTitle = $(dom).attr("showtitle"); var timeHtml = ""; var sysSecond = (parseInt(endtime) - parseInt(nowtime))/1000; if(sysSecond>=0) { var second = Math.floor(sysSecond % 60); // 计算秒 var minite = Math.floor((sysSecond / 60) % 60); //计算分 var hour = Math.floor((sysSecond / 3600) % 24); //计算小时 var day = Math.floor((sysSecond / 3600) / 24); //计算天 if(day > 0) timeHtml ="<span>"+day+"</span>天"; timeHtml = timeHtml+"<span>"+hour+"</span>时<span>"+minite+"</span>分"+"<span>"+second+"</span>秒"; timeHtml = showTitle+timeHtml; $(dom).html(timeHtml); nowtime = parseInt(nowtime) + timespan; } else { $("#countdown").stopTime(); } }; $.show_countdown($("#countdown")); $("#countdown").everyTime(timespan,function(){ $.show_countdown($("#countdown")); }); } function download_youhui(id){ var query = new Object(); query.act = "download_youhui"; query.data_id = id; $.ajax({ url:ajax_url, data:query, type:"POST", dataType:"json", success:function(obj){ if(obj.status) { $.showSuccess(obj.info,function(){ if(obj.jump) location.href = obj.jump; }); } else { if(obj.info) { $.showErr(obj.info,function(){ if(obj.jump) location.href = obj.jump; }); } else { if(obj.jump) location.href = obj.jump; } } } }); }
// array to get buttons started let array = ["Mario", "Luigi", "Link", "Kirby", "Yoshi", "Captain Falcon", "Princess Peach", "Toad", "Bowser"]; let userArray = []; function createButton() { let inputValue = $("#input").val().trim() let newButton = $("<button>"); newButton.text(inputValue).addClass("newButton characterButton btn btn-info") .attr("value", inputValue).attr("id", inputValue); // Removed draggable event for the time being .attr("draggable", "true").attr("ondragstart", "drag(event)") $(".newButtonBar").append(newButton)//.append(`<input type="checkbox" value="${inputValue}" class="checkbox"/>`); } // create buttons for each item in the array for (let i = 0; i < array.length; i++) { $(".buttonBar").append(` <button class="characterButton btn btn-info" id="${array[i]}" value="${array[i]}">${array[i]}</button> `) }; // create new button based on user input $(".submit").on("click", function () { event.preventDefault(); let userInput = $("#input").val().trim().toLowerCase() // check array for existing value and push to the user array if it doens't exist if (!userArray.includes(userInput)) { userArray.push(userInput); createButton(); } $("#input").val(""); }); // register value when button is clicked $(document).on("click", ".characterButton", function () { getGifs($(this).val(), 10); }); // change src from still to animated src on click event $(document).on("click", "img", function () { let state = $(this).attr("data-state") if (state === "still") { $(this).attr("data-state", "animated").attr("src", $(this).attr("animated")); } else { $(this).attr("data-state", "still").attr("src", $(this).attr("still")); } }); // add favorite gifs to favorites section and store in local storage $(document).on("click", ".favButton", function () { let gifUrl = $(this).val(); let newDiv = $("<div>"); let img = $("<img>") newDiv.addClass("gifDiv mb-1") img.attr("src", gifUrl) $(".favoriteGifs").prepend(newDiv) newDiv.append(img) favGifs.push(JSON.stringify(gifUrl)); localStorage.setItem("User Input", JSON.stringify(favGifs)); }); function loadFavs() { for (let h = 0; h < favGifs.length; h++) { let newDiv = $("<div>"); let img = $("<img>") newDiv.addClass("gifDiv mb-1") img.attr("src", favGifs[h].replace(/\"/g, "")) $(".favoriteGifs").prepend(newDiv) newDiv.append(img) } } let favGifs = JSON.parse(localStorage.getItem("User Input")) if (!Array.isArray(favGifs)) { favGifs = [] } loadFavs(); /* Removed draggable event for now as unable to figure out data transfer. Will attempt later. // testing out draggable items function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); } function drop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } */
var base = {}; /** * ******************************************************************************************************************************** * add the page event actions: * ******************************************************************************************************************************** */ $(document).on("mobileinit", function () { // Reference: http://api.jquerymobile.com/global-config/ //$.mobile.ajaxEnabled = false; //$.mobile.ignoreContentEnabled = true; }); // PERFORM ACTIONS ON PAGE LOAD SINCE PAGES ARE LOADED VIA AJAX WITH JQUERY MOBILE $(document).on('pageshow', function () { // add generic suggest fields (ORM type suggest) base.add_suggest(); }); $(document).on('pageshow', "#page_cl4admin", function () { base.setup_admin_page(); }); $(document).on('pageshow', "#page_login", function () { if ($('#username').val() == '') { $('#username').focus(); } else { $('#password').focus(); } $('#reset_password').click(function() { base.show_page_load(this); $.ajax({ type: 'POST', url: 'forgot', data: 'reset_username=' + $('#reset_username').val(), dataType: 'json', success: function(data) { window.location='/'; }, error: function(msg) { alert('rest password ajax call failed, please contact your system administrator'); window.location='/'; } }); }); }); $(document).on( "click", ".show-page-loading-msg", function() { base.show_page_load(this); }).on( "click", ".hide-page-loading-msg", function() { $.mobile.loading( "hide" ); }); /** * ******************************************************************************************************************************** * Here are the base methods: * ******************************************************************************************************************************** */ /** * add the suggest feature to any relevant input fields (with class js_cl4_suggest, as per Form::suggest()) */ base.add_suggest = function() { $('.js_cl4_suggest').on('keyup', function(e, data) { var search_field = $(this); var search_field_id = search_field.attr('id'); var value = $(this).val(); var model_name = $(this).data('model_name'); var column_name = $(this).data('column_name'); var result_ul = $('#ajax_search_for_' + search_field_id); // this field is created by classes/Form.php var value_field = $('#id_for_' + search_field_id); // this field is created by classes/Form.php // refresh the ul in case it was just added // set up the search results list view //if (result_ul.hasClass('ui-listview')) { // $(result_ul).listview('refresh'); //} else { // $(result_ul).trigger('create'); //} if (value && value.length > 2) { base.console('ajax suggest activated for model ' + model_name + ' and field ' + column_name + ' id will go to field: ' + '#id_for_' + search_field_id); //base.console('the id will be stored at ' + '#id_for_' + search_field.attr('name')) // add the waiting indicator result_ul.html('<li><i class="fa fa-cog fa-spin"></i> loading...</li>').listview().listview("refresh").fadeIn(); $.ajax({ type: 'GET', cache: false, url: '/dbadmin/' + model_name + '/lookup/0/' + column_name + '?q=' + value, dataType: 'json', success: function(response) { var html = ""; // populate the result listing $.each(response.data, function (i, val) { html += '<li data-id="' + val.id + '">' + val.name + "</li>"; }); result_ul.html(html); result_ul.listview("refresh"); result_ul.trigger("updatelayout"); // add the click action on the result items // todo: save the current scroll position and return to it after click or cancel // todo: add cancel? esc or click somewhere? $('#ajax_search_for_' + search_field_id + " > li").on('click', function() { result_ul.hide(); base.console('id ' + $(this).data('id') + ' stored for ' + $(this).text() + ' in ' + '#id_for_' + search_field_id); search_field.val($(this).text()); // set the id value and spark a change event so that we can add custom code in our application to catch the change $('#id_for_' + search_field_id).val($(this).data('id')).change(); }); }, error: function(msg) { } }); } }); } /** * log a message to the javascript console if supported * * @type Object */ base.console = function(msg) { if (window.console && cl4_in_debug) console.log(msg); } /** * Retreive the smart parameter. * * @param parameter_name * @param default_value * @param type */ base.get_smart_parameter = function(parameter_name, default_value, type) { $.ajax({ type: 'POST', cache: false, url: '/ajax/get_smart_parameter?parameter_name=' + parameter_name + '&default=' + default_value + '&type=' + type, dataType: 'json', success: function(data) { if (timeportal.process_ajax(data)) { cl4.ajax_log_msg(data['log']); } }, error: function(msg) { cl4.add_ajax_error('The smart parameter was not set because an ajax error occurred.'); } }); } /** * Set the specified smart paramter value. * * @param parameter_name * @param value * @param type * @param success_function */ base.set_smart_parameter = function(parameter_name, value, type, success_function) { $.ajax({ type: 'GET', cache: false, url: '/ajax/get_smart_parameter?parameter_name=' + parameter_name + '&' + parameter_name + '=' + value + '&type=' + type, dataType: 'json', success: function(data) { if (base.process_ajax(data)) { base.console('parameter ' + parameter_name + ' set to ' + data['html']); // execute the success_function if it exists if (success_function) { success_function(); } return true; } }, error: function(msg) { cl4.add_ajax_error('The smart parameter ' + parameter_name + ' was not set because an ajax error occurred.'); return false; } }); } /** * add the actions required for the cl4 editable list / admin pages */ base.setup_admin_page = function() { base.console('set up editable list / admin actions'); // buttons and checkbox at the top of an editable list $('.js_cl4_button_link_form').on('click', cl4.button_link_form); $('.js_cl4_button_link').on('click', cl4.button_link); $('.js_cl4_multiple_edit').on('click', cl4.multiple_edit); $('.js_cl4_export_selected').on('click', cl4.export_selected); $('.js_cl4_multiple_edit_form').on('change', cl4.multiple_edit_form); $('.js_cl4_check_all_checkbox').on('click', cl4.check_all_checkbox); $('.cl4_add_multiple_count').on('change', cl4.add_multiple_form); // for checkboxes in tables to add .selected to the row $('.js_cl4_row_checkbox').on('change', cl4.row_checked); // found in views/cl4/cl4admin/header.php $('.js_cl4_model_select_form').on('change', cl4.model_select_change); $('.js_cl4_model_select_go').on('click', cl4.model_select_change); } /** * update a div with html from an ajax request * * @type Object */ base.load_into = function(target_element, source_url, success_function) { base.console('base.load_into ' + target_element.attr('id') + ' with ' + source_url); // show and add a waiting indicator to the target element target_element.html('<i class="fa fa-cog fa-spin"></i> Loading, please wait.'); $.ajaxSetup({ cache: false }); $.ajax({ type: 'GET', cache: false, url: source_url, dataType: 'json', success: function(data) { if (base.process_ajax(data)) { // add the HTML target_element.html(data['html']).trigger("create"); // execute the success_function if it exists if (success_function) { success_function(target_element); } } else { target_element.html(data['html']).show(); } }, error: function(msg) { target_element.html('Sorry, an error occured. The information cannot be loaded right now.'); } }); } base.process_ajax = function(return_data) { if (typeof return_data != 'object' || jQuery.isEmptyObject(return_data)) { base.console('The returned JSON data is not parsable'); return false; } if (typeof return_data.debug_msg != 'undefined' && return_data.debug_msg != '') { base.console(return_data.debug_msg); } // check to see if we've received the status, because we need it for the rest if (typeof return_data.status == 'undefined') { base.console('No status property in JSON data'); return; } switch (return_data.status) { // successful case 1 : base.console('AJAX status is successful'); return true; break; // not logged in case 2 : //cl4.add_default_ajax_error(return_data, cl4.ajax_error_msgs.not_logged_in); base.console('The user is not logged in'); return false; break; // timed out case 3 : //cl4.add_default_ajax_error(return_data, cl4.ajax_error_msgs.timed_out); base.console('The user has timed out'); return false; break; // not allowed (permissions) case 4 : //cl4.add_default_ajax_error(return_data, cl4.ajax_error_msgs.not_allowed); base.console('The user does not have permissions'); return false; break; // not found 404 case 5 : //cl4.add_default_ajax_error(return_data, cl4.ajax_error_msgs.not_found_404); base.console('The page/path could not be found'); return false; break; // validation error case 6 : //cl4.add_ajax_validation_msg(return_data); base.console('There was a validation error'); return false; break; // unknown error case 0 : default : //cl4.add_default_ajax_error(return_data); //if (cl4_in_debug) { if (typeof return_data.debug_msg == 'undefined' || return_data.debug_msg == '') { base.console('An unknown error occurred'); } //} return false; } // switch } base.reload_page = function() { window.location.href = window.location.href; } base.show_page_load = function(target) { var $this = $( target ), theme = $this.jqmData( "theme" ) || $.mobile.loader.prototype.options.theme, msgText = $this.jqmData( "msgtext" ) || $.mobile.loader.prototype.options.text, textVisible = $this.jqmData( "textvisible" ) || $.mobile.loader.prototype.options.textVisible, textonly = !!$this.jqmData( "textonly" ); html = $this.jqmData( "html" ) || ""; $.mobile.loading( "show", { text: msgText, textVisible: textVisible, theme: theme, textonly: textonly, html: html }); }
var searchData= [ ['addchild',['AddChild',['../classIComposite.html#a889fcd5161b20592299d25d4e00727b0',1,'IComposite']]], ['addcomponent',['AddComponent',['../classCTower.html#aaabd89603fc2b72be4d42a30e6a6adff',1,'CTower']]] ];
import * as React from 'react'; import './Description.css' export class Description extends React.Component { render() { return ( <div className='stack'> <h1><em>uSober</em></h1> <div className='icons'> <img src='selfie.svg' width='20%' alt='' /> <img src='tap.svg' width='20%' alt='' /> <img src='balance2.svg' width='20%' alt='' /> </div> <div className='instructions'> <p>Using a multi stage process we aim to infer how likely it is you are cognitively impaired. Using computer vision, artificial intelligence, and data interpolation.</p> <p className='tos'> The information is provided "as is" without warranty of any kind. </p> </div> </div> ) } } export default Description
const nunjucks = require('nunjucks'); const path = require('path'); const nodemailer = require('nodemailer'); const Promise = require("bluebird"); const dateFilter = require('../nunjucks/dateFilter'); const currencyFilter = require('../nunjucks/currency'); const limitTo = require('../nunjucks/limitTo'); const jsonFilter = require('../nunjucks/json'); const timestampFilter = require('../nunjucks/timestamp'); const formatTransporter = function ({ host, port, secure, auth }) { return { host: host ? host : process.env.MAIL_SERVER_URL, port: port ? port : process.env.MAIL_SERVER_PORT, secure: secure ? secure : process.env.MAIL_SERVER_SECURE, auth: { user: (auth && auth.user) ? auth.user : process.env.MAIL_SERVER_USER_NAME, pass: (auth && auth.pass) ? auth.pass : process.env.MAIL_SERVER_PASSWORD, }, }; }; exports.send = function ({subject, toName, toEmail, templateString, template, variables, fromEmail, fromName, replyTo, transporterConfig}) { /** * Enrich variables with URLS in order to make absolute urls in E-mails */ variables = Object.assign(variables, { emailAssetsUrl: process.env.EMAIL_ASSETS_URL, appUrl: process.env.APP_URL }); /** * Initiatilize Nunjucks to render E-mail template */ const nunjucksEnv = nunjucks.configure(path.resolve(__dirname,'../views'), { autoescape: true, }); nunjucksEnv.addFilter('date', dateFilter); /** * This is for legacy reasons * if extends 'emails/layout.html' then render as a string * if not included then include by rendering the string and then rendering a blanco * the layout by calling the blanco template */ if (templateString) { if (templateString.includes("{% extends 'emails/layout.html' %}")) { templateString = nunjucks.renderString(templateString, variables) } else { templateString = nunjucks.render('emails/blanco.html', Object.assign(variables, { message: nunjucks.renderString(templateString, variables) })); } } /** * Render email template */ const mail = templateString ? templateString : nunjucks.render(template, variables); /** * Format the to name */ const to = !!toName ? `${toName}<${toEmail}>` : toEmail; /** * If from name & e-mail not specified fallback to default in .env */ fromEmail = fromEmail ? fromEmail : process.env.FROM_EMAIL; fromName = fromName ? fromName : process.env.FROM_NAME; /** * Format Message object */ const message = { from: `${fromName}<${fromEmail}>`,// sender@server.com', to: to, subject: subject, html: mail, }; if (replyTo) { message.replyTo = replyTo; } /** * Create instance of MAIL transporter */ transporterConfig = transporterConfig ? transporterConfig : {}; const transporter = nodemailer.createTransport(formatTransporter(transporterConfig)); return new Promise(function(resolve, reject) { // send mail with defined transport object transporter.sendMail(message, (error, info) => { if (error) { console.log('email error', error); return reject(error); } else { console.log('Message sent: %s', info.messageId); // Preview only available when sending through an Ethereal account // console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info)); resolve(); } }) }); }
import {Wall} from './wall.js'; export class Level { constructor(ctx) { this.ctx = ctx; this.walls = this.createWalls(); } render(){ this.walls.forEach((element) => element.render()); } createWalls(){ //Some logic to import the walls from a file or create //them from IA //Now, we are using a fixed pool of walls let poolWalls = [ [[21,0],[21,38]], [[21,60],[21,90]], [[0,90],[21,90]], [[42,21],[72,21]], [[95,0],[95,50]], [[120,21],[165,21]], [[120,21],[120,60]], [[165,21],[165,60]], [[143,42],[143,60]], ]; let walls = []; for (let i = 0; i < poolWalls.length; i++) { let startX = poolWalls[i][0][0], startY = poolWalls[i][0][1], endX = poolWalls[i][1][0], endY = poolWalls[i][1][1]; walls.push(new Wall(this.ctx, poolWalls[i][0], poolWalls[i][1])); //walls.push(new Wall(this.ctx, [this.ctx.canvas.clientWidth - startX, startY], [this.ctx.canvas.clientWidth - endX, endY])); } return walls; } }
(function() { 'use strict'; const showName = (name) => { console.log(name); }; showName('Manh'); })();
const { Given, When, Then } = require('cucumber'); const assert = require('assert'); const scope = require('../../support/scope'); const testFunctions = require('../../support/functions'); const config = require('../../support/config'); const { tenSeconds, thirtySeconds, oneMinute } = require('../../support/constants'); Given('I am logged in', { timeout: oneMinute }, async () => { const page = scope.context.currentPage; await testFunctions.login(page); await page.waitForSelector(".spinner", { timeout: oneMinute }); await page.waitForSelector("button.logout-button"); }); Given('I have rejected microphone permissions', { timeout: oneMinute }, async () => { const page = scope.context.currentPage; page.on('dialog', async dialog => { await dialog.dismiss(); }); }); Given('I have accepted microphone permissions', { timeout: oneMinute }, async () => { const page = scope.context.currentPage; page.on('dialog', async dialog => { await dialog.accept(); }); }); Given('I am on the home page', async () => { if (!scope.browser) scope.browser = await scope.driver.launch(config.browserSettings); scope.context.currentPage = await scope.browser.newPage(); scope.context.currentPage.setViewport(config.windowSize); const url = scope.host; const homePage = await scope.context.currentPage.goto(url, { waitUntil: 'networkidle2' }); return homePage; }); When('I submit a valid room choice by click', { timeout: tenSeconds }, () => { const page = scope.context.currentPage; return testFunctions.chooseValidRoom(page); }); When('I submit an invalid room choice by click', { timeout: tenSeconds }, () => { const page = scope.context.currentPage; return testFunctions.chooseInvalidRoom(page); }); When('I wait for over 20 seconds', { timeout: thirtySeconds }, async () => { const delay = (time) => { return new Promise(function(resolve) { setTimeout(resolve, time) }); } await delay(20001); }); When('I press the Reset Screen button', async () => { const page = scope.context.currentPage; await page.waitForSelector("table"); // booking details should appear await page.hover("button#resetScreen"); await page.click("button#resetScreen"); }); Then('I should be shown some booking details', async () => { const page = scope.context.currentPage; await page.waitForSelector("button"); // Reset button should appear const tableHeading = await page.$eval("h2", element => element.innerHTML); const tableIsPresent = await page.$eval("table", element => element.outerHTML); assert(tableIsPresent); assert(tableHeading == "Booking Details"); }); Then('I should be shown an error banner with a helpful prompt', async () => { const page = scope.context.currentPage; const errorBannerWithPrompt = await page.$eval("h4", element => element.innerHTML); assert(errorBannerWithPrompt == "Room not found - Please choose one of the other rooms."); }); Then('I should be shown an error banner with a helpful prompt for voice', async () => { const page = scope.context.currentPage; const errorBannerWithPrompt = await page.$eval("h2", element => element.innerHTML); assert(errorBannerWithPrompt == "Room Not found - Please try again and say the room number. Alternatively, consult the receptionist for help."); }); Then('I should be shown the initial room choice panel', async () => { const page = scope.context.currentPage; const roomChoicePanelHeading = await page.$eval("h4", element => element.innerHTML); const validRoomChoiceExists = await page.$eval("#roomOne", element => element.innerHTML); const invalidRoomChoiceExists = await page.$eval("#invalidRoom", element => element.innerHTML); assert(roomChoicePanelHeading == "Welcome to your holiday - Choose a Room below"); assert(validRoomChoiceExists); assert(invalidRoomChoiceExists); });
///Validations with user name and password... // let userEmail = 'asad123' // let password = 'asad123asad123!@' // let userChecker = function(myString){ // if((myString.includes(123)) && (myString.length > 6)){ // return true // } // return false // } // let passChecker = function(pass){ // if((pass.includes('123!')) && (pass.length > 7)){ // return true // } // return false // } // //Calling the function.. // console.log('User name is : ',userChecker(userEmail)) // console.log('Password is : ',passChecker(password)) //The New practice inner of there.... var firstOne = {} var secondOne = firstOne console.log(firstOne == secondOne);
export class Http { static instance = new Http(); async get(url) { try { const request = (await fetch(url)).json(); return request; } catch (e) { console.log('Error get', e); throw e; } } async post(url, data) { try { const request = ( await fetch(url, { method: 'POST', body: data, }) ).json(); return request; } catch (e) { console.log('Error post', e); throw e; } } }
import React from 'react' import renderer from 'react-test-renderer' import { StyleRoot } from '@instacart/radium' import LoadingBox from '../LoadingBox' it('renders the standard LoadingBox correctly', () => { const tree = renderer .create( <StyleRoot> <LoadingBox style={{ width: '50px' }} /> </StyleRoot> ) .toJSON() expect(tree).toMatchSnapshot() }) it('renders the line LoadingBox', () => { const tree = renderer .create( <StyleRoot> <LoadingBox shape="line" /> </StyleRoot> ) .toJSON() expect(tree).toMatchSnapshot() }) it('renders the circle LoadingBox', () => { const tree = renderer .create( <StyleRoot> <LoadingBox shape="circle" /> </StyleRoot> ) .toJSON() expect(tree).toMatchSnapshot() }) it('renders the square LoadingBox', () => { const tree = renderer .create( <StyleRoot> <LoadingBox shape="square" /> </StyleRoot> ) .toJSON() expect(tree).toMatchSnapshot() }) it('renders the dark LoadingBox', () => { const tree = renderer .create( <StyleRoot> <LoadingBox background="dark" /> </StyleRoot> ) .toJSON() expect(tree).toMatchSnapshot() }) it('renders the light LoadingBox', () => { const tree = renderer .create( <StyleRoot> <LoadingBox background="light" /> </StyleRoot> ) .toJSON() expect(tree).toMatchSnapshot() }) it('renders the LoadingBox with a size', () => { const tree = renderer .create( <StyleRoot> <LoadingBox size={100} /> </StyleRoot> ) .toJSON() expect(tree).toMatchSnapshot() }) it('renders the LoadingBox with a combination of props', () => { const tree = renderer .create( <StyleRoot> <LoadingBox size={200} background="dark" shape="circle" /> </StyleRoot> ) .toJSON() expect(tree).toMatchSnapshot() })
'use strict' import { StyleSheet, View, Text, TextInput, TouchableHighlight, Image, PixelRatio, Platform } from 'react-native' import React, {Component} from 'react'; import {connect} from 'react-redux'; import { deleteMatch} from '../actions' import ActionSheet from 'react-native-actionsheet'; import teamMap from '../../../utils/teams' const CANCEL_INDEX = 1; const DESTRUCTIVE_INDEX = 1; //Buttons for Action Sheet var options = ['Delete', 'Cancel']; class MatchModal extends Component { constructor(props){ super(props); this.state = { enableButton: false, }; } //show options showOptions(){ this.ActionSheet.show(); //ref assigned inside the render } //handle options handlePress(buttonIndex) { if (buttonIndex === 0) this.onDelete(); } onDelete(){ const { matches, index } = this.props; const match = matches[index]; this.props.deleteMatch(match, (error) => alert(error.message)); } render () { const {matches , index} = this.props; const match = matches[index]; const {homeTeam , awayTeam , homescore , awayscore, date} = match; let cssType = 'Unstart'; const homeTeamLogo = teamMap[homeTeam].logo; const awayTeamLogo = teamMap[awayTeam].logo; return ( <TouchableHighlight onPress={this.showOptions.bind(this)} underlayColor='transparent'> <View style={[styles.container, {backgroundColor: teamMap[homeTeam].color}]} > <View style={styles.team}> <Image style={styles.teamLogo} source={homeTeamLogo}/> <Text style={styles.teamCity}>{teamMap[homeTeam].city}</Text> <Text style={styles.teamName}>{teamMap[homeTeam].team}</Text> </View> <View style={styles.gameInfo}> <Text style={[styles.infoProcess, styles.dateText]}>{date[0]+"-"+date[1]+"-"+date[2]}</Text> { <View style={styles.infoScorePanel}> <Text style={styles.infoScore}>{homescore}</Text> <View style={styles.infoDivider} /> <Text style={styles.infoScore}>{awayscore}</Text> </View> } </View> <View style={styles.team}> <Image style={styles.teamLogo} source={awayTeamLogo} /> <Text style={styles.teamCity}>{teamMap[awayTeam].city}</Text> <Text style={styles.teamName}>{teamMap[awayTeam].team}</Text> </View> <ActionSheet ref={o => this.ActionSheet = o} options={options} cancelButtonIndex={CANCEL_INDEX} destructiveButtonIndex={DESTRUCTIVE_INDEX} onPress={this.handlePress.bind(this)} /> </View> </TouchableHighlight> ); } } const mapStateToProps = (state , props)=>{ return { matches: state.matchesReducer.matches, }; }; export default connect(mapStateToProps , {deleteMatch,})(MatchModal); const matchFontSize = Platform.OS === 'ios' ? 31 : 25 const styles = StyleSheet.create({ container: { borderRadius: 5, flex: 1, flexDirection: 'row', height: 95, marginHorizontal: 12, marginBottom: 10 }, // Team team: { alignItems: 'center', borderRadius: 5, flex: 1.5 }, teamLogo: { width: 50, height: 50, marginTop: 10 }, teamCity: { color: '#fff', fontSize: 11, marginTop: 2 }, teamName: { color: '#fff', fontWeight: 'bold', fontSize: 13, position: 'relative', top: 0 }, // Info gameInfo: { alignItems: 'center', flex: 1.5, flexDirection: 'column' }, scoreInput:{ textAlign: 'center', height: 50, borderWidth: 2, borderColor: '#FF5722', borderRadius: 10 , backgroundColor : "#FFFFFF" }, infoProcess: { color: '#fff', fontSize: 10, marginTop: 22, marginBottom: 3 }, dateText: { fontSize: 22, position: 'relative', top: 13 }, infoScorePanel: { flex: 1, flexDirection: 'row', justifyContent: 'center' }, infoScore: { color: '#fff', fontWeight: '100', fontSize: matchFontSize, textAlign: 'center', width: 50 }, infoDivider: { backgroundColor: 'rgba(255, 255, 255, 0.3)', height: 25, marginTop: 7, marginLeft: 10, marginRight: 10, width: 2 / PixelRatio.get() } , })