text
stringlengths
7
3.69M
var variables________________________________c________________8js________8js____8js__8js_8js = [ [ "variables________________c________8js____8js__8js_8js", "variables________________________________c________________8js________8js____8js__8js_8js.html#a807e5474d0003c5eabe893159bd4b920", null ] ];
/* * Please see the included README.md file for license terms and conditions. */ /** @file app.js * Purpose: contains all of the javascript for the index file * * @author Keith Gudger * @copyright (c) 2016, Keith Gudger, all rights reserved * @license http://opensource.org/licenses/BSD-2-Clause * @version Release: 1.0 * @package CoastalWatershedCouncil * */ var currentLatitude = 0; var currentLongitude = 0; var options = { // Intel GPS options timeout: 10000, maximumAge: 20000, enableHighAccuracy: true }; // The function below is an example of the best way to "start" your app. // This example is calling the standard Cordova "hide splashscreen" function. // You can add other code to it or add additional functions that are triggered // by the same event or other events. function onAppReady() { queryString = "command=getDate"; sendfunc(queryString) ready(); } document.addEventListener("app.Ready", onAppReady, false) ; // The app.Ready event shown above is generated by the init-dev.js file; it // unifies a variety of common "ready" events. See the init-dev.js file for // more details. You can use a different event to start your app, instead of // this event. A few examples are shown in the sample code above. If you are // using Cordova plugins you need to either use this app.Ready event or the // standard Crordova deviceready event. Others will either not work or will // work poorly. // NOTE: change "dev.LOG" in "init-dev.js" to "true" to enable some console.log // messages that can help you debug Cordova app initialization issues. /** * Fires when DOM page loaded */ function ready() { if (navigator.geolocation) { var location_timeout = setTimeout("defaultPosition()", 10000); // changed to 2 seconds console.log("In Ready"); navigator.geolocation.getCurrentPosition( function(pos) { clearTimeout(location_timeout); showPosition(pos); }, function(err) { clearTimeout(location_timeout); console.warn('ERROR(' + err.code + '): ' + err.message); defaultPosition() }, options ); } else { console.warn("Geolocation failed. \nPlease enable GPS in Settings.", 1); defaultPosition(); } $('#date-field').datepick({dateFormat: 'yyyy-mm-dd', onClose: function(dates) { setDate(dates); } }); $('#arrive-field').timeEntry({spinnerImage: './images/spinnerDefault.png'}); /* $('#collect-field').timeEntry({spinnerImage: './images/spinnerDefault.png'}); $('#date-field2').datepick({dateFormat: 'yyyy-mm-dd', onClose: function(dates) { setDate(dates); } }); $('#arrive-field2').timeEntry({spinnerImage: './images/spinnerDefault.png'}); $('#depart-field2').timeEntry({spinnerImage: './images/spinnerDefault.png'}); $('#rtime-field2').timeEntry({spinnerImage: './images/spinnerDefault.png'});*/ $('#date-field3').datepick({dateFormat: 'yyyy-mm-dd', onClose: function(dates) { setDate(dates); } }); $('#arrive-field3').timeEntry({spinnerImage: './images/spinnerDefault.png'}); $('#sample-field3').timeEntry({spinnerImage: './images/spinnerDefault.png'}); $('#tcoll1_in').timeEntry({spinnerImage: './images/spinnerDefault.png'}); $('#tcoll2_in').timeEntry({spinnerImage: './images/spinnerDefault.png'}); $('#tcoll3_in').timeEntry({spinnerImage: './images/spinnerDefault.png'}); setupDate(); } /** * date setup */ function setupDate() { var currentDate = new Date() var day = currentDate.getDate() var month = currentDate.getMonth() + 1 if(day < 10) { day = '0' + day; } if( month < 10 ) { month = '0' + month ; } var year = currentDate.getFullYear() var ndate = year + '-' + month + '-' + day; var out = document.getElementById("datein"); var dout = document.getElementById("date-field"); out.value = dout.value = ndate ; /* out = document.getElementById("datein2"); dout = document.getElementById("date-field2"); out.value = dout.value = ndate ;*/ out = document.getElementById("datein3"); dout = document.getElementById("date-field3"); out.value = dout.value = ndate ; } // setupDate /** * set date function for date field */ function setDate(dates) { var out = document.getElementById("datein"); // var out2 = document.getElementById("datein2"); var out3 = document.getElementById("datein3"); var selected = ''; for (var i = 0; i < dates.length; i++) { selected += ',' + $.datepick.formatDate('yyyy-mm-dd',dates[i]); } // alert('Selected dates are: ' + selected.substring(1)); out.value = /*out2.value = */out3.value = selected.substring(1) ; } /** * sets current latitude and longitude from ready() function */ function showPosition(position) { console.log('In showPosition'); if ( position ) { currentLatitude = position.coords.latitude; currentLongitude = position.coords.longitude; } setupPosition(); }; /** * set up location position */ function setupPosition() { var latid = document.getElementById("latin"); var lonid = document.getElementById("lonin"); latid.value = currentLatitude; lonid.value = currentLongitude; /* latid = document.getElementById("latin2"); lonid = document.getElementById("lonin2"); latid.value = currentLatitude; lonid.value = currentLongitude;*/ latid = document.getElementById("latin3"); lonid = document.getElementById("lonin3"); latid.value = currentLatitude; lonid.value = currentLongitude; console.log("Lat is " + latid.value + " Lon is " + lonid.value); } /** * on fail from ready, default position */ function defaultPosition() { console.log('In defaultPosition'); showPosition(null); // alert("defaultPosition"); } /** * onclick function for "minus" button */ function minus_one(elt) { var val = document.getElementById(elt); if (val.value > 0) val.value--; } /** * onclick function for "plus" button */ function plus_one(elt) { var val = document.getElementById(elt); val.value++; } /** * onblur function for date field */ function fillDate(elt) { var val = document.getElementById(elt).value; var out = document.getElementById("datein"); out.value = val ; console.log("date is " + out.value); } /** * sendData function, called when submit clicked */ function sendData() { var out = document.getElementById("name-in").value; if ( out == "" ) { alert("Please enter your name before submitting, thanks."); } else if ( document.getElementById("name-in").value == "" ) { alert("Please enter your name before submitting, thanks."); } else if ( document.getElementById("site-name").value == "" ) { alert("Please enter the site name before submitting, thanks."); } else if ( document.getElementById("site-id").value == "" ) { alert("Please enter the site id before submitting, thanks."); } else if ( document.getElementById("arrive-field").value == "" ) { alert("Please enter the arrival time before submitting, thanks."); } else { var queryString = $('#fielddataform').serialize(); queryString = "command=send&" + queryString; sendfunc(queryString); // alert(queryString); document.getElementById("fielddataform").reset() setupDate(); setupPosition(); var ele = document.getElementById('dataCard'); window.scrollTo(ele.offsetLeft,ele.offsetTop); } console.log("Should switch now."); } /** * "Ajax" function that sends and processes xmlhttp request * @param params is GET request string */ function sendfunc(params) { var xmlhttp; try { xmlhttp=new XMLHttpRequest(); } catch(e) { xmlhttp = false; console.log(e); } if (xmlhttp) { xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { returnedList = (xmlhttp.responseText); console.log("Returned value is " + returnedList.search("Collector Entered")); if ( returnedList.search("Collector Entered") < 0 ) { returnedList = JSON.parse(xmlhttp.responseText); if (typeof (returnedList["Date"]) !== 'undefined') { var val = document.getElementById("date-field"); var ndate = returnedList["results"]; if ( ndate != undefined && ndate != "0000-00-00") { val.value = returnedList["results"]; val.disabled = true; } } } else { // $( ":mobile-pagecontainer" ).pagecontainer( "change", "#summary", { role: "dialog" } ); confirm("Thank you for your data submission!"); } } } xmlhttp.open("GET","http://coastalwatershedcouncil.tk/server.php" + '?' + params, true); // xmlhttp.open("GET","http://www.saveourshores.org/server.php" + '?' + params, true); xmlhttp.send(null); } }; // sendfunc /** * onclick function for web addresses */ function splashclick(url) { // alert("Typeof is " + typeof(intel)); if (typeof (intel) === 'undefined') window.open(url,'_system'); else intel.xdk.device.launchExternal(url); }; // 37.0067 -121.97 /** * photoCap function, called when Take Photo clicked */ function photoCap() { console.log('In photoCap Lat= '+currentLatitude + " Lon=" + currentLongitude); // alert("Taking Photo"); if (butid = document.getElementById('saveButt')) butid.parentNode.removeChild(butid); if(navigator.camera) { var canid = document.getElementById('can_id'); navigator.camera.getPicture(function(imageData){ var canvas = document.getElementById('canvas'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; // style="width:auto;height:500px;" // canvas.style.width = "auto"; // canvas.style.height = "500px"; // canvas.style.height = "auto"; var ctx = canvas.getContext('2d'); var image = new Image(); image.src = "data:image/jpeg;base64," + imageData; // image.src = imageData; image.onload = function(e) { ctx.drawImage(image,0,0, image.width, image.height, 0,0, canvas.width, canvas.height); ctx.lineWidth=3; ctx.fillStyle="yellow"; // ctx.lineStyle="#ffff00"; ctx.font="15px sans-serif"; var text = "Lat=" + currentLatitude ; ctx.strokeStyle = 'black'; ctx.strokeText(text,10,15); ctx.fillText(text,10,15); text = "Lon=" + currentLongitude; ctx.strokeText(text,10,35); ctx.fillText(text,10,35); text = new Date() ; ctx.strokeText(text,10,55); ctx.fillText(text,10,55); var btn = document.createElement("button"); btn.innerHTML = "Save Photo"; btn.setAttribute("id", "saveButt"); btn.className="blue_sub"; btn.onclick = savePhoto; canid.appendChild(btn); } // console.log(imageData); }, null, {sourceType:Camera.PictureSourceType.CAMERA, quality: 50, // targetWidth: 1500, targetHeight: 2048, correctOrientation: true, encodingType: Camera.EncodingType.JPEG, destinationType: Camera.DestinationType.DATA_URL}); } else { alert("Camera not supported on this device."); } } function cameraError(message) { alert ("Camera Operation Failed with error " + message); } /** * savePhoto function, called when photo save button clicked */ function savePhoto() { window.canvas2ImagePlugin.saveImageDataToLibrary( function(msg){ alert("Saving Photo"); console.log(msg); var canvas = document.getElementById('canvas'); // style="width:auto;height:500px;" canvas.width = "0px"; canvas.height = "0px"; var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); var butid = document.getElementById('saveButt'); butid.parentNode.removeChild(butid); }, function(err){ console.log(err); }, document.getElementById('canvas') ); }
// @ts-check /* eslint no-redeclare: 0 */ /* eslint camelcase: 0 */ /* eslint indent: ["error", 4, { "ignoredNodes": ["ConditionalExpression"] }] */ /* eslint curly: ["error", "multi", "consistent"] */ // var http = require('http'); /* var log4js = require('log4js') log4js.configure({ appenders: { console: { type: 'console' }, file: { type: 'file', filename: 'logs-error.log', category: 'webserver' } }, categories: { default: { appenders: ['console'], level: 'info' } } }) */ const express = require('express') const app = express() app.use(require('body-parser').json()) app.get('/', (req, res) => res.send(`<html> <header>zService</header> <body> <pre> usage: GET /kill : stop the service POST /control-mouse : create mouse event { "mode": "move"|"move_click"|"click", "x": number, "y": number, "speed": number, /* default is 3.0 */ "smooth": boolean, } or { "mode": "drag" "start_x": number, "start_y": number, "end_x": number, "end_y": number, } or { "mode": "scroll" "amount": number, } POST /keypress: { key: string, flag: "shift"|, } POST /control-keyboard: { "mode": "key" } or { "mode": "paste"|"f[1-12]"|"backspace"|"delete" ... } </pre> </body> </html>`)) // app.listen(3000, () => console.log('Example app listening on port 3000!')) const robot = require('robotjs') app.get('/kill', (req, res) => { setTimeout(() => process.exit(1), 20); res.json({ message: 'bye in 20 ms' }); }); app.get('/control-mouse', (req, res) => res.status(500).json({ error: 'Missing POST data' })) app.post('/control-mouse', (req, res) => { const { mode, data } = req.body robot.updateScreenMetrics(); console.log(mode, data) if (mode === 'set_mouse_position' || mode === 'move') { const { x, y, smooth } = data let speed = data.speed | 3.0; let time = 0; if (smooth) time = robot.moveMouseSmooth(x, y, speed) else robot.moveMouse(x, y) return res.json({ message: 'ok', time }) } if (mode === 'click_mouse_position' || mode === 'move_click') { const { x, y, smooth } = data let speed = data.speed | 3.0; let time = 0; if (smooth) time = robot.moveMouseSmooth(x, y, speed) else robot.moveMouse(x, y) robot.mouseClick() return res.json({ message: 'ok', time }) } if (mode === 'click') { robot.mouseClick() return res.json({ message: 'ok' }) } if (mode === 'drag') { const { start_x, start_y, end_x, end_y } = data // , duration robot.moveMouse(start_x, start_y) robot.mouseToggle('down') robot.dragMouse(end_x, end_y) robot.mouseToggle('up') return res.json({ message: 'ok' }) } if (mode === 'scroll') { const { amount } = data // , duration robot.scrollMouse(0, amount) // duration) return res.json({ message: 'ok' }) } console.log('error 500', data) return res.status(500).json({ error: 'unsupported control-mouse' }) }) // curl --header "Content-Type: application/json" --data '{"key":"2", "flag":"shift"}' -X POST http://127.0.0.1:9000/keypress app.post('/keypress', (req, res) => { const { key, flag } = req.body robot.keyTap(key, flag) return res.json({ message: 'ok' }) }) // curl --header "Content-Type: application/json" --data '{"mode":"key","data":{"input":"@"}}' -X POST http://127.0.0.1:9000/control-keyboard // curl --header "Content-Type: application/json" --data '{"mode":"key","data":{"input":"T@TO"}}' -X POST http://127.0.0.1:9000/control-keyboard app.post('/control-keyboard', (req, res) => { const { mode, data } = req.body if (mode === 'simulate_keyboard' || mode === 'keyboard' || mode === 'key') { console.log(mode, data) var { input, interval } = data var cpm = 60000 / interval // console.log('Typing speed:', cpm) const time = robot.typeStringDelayed(input, cpm) return res.json({ message: 'ok', time }) } else { console.log(mode) } // if (mode == 'copy') { // input_txt = data['input'] // clipboard.copy(input_txt) // return res.json({message:'ok'}); // } //if (mode === 'arobase') { // robot.keyTap('2', 'shift') // return res.json({ message: 'ok' }) //} if (mode === 'paste') { robot.keyTap('v', 'control') return res.json({ message: 'ok' }) } if (mode === 'simulate_enter') { // deprecated robot.keyTap('enter') return res.json({ message: 'ok' }) } switch (mode) { case 'f1': case 'f2': case 'f3': case 'f4': case 'f5': case 'f6': case 'f7': case 'f8': case 'f9': case 'f10': case 'f11': case 'f12': case 'backspace': case 'delete': case 'enter': case 'tab': case 'escape': case 'up': case 'down': case 'right': case 'left': case 'home': case 'end': case 'pageup': case 'pagedown': case 'command': case 'alt': case 'control': case 'shift': case 'right_shift': case 'space': case 'printscreen': case 'insert': case 'audio_mute': case 'audio_vol_down': case 'audio_vol_up': case 'audio_play': case 'audio_stop': case 'audio_pause': case 'audio_prev': case 'audio_next': //case 'audio_rewind': http://robotjs.io/docs/syntax robot.keyTap(mode) return res.json({ message: 'ok' }) } return res.status(500).json({ error: 'unsupported control-keyboard' }) }) module.exports = app
import _ from 'lodash'; import { Noise } from 'noisejs'; import { calc } from 'popmotion'; import PIXI from '../../../utils/pixi'; import { mean } from '../../../utils/2d'; const noise = new Noise(); noise.seed(Math.random()); const thunderPoint = (points, index, target, middlePoints) => { const lastPoint = points[index - 1]; const stepLength = calc.distance(lastPoint, target) / (middlePoints - index); const angle = calc.angle(lastPoint, target); const pointNoise = Number(noise.perlin2(lastPoint.x, lastPoint.y)); const normal = calc.pointFromAngleAndDistance(lastPoint, angle, stepLength); const angleA = _.random(0, 180); const lengthA = _.random(40, 140) * pointNoise; const angleB = _.random(0, 130); const lengthB = _.random(40, 140) * pointNoise; return mean( calc.pointFromAngleAndDistance(normal, angleA, lengthA), calc.pointFromAngleAndDistance(normal, angleB, lengthB) ); }; const thunderPath = (points, target, middlePoints = 60, current = 1) => { if (current >= middlePoints) return [...points, target]; return thunderPath( [...points, thunderPoint(points, current, target, middlePoints)], target, middlePoints, current + 1 ); }; export const buildThunderLines = (initial, lineStyles, application) => lineStyles.map(style => { const graphic = new PIXI.Graphics(); graphic.initial = initial; graphic.filters = [style.blur]; graphic.style = style; application.stage.addChild(graphic); return graphic; }); export default thunderPath;
describe('Weather', function() { var weather; beforeEach(function() { weather = new Weather(); }); it('Responds to stormy?', function() { expect(weather.isStormy).toBe(true||false); }) })
var express = require('express'), http = require('http'), conf = require('./conf'); var app = require('express')(), server = require('http').createServer(app), io = require('socket.io').listen(server); conf(app); server.listen(app.get('port'), function() { console.log("Express server listening on port " + app.get('port')); }); io.sockets.on('connection', function (socket) { socket.on('chat', function (data) { socket.broadcast.emit('chat', data); }); });
import { combineReducers } from 'redux' import { JOIN_ZONE, LEAVE_ZONE, REQUEST_ZONES, RECEIVE_ZONES, SELECT_ZONE, SET_HOVER_TARGET, REMOVE_HOVER_TARGET, START_CHANGE_REQUEST, END_CHANGE_REQUEST } from '../actions/ZoneActions' function availableZones(state = { fetching: true, selected: '', hovering: '', zones: [] }, action) { switch (action.type) { case JOIN_ZONE: case LEAVE_ZONE: case REQUEST_ZONES: return Object.assign({}, state, { fetching: true }) case RECEIVE_ZONES: return Object.assign({}, state, { fetching: false, selected: !!state.selected ? state.selected : action.zones[0].coordinator.roomName, zones: action.zones, lastUpdated: action.receivedAt }) case SELECT_ZONE: return Object.assign({}, state, { selected: action.name }) case SET_HOVER_TARGET: return Object.assign({}, state, { hovering: action.name }) case REMOVE_HOVER_TARGET: return Object.assign({}, state, { hovering: '' }) default: return state } } function zoneChangeRequest(state = { speaker: '', zone: '' }, {type, speaker, zone}) { switch (type) { case START_CHANGE_REQUEST: return Object.assign({}, state, { speaker, zone }) case END_CHANGE_REQUEST: return Object.assign({}, state, { speaker: '', zone: '' }) default: return state } } const ZoneReducer = combineReducers({ availableZones, zoneChangeRequest }) export default ZoneReducer
import Ember from 'ember'; /** * Clamp.js Component * Ember component for http://joe.sh/clamp-js * * @module * @augments ember/Component */ export default Ember.Component.extend({ clampDelay: 100, // Events /** * Initializes clamping on the nested content. * * @function * @returns {undefined} */ didInsertElement: function() { this.set('originalContent', this.get('element').innerHTML); this.setWidth(); this.clamp(); this.bindResizeListener(); }, /** * CCD-42564 * Unbinds the resize event when the component is de-rendered * * @function * @returns {undefined} */ willDestroyElement: function() { Ember.$(window).off(`resize.${this.elementId}`); }, // Methods /** * Stores most recent clamped width, for comparison * * @function * @returns {undefined} */ setWidth: function() { this.set('lastWidth', this.$().width()); }, /** * Binds debounced window resize event * * @function * @returns {undefined} */ bindResizeListener: function() { Ember.$(window).on(`resize.${this.elementId}`, () => { Ember.run.debounce(this, this.performResize, this.clampDelay); }); }, /** * Reclamps the content if the component width has changed * * @function * @returns {undefined} */ performResize: function() { if (this.$().width() !== this.get('lastWidth')) { this.setWidth(); this.recalcClamp(); } }, /** * Reimplements original content and reclamps for new size * * @function * @returns {undefined} */ recalcClamp: function() { this.get('element').innerHTML = this.get('originalContent'); this.clamp(); }, /** * calls Clamp.js on container * * @function * @returns {undefined} */ clamp: function() { $clamp(this.get('element'), {clamp: this.get('lines'), useNativeClamp: false}); } });
import React from 'react' import PersonalSummary from '../myprofile/PersonalSummary'; import EducationalSummary from '../myprofile/EducationalSummary'; import ProjectsSummary from '../myprofile/ProjectsSummary'; import ExperianceSummary from '../myprofile/ExperianceSummary'; import TechnicalSkills from '../myprofile/TechnicalSkills'; import Awards from '../myprofile/Awards'; class Body extends React.Component { render() { var tags = <div> <PersonalSummary></PersonalSummary> <EducationalSummary> </EducationalSummary> <ExperianceSummary></ExperianceSummary> <TechnicalSkills> </TechnicalSkills> <Awards></Awards> <ProjectsSummary> </ProjectsSummary> </div> return(tags) } } export default Body
const app = require('./src/app'); const server = app.listen(5000, () => { console.log('Example app listening on port 5000!'); }); // The signals we want to handle // NOTE: although it is tempting, the SIGKILL signal (9) cannot be intercepted and handled var signals = { 'SIGHUP': 1, 'SIGINT': 2, 'SIGTERM': 15 }; // Do any necessary shutdown logic for our application here const shutdown = (signal, value) => { console.log("shutdown!"); server.close(() => { console.log(`server stopped by ${signal} with value ${value}`); process.exit(128 + value); }); }; // Create a listener for each of the signals that we want to handle Object.keys(signals).forEach((signal) => { process.on(signal, () => { console.log(`process received a ${signal} signal`); shutdown(signal, signals[signal]); }); });
import React, { useState } from 'react' import { Result, Button } from 'antd'; const Success = () => { return ( <div> <Result status="success" title="Registration Successful!!!" subTitle="Your account is successfully registered with us. Please proceed to Login Page." extra={[ <Button href="/login" type="primary" key="console"> Login </Button> ]} /> </div> ); } export default Success;
class RenderSpells { static $getRenderedSpell (sp, subclassLookup) { const renderer = Renderer.get(); const renderStack = []; renderer.setFirstSection(true); renderStack.push(` ${Renderer.utils.getBorderTr()} ${Renderer.utils.getExcludedTr(sp, "spell", UrlUtil.PG_SPELLS)} ${Renderer.utils.getNameTr(sp, {page: UrlUtil.PG_SPELLS})} <tr><td class="rd-spell__level-school-ritual" colspan="6"><span>${Parser.spLevelSchoolMetaToFull(sp.level, sp.school, sp.meta, sp.subschools)}</span></td></tr> <tr><td colspan="6"><span class="bold">施法時間:</span>${Parser.spTimeListToFull(sp.time)}</td></tr> <tr><td colspan="6"><span class="bold">射程:</span>${Parser.spRangeToFull(sp.range)}</td></tr> <tr><td colspan="6"><span class="bold">構材:</span>${Parser.spComponentsToFull(sp.components, sp.level)}</td></tr> <tr><td colspan="6"><span class="bold">持續時間:</span>${Parser.spDurationToFull(sp.duration)}</td></tr> ${Renderer.utils.getDividerTr()} `); const entryList = {type: "entries", entries: sp.entries}; renderStack.push(`<tr class="text"><td colspan="6" class="text">`); renderer.recursiveRender(entryList, renderStack, {depth: 1}); if (sp.entriesHigherLevel) { const higherLevelsEntryList = {type: "entries", entries: sp.entriesHigherLevel}; renderer.recursiveRender(higherLevelsEntryList, renderStack, {depth: 2}); } renderStack.push(`</td></tr>`); const stackFroms = []; const fromClassList = Renderer.spell.getCombinedClasses(sp, "fromClassList"); if (fromClassList.length) { const [current, legacy] = Parser.spClassesToCurrentAndLegacy(fromClassList); stackFroms.push(`<div><span class="bold">職業:</span>${Parser.spMainClassesToFull(current)}</div>`); if (legacy.length) stackFroms.push(`<div class="text-muted"><span class="bold">職業: (舊版): </span>${Parser.spMainClassesToFull(legacy)}</div>`); } const fromSubclass = Renderer.spell.getCombinedClasses(sp, "fromSubclass"); if (fromSubclass.length) { const [current, legacy] = Parser.spSubclassesToCurrentAndLegacyFull(sp, subclassLookup); stackFroms.push(`<div><span class="bold">子職業:</span>${current}</div>`); if (legacy.length) { stackFroms.push(`<div class="text-muted"><span class="bold">子職業: (舊版): </span>${legacy}</div>`); } } const fromClassListVariant = Renderer.spell.getCombinedClasses(sp, "fromClassListVariant"); if (fromClassListVariant.length) { const [current, legacy] = Parser.spVariantClassesToCurrentAndLegacy(fromClassListVariant); if (current.length) { stackFroms.push(`<div><span class="bold">可選/變體 職業: </span>${Parser.spMainClassesToFull(current)}</div>`); } if (legacy.length) { stackFroms.push(`<div class="text-muted"><span class="bold">可選/變體 職業 (舊版): </span>${Parser.spMainClassesToFull(legacy)}</div>`); } } const fromRaces = Renderer.spell.getCombinedRaces(sp); if (fromRaces.length) { fromRaces.sort((a, b) => SortUtil.ascSortLower(a.name, b.name) || SortUtil.ascSortLower(a.source, b.source)); stackFroms.push(`<div><span class="bold">種族:</span>${fromRaces.map(r => `${SourceUtil.isNonstandardSource(r.source) ? `<span class="text-muted">` : ``}${renderer.render(`{@race ${Parser.RaceToDisplay(r.name)}|${r.source}}`)}${SourceUtil.isNonstandardSource(r.source) ? `</span>` : ``}`).join(", ")}</div>`); } const fromBackgrounds = Renderer.spell.getCombinedBackgrounds(sp); if (fromBackgrounds.length) { fromBackgrounds.sort((a, b) => SortUtil.ascSortLower(a.name, b.name) || SortUtil.ascSortLower(a.source, b.source)); stackFroms.push(`<div><span class="bold">背景:</span>${fromBackgrounds.map(r => `${SourceUtil.isNonstandardSource(r.source) ? `<span class="text-muted">` : ``}${renderer.render(`{@background ${r.name}|${r.source}}`)}${SourceUtil.isNonstandardSource(r.source) ? `</span>` : ``}`).join(", ")}</div>`); } if (sp.eldritchInvocations) { sp.eldritchInvocations.sort((a, b) => SortUtil.ascSortLower(a.name, b.name) || SortUtil.ascSortLower(a.source, b.source)); stackFroms.push(`<div><span class="bold">魔能祈喚:</span>${sp.eldritchInvocations.map(r => `${SourceUtil.isNonstandardSource(r.source) ? `<span class="text-muted">` : ``}${renderer.render(`{@optfeature ${r.name}|${r.source}}`)}${SourceUtil.isNonstandardSource(r.source) ? `</span>` : ``}`).join(", ")}</div>`); } if (stackFroms.length) { renderStack.push(`<tr class="text"><td colspan="6">${stackFroms.join("")}</td></tr>`) } if (sp._scrollNote) { renderStack.push(`<tr class="text"><td colspan="6"><section class="text-muted">`); renderer.recursiveRender(`{@italic Note: Both the {@class fighter||${Renderer.spell.STR_FIGHTER} (${Renderer.spell.STR_ELD_KNIGHT})|eldritch knight} and the {@class rogue||${Renderer.spell.STR_ROGUE} (${Renderer.spell.STR_ARC_TCKER})|arcane trickster} spell lists include all {@class ${Renderer.spell.STR_WIZARD}} spells. Spells of 5th level or higher may be cast with the aid of a spell scroll or similar.}`, renderStack, {depth: 2}); renderStack.push(`</section></td></tr>`); } renderStack.push(` ${Renderer.utils.getPageTr(sp)} ${Renderer.utils.getBorderTr()} `); return $(renderStack.join("")); } static async pGetSubclassLookup () { const subclassLookup = {}; Object.assign(subclassLookup, await DataUtil.loadJSON(`data/generated/gendata-subclass-lookup.json`)); const homebrew = await BrewUtil.pAddBrewData(); RenderSpells.mergeHomebrewSubclassLookup(subclassLookup, homebrew); return subclassLookup } static mergeHomebrewSubclassLookup (subclassLookup, homebrew) { if (homebrew.class) { homebrew.class.filter(it => it.subclasses).forEach(c => { (subclassLookup[c.source] = subclassLookup[c.source] || {})[c.name] = subclassLookup[c.source][c.name] || {}; const target = subclassLookup[c.source][c.name]; c.subclasses.forEach(sc => { sc.source = sc.source || c.source; sc.shortName = sc.shortName || sc.name; (target[sc.source] = target[sc.source] || {})[sc.shortName] = target[sc.source][sc.shortName] || {name: sc.name} }); }) } if (homebrew.subclass) { homebrew.subclass.forEach(sc => { const clSrc = sc.classSource || SRC_PHB; sc.shortName = sc.shortName || sc.name; (subclassLookup[clSrc] = subclassLookup[clSrc] || {})[sc.className] = subclassLookup[clSrc][sc.className] || {}; const target = subclassLookup[clSrc][sc.className]; (target[sc.source] = target[sc.source] || {})[sc.shortName] = target[sc.source][sc.shortName] || {name: sc.name} }) } } }
import React from "react"; import styled from "styled-components"; import { Form, Table } from "reactstrap"; import { IconButton } from "@material-ui/core"; import moment from "moment"; import { FormGroup, SingleSelectFormat, Loading } from "../../../common"; import AddIcon from "@material-ui/icons/Add"; // import SearchIcon from "@material-ui/icons/Search"; import { OPTIONS_MONTHS, OPTIONS_YEARS } from "../../../../utils/constants"; import { updateDatePaymentsInvoices, getPaymentsInvoices, } from "../../../../redux/actions/parent"; import noData from "../../../../assets/images/no-data-payment.svg"; import file from "../../../../assets/images/file-pdf.svg"; import dowload from "../../../../assets/images/dowload.svg"; import { formatExp } from "../../../../utils/helpers"; import { useSelector } from "react-redux"; const StyledPayment = styled.section` margin: 30px 15px auto; .form-info, .invoices { background: #ffffff; box-shadow: 0px 5px 25px rgba(98, 84, 232, 0.203944); border-radius: 4px; max-width: 1340px; p { text-align: left; color: #08135a; font-size: 14px; } } .form-info { padding: 30px 28px 28px; margin: 0 auto 30px; .form-inner { border: 2px solid #b5beec; border-radius: 4px; padding: 20px 18px; p { font-weight: 400; } > div { overflow: hidden; } .--nodata { div { font-size: 21px; color: #b5beec; } } } .form-info__group { overflow: hidden; } .--form { display: flex; align-items: center; justify-content: center; > div { display: flex; max-width: 850px; } } .form__item { display: flex; width: 50%; > div { flex: 1; } p { margin-left: 10px; color: #b5beec; font-size: 9px; margin-bottom: 10px; } } .form-group { margin: 0 10px 20px 10px; input { min-height: 36px; font-size: 12px; padding: 0px; border: none; &[disabled] { background: #fff; } } } @media only screen and (max-width: 880px) { .form__item { width: 100%; .form__item__inner { width: 50%; } } .--form > div { display: block; } .form-group input { border-radius: 4px; padding: 8px 8px 8px 15px; border: 1px solid #b5beec; } } @media only screen and (max-width: 550px) { .form__item { .form__item__inner { width: 100%; } } .number-name-card { display: block; } .info-card { .expiry-date, .zip-code, .cvv-code { width: 100%; } } .--form { display: block; } } @media only screen and (max-width: 440px) { padding: 30px 10px 10px; .form-inner { padding: 20px 5px; .--nodata { div { font-size: 18px; color: #b5beec; margin-bottom: 10px; line-height: 22px; } } } .form-group { input { font-size: 10px; } } .form__item { display: block; p { margin-bottom: 0px; } } } } .checkbox { display: block; position: relative; padding-left: 35px; cursor: pointer; user-select: none; .input_checkbox { position: absolute; opacity: 0; cursor: pointer; height: 0; width: 0; &:checked ~ .checkmark:after { display: block; } &:checked ~ .checkmark { background: #6254e8; border: none; } } .checkmark { position: absolute; left: 10px; top: 30px; height: 20px; width: 20px; background-color: #fff; border: 2px solid #b5beec; border-radius: 100%; &:after { content: ""; position: absolute; display: none; border: 2px solid #fff; border-radius: 100%; top: 3px; left: 3px; width: 14px; height: 14px; } } } .add { border: none; padding: 3px 15px; font-size: 12px; color: #ffffff; line-height: 34px; font-weight: 500; transition: 0.3s ease; background: #6254e8; border-radius: 30px; margin: 10px; &:hover { transform: translateY(-3px); box-shadow: 0 4px 8px 0 #6556f8; } svg { width: 20px; margin: 0 3px 2px 0; } } .invoices { padding: 30px 28px 60px; margin: 0 auto 50px; .invoices__header { display: flex; justify-content: space-between; .invoices__date { display: flex; width: 100%; max-width: 300px; > div { width: 50%; } } } } .-noData-incoice { padding-top: 20px; div { color: #b5beec; font-size: 21px; text-align: left; } img { width: 80%; max-width: 460px; } } .invoices__search { position: relative; input { width: 100%; border: 1px solid #ced4da; border-radius: 4px; padding: 7.5px 10px; &::placeholder { color: #b5beec !important; } } svg { position: absolute; right: 5px; top: 7px; width: 24px; height: 24px; color: #b5beec; } } table { tr { border-bottom: 1px solid #b5beec; th { color: #b5beec; font-size: 12px; text-align: left; font-weight: 400; text-transform: capitalize; padding: 10px 15px 10px 0; } td { color: #08135a; font-size: 12px; text-align: left; padding: 10px 15px 10px 0; vertical-align: middle; &:last-child { padding: 15px 0; text-align: right; } button { width: 46px; } } td: first-child { font-weight: 600; img { margin-right: 10px; } } td:nth-child(3) { p { font-size: 14px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-bottom: 0; @media (max-width: 1130px) { width: 300px; } @media (max-width: 735px) { width: 250px; } } } @media (max-width: 735px) { td:nth-child(2) { width: 142px; } td: last-child { padding: 10px 0; } td { padding: 10px 10px 10px 0; } } @media (max-width: 370px) { td { button { width: 36px; padding: 7px; } } } } } @media only screen and (max-width: 755px) { .invoices .invoices__header { display: block; .invoices__date { max-width: inherit; } } } @media only screen and (max-width: 677px) { margin: 30px 0px auto; } @media only screen and (max-width: 650px) { table tr td:nth-child(3), th:nth-child(3) { display: none; } } @media only screen and (max-width: 550px) { .invoices .invoices__header .invoices__date { flex-direction: column; > div { width: 100%; max-width: 175px; margin: 0 auto 7px; } } } @media only screen and (max-width: 440px) { .form-info .add { float: inherit; } .-noData-incoice div { font-size: 18px !important; line-height: 20px; } } .edit { cursor: pointer; color: #6254e8; border-bottom: 1px solid #6254e8; &:hover { color: #f6732f; border-bottom: 1px solid #f6732f; } } @media only screen and (max-width: 880px) { .edit { top: 119px; } } @media only screen and (max-width: 550px) { .edit { position: inherit; width: 27px; float: right; margin-right: 13px; } } @media only screen and (max-width: 450px) { .invoices { padding: 30px 15px; } } @media only screen and (max-width: 440px) { .checkbox { padding-left: 26px; } .checkmark { left: 5px; } } `; function Payment({ handleToggleModalCardUpdated, storeCardInfo }) { // const [form, setForm] = React.useState({ // option: null // }); // const handleCheckbox = event => { // setForm({ // ...form, // reason: event.target.value // }); // }; const storeDateInvoices = useSelector( (store) => store.parent.datePaymentsInvoices ); const storePaymentsInvoices = useSelector( (store) => store.parent.paymentsInvoices ); const isLoadingInvoices = storePaymentsInvoices.loading; const formatMonth = moment(storeDateInvoices).format("MMMM"); const formatYear = moment(storeDateInvoices).format("YYYY"); React.useEffect(() => { getPaymentsInvoices(moment(storeDateInvoices).format("YYYY-MM")); }, [storeDateInvoices]); const handleChangeMonth = ({ value }) => { updateDatePaymentsInvoices(moment(storeDateInvoices).month(value)); }; const handleChangeYear = ({ value }) => { updateDatePaymentsInvoices(moment(storeDateInvoices).year(value)); }; const isLoadingCardInfo = storeCardInfo.loading; return ( <StyledPayment> <div className="container"> <Form className="form-info"> <p>Credit card </p> <div className="form-inner"> <p>Credit card on file</p> {isLoadingCardInfo ? ( <Loading /> ) : storeCardInfo.data && Object.keys(storeCardInfo.data).length ? ( <div> <div className="form-info__group"> {/* <label className="checkbox"> */} {/* <input type="radio" className="input_checkbox" name="reason" onChange={handleCheckbox} value={1} checked /> <span className="checkmark"></span> */} <div className="--form"> <div> <div className="form__item number-name-card"> <div className="form__item__inner"> <p>CARD NUMBER</p> <FormGroup propsInput={{ name: "cardNumber", placeholder: "Card number ", value: `**** **** **** ${storeCardInfo.data.last4}`, disabled: true, }} /> </div> <div className="form__item__inner"> <p>NAME ON CARD</p> <FormGroup propsInput={{ name: "nameOnCard", placeholder: "Name on card ", value: storeCardInfo.data.name, disabled: true, }} /> </div> </div> <div className="form__item info-card"> <div className=" expiry-date"> <p>EXPIRY DATE</p> <FormGroup propsInput={{ name: "expiry date", placeholder: " expiry date ", value: formatExp( storeCardInfo.data.exp_month, storeCardInfo.data.exp_year ), disabled: true, }} /> </div> </div> </div> <div className="edit" onClick={handleToggleModalCardUpdated} > Edit </div> </div> {/* </label> */} </div> </div> ) : ( <div className="--nodata"> <div>No credit card linked to your account</div> <button className="add find" onClick={handleToggleModalCardUpdated} > {" "} <AddIcon /> Add a new credit card </button> </div> )} </div> </Form> <div className="invoices"> <div className="invoices__header"> <p>Invoices</p> <div className="invoices__date"> <SingleSelectFormat options={OPTIONS_MONTHS} placeholder="Month" onChange={handleChangeMonth} value={{ value: formatMonth, label: formatMonth }} /> <SingleSelectFormat options={OPTIONS_YEARS} placeholder="Year" onChange={handleChangeYear} value={{ value: formatYear, label: formatYear }} /> </div> </div> <div className="invoices__body"> {isLoadingInvoices ? ( <Loading /> ) : storePaymentsInvoices.data && storePaymentsInvoices.data.length ? ( <Table borderless> <thead> <tr> <th>Title</th> <th>Lesson Date</th> <th>Time</th> <th>Teacher</th> <th>Price</th> <th></th> </tr> </thead> <tbody> {storePaymentsInvoices.data.map((item, index) => ( // {[{ name: "123", description: "123", date: "2020-11-11", link: "123" }].map((item, index) => ( <tr key={index}> <td> <img src={file} alt="file" /> {`#MEL-${item.id}`} </td> <td>{moment(item.lesson_date).format("MMMM DD, YYYY")}</td> <td>{item.start_hour} - {item.end_hour}</td> <td> <p>{item.first_name} {item.last_name}</p> </td> <td> <p>{item.gross_price}</p> </td> <td> <a href={item.invoice_url} target="_blank" download rel="noopener noreferrer" > <IconButton> <img src={dowload} alt="dowload" /> </IconButton> </a> </td> </tr> ))} </tbody> </Table> ) : ( <div className="-noData-incoice"> <div>No invoices found</div> <img src={noData} alt="noData" /> </div> )} </div> </div> </div> </StyledPayment> ); } export default Payment;
import { createAction } from '_Utils/tools' import { combineReducers } from 'redux' export const ACTIONS = { EXAMPLE_ACTION: 'example/example-action/started', EXAMPLE_ACTION_SUCCESS: 'example/example-action/success', EXAMPLE_ACTION_FAILED: 'example/example-action/failed' } // Statement Entries export const exampleActionStarted = createAction(ACTIONS.EXAMPLE_ACTION_STARTED) export const exampleActionSuccess = createAction(ACTIONS.EXAMPLE_ACTION_SUCCESS) export const exampleActionFailed = createAction(ACTIONS.EXAMPLE_ACTION_FAILED) const initialStateExample = { isExampleLoading: false, isExampleError: false, isExampleSuccess: false } export const exampleReducer = (state = initialStateExample, action) => { const { type, payload } = action switch (type) { case ACTIONS.EXAMPLE_ACTION_STARTED: { return { ...state, isExampleLoading: true, isExampleError: false, isExampleSuccess: false } } case ACTIONS.EXAMPLE_ACTION_SUCCESS: { return { ...state, isExampleLoading: false, isExampleError: false, isExampleSuccess: true } } case ACTIONS.EXAMPLE_ACTION_FAILED: { return { ...state, isExampleLoading: false, isExampleError: true, isExampleSuccess: false } } } } export const example = combineReducers({ exampleReducer })
var trank = angular.module("trankApp"); trank.controller("LugaresController", function ($rootScope, $scope, $timeout, categoria, lugares, lugaresApi) { $rootScope.title = "Lugares da Categoria " + categoria[0].nome; $rootScope.meta_desc = "Tranks - Lista de lugares da categoria " + categoria[0].nome; $rootScope.trocaBkg(); $scope.$on("$viewContentLoaded", function () { $timeout(function() { initInicio(); },0); }); $scope.categoria = categoria[0]; $scope.lugares = lugares; $scope.categorias_lugar = {}; for (var j=0; j< $scope.lugares.length;j++){ var cs = []; var lugar = $scope.lugares[j]; for (var i = 0; i < lugar.categorias.length; i++) { cs.push(lugaresApi.listarCategoria(lugar.categorias[i])[0]); } $scope.categorias_lugar[lugar.id] = cs; } $scope.range = function(numero){ return new Array(parseInt(numero)); } }); function initLugares(){ $(".jrate").each(function(i,obj){ var rating = $(this).data('rating'); $(this).raty({ starType: 'i', score: rating, readOnly: true, halfShow: true, }); }); }
/* * 定义所有的action类型 * */ export const START = 'START'; export const STOP = 'STOP'; export const RESET = 'RESET'; export const RUN_TIMER = 'RUN_TIMER';
(function () { 'use strict' var createApp = function (context) { const Home = { template: '<div>home</div>' } const Foo = { template: '<div>foo</div>' } const Bar = { template: '<div>bar {{test}}</div>', data : function(){ return { test : '' } }, created : function(){ var vm = this axios.get('/user/client') .then(function (response) { console.log(response); vm.test = response.data }) .catch(function (error) { console.log(error); }); } } const router = new VueRouter({ mode: 'history', routes: [ { path: '/', component: Home }, { path: '/foo', component: Foo }, { path: '/bar', component: Bar } ] }) Vue.use(VueRouter) return new Vue({ router: router, template: ` <div id="app"> <h1>Basic</h1> <ul> <li><router-link to="/">/</router-link></li> <li><router-link to="/foo">/foo</router-link></li> <li><router-link to="/bar">/bar</router-link></li> </ul> <div>You have been here for {{ counter }} seconds.</div> <router-view></router-view> </div> `, data: { counter: 0 }, created: function () { var vm = this setInterval(function () { vm.counter += 1 }, 1000) } }) } if (typeof module !== 'undefined' && module.exports) { module.exports = createApp } else { this.app = createApp() } }).call(this)
'use strict'; const chai = require('chai'); const chaiHttp = require('chai-http'); const server = require('../../server'); const Entry = require('../../app/models/entry'); const User = require('../../app/models/user'); const jwt = require('jsonwebtoken'); const config = require('../../config'); const expect = chai.expect; chai.use(chaiHttp); describe('Entries Controller', () => { describe('GET #search', () => { describe('when user token is invalid', () => { it('returns status false', (done) => { chai.request(server) .get('/entries/search') .query({ site: 'www.google.com' }) .end((err, res) => { expect(res.body.success).to.be.false; done(); }); }); it('returns the correct message', (done) => { chai.request(server) .get('/entries/search') .query({ site: 'www.google.com' }) .end((err, res) => { expect(res.body.message).to.equals('Invalid session token.'); done(); }); }); }); describe('when user token is valid', () => { let user = null; let params = {}; beforeEach((done) => { const userPromise = new User({ email: 'test@test.com', password: 'password' }).save(); const token = jwt.sign({ email: 'test@test.com' }, config.secret, { expiresIn: '365d' }); params = { site: 'www.google.com', token: token }; userPromise.then((newUser) => { user = newUser; done(); }) }); describe('when entry matches with any user entries', () => { let entry1, entry2, entry3; beforeEach((done) => { entry1 = { site: 'www.google.com', email: 'user1@gmail.com', password: 'password', user_id: user.id }; entry2 = { site: 'www.google.com', email: 'user2@gmail.com', password: 'other-password', user_id : user.id }; entry3 = { site: 'www.facebook.com', email: 'user1@gmail.com', password: 'password', user_id: user.id }; Entry.collection.insert([entry1, entry2, entry3], (err, docs) => { done(); }) }); it('returns a list of the entries', (done) => { chai.request(server) .get('/entries/search') .query(params) .end((err, res) => { expect(res.body.entries).to.have.lengthOf(2); done(); }); }) }); describe('when entry does not match with any user entries', () => { it('returns an empty list of the entries', (done) => { params.site = 'www.unknown-site.com'; chai.request(server) .get('/entries/search') .query(params) .end((err, res) => { expect(res.body.entries).to.be.empty; done(); }); }) }); }); }); describe('POST #create', () => { let user = null; let params = {}; beforeEach((done) => { const userPromise = new User({ email: 'test@test.com', password: 'password' }).save(); params = { email: 'test@test.com', password: 'other-password', site: 'www.gmail.com' }; userPromise.then((newUser) => { user = newUser; done(); }) }); describe('when user token is not present', () => { it('returns status false', (done) => { chai.request(server) .post('/entries') .send(params) .end((err, res) => { expect(res.body.success).to.be.false; done(); }); }); it('returns the correct message', (done) => { chai.request(server) .post('/entries') .send(params) .end((err, res) => { expect(res.body.message).to.equals('Invalid session token.'); done(); }); }); }); describe('when user token is present', () => { describe('when user token is valid', () => { beforeEach(() => { const token = jwt.sign({ email: 'test@test.com' }, config.secret, { expiresIn: '365d' }); params.token = token; }); describe('with valid params', () => { it('returns success as true', (done) => { chai.request(server) .post('/entries') .send(params) .end((err, res) => { expect(res.body.success).to.be.true; done(); }); }); it('associates the entry to the user', (done) => { chai.request(server) .post('/entries') .send(params) .end((err, res) => { const query = Entry.find({ user_id: user.id }).exec(); query.then((entries) => { expect(entries).to.have.lengthOf(1); done(); }); }); }); }); describe('with invalid params', () => { beforeEach(() => { params.site = ''; }); it('returns success as false', (done) => { chai.request(server) .post('/entries') .send(params) .end((err, res) => { expect(res.body.success).to.be.false; done(); }); }); it('returns error message', (done) => { chai.request(server) .post('/entries') .send(params) .end((err, res) => { expect(res.body.message).to.equals('Site is required'); done(); }); }); }); }); describe('when user token is invalid', () => { beforeEach(() => { params.token = 'not-valid-token'; }); it('returns success as false', (done) => { chai.request(server) .post('/entries') .send(params) .end((err, res) => { expect(res.body.success).to.be.false; done(); }); }); it('returns the correct message', (done) => { chai.request(server) .post('/entries') .send(params) .end((err, res) => { expect(res.body.message).to.equals('Invalid session token.'); done(); }); }); }); }); }); });
const Converter = require('../converter') const length = require('./length') const angle = require('./angle') const time = require('./time') module.exports = [ new Converter("length", length), new Converter("angle", angle), new Converter("time", time) ]
import React from 'react'; import { query } from './webpack'; import { match } from 'react-router'; import render from './render'; import routes from '../../client/routes'; function findInWebpack (file, callback) { query(file, (err, body) => { callback(err, body); }); } export default (request, response, next) => { findInWebpack('index.html', (error, body) => { match( {routes, location: request.url}, (routingError, redirectLocation, renderProps ) => { if (error) { return response.status(500).send(error.message); } if (redirectLocation) { return response.redirect(302, redirectLocation.pathname + redirectLocation.search); } if (renderProps) { render( renderProps, body ).then((html) => { response.status(200).send(html); }, (renderError) => { console.error('failed to load', renderError); response.status(500).send(JSON.stringify(renderError)); }); } else { return response.status(404).send(); } }); }); };
const starwars = require("starwars"); const app = document.getElementById("app"); app.innerText = starwars();
import main from 'main' import map from 'ramda/src/map' import value from 'main/processes/value' import selection from 'main/processes/selection' const cynics = [ 'Antisthenes', 'Diogenes of Sinope', 'Onesicritus', 'Philiscus of Aegina' ] const select = (v) => console.log('VALUE:', v) const selectText = (v) => console.log('SELECTION:', v) const view = () => ['main', [ ['input', {select: [selectText, selection], value: `Cynicism (Greek: κυνισμός) is a school of Ancient Greek philosophy as practiced by the Cynics (Greek: Κυνικοί, Latin: Cynici). For the Cynics, the purpose of life was to live in virtue, in agreement with nature. As reasoning creatures, people could gain happiness by rigorous training and by living in a way which was natural for themselves, rejecting all conventional desires for wealth, power, sex and fame. Instead, they were to lead a simple life free from all possessions.`}], ['h4', 'Favorite cynic:'], ['select', {change: [select, value]}, [ ['option', '=== Choose ==='], ...map((value) => ( ['option', {value}, value] ), cynics) ]] ]] main(view)
$.fn.dataTableExt.afnSortData['dom-checkbox'] = function ( oSettings, iColumn ) { var aData = []; $( 'td:eq('+iColumn+') input', oSettings.oApi._fnGetTrNodes(oSettings) ).each( function () { aData.push( this.checked==true ? "1" : "0" ); } ); return aData; } $.fn.dataTableExt.afnSortData['dom-class'] = function ( oSettings, iColumn ) { var aData = []; $(oSettings.oApi._fnGetTrNodes(oSettings)).find('td:eq('+iColumn+')').each( function () { aData.push( this.bgColor=="#00ff00" ? "1" : "0" ); } ); return aData; } $(function(){criteriaInit();}); var criteriaSortedTable=null; function criteriaInit(){ criteriaSortedTable=$('#criteriaList').dataTable({"aaSorting": [[ 2, "asc" ]], "bLengthChange":false, "sPaginationType":"two_button", "bAutoWidth":false, "iDisplayLength":10, "bFilter": true,"aoColumns": [{ "sSortDataType": "dom-checkbox" }, {"sType":"html"}, null, null]}); } /* competition stuff */ $(function(){competitionInit();resetCompetitionForm();}); var competitionSortedTable; function competitionInit(){ var params={"bAutoWidth":false,"aaSorting": [[ 2, "asc" ]],"sPaginationType":"full_numbers","aoColumns": [{"sType":"html"}, null, null, null]}; competitionSortedTable=$('#competitionList').dataTable(); } function resetCompetitionForm(){ $(criteriaSortedTable.fnGetNodes()).find(':input').attr("checked", false).attr("enabled", true); criteriaSortedTable.fnSort([[1, 'asc']]); $("#competitionForm :input[type=text]").val(""); $('#competitionForm :input').removeClass('redborder'); $("#competitionForm select").val(""); $("#competitionForm textarea").val(""); $("#competitionTitle").html("Add competition"); $('#competitionForm').attr('url', BASE+'/ajax/competition/create'); $('#competitionForm tr[id=submittr] td').html('<input type=submit value=Add ><br /><input type=button value="Select all" onclick="javascript:$(criteriaSortedTable.fnGetNodes()).find(\':input\').attr(&quot;checked&quot;, true);" /><input type=button value="Select none" onclick="javascript:$(criteriaSortedTable.fnGetNodes()).find(\':input\').attr(&quot;checked&quot;, false);" /><div id=errordiv ></div>'); } function createCompetitionCallback(data){ $('#competitionForm :input').removeClass('redborder'); $('#competitionForm tr[id=submittr] td div[id=errordiv]').html(''); data=$.parseJSON(data); if(data.success){ name=$('#competitionForm :input:eq(0)').val(); de=makehtml($('#competitionForm :input:eq(4)').val()); ord=makehtml($('#competitionForm :input:eq(1)').val()); gp=makehtml($('#competitionForm :input:eq(2)').val()); g=makehtml($('#competitionForm :input:eq(2) option:selected').text()); tp=makehtml($('#competitionForm :input:eq(3)').val()); t=makehtml($('#competitionForm :input:eq(3) option:selected').text()); var isUp=$(competitionSortedTable.fnGetNodes()).filter('#competitionList'+data.id); if(isUp.size()){ $(isUp).children('td:nth-child(1)').html('<a href=\'javascript:populateCompetitionForm("'+data.id+'")\' >'+name+'</a><br><i>'+de+'</i>'); isUp.attr("categories", data.categories); }else{ var a=competitionSortedTable.fnAddData(['<a href=\'javascript:populateCompetitionForm("'+data.id+'")\' >'+name+'</a><br /><i>'+de+'</i>', ord, g, t]); var oSettings = competitionSortedTable.fnSettings(); var nTr = oSettings.aoData[ a[0] ].nTr; nTr.setAttribute('id', 'competitionList'+data.id); nTr.setAttribute("categories", data.categories); } resetCompetitionForm(); $('#competitionList'+data.id+' td:nth-child(3)').attr('group', gp); $('#competitionList'+data.id+' td:nth-child(3)').html(gp==0?"<em>"+g+"</em>":g); $('#competitionList'+data.id+' td:nth-child(4)').attr('type', tp); $('#competitionList'+data.id+' td:nth-child(4)').html(t); $('#competitionList'+data.id+' td:nth-child(2)').html(ord); $('#competitionList'+data.id+' td:nth-child(3)').attr("onclick","javascript:updateCompCol("+data.id+",3)"); $('#competitionList'+data.id+' td:nth-child(4)').attr("onclick","javascript:updateCompCol("+data.id+",4)"); $('#competitionList'+data.id+' td:nth-child(5)').attr("onclick","javascript:updateCompCol("+data.id+",5)"); if(isUp.size()) $('#competitionForm tr[id=submittr] td div[id=errordiv]').html('Competition updated'); else $('#competitionForm tr[id=submittr] td div[id=errordiv]').html('Competiton added'); }else{ err=$('#competitionForm :input[name|='+data.error+']'); if(err.size()){ err.addClass('redborder'); }else $('#competitionForm tr[id=submittr] td div[id=errordiv]').html("<font color=red >"+data.error+"</font>"); } } function ctypeChange(){ if($('#competitionForm :input:eq(3)').val()==1){ $(criteriaSortedTable.fnGetNodes()).find(':input').attr("disabled", "disabled"); }else{ $(criteriaSortedTable.fnGetNodes()).find(':input').attr("disabled", ""); } } function populateCompetitionForm(id){ resetCompetitionForm(); var cats=$('#competitionList'+id).attr("categories").split(","); if(cats){ var selector='#criteriaList'+cats.join(",#criteriaList"); $(criteriaSortedTable.fnGetNodes()).filter(selector).find(':input').attr("checked", true); criteriaSortedTable.fnSort([[0, 'desc']]); } $('#competitionForm :input:eq(0)').val($('#competitionList'+id+' td:nth-child(1) a').html()); $('#competitionForm :input:eq(1)').val($('#competitionList'+id+' td:nth-child(2)').html()); $('#competitionForm :input:eq(2)').val($('#competitionList'+id+' td:nth-child(3)').attr("group")); $('#competitionForm :input:eq(3)').val($('#competitionList'+id+' td:nth-child(4)').attr("type")); $('#competitionForm :input:eq(4)').val($('#competitionList'+id+' td:nth-child(1) i').html()); $('#competitionForm').attr('url', BASE+'/ajax/competition/edit/'+id); $('tr[id=submittr] td').html('<div id=errordiv ></div><input type=submit value="Update" /> &nbsp; <input type=button value="Delete" onclick="javascript:askDeleteCompetition('+id+')"> &nbsp; <input type=button value="Clear" onclick="javascript:resetCompetitionForm()"><br /><input type=button value="Select all" onclick="javascript:$(criteriaSortedTable.fnGetNodes()).find(\':input\').attr(&quot;checked&quot;, true);" /><input type=button value="Select none" onclick="javascript:$(criteriaSortedTable.fnGetNodes()).find(\':input\').attr(&quot;checked&quot;, false);" />'); } function askDeleteCompetition(id){ $('#competitionForm tr:eq(4) td:nth-child(1)').html('Are you sure you want <br />to delete this competition?<br /><input type=button value="No" onclick="javascript:resetCompetitionForm()"/><br /><br /> \<input type=button value="Delete" onclick="javascript:deleteCompetition('+id+')">'); } function deleteCompetition(id){ $.getJSON(BASE+'/ajax/competition/delete/'+id, '', function(data){ if(data.success=='False'){ resetCompetitionForm(); $('#competitionForm tr:eq(3) td div[id=errordiv]').html('<font color=red >Error deleting competition</font>'); }else{ resetCompetitionForm(); $('#competitionForm tr:eq(3) td div[id=errordiv]').html('Competition deleted'); del=$(competitionSortedTable.fnGetNodes()).filter('#competitionList'+id)[0]; competitionSortedTable.fnDeleteRow(del); } }); } function submitForm2(id, callback){ form="#"+id; data=$(form).serialize()+"&"; data+=$(criteriaSortedTable.fnGetNodes()).find(":input").serialize(); $.ajax({url:$(form).attr("url"), data:data, type:"POST", dateType:"json", success:callback}); } function submitForm(id, callback){ form="#"+id; data=$(form).serialize(); $.ajax({url:$(form).attr("url"), data:data, type:"POST", dateType:"json", success:callback}); } function makehtml(text) { var textneu = text.replace(/&/,"&amp;"); textneu = textneu.replace(/</,"&lt;"); textneu = textneu.replace(/>/,"&gt;"); textneu = textneu.replace(/\r\n/,"<br>"); textneu = textneu.replace(/\n/,"<br>"); textneu = textneu.replace(/\r/,"<br>"); return(textneu); }
"use strict"; var app = { loading: function (){ // load image; setTimeout(function (){ $('.state .loadImage').fadeIn(); // download progress setTimeout(function (){ $('.stateLoad').fadeOut(); // into state01 app.state01(); }, 1500); }, 150); }, state01: function (){ $('.state01').fadeIn(); // show text setTimeout(function (){ $('.text').addClass('animated fadeInLeft'); // show men1 setTimeout(function (){ $('.man01').addClass('animated rubberBand'); // show men2 setTimeout(function (){ $('.man02').addClass('animated rubberBand'); //show next button setTimeout(function (){ $('.state01 .next').fadeIn(); }, 800); }, 800); }, 800); }, 100); }, state02: function (){ $('.state01').addClass('animated fadeOutLeft'); $('.state02').removeClass('hide'). addClass('animated fadeInRight'); //show title01 setTimeout(function (){ $('.state02 .text01').addClass('animated bounceInLeft'); // show title02 setTimeout(function (){ $('.state02 .text02').addClass('animated bounceInLeft'); //show entry01 setTimeout(function (){ $('.state02 .entry01').addClass('animated bounceInDown'); //show entry02 setTimeout(function (){ $('.state02 .entry02').addClass('animated bounceInDown'); //show next button setTimeout(function (){ $('.state02 .next').fadeIn(); }, 800); }, 400); }, 400); }, 400); }, 800); }, stateFinishe: function (){ $('.state02').addClass('animated fadeOut'); setTimeout(function (){ $('.stateFinish').removeClass('hide').addClass('animated fadeIn'); }, 500); }, init: function (){ app.loading(); $('.state01 .next').click(function (){ // into state02 app.state02(); }); $('.state02 .next').click(function (){ // into state02 app.stateFinishe(); }); } }; $(function (){ app.init(); });
import React, { Component } from "react"; import axios from "./axios"; import { editProfile } from "./actions"; import { connect } from "react-redux"; import { withRouter } from "react-router-dom"; const mapStateToProps = (state, props) => { return { ...props, firstName: state.me.firstName, lastName: state.me.lastName, bio: state.me.bio, city: state.me.city, food: state.me.food, chef: state.me.chef, email: state.me.email, id: state.me.id, profilePic: state.me.profilePic, coverPic: state.me.coverPic }; }; class EditInfos extends Component { constructor(props) { super(); this.state = { error: null }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.state = { firstName: props.firstName || "", lastName: props.lastName || "", bio: props.bio || "", city: props.city || "", food: props.food || "", chef: props.chef || "", email: props.email || "", password: "" }; } handleChange(e) { this.setState({ [e.target.name]: e.target.value }); } handleSubmit(e) { e.preventDefault(); axios.post("/profile/edit", this.state).then(resp => { if (resp.data.error) { this.setState({ error: resp.data.error }); } else { this.props.dispatch( editProfile( this.props.id, this.props.profilePic, this.props.coverPic, this.state ) ); this.props.history.push("/"); } }); } render() { return ( <div className="registration"> <div className="form-wrapper2"> <div className="form-wrapper"> {this.state.error ? ( <div>{this.state.error}</div> ) : null} <div className="edit-profile">Edit Profile</div> <form className="form-edit"> <div className="wrapper-email"> <input className="inputs-edit" onChange={this.handleChange} name="firstName" value={this.state.firstName} type="text" /> <div className="down-input">First Name</div> <input className="inputs-edit" onChange={this.handleChange} name="lastName" value={this.state.lastName} type="text" /> <div className="down-input">Last Name</div> <input className="inputs-edit" onChange={this.handleChange} name="email" value={this.state.email} type="text" /> <div className="down-input">Email</div> <input className="inputs-edit" onChange={this.handleChange} name="password" placeholder="Type a new password" value={this.state.password} type="password" /> <div className="down-input">Password</div> </div> <div className="wrapper-editprof"> <input className="inputs-edit" onChange={this.handleChange} name="bio" value={this.state.bio} type="text" /> <div className="down-input">Bio</div> <input className="inputs-edit" onChange={this.handleChange} name="city" value={this.state.city} type="text" /> <div className="down-input"> City and Country </div> <input className="inputs-edit" onChange={this.handleChange} name="food" value={this.state.food} type="text" /> <div className="down-input">Favorite Foods</div> <input className="inputs-edit" onChange={this.handleChange} name="chef" value={this.state.chef} type="text" /> <div className="down-input">Favorite Chefs</div> </div> </form> <button className="editbutton" type="submit" onClick={this.handleSubmit} > Save </button> </div> </div> </div> ); } } export default withRouter(connect(mapStateToProps)(EditInfos));
/* $FreeBSD$ */ /* * Please do not commit to this file without receiving review from * webstats@FreeBSD.org. */ /* Teach jslint the appropriate style rules. */ /*jslint browser:true*/ var enable_ga = true; var allow_track = true; var h = document.location.hostname; /* * Check that the hosting domain is actually a FreeBSD.org domain, so * we don't accidentally obtain data from mirrors. */ var fbsdregex = /((docs|security|svnweb|cgit|wiki|www)\.freebsd\.org|google\.com)$/i; if (typeof navigator.doNotTrack !== "undefined" && (navigator.doNotTrack == "yes" || navigator.doNotTrack == "1")) { allow_track = false; } if (enable_ga && allow_track && fbsdregex.test(h)) { var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-22767463-1']); _gaq.push(['_setDomainName', 'freebsd.org']); _gaq.push(['_setAllowHash', false]); _gaq.push (['_gat._anonymizeIp']); /* * If we ever want to track sites other than FreeBSD.org, * uncomment the next line. */ //_gaq.push(['_setAllowLinker', true]); // This is what we track _gaq.push(['_trackPageview']); _gaq.push(['_trackPageLoadTime']); ( function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = 'https://ssl.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); }
/** * 클로저는 이너함수가 스코프 밖에 있는 변수에 접근하는 것 * 정보은닉, 함수 팩토리를 생성할 때 사용 */ const arr = [10, 11, 12, 13]; for (var i = 0; i < arr.length; i++) { setTimeout(function() { console.log("index : " + i); }, 3000); } // 결과 값 모두 3 // 이유 : setTimeout의 함수는 3초뒤에 실행됨. 그러므로 for문이 종료된 이후 // 마지막 인덱스가 적용됨 // setTimeout의 스코프와 for문의 스코프가 다르기 때문에 발생 //해결 // 1 // i 값을 setTimeout함수안에 전달하여 각 함수 호출마다 올바른 값을 접근하게 함 for (var i = 0; i < arr.length; i++) { setTimeout( (function(local_i) { return function() { console.log("index : " + local_i); }; })(i), 3000 ); } // 2 // es6의 let 키워드는 스코프가 block 스코프이므로 해결 됨 for (let i = 0; i < arr.length; i++) { setTimeout(function() { console.log("index : " + i); }, 3000); }
import gql from 'graphql-tag' const repositories = gql` query repositories( $login: String! $number_of_repos: Int $orderBy: RepositoryOrder ) { user(login: $login) { repositories(last: $number_of_repos, orderBy: $orderBy) { totalCount nodes { name forkCount stargazers { totalCount } owner { login } description isPrivate pushedAt primaryLanguage { name color } } } } } ` export default repositories
"use strict"; const express = require("express"); const multer = require("multer"); const checkAccountSession = require("../controllers/account/check-account-session"); const checkRolePermission = require("../controllers/account/check-role-permission"); const createCompany = require("../controllers/company/create-company-controller"); const getCompany = require("../controllers/company/get-company-controller"); const getCompanies = require("../controllers/company/get-companies-controller"); const getCompanyCities = require("../controllers/company/get-company-cities-controller"); const getCompaniesCities = require("../controllers/company/get-companies-cities-controller"); const updateCompanyData = require("../controllers/company/update-company-controller"); const uploadCompanyLogo = require("../controllers/company/upload-logo-company-controller"); const upload = multer(); const router = express.Router(); router.get("/v1/companies", getCompanies); router.get("/v1/companies/:companyId", getCompany); router.get("/v1/companies/cities/active", getCompaniesCities); router.get("/v1/companies/cities/:companyId", getCompanyCities); router.post("/v1/companies", checkAccountSession, checkRolePermission("1", "2"), createCompany); router.post( "/v1/companies/logo", checkAccountSession, checkRolePermission("2"), upload.single("logo"), uploadCompanyLogo ); router.put("/v1/companies/:companyId", checkAccountSession, checkRolePermission("2"), updateCompanyData); module.exports = router;
import React from "react"; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import { Paper } from "@material-ui/core"; class TableDashboard extends React.Component { render () { const { tasks } = this.props; return ( <TableContainer component={Paper}> <Table> <TableHead> <TableRow> <TableCell>Type</TableCell> <TableCell>Task name</TableCell> <TableCell>Creation Date</TableCell> <TableCell>Duration</TableCell> <TableCell>Status</TableCell> </TableRow> </TableHead> <TableBody> {tasks && tasks.map(item => { return ( <TableRow> <TableCell>{item.id}</TableCell> <TableCell>{item.name}</TableCell> <TableCell>{item.year}</TableCell> <TableCell>{item.color}</TableCell> <TableCell>{item.pantone_value}</TableCell> </TableRow> ) })} </TableBody> </Table> </TableContainer> ) } } export default TableDashboard;
import Tumbler from './Tumbler'; export default Tumbler;
var tablero; var monopoly = { monopolyURI: '/img/metropoly-575.png', monopolyOK: false, casillas:[ [20,525], [20,475], [20,425], [20,375], [20,325], [20,275], [20,225], [20,175], [20,125], [20,75], [20,25], [70,25], [120,25], [170,25], [220,25], [270,25], [320,25], [370,25], [420,25], [470,25], [520,25], [520,75], [520,125], [520,175], [520,225], [520,275], [520,325], [520,375], [520,425], [520,475], [520,525], [470,525], [420,525], [370,525], [320,525], [270,525], [120,525], [70,525], [20,525], ] }; var dados = []; var fichas = [ {x:0,y:0}, {x:0,y:25}, {x:0,y:50}, {x:25,y:0}, {x:25,y:25}, {x:25,y:50} ]; window.player = [{ x: 20, y: 525, playerURI: '/img/ficha.png', playerOK: false }]; function iniciar(){ var canvas = document.getElementById('tablero'); tablero = canvas.getContext('2d'); monopoly.image = new Image(); monopoly.image.src = monopoly.monopolyURI; monopoly.image.onload = tableroListo; player[0].image = new Image(); player[0].image.src = player[0].playerURI; player[0].image.onload = playerListo; dados[1] = new Image(); dados[1].src = '/img/d1.png'; dados[2] = new Image(); dados[2].src = '/img/d2.png'; dados[3] = new Image(); dados[3].src = '/img/d3.png'; dados[4] = new Image(); dados[4].src = '/img/d4.png'; dados[5] = new Image(); dados[5].src = '/img/d5.png'; dados[6] = new Image(); dados[6].src = '/img/d6.png'; document.addEventListener('keydown', function (e){ if(e.keyCode == 38){ io.emit('dados::tirar'); } }); } function moverPieza(){ player[0].x = monopoly.casillas[player[0].posicion - 1][0]; player[0].y = monopoly.casillas[player[0].posicion - 1][1]; console.log(player[0].posicion) dibujar(); } function tableroListo(){ monopoly.monopolyOK = true; dibujar(); } function playerListo(){ player[0].playerOK = true; dibujar(); } function dibujar(){ if(monopoly.monopolyOK){ tablero.drawImage(monopoly.image, 0, 0); } if(player[0].playerOK){ tablero.drawImage(player[0].image, fichas[0].x, fichas[0].y, 25, 25, player[0].x, player[0].y, 25, 25); } if(typeof(player[0].dado)!=='undefined'){ tablero.drawImage(dados[player[0].dado.uno], 199,199); tablero.drawImage(dados[player[0].dado.dos], 275,275) } }
document.addEventListener('DOMContentLoaded', () => { // Get all "navbar-burger" elements const $navbarBurgers = Array.prototype.slice.call(document.querySelectorAll('.navbar-burger'), 0); // Check if there are any navbar burgers if ($navbarBurgers.length > 0) { // Add a click event on each of them $navbarBurgers.forEach( el => { el.addEventListener('click', () => { // Get the target from the "data-target" attribute const target = el.dataset.target; const $target = document.getElementById(target); // Toggle the "is-active" class on both the "navbar-burger" and the "navbar-menu" el.classList.toggle('is-active'); $target.classList.toggle('is-active'); }); }); } }); document.querySelector('a#open-modal').addEventListener('click', function(event) { event.preventDefault(); var modal = document.querySelector('.modal'); // assuming you have only 1 var html = document.querySelector('html'); modal.classList.add('is-active'); html.classList.add('is-clipped'); modal.querySelector('.modal-background').addEventListener('click', function(e) { e.preventDefault(); modal.classList.remove('is-active'); html.classList.remove('is-clipped'); }); }); // // document.addEventListener('DOMContentLoaded', function () { // // // // // Modals // // // // var rootEl = document.documentElement; // // var allModals = getAll('.modal'); // // var modalButtons = getAll('#myModal'); // // var modalCloses = getAll('.modal-background, .modal-close, .modal-card-head .delete, .modal-card-foot .button'); // // // // if (modalButtons.length > 0) { // // modalButtons.forEach(function (el) { // // el.addEventListener('click', function () { // // var target = document.getElementById(el.dataset.target); // // rootEl.classList.add('is-clipped'); // // target.classList.add('is-active'); // // }); // // }); // // } // // // // if (modalCloses.length > 0) { // // modalCloses.forEach(function (el) { // // el.addEventListener('click', function () { // // closeModals(); // // }); // // }); // // } // // // // document.addEventListener('keydown', function (event) { // // var e = event || window.event; // // if (e.keyCode === 27) { // // closeModals(); // // } // // }); // // // // function closeModals() { // // rootEl.classList.remove('is-clipped'); // // allModals.forEach(function (el) { // // el.classList.remove('is-active'); // // }); // // } // // // // // Functions // // // // function getAll(selector) { // // return Array.prototype.slice.call(document.querySelectorAll(selector), 0); // // } // // });
import {createActions} from 'src/App/helpers' const actions = createActions('HDSWITCH', [ 'TOGGLE_HD' ]) export default actions
$(function(){ var ConditionIFItem, conditionIFItem; // 注册一个Condition IF类型 ConditionIFItem = function(spec, inherit){ inherit = inherit || Design.item.root; var that = inherit(spec), superRemove = Object.superior.call(that, 'remove'), superGetNexts = Object.superior.call(that, 'getNexts'), superSetNext = Object.superior.call(that, 'setNext'), superApplyEvents = Object.superior.call(that, 'applyEvents'); var applyEvents = function nodeApplyEvents($elm){ superApplyEvents.apply(that, arguments); var $ep = $('.ep-container', $elm); Design.jsPlumber.makeSource($ep.filter('.failure'), { anchor: "Left", connector:[ "StateMachine", { curviness:20 } ], connectorStyle:{ strokeStyle: 'red', lineWidth:2, outlineColor:"transparent", outlineWidth:4 }, }); Design.jsPlumber.makeSource($ep.filter('.success'), { anchor:"Right", connector:[ "StateMachine", { curviness:20 } ], connectorStyle:{ strokeStyle: 'green', lineWidth:2, outlineColor:"transparent", outlineWidth:4 }, }); }, remove = function remove($elm) { spec.jsPlumber.detachAllConnections($('.ep-container.failure', $elm)); spec.jsPlumber.detachAllConnections($('.ep-container.success', $elm)); superRemove.apply(this, arguments); } getNexts = function getNexts($elm){ var $ep = $('.ep-container', $elm), $failure = $ep.filter('.failure'), $success = $ep.filter('.success'), result = []; if ( $failure.length > 0 ){ spec.jsPlumber.select({'source': $failure}).each(function(c){ result.push({ 'relation': 'false', 'next': c.target }) }) } if ( $success.length > 0 ){ spec.jsPlumber.select({'source': $success}).each(function(c){ result.push({ 'relation': 'true', 'next': c.target }) }) } return result; }, setNext = function setNext($elm, next, relation){ var $ep = $('.ep-container', $elm); if ( !relation ){ return; } if ( relation === 'true' ){ $elm = $ep.filter('.success'); } else { $elm = $ep.filter('.failure'); } var c = spec.jsPlumber.connect({'source': $elm, 'target': next}); c.getOverlay().setLabel(relation); }; that.applyEvents = applyEvents; that.getNexts = getNexts; that.setNext = setNext; that.remove = remove; return that; } conditionIFItem = ConditionIFItem({'className': 'condition-if', 'modalName': '#script-modal'}, Design.item.root); Design.item.register('condition-if', conditionIFItem); })
define(['dataTables'], function(){ wgn.console('programs module loaded','f'); // wgn.loadCss('stylesheets/wgn.marketcontext.css'); wgn.marketcontext = wgn.marketcontext || {}; wgn.marketcontext.selectedRow = false; wgn.marketcontext.parameters = wgn.marketcontext.parameters || {}; wgn.marketcontext.mpModal = wgn.marketcontext.mpModal || {}; //Initialize callbacks wgn.marketcontext.programListFn = wgn.marketcontext.programListFn || {}; wgn.marketcontext.programListFn.callback = wgn.marketcontext.programListFn.callback || {}; wgn.marketcontext.deleteRowFn = wgn.marketcontext.deleteRowFn || {}; wgn.marketcontext.deleteRowFn.callback = wgn.marketcontext.deleteRowFn.callback || {}; wgn.dtRowsHandler = function(nRow, aData, iDisplayIndex, iDisplayIndexFull){ $(nRow).click(function(){ wgn.tableSelector = '#' + $(this)[0].parentNode.parentNode.id; if ($(this).hasClass('selected')){ $(this).removeClass('selected'); $('#editModal, #deleteRow').addClass('disabled'); wgn.marketcontext.selectedRow = false; } else{ $(wgn.tableSelector + ' tr').removeClass('selected'); $(this).addClass('selected'); $('#editModal, #deleteRow').removeClass('disabled'); wgn.marketcontext.selectedRow = true; wgn.marketcontext.selectedData = aData; } }); }; function programList(){ $.ajax({ url: wgn.routes.controllers.DrProgram.listDrProgram().url, contentType: 'application/json', dataType: 'json', type: wgn.routes.controllers.DrProgram.listDrProgram().method, cache: false }) .done(function(data){ wgn.marketcontext.list = data; $('#program_table').dataTable().fnClearTable(); $('#program_table').dataTable().fnAddData(wgn.marketcontext.list.drPrograms); wgn.console("program list loaded","f"); }) .complete(function(){ if (typeof(wgn.marketcontext.programListFn.callback) == "function"){ wgn.marketcontext.programListFn.callback(); wgn.console("callback from programListFn() executed: " + wgn.marketcontext.programListFn.callback.name + "()","f"); wgn.marketcontext.programListFn.callback = {}; } }); } function periodParse(thePeriod, unitSelector){ var theUnits; var formattedUnits; thePeriod = thePeriod.replace("P","").replace("Y","").replace("-","").replace("T",""); var period_patt=/[0-9]+S/g; //test for seconds var period_result = period_patt.exec(thePeriod); if (period_result != null){ theUnits = "seconds"; formattedUnits = messages_arr.programs.units.seconds; } var period_patt=/[0-9]+M/g; //test for minutes var period_result = period_patt.exec(thePeriod); if (period_result != null){ theUnits = "minutes"; formattedUnits = messages_arr.programs.units.minutes; } var period_patt=/[0-9]+H/g; //test for hours var period_result = period_patt.exec(thePeriod); if (period_result != null){ theUnits = "hours"; formattedUnits = messages_arr.programs.units.hours; } var period_patt=/[0-9]+D/g; //test for days var period_result = period_patt.exec(thePeriod); if (period_result != null){ theUnits = "days"; formattedUnits = messages_arr.programs.units.days; } thePeriod = thePeriod.replace(/D/g,"").replace(/H/g,"").replace(/M/g,"").replace(/S/g,""); $("#" + unitSelector + " option[value=" + theUnits + "]").prop('selected', true); if (typeof(unitSelector) == "undefined"){ var viewFormat = thePeriod + " " + formattedUnits; return viewFormat; } else{ return thePeriod; } } function getCas(){ $.ajax({ // get current _cas url: wgn.routes.controllers.DrProgram.getDrProgram(wgn.marketcontext.selectedData["marketContext"]).url, type: wgn.routes.controllers.DrProgram.getDrProgram().method, cache: false }) .done(function(data){ wgn.marketcontext.parameters._cas = data["_cas"]; }) } // dataTable rendering $(document).ready(function(){ $('.jodaDuration').jodaDurationCheck(); //validate when the value changes (listener) if ($.urlParam('demo') == 'true'){ $("[data-demo='true']").css("display","block"); } // Default header class modification // Use $.fn.dataTableExt.oStdClasses when bjQueryUI is false $.extend($.fn.dataTableExt.oJUIClasses, { "sSortAsc": "header headerSortDown", "sSortDesc": "header headerSortUp", "sSortable": "header" }); //bjQueryUI is to enable Themeroller support // Table initialization $('#program_table').dataTable({ "bJQueryUI": true, "sPaginationType": "full_numbers", "sDom": 't<"F"fp>', "oLanguage": { "sUrl": wgn.assetsRoot + "/assets/javascripts/lang/jquery.dataTables." + wgn.browserLang + ".json" }, // "aoColumns": [ // {"mData": "programName"}, // {"mData": "marketContext"}, // {"mData": "notifyPeriod"}, // {"mData": "freezePeriod"} // ], "aoColumns": [ {"mData": "programName"}, {"mData": "marketContext"} ], "fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull){ wgn.dtRowsHandler(nRow, aData, iDisplayIndex, iDisplayIndexFull); var marketContext = aData['marketContext']; $('td:eq(1)', nRow).html(marketContext); // nRow.setAttribute('id',aData['id']); // var notifyRaw = aData['notifyPeriod']; // var notifyFormat = periodParse(notifyRaw); // $('td:eq(2)', nRow).html(notifyFormat); // var freezeRaw = aData['freezePeriod']; // var freezeFormat = periodParse(freezeRaw); // $('td:eq(3)', nRow).html(freezeFormat); }, "fnDrawCallback": function(oSettings){ // wgn.console('program table has been redrawn'); }, "fnInitComplete": function(oSettings, json){ programList(); } }); $('#eventPropagationType').change(function(){ if ($(this)[0].value == 'TRANSLATED'){ $('#downstream_programs_field').addClass('event_translated'); } else{ $('#downstream_programs_field').removeClass('event_translated'); } }); $('button.alertClose.close').on('click', function(){ $(this).parent().addClass("fade"); }) $('#mpModal').css('max-height',wgn.modalAvailHeight); $('#mpModal .modal-body').css('max-height',wgn.modalContentAvailHeight); }); // show add modal $('#addModal').on('click',function(){ $('#program_table tr').removeClass('selected'); $('#editModal, #deleteRow').addClass('disabled'); wgn.marketcontext.selectedRow = false; wgn.marketcontext.mpModal.headerText = wgn.messages_arr.programs.add_title; $('#mpModal .modal-title').text(wgn.marketcontext.mpModal.headerText); $("#mpModal .invalid").removeClass('invalid'); $('#mpModal [data-key="marketContext"]').val(''); $('#mpModal [data-key="programName"]').val(''); $('#mpModal [data-key="eventPropagationType"] option[value="PASS_THROUGH"]').prop('selected', true); $('#mpModal [data-key="policy"] option[value="CPP"]').prop('selected', true); // $('#mpModal #notifyPeriod').val('0'); // $("#mpModal #notify_units option[value=days]").prop('selected', true); // $('#mpModal #freezePeriod').val('0'); // $("#mpModal #freeze_units option[value=days]").prop('selected', true); $('#mpModal #tiempo').val('0'); delete wgn.marketcontext.parameters._cas; wgn.marketcontext.submitUrl = wgn.routes.controllers.DrProgram.addDrProgram().url; wgn.marketcontext.submitType = wgn.routes.controllers.DrProgram.addDrProgram().method; $('#mpModal').modal('show'); }) // show edit modal $('#editModal').on('click',function(){ if (wgn.marketcontext.selectedRow){ wgn.marketcontext.mpModal.headerText = wgn.messages_arr.programs.edit_title; $('#mpModal .modal-title').text(wgn.marketcontext.mpModal.headerText); $("#mpModal .invalid").removeClass('invalid'); $('#mpModal [data-key="marketContext"]').val(wgn.marketcontext.selectedData["marketContext"]); $('#mpModal [data-key="programName"]').val(wgn.marketcontext.selectedData["programName"]); $('#mpModal [data-key="eventPropagationType"] option[value=' + wgn.marketcontext.selectedData["eventPropagationType"] + ']').prop('selected', true); $('#mpModal [data-key="policy"] option[value=' + wgn.marketcontext.selectedData["policy"] + ']').prop('selected', true); //var notifyPeriod_temp = wgn.marketcontext.selectedData["notifyPeriod"]; //notifyPeriod_temp = periodParse(notifyPeriod_temp,"notify_units"); //$('#mpModal #notifyPeriod').val(notifyPeriod_temp); //var freezePeriod_temp = wgn.marketcontext.selectedData["freezePeriod"]; //freezePeriod_temp = periodParse(freezePeriod_temp,"freeze_units"); //$('#mpModal #freezePeriod').val(freezePeriod_temp); getCas(); wgn.marketcontext.submitUrl = wgn.routes.controllers.DrProgram.updateDrProgram(wgn.marketcontext.selectedData["marketContext"]).url; wgn.marketcontext.submitType = wgn.routes.controllers.DrProgram.updateDrProgram().method; $('#mpModal').modal('show'); } }) // delete a program row $('#deleteRow').on('click',function(){ if (wgn.marketcontext.selectedRow){ var errorMessage = ""; var lineBreak = ""; // $("[data-prompt='delete']").removeClass('fade'); // return; delete wgn.marketcontext.parameters._cas; wgn.marketcontext.submitUrl = wgn.routes.controllers.DrProgram.deleteDrProgram(wgn.marketcontext.selectedData["marketContext"]).url; wgn.marketcontext.submitType = wgn.routes.controllers.DrProgram.deleteDrProgram().method; $.ajax({ url: wgn.marketcontext.submitUrl, type: wgn.marketcontext.submitType, cache: false, beforeSend: function(){ wgn.console('program delete requested','f'); } }) .done(function(data){ wgn.console('program delete successful','f'); programList(); $('tr').removeClass('selected'); $('#editModal, #deleteRow').addClass('disabled'); wgn.marketcontext.selectedRow = false; }) .fail(function(data){ wgn.marketcontext.errors = $.parseJSON(data.responseText); for (i in wgn.marketcontext.errors.globalErrors){ errorMessage = errorMessage + lineBreak + wgn.marketcontext.errors.globalErrors[i]; lineBreak = "<br/>"; } $('.alert-error span').html(errorMessage); $('.alert-error').removeClass('fade'); }) .complete(function(data){ if (typeof(wgn.marketcontext.deleteRowFn.callback) == "function"){ wgn.marketcontext.deleteRowFn.callback(); wgn.console("callback from deleteRow() executed: " + wgn.marketcontext.deleteRowFn.callback.name + "()","f"); wgn.marketcontext.deleteRowFn.callback = {}; } }); return; } }) // form post add and edit $('#modalSubmit').on('click',function(){ wgn.console('programs form submit request','f'); $('#mpModal .modal-title').text(wgn.marketcontext.mpModal.headerText); $("#mpModal .invalid").removeClass('invalid'); var invalidFields = 0; var modalErrorMsg = ""; var lineBreak = ""; wgn.marketcontext.parameters.programName = $('#mpModal [data-key="programName"]').val(); if (wgn.marketcontext.parameters.programName == ""){ $('#mpModal .programName_marker').addClass("invalid"); invalidFields++; } wgn.marketcontext.parameters.marketContext = $('#mpModal [data-key="marketContext"]').val(); // wgn.marketcontext.parameters.marketContext = wgn.marketcontext.parameters.marketContext; if (wgn.marketcontext.parameters.marketContext == ""){ $('#mpModal .marketContext_marker').addClass("invalid"); invalidFields++; } switch(true){ case (invalidFields == 1): modalErrorMsg = wgn.messages_arr.programs.field_error; break; case (invalidFields > 1): modalErrorMsg = wgn.messages_arr.programs.field_errors; break; default: break; } if (modalErrorMsg != ""){ $('.modal-title').html(modalErrorMsg); return; } var npSelected = $('#mpModal [data-key="notifyUnits"]')[0]["value"]; switch(true){ case (npSelected == "days"): // wgn.marketcontext.parameters.notifyPeriod = "P" + $('#mpModal #notifyPeriod').val() + "D"; break; case (npSelected == "hours"): // wgn.marketcontext.parameters.notifyPeriod = "PT" + $('#mpModal #notifyPeriod').val() + "H"; break; case (npSelected == "minutes"): // wgn.marketcontext.parameters.notifyPeriod = "PT" + $('#mpModal #notifyPeriod').val() + "M"; break; case (npSelected == "seconds"): // wgn.marketcontext.parameters.notifyPeriod = "PT" + $('#mpModal #notifyPeriod').val() + "S"; break; } var fpSelected = $('#mpModal [data-key="freezeUnits"]')[0]["value"]; switch(true){ case (fpSelected == "days"): // wgn.marketcontext.parameters.freezePeriod = "P" + $('#mpModal #freezePeriod').val() + "D"; break; case (fpSelected == "hours"): // wgn.marketcontext.parameters.freezePeriod = "PT" + $('#mpModal #freezePeriod').val() + "H"; break; case (fpSelected == "minutes"): // wgn.marketcontext.parameters.freezePeriod = "PT" + $('#mpModal #freezePeriod').val() + "M"; break; case (fpSelected == "seconds"): // wgn.marketcontext.parameters.freezePeriod = "PT" + $('#mpModal #freezePeriod').val() + "S"; break; } wgn.marketcontext.parameters.eventPropagationType = $('#mpModal [data-key="eventPropagationType"]')[0]["value"]; wgn.marketcontext.parameters.policy = $('#mpModal [data-key="policy"]')[0]["value"]; $.ajax({ url: wgn.marketcontext.submitUrl, contentType: "application/json", dataType: 'json', data: JSON.stringify(wgn.marketcontext.parameters), type: wgn.marketcontext.submitType, cache: false, error: function(){ wgn.console('ajax request error!','f'); }, statusCode: { 400: function(){ wgn.console('400 http response: bad request...','f'); } } }) .done(function(data){ $('#mpModal').modal('hide'); programList(); $('#editModal, #deleteRow').addClass('disabled'); wgn.marketcontext.selectedRow = false; }) .fail(function(data){ wgn.marketcontext.errors = $.parseJSON(data.responseText); for (i in wgn.marketcontext.errors.fieldErrors){ //field error object iteration j = i.replace('VertexDrProgram.',''); switch(true){ case ($('.' + j + '_marker').length == 1): $('.' + j + '_marker').addClass("invalid"); invalidFields++; break; case ($('#' + j).length == 1): $('#' + j).addClass("invalid"); invalidFields++; break; default: //no field to mark break; } } for (k in wgn.marketcontext.errors.globalErrors){ //global error array iteration modalErrorMsg = modalErrorMsg + lineBreak + wgn.marketcontext.errors.globalErrors[k]; lineBreak = "<br/>"; } switch(true){ case (invalidFields == 1): modalErrorMsg = modalErrorMsg + lineBreak + wgn.messages_arr.programs.field_error; lineBreak = "<br/>"; break; case (invalidFields > 1): modalErrorMsg = modalErrorMsg + lineBreak + wgn.messages_arr.programs.field_errors; lineBreak = "<br/>"; break; default: break; } if (modalErrorMsg != ""){ $('.modal-title').html(modalErrorMsg); } }); }); $('#calendario').on('change',function(){ wgn.selectContext = $($(this)[0].selectedOptions[0]).attr('data-limit'); $('#tiempo').attr('max',wgn.selectContext); if ($('#tiempo').val() > wgn.selectContext){ $('#tiempo').val(wgn.selectContext) } }); });
const app = getApp() Page({ /** * 页面的初始数据 */ data: { StatusBar: app.globalData.StatusBar, CustomBar: app.globalData.CustomBar, TabbarBot: app.globalData.tabbar_bottom, hidden: true, defaultAdd:false, region:['广东省', '广州市', '番禺区'] }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { wx.showLoading({ title: '加载中...', }); wx.getSetting({ success:res=>{ if (!res.authSetting['scope.userInfo']) { wx.navigateTo({ //跳转到授权页面 url: '/pages/component/auth/auth' }) } } }); }, // 返回到地址列表展示页面 returnAddList: function () { wx.navigateBack({ }) }, // 用户改变省市区三级地区时触发的事件,保存到data RegionChange:function(e) { this.setData({ region:e.detail.value }) }, //保存用户新增的收获到data formSubmit:function(e) { console.log(e) var detailMes = e.detail.value; var len = detailMes.phone.length; var that =this; //正则表达式验证 let mobile = /^1\d{10}$/ //正则表达式验证,输入格式有误,弹出modal提示 if (!(len == 11 && mobile.test(detailMes.phone))) { wx.showModal({ title: '提示', content: '你输入的电话号码格式有误,请重新输入', showCancel: false, success(res) { if (res.confirm) { } } }) return; } let addDesc = { cusName: detailMes.name, cusPhone: detailMes.phone, cusAdd: detailMes.descAdd, region:that.data.region, defaultAdd:that.data.defaultAdd } getApp().globalData.addArr.push(addDesc); wx.setStorage({ key: 'addArr', data: app.globalData.addArr, success:function(res) { // console.log(res); }, fail:function(res) { console.log(res); } }) wx.navigateBack({ }) }, // switch选择框改变时触发,判断是否为默认地址 switchChange:function(e) { console.log(e); const that =this; that.setData({ defaultAdd:e.detail.value }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { wx.hideLoading(); }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })
NewsReader.Routers.Router = Backbone.Router.extend({ routes: { "" : "index", 'feeds/:id' : 'feedShow' }, initialize: function(options) { this.feeds = new NewsReader.Collections.Feeds(); this.$rootEl = options.$rootEl; }, index: function () { this.indexView = new NewsReader.Views.FeedsIndex({collection: this.feeds}); this.feeds.fetch(); this.$rootEl.html(this.indexView.$el); }, feedShow: function(id) { var feed = this.feeds.getOrFetch(id); var feedShow = new NewsReader.Views.FeedShow({model: feed}); feed.fetch(); this.$rootEl.html(feedShow.$el); } });
import { AppError } from "../errors"; import { User } from "../models"; class UserController { async destroy(req, res) { const { userId: id } = req; const messages = { success: "Usuário deletado com sucesso.", error: "Ocorreu um erro. Por favor, tente novamente mais tarde.", userNotFound: 'Usuário não encontrado. Verifique os dados e tente novamente.' } let user; try { user = await User.findOne({ where: { id } }); } catch (error) { throw new AppError(messages.error); } if (!user) { throw new AppError(messages.userNotFound); } try { await user.destroy(); return res.json({ message: messages.success }); } catch (error) { throw new AppError(messages.error); } } async update(req, res) { const { userId: id, body: { name, email } } = req; const messages = { success: "Informações atualizadas com sucesso.", error: "Ocorreu um erro. Por favor, tente novamente mais tarde.", userNotFound: 'Usuário não encontrado. Verifique os dados e tente novamente.' } let user; try { user = await User.findOne({ where: { id } }); } catch (error) { throw new AppError(messages.error); } if (!user) { throw new AppError(messages.userNotFound); } try { await User.update({ name, email }, { where: { id } }); return res.json({ message: messages.success }); } catch (error) { throw new AppError(messages.error); } } }; export default new UserController();
/* * Copyright (C) 2009-2017 SAP SE or an SAP affiliate company. All rights reserved. */ sap.ui.define([ 'jquery.sap.global', 'sap/ui/core/Control', 'sap/ui/thirdparty/d3', "sap/ui/core/ResizeHandler", "sap/ui/model/json/JSONModel" ], function($, Control, d3, ResizeHandler, JSONModel) { 'use strict'; return Control.extend('fin.re.conmgmts1.controls.timeline.TimeLine', { metadata: { properties: { from: { type: 'object', bindable: true }, to: { type: 'object', bindable: true }, currentTimeline: { type: 'object', bindable: true }, next: { type: 'boolean', bindable: true } }, aggregations: { items: { type: 'fin.re.conmgmts1.controls.timeline.TimeLineItem', multiple: true, singularName: 'item', bindable: true } }, defaultAggregation: 'items', events: { press: { enableEventBubbling: true } } }, _sResizeHandlerId: null, init: function() { }, renderer: function(oRm, oControl) { oRm.write("<div"); oRm.writeControlData(oControl); oRm.addClass('timeline-chart-container'); oRm.writeClasses(); oRm.write('>'); oRm.write("</div>"); }, openPopOver: function(source, event) { if (!this._reminderPopover) { this._reminderPopover = sap.ui.xmlfragment('fin.re.conmgmts1.view.contractstermblocks.TimelinePopover', this); this.addDependent(this._reminderPopover); } this._reminderPopover.setModel(new JSONModel({ date: event.dateTo, info: event.eventInfo }), 'selectedTimelineEvent'); this._reminderPopover.openBy(source); }, _mapEventsColor: function(events, type) { var colorValue = '#000'; switch (type) { case 'L': colorValue = '#fac364'; break; case 'M': colorValue = '#d998cb'; break; case 'V': colorValue = '#5cbae6'; break; case 'W': colorValue = '#b6d957'; break; case 'R': colorValue = '#5cbae6'; break; case 'K': colorValue = '#d998cb'; break; default: colorValue = '#000'; } events.map(function(e) { if (e.eventType === 'R' && e.dateFrom.getTime() < new Date().getTime()) { e.color = "#888888"; } else { e.color = colorValue; } }); return events; }, _mapEventsIcon: function(events, type) { var iconValue = '\ue220'; switch (type) { case 'L': iconValue = '\ue22a'; break; case 'M': iconValue = '\ue22a'; break; case 'V': iconValue = '\ue053'; break; case 'W': iconValue = '\ue0a7'; break; case 'R': iconValue = '\ue030'; break; case 'K': iconValue = '\ue22a'; break; default: iconValue = '\ue220'; } events.map(function(d) { d.icon = iconValue; }); return events; }, _getDaysDiff: function(eventA, eventB) { // 86400000 = 1000 * 60 * 60 * 24 var dateToMonthNumber = parseInt(eventA.dateTo.getTime() / 86400000, 0); var dateFromMonthNumber = parseInt(eventB.dateFrom.getTime() / 86400000, 0); return dateToMonthNumber - dateFromMonthNumber; }, _addHeightByCount: function(eventsRow, height) { var result = height; if (eventsRow === 1) { result = result + 35; } else if (eventsRow === 0) { result = result; } else { result = result + (eventsRow - 1) * 15 + 35; } return result; }, _getLengthDiff: function(eventA, eventB) { var longA = parseInt((eventA.dateTo.getTime() - eventA.dateFrom.getTime()) / 86400000, 0); var longB = parseInt((eventB.dateTo.getTime() - eventB.dateFrom.getTime()) / 86400000, 0); return longA - longB; }, _setY: function(events, startY) { var count = 0; var currentCount = 0; var baseEvent; if (events.length > 0) { baseEvent = events[0]; count = count + 1; events[0].y = startY; currentCount = 1; } var yValue = startY; for (var i = 1; i < events.length; i++) { var daysDiff = this._getDaysDiff(baseEvent, events[i]); if (daysDiff < -45) { yValue = startY; baseEvent = events[i]; if (currentCount > count) { count = currentCount; } currentCount = 1; } else { yValue = yValue + 15; currentCount = currentCount + 1; if (this._getLengthDiff(baseEvent, events[i]) < -5) { baseEvent = events[i]; } } events[i].y = yValue; } if (currentCount > count) { count = currentCount; } return { count: count, events: events }; }, _getSortedEventsByType: function(events, type) { var filteredEvents = events.filter(function(d) { return d.eventType === type; }); var sortedEvents = filteredEvents.sort(function(a, b) { if (type === 'W' || type === 'V') { return b.dateFrom.getTime() - a.dateFrom.getTime(); } else { return a.dateFrom.getTime() - b.dateFrom.getTime(); } }); sortedEvents = this._mapEventsColor(sortedEvents, type); sortedEvents = this._mapEventsIcon(sortedEvents, type); if (type === 'V' || type === 'W') { sortedEvents = filteredEvents.filter(function(d) { // 86400000 = 1000 * 60 * 60 * 24 var daysOfEvent = parseInt(d.dateFrom.getTime() / 86400000, 0); var daysOfCurrent = parseInt(new Date().getTime() / 86400000, 0); return daysOfEvent >= daysOfCurrent; }); } if (this.getNext() && sortedEvents.length > 0 && type != 'R') { sortedEvents = (type === 'V' || type === 'W') ? [sortedEvents[sortedEvents.length - 1]] : [sortedEvents[0]]; } return sortedEvents; }, _breakDateText: function(dateText, separator) { return dateText.split(separator); }, _drawReminders: function(svg, events, x, y) { var that = this; var reminders = svg.append("g"); reminders.selectAll(".reminder") .data(events) .enter().append("text") .attr("class", "reminder") .attr("x", function(d) { return x(d.dateFrom); }) .attr("y", y) .on("click", function(d) { that.openPopOver(this, d); }) .style("display", "none") .attr("dy", ".35em") .attr("dx", "-.80em") .style("font-family", "SAP-icons") .style("fill", function(d) { return d.color; }) .text(function(d) { return d.icon; }); }, _drawEvent: function(svg, events, x, width) { // draw line var lines = svg.append("g"); lines.selectAll(".itemline") .data(events) .enter().append("line") .attr("class", "itemline") .attr("y1", function(d) { return d.y; }) .attr("y2", function(d) { return d.y; }) .attr("x1", function(d) { if (x(d.dateFrom) < 0) { return 0; } else if (x(d.dateFrom) > (width - 264)) { return (width - 264); } else { return x(d.dateFrom); } }) .attr("x2", function(d) { return x(d.dateTo) > (width - 264) ? (width - 264) : x(d.dateTo); }) .style("fill", "none") .style("stroke", function(d) { return d.color; }) .style("stroke-width", "3") .style("shape-rendering", "crispEdges"); // draw end dot of line lines.selectAll(".enddot") .data(events) .enter().append("line") .attr("class", "enddot") .attr("y1", function(d) { return d.y - 5; }) .attr("y2", function(d) { return d.y + 5; }) .attr("x1", function(d) { return x(d.dateTo); }) .attr("x2", function(d) { return x(d.dateTo); }) .style("display", function(d) { return x(d.dateTo) > (width - 264) ? "none" : ""; }) .style("stroke-width", "3") .style("shape-rendering", "crispEdges") .style("stroke", function(d) { return d.color; }); if ((events.length > 0) && (events[0].eventType === "V" || events[0].eventType === "W")) { // draw end dot of line lines.selectAll(".dotline") .data(events) .enter().append("line") .attr("class", "dotline") .attr("y1", function(d) { return d.y; }) .attr("y2", function(d) { return d.y; }) .attr("x1", function(d) { return x(d.notifDateTo); }) .attr("x2", function(d) { return x(d.dateFrom); }) .style("stroke-dasharray", "3,5") .style("stroke-width", "3") .style("shape-rendering", "crispEdges") .style("stroke", function(d) { return d.color; }); } // draw start icon of line lines.selectAll(".starticon") .data(events) .enter().append("text") .attr("class", "starticon") .attr("x", function(d) { return d.notifDateTo === undefined ? x(d.dateFrom) : x(d.notifDateTo); }) .attr("y", function(d) { return d.y; }) .attr("dy", ".35em") .attr("dx", "-.80em") .style("font-family", "SAP-icons") .style("fill", function(d) { return d.color; }) .text(function(d) { return d.icon; }); }, resize: function() { var oBundle = this.getModel("i18n").getResourceBundle(); var today = oBundle.getText("Terms.Timeline.Label.Today"); var showReminders = oBundle.getText("Terms.Timeline.Label.ShowReminders"); var that = this; var customTimeFormat = d3.time.format.multi([ ["%b", function(d) { return d.getMonth(); }], ["%b:%Y", function() { return true; }] ]); //var $container = $('.timeline-chart-container'); var width = parseInt(d3.select(".timeline-chart-container").style("width"), 10); var timeTicksRange = width > 800 ? 3 : 12; var height = parseInt(d3.select(".timeline-chart-container").style("height"), 10); var cItems = this.getItems(); var mockUpItems = []; for (var i = 0; i < cItems.length; i++) { mockUpItems.push({ "dateFrom": cItems[i].getProperty("dateFrom"), "dateTo": cItems[i].getProperty("dateTo"), "eventType": cItems[i].getProperty("eventType"), "eventLevel": cItems[i].getProperty("eventLevel"), "eventInfo": cItems[i].getProperty("eventInfo"), "notifDateTo": cItems[i].getProperty("notifDateTo") }); } var current = this.getCurrentTimeline(); height = 75; if (!(current instanceof Array)) { var eventsAndCount = this._setY(this._getSortedEventsByType(mockUpItems, "V"), height); var optionalRenewals = eventsAndCount.events; height = this._addHeightByCount(eventsAndCount.count, height); eventsAndCount = this._setY(this._getSortedEventsByType(mockUpItems, "W"), height); var automaticRenewals = eventsAndCount.events; height = this._addHeightByCount(eventsAndCount.count, height); eventsAndCount = this._setY(this._getSortedEventsByType(mockUpItems, "L"), height); var contracteeBreakOptions = eventsAndCount.events; height = this._addHeightByCount(eventsAndCount.count, height); eventsAndCount = this._setY(this._getSortedEventsByType(mockUpItems, "M"), height); var contractorBreakOptions = eventsAndCount.events; height = this._addHeightByCount(eventsAndCount.count, height); eventsAndCount = this._setY(this._getSortedEventsByType(mockUpItems, "K"), height); var breakOptions = eventsAndCount.events; height = this._addHeightByCount(eventsAndCount.count, height); var reminders = this._getSortedEventsByType(mockUpItems, "R", -0.3); var from = this.getFrom(); var to = this.getTo(); var id = this.getId(); var x = d3.time.scale().domain([from, to]).range([0, width - 264]); var xAxis = d3.svg.axis().scale(x).orient("bottom").tickSize(6, 0).tickFormat(customTimeFormat).ticks(d3.time.months, timeTicksRange); var svg = d3.select("svg").remove(); svg = d3.select("#" + id) .append("svg") .attr("width", width) .attr("height", height) .append("g") //.call(d3.behavior.zoom().scaleExtent([1, 8]).on("zoom", zoom)) .style("font", "11px sans-serif"); svg.append("g") .attr("transform", "translate(0," + 40 + ")") .attr("class", "x axis") .call(xAxis); // draw current time period current.color = '#000'; var currentPeriod = svg.append("g"); currentPeriod.append("line") .attr("y1", 40) .attr("y2", 40) .attr("x1", function() { return x(current.dateFrom); }) .attr("x2", function() { return x(current.dateTo) > (width - 264) ? (width - 264) : x(current.dateTo); }) .style("fill", "none") .style("stroke", "#000") .style("stroke", "#000") .style("stroke-width", "3") .style("shape-rendering", "crispEdges"); currentPeriod.append("circle") .attr("cx", function() { return x(current.dateFrom); }) .attr("cy", 40) .attr("r", 4) .style("fill", "#000"); if (x(current.dateTo) <= (width - 264)) { currentPeriod.append("line") .attr("y1", 35) .attr("y2", 45) .attr("x1", x(current.dateTo)) .attr("x2", x(current.dateTo)) .style("stroke-width", "3") .style("stroke", "#000"); } //var colorDef = [contracteeBreakOptions[0], contractorBreakOptions[0], renewals[0]]; var colorDef = []; if (current) { colorDef.push(current); } if (optionalRenewals.length > 0) { colorDef.push(optionalRenewals[0]); } if (automaticRenewals.length > 0) { colorDef.push(automaticRenewals[0]); } if (contracteeBreakOptions.length > 0) { colorDef.push(contracteeBreakOptions[0]); } if (contractorBreakOptions.length > 0) { colorDef.push(contractorBreakOptions[0]); } if (breakOptions.length > 0) { colorDef.push(breakOptions[0]); } // draw legend var legend = svg.selectAll(".legend") .data(colorDef) .enter().append("g") .attr("class", "legend") .attr("transform", function(d, i) { return "translate(0," + (i + 2) * 18 + ")"; }); legend.append("line") .attr("y1", 6) .attr("y2", 6) .attr("x1", width - 214) .attr("x2", width - 190) .style("stroke", function(d) { return d.color; }) .style("stroke-width", "3"); legend.append("text") .attr("x", width - 184) .attr("y", 6) .attr("dy", ".35em") .style("text-anchor", "start") .text(function(d) { return d.eventInfo; }); // draw events and reminders this._drawEvent(svg, optionalRenewals, x, width); this._drawEvent(svg, automaticRenewals, x, width); this._drawEvent(svg, contracteeBreakOptions, x, width); this._drawEvent(svg, contractorBreakOptions, x, width); this._drawEvent(svg, breakOptions, x, width); this._drawReminders(svg, reminders, x, 55); // draw start today line svg.append("g").append("line") .attr("y1", 15) .attr("y2", height) .attr("x1", x(new Date())) .attr("x2", x(new Date())) .style("stroke", "#000") .style("stroke-width", "1") .style("stroke-dasharray", "5"); svg.append("text") .attr("x", x(new Date())) .attr("y", 1) .attr("dy", ".70em") .attr("dx", "1.1em") .style("text-anchor", "end") .text(today); d3.selectAll("g.tick line").each(function(d) { d3.select(this) .attr("y1", height) .attr("y2", "-5"); }); d3.selectAll("g.tick text").each(function(d) { var dateTexts = that._breakDateText(d3.select(this).text(), ":"); d3.select(this).text(''); d3.select(this).append('tspan') .attr('y', '0') .attr('dy', '-0.5em') .text(dateTexts[0]); d3.select(this).append('tspan') .attr('y', '0') .attr('dx', '-1.5em') .attr('dy', '1.2em') .text(dateTexts[1]); }); // checkbox svg.append("foreignObject") .attr("width", 200) .attr("height", 200) .attr("x", width - 214) .attr("y", 0) .append("xhtml:body") .html("<form><input type=checkbox id=check>" + showReminders + "</input></form>") .on("click", function(d, i) { if (svg.select("#check").node().checked) { svg.selectAll(".reminder").style("display", ""); } else { svg.selectAll(".reminder").style("display", "none"); } }); } }, onAfterRendering: function() { this.resize(); this._sResizeHandlerId = ResizeHandler.register(this, $.proxy(this.resize, this)); } }); }, true);
var fs = require("fs"); fs.readFileSync("input.txt").toString().split("\n").forEach(function (line) { if (line !== "") { swapElements(line); } }); function swapElements(line) { var temp = line.trim().split(":"), numbers = temp[0].trim().split(" ").map(function (n) { return parseInt(n); }), swapRules = temp[1].trim().split(", "); swapRules.forEach(function (r) { var temp2 = r.split("-"); swap(parseInt(temp2[0]), parseInt(temp2[1]), numbers); }); console.log(numbers.join(" ")); } function swap(from, to, numbers) { if (from === to) { return; } var temp = numbers[from]; numbers[from] = numbers[to]; numbers[to] = temp; }
import React from 'react' import numeral from 'numeral' import moment from 'moment' import ExternalLink from './ExternalLink' const FeaturedDataset = ({ dataset, onClick }) => { const { peername, name, meta, structure, commit } = dataset const description = meta && meta.description ? meta.description : 'No description' const title = meta && meta.title ? meta.title : `No Title - ${name}` const { entries, length } = structure const { timestamp } = commit let keywordElements = null if (meta && meta.keywords) { keywordElements = meta.keywords.map((keyword) => ( <div key={keyword} className='keyword badge badge-secondary mr-2'>{keyword}</div> )) } return ( <div className='card featured-dataset index-card index-shadow' onClick={onClick}> <ExternalLink to={`https://qri.cloud/${peername}/${name}`}> <div className='card-body px-3'> <div className='row'> <div className='col-12'> <div className='dataset-reference'> <p className='dataset-reference-item'>{peername}/</p> <p className='dataset-reference-item'>{name}</p> </div> <div className='pb-1'> <span className='details mr-2'>{moment(timestamp).fromNow()}</span> <span className='details mr-2'>{numeral(length).format('0.0b')}</span> <span className='details mr-2'>{numeral(entries).format('0,0')} entries</span> </div> <div className='dataset-keywords mb-3'> { keywordElements } </div> <div className='dataset-title title mb-2'>{ title }</div> <div className='dataset-description'>{ description }</div> </div> </div> </div> </ExternalLink> </div> ) } export default FeaturedDataset
import React, { PropTypes } from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Layout.less'; import Header from '../Header'; import Sidebar from '../Sidebar'; import Loading from '../Loading'; import { Breadcrumb } from 'antd'; const BreadcrumbItem = Breadcrumb.Item; const HeaderV = Header.Vertical; const getUsername = () => { const username = 'username='; const cookie = document.cookie; const begin = cookie.indexOf(username) + username.length; const end = cookie.indexOf(';', begin); return unescape(cookie.substring(begin, end < 0 ? cookie.length : end)); }; class Layout extends React.Component { static propTypes = { children: PropTypes.node, nav1: PropTypes.string, nav2: PropTypes.string, settingUrl: PropTypes.string, navigation: PropTypes.array, sidebars: PropTypes.object, openKeys: PropTypes.object, onOpenChange: PropTypes.func, onMenuClick: PropTypes.func }; constructor(props) { super(props); this.state = {mode: 'expand', username: getUsername(), url: {}}; } componentWillReceiveProps(props) { if (!props.loading) { this.setState({url: Object.assign({}, this.state.url, {[props.nav1]: `/${props.nav1}/${props.nav2}`})}); } } onOpenChange = (openKeys) => { const {nav1, onOpenChange} = this.props; if (onOpenChange) { onOpenChange(nav1, openKeys); } }; findNavItem = (key) => { return this.props.navigation.find(item => item.key === key); }; headerProps = (selectKey) => { return { selectKey, url: this.state.url, setting: this.findNavItem('basic'), message: this.findNavItem('message'), messageCount: this.props.messageCount, username: this.state.username, onMenuClick: this.props.onMenuClick }; }; headerVProps = (selectKey) => { const keys = ['basic', 'message']; return { selectKey, url: this.state.url, items: this.props.navigation.filter(item => !keys.includes(item.key)) }; }; sidebarProps = (nav1, nav2) => { const item = this.props.navigation.find(item => item.key === nav1) || {}; return { mode: this.state.mode, title: item.title, activeKey: nav2, items: this.props.sidebars[nav1] || [], openKeys: (this.props.openKeys || {})[nav1], onOpenChange: this.onOpenChange, onModeChange: mode => this.setState({mode}) }; }; toPageTitle = () => { const {pageTitles, nav2} = this.props; return ( <Breadcrumb separator=">"> {pageTitles[nav2].map((item, index) => (<BreadcrumbItem key={index}>{item}</BreadcrumbItem>))} </Breadcrumb> ); }; render() { const {loading, nav1='', nav2='', children} = this.props; return ( <div className={s.root}> <Header {...this.headerProps(loading || nav1)} /> <div> <HeaderV {...this.headerVProps(loading || nav1)} /> <aside>{nav2 ? <Sidebar {...this.sidebarProps(nav1, nav2)} /> : null}</aside> {nav2 ? this.toPageTitle() : null} {loading ? <Loading /> : <section>{children}</section>} </div> </div> ) }; } export default withStyles(s)(Layout);
const readlineSync = require("readline-sync"); const t = Number(readlineSync.question("\nEnter a temperature: ")); const s = String(readlineSync.question("Enter a scale: ")) const ffp = 32; const fbp = 212; const cfp = 0; const cbp = 100; const kfp = 273; const kbp = 373; if (t < (Number.MIN_SAFE_INTEGER) || t > Number.MAX_SAFE_INTEGER) { console.log("\nInvalid.\n") } else if (t <= ffp && (s == "F" || s == "f")){ console.log("\nSolid.\n") } else if ((t > ffp && t < fbp) && (s == "F" || s == "f")){ console.log("\nLiquid.\n") } else if (t >= fbp && (s == "F" || s == "f")){ console.log("\nGas.\n") } else if (t <= cfp && (s == "C" || s == "c")){ console.log("\nSolid.\n") } else if ((t > cfp && t < cbp) && (s == "C" || s == "c")){ console.log("\nLiquid.\n") } else if (t >= cbp && (s == "C" || s == "c")){ console.log("\nGas.\n") } else if (t <= kfp && (s == "K" || s == "k")){ console.log("\nSolid.\n") } else if ((t > kfp && t < fbp) && (s == "K" || s == "k")){ console.log("\nLiquid.\n") } else if (t >= kbp && (s == "K" || s == "k")){ console.log("\nGas.\n") } else { console.log("\nInvalid.\n") }
window.addEventListener('load', () => { const game = new Game('canvas-game') game.start() // ==================================== // Computer / Laptops // ==================================== document.addEventListener('keydown', event => { game.onKeyEvent(event) }) document.addEventListener('keyup', event => { game.onKeyEvent(event) }) // ==================================== // Mobile Events // ==================================== game.canvas.addEventListener('touchstart', event => { event.keyCode = KEY_UP; game.onKeyEvent(event); }); game.canvas.addEventListener('touchend', event => { event.keyCode = KEY_UP; game.onKeyEvent(event); }); // Desactivar Zoom let lastTouchEnd = 0; document.addEventListener('touchend', function (event) { let now = (new Date()).getTime(); if (now - lastTouchEnd <= 300) { event.preventDefault(); } lastTouchEnd = now; }, false); });
'use strict'; const key = 'bea1ef37a31e4f89ac4102550211508'; const url = 'https://api.weatherapi.com/v1/current.json?key=bea1ef37a31e4f89ac4102550211508&q=iasi&aqi=yes'; const form = document.querySelector('[data-form]'); form.addEventListener('submit', handleSubmit); function handleSubmit(e) { e.preventDefault(); const input = e.target.elements.city.value; const result = document.querySelector('[data-result]'); const img = document.querySelector('[data-weather-icon]'); const details = document.querySelector('[data-details]'); fetch(`https://api.weatherapi.com/v1/current.json?key=${key}&q=${input}&aqi=no`) .then((response) => response.json()) .then((responseJson) => { result.innerText = responseJson.current.temp_c + ' °C'; img.style.display = 'inline'; img.src = responseJson.current.condition.icon; details.innerText = responseJson.current.condition.text; }); }
import React from 'react'; import { StyleSheet, Text, View, StatusBar, TextInput, TouchableOpacity, Alert, } from 'react-native'; import firebase, { auth } from "firebase"; import config from '../config/firebase'; export default class SignUpScreen extends React.Component { state = { email :null, password : null, } Signup = ()=>{ if(this.state.email == null && this.state.password == null){ Alert.alert("Error","All fields are mandatory") return; } try{ firebase .auth() .createUserWithEmailAndPassword (this.state.email,this.state.password). catch((error) => Alert.alert(error.toString(error))) .then((user) => { console.log(user); if(user){ Alert.alert("Account Created"); this.props.navigation.navigate('Home') } }); }catch (error) { console.log(error.toString(error)); } } render() { return ( <View style={styles.container}> <StatusBar translucent backgroundColor="transparent" /> <Text style={styles.textProp}>Sign up</Text> <View> <TextInput placeholderTextColor={'#86898E'} placeholder={'Email'} style={styles.emailField} onChangeText={(email)=>{this.setState({email})}} /> <View> <TextInput secureTextEntry={true} style={styles.default} placeholderTextColor={'#86898E'} placeholder={'Password'} style={styles.pwdField} onChangeText={(password)=>{this.setState({password})}} /> <View> <TouchableOpacity style={styles.signButton} activeOpacity={0.5} onPress={this.Signup}> <Text style={styles.btnTxt}> Sign up </Text> </TouchableOpacity> <View> <Text style={styles.bodyTxt}>Already a member? </Text> <TouchableOpacity onPress={() => this.props.navigation.navigate('Login')}> <Text style={styles.signInTxt}>Sign in </Text> </TouchableOpacity> </View> <View> <Text style={styles.footerTxt}>WeGo</Text> </View> </View> </View> </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#ffffff', alignItems: 'center', justifyContent: 'center', }, textProp: { fontFamily: 'Montserrat-Bold', fontSize: 38, color: '#314256', marginTop: 32, marginBottom: 0, marginRight: 0, marginLeft: 37, alignSelf: 'flex-start', }, emailField: { fontFamily: 'Montserrat-Light', fontSize: 14, color: '#86898E', width: 286, height: 60, backgroundColor: '#E1E6EC', borderRadius: 30, paddingLeft: 22, marginTop: 98, marginBottom: 0, marginLeft: 0, marginRight: 0, }, pwdField: { fontFamily: 'Montserrat-Light', fontSize: 14, color: '#86808E', width: 286, height: 60, backgroundColor: '#E1E6EC', borderRadius: 30, paddingLeft: 22, marginTop: 36, marginBottom: 0, marginLeft: 0, marginRight: 0, }, btnTxt: { fontFamily: 'Montserrat-Regular', fontSize: 14, textAlign: 'center', color: '#ffffff', backgroundColor: '#0176FB', padding: 0, marginTop: 10, paddingTop: 15, paddingBottom: 15, borderRadius: 30, width: 138, height: 52, }, signButton: { alignSelf: 'center', marginTop: 47, marginLeft: 0, marginRight: 0, marginBottom: 0, }, bodyTxt: { fontFamily: 'Montserrat-Regular', fontSize: 14, color: '#314256', marginTop: 58, marginBottom: 0, marginRight: 0, marginLeft: 0, alignSelf: 'center', }, signInTxt: { fontFamily: 'Montserrat-Bold', fontSize: 14, color: '#0176FB', alignSelf: 'center', }, footerTxt: { fontFamily: 'Montserrat-Bold', fontSize: 20, alignSelf: 'center', color: '#314256', marginTop: 90, marginBottom: 16, marginRight: 0, marginLeft: 0, }, });
import React, { useState } from 'react' import { Button, Input } from '../GlobalStyles'; const TodoForm = ({ addTodo }) => { const [todo, setTodo] = useState({ id: '', task: '', completed: false }); const changeAction = (event) => { setTodo({ ...todo, task: event.target.value }); } const handleSubmit = (event) => { event.preventDefault(); if (todo.task.trim()) { addTodo({ ...todo, id: Math.floor(Math.random() * 10000) }) setTodo({ ...todo, task: "" }) } } return ( <form onSubmit={handleSubmit} > <h1>Todo List 📓</h1> <Input name="task" type="text" onChange={changeAction} value={todo.task} /> <Button type='submit'> Add todo </Button> </form> ) } export default TodoForm
angular.module('about') .component('about', { templateUrl: 'app/components/about/about.html' });
export {EditPanel} from './edit-panel';
// import mock from 'mock' // console.log(mock)
function openVentana1() { $(".ventana2").slideDown("slow"); } function closeVentana1() { $(".ventana2").slideUp("fast"); }
export const setCity = city => ({ type: 'SET_CITY', payload: { city } }) export const setCoordinates = (coordinates) => ({ type: 'SET_COORDINATES', payload: { coordinates } }) export const setData = (weather) => ({ type: 'SET_DATA', payload: { weather } })
import { FETCH_CURRENT_USER, CURRENT_USER_REQUEST, CURRENT_USER_RESPONSE, CURRENT_USER_ERROR, CURRENT_USER_CLEAR } from "./constants"; const initialState = { currentUser: null, currentUserIsLoading: false, currentUserIsLoaded: false, currentUserError: false }; const currentUserReducer = (state = initialState, action) => { switch (action.type) { case FETCH_CURRENT_USER: return { ...state }; case CURRENT_USER_REQUEST: return { ...state, currentUserIsLoading: true, currentUserIsLoaded: false, currentUserError: false }; case CURRENT_USER_RESPONSE: return { ...state, currentUserIsLoading: false, currentUserIsLoaded: true, currentUserError: false, currentUser: action.payload }; case CURRENT_USER_ERROR: return { ...state, currentUserIsLoading: false, currentUserIsLoaded: false, currentUserError: true }; case CURRENT_USER_CLEAR: { return { ...state, currentUser: null }; } default: return state; } }; export default currentUserReducer;
export { get as getAvailability } from './get'; export { AVAILABILITY_NOT_AVAILABLE, AVAILABILITY_CHECK_IN, AVAILABILITY_CHECK_IN_AND_OUT, AVAILABILITY_CHECK_OUT, } from './constants';
import React from 'react'; import {applyMiddleware, createStore} from 'redux' import {logger} from "redux-logger"; import rootReducer from "./Reducers/Reducer"; export default () => { const store = createStore(rootReducer, applyMiddleware(logger)); return store; }
import React from 'react'; import { Container, Row, Col, Button } from "react-bootstrap"; import HomePageNav from '../../components/NavBarHomePage'; import styles from './styles.module.css'; import { useHistory } from "react-router-dom"; import image from '../../image/image2.png' function HomePage() { const history = useHistory() return ( <> <HomePageNav /> <img src={image} alt="=" className={styles.image} style={{ position: 'absolute' }} /> <Container fluid style={{ position: 'relative', width: '100%'}}> <Row> <Col xs={0} sm={0} md={1} lg={1} /> <Col xs={12} sm={12} md={12} lg={6} className={styles.containerTopText}> <h2 className={styles.h1}>GPPP_WEB - Gestão do Perfil Profissiográfico Previdenciário </h2> <br></br><br></br> <h4 className={styles.h2}> Disponibilizar uma aplicação WEB de Gestão do PPP (GPPP_WEB) que viabilize a formalização das requisições, a elaboração e disponibilização do PPP, nos termos da legislação vigente, com celeridade e segurança. </h4> <br></br><br></br> <h4 className={styles.h2}>Exigilize o processo de solicitação na sua empresa</h4> <br></br><br></br> <Button variant="primary" className="btnEdit" onClick={() => history.push('/created_user_employee')}>Cadastrar</Button> </Col> </Row> </Container> </> ) } export default HomePage
const mongoose = require('mongoose') const Schema = mongoose.Schema const scrapVideoSchema = new mongoose.Schema({ company_id: { type: Schema.Types.ObjectId, ref: 'company', required: true }, video_id: { type: Schema.Types.ObjectId, ref: 'video', required: true } }) const ScrapVideoModel = mongoose.model('scrapVideo', scrapVideoSchema) module.exports = ScrapVideoModel
module.exports = () => ({ '/': { page: '/' }, '/legal': { page: '/legal' }, '/privacy-policy': { page: '/privacy-policy' }, '/terms': { page: '/terms' }, '/products/cove-touch': { page: '/products/cove-touch' }, '/products/motion-sensor-alarm': { page: '/products/motion-sensor-alarm' }, '/products/window-security-device': { page: '/products/window-security-device' }, '/products/carbon-monoxide-detector': { page: '/products/carbon-monoxide-detector' }, '/products/smoke-detector': { page: '/products/smoke-detector' }, '/products/medical-alert-device': { page: '/products/medical-alert-device' }, '/products/glass-break-sensor': { page: '/products/glass-break-sensor' }, '/products/doorbell-camera': { page: '/products/doorbell-camera' }, '/products/home-security-camera': { page: '/products/home-security-camera' }, '/products/door-security-device': { page: '/products/door-security-device' }, '/products/flood-detection-sensor': { page: '/products/flood-detection-sensor' }, '/package-types': { page: '/packageTypes' }, '/medical': { page: '/medical' }, '/login': { page: '/login' }, '/homepage': { page: '/homepage' }, '/doorbell': { page: '/bell' }, '/individual_product': { page: '/products' }, '/checkout': { page: '/checkout', query: { stage: 'customer' } }, '/checkout/customer': { page: '/checkout', query: { stage: 'customer' } }, '/checkout/shipping': { page: '/checkout', query: { stage: 'shipping' } }, '/checkout/payment': { page: '/checkout', query: { stage: 'payment' } }, '/checkout/products': { page: '/checkout/products' }, '/walkthrough': { page: '/productwalkthrough/productWalkthrough' }, '/cart': { page: '/cart' }, '/order-confirmation': { page: '/checkout/orderConfirmation' }, '/order-summary': { page: '/checkout/orderSummary' }, '/monitoring-plan': { page: '/monitoringPlan' }, '/account': { page: '/account' }, '/account/summary': { page: '/account/summary' }, '/account/info': { page: '/account/info' }, '/account/info/notifications': { page: '/account/info/notifications' }, '/account/info/permit-number': { page: '/account/info/permitNumber' }, '/account/info/email': { page: '/account/info/email' }, '/account/info/phone': { page: '/account/info/phone' }, '/account/info/password': { page: '/account/info/password' }, '/account/info/bill-date': { page: '/account/info/billDate' }, '/account/info/monitored-address': { page: '/account/info/monitoredAddress' }, '/account/info/primary-phone': { page: '/account/info/primaryPhone' }, '/account/info/secondary-phone': { page: '/account/info/secondaryPhone' }, '/account/info/edit-emergency-contact': { page: '/account/info/editEmergencyContact' }, '/account/info/add-emergency-contact': { page: '/account/info/addEmergencyContact' }, '/account/info/add-user': { page: '/account/info/addUser' }, '/account/info/edit-user': { page: '/account/info/editUser' }, '/account/info/add-equipment': { page: '/account/info/addEquipment' }, '/account/info/return-equipment': { page: '/account/info/returnEquipment' }, '/account/info/alarm-insurance-certificate': { page: '/account/info/alarmInsuranceCertificate' }, '/account/subscriptions': { page: '/account/subscriptions' }, '/account/subscriptions/details': { page: '/account/subscriptions/details' }, '/account/subscriptions/activate': { page: '/account/subscriptions/activate' }, '/account/subscriptions/change': { page: '/account/subscriptions/change' }, '/account/subscriptions/cancel': { page: '/account/subscriptions/cancel' }, '/account/subscriptions/pay-balance': { page: '/account/subscriptions/payBalance' }, '/account/subscriptions/finance-details': { page: '/account/subscriptions/financeDetails' }, '/account/subscriptions/documents-agreements': { page: '/account/subscriptions/documentsAgreements' }, '/account/payment-methods': { page: '/account/paymentMethods' }, '/account/addresses': { page: '/account/addresses' }, '/account/addresses/change-monitored-address': { page: '/account/addresses/changeMonitoredAddress' }, '/account/addresses/add-shipping-address': { page: '/account/addresses/addShippingAddress' }, '/account/order-history': { page: '/account/orderHistory' }, '/account/order-history/order-details': { page: '/account/orderHistory/orderDetails' }, '/account/rewards': { page: '/account/rewards' }, '/account/equipment': { page: '/equipment', query: {} }, '/account/addequipment': { page: '/addEquipment' }, '/account/cancel': { page: '/cancelmembership' }, '/account/refer': { page: '/refer' }, '/account/password': { page: '/password' }, '/account/payoffbalance': { page: '/payoffbalance' }, '/account/phone': { page: '/phonenumber' }, '/account/loyalty': { page: '/loyaltycredits' }, '/account/email': { page: '/email' }, '/security': { page: '/security' }, '/starterkit': { page: '/starterkit' }, });
$(function(){ $('#hamburger-btn').on('click',function(){ $(this).toggleClass('on'); }); $('#hamburger-btn').on('click',function(){ $('.menu-target').toggleClass('hide'); }); });
const {multiplication, division} = require('../math') let result, expected result = multiplication(4, 2) expected = 8 if (result !== expected) { throw new Error(`${result} is not equal to ${expected}`) } result = division(4, 2) expected = 2 if (result !== expected) { throw new Error(`${result} is not equal to ${expected}`) }
var viewModel = { docs: ko.observableArray(), type: ko.observable() } viewModel.docName = ko.computed(function() { var t = viewModel.type(), arr = viewModel.docs() for(var i = 0;i<arr.length;i++) { if(t == arr[i]._id) return arr[i].name } return ''; }, viewModel) addEventListener('load', function () { ko.applyBindings(viewModel); }); $(document).ready(function() { var loadMask = $("#loader-mask") $("#docUploadForm").submit(function() { loadMask.css("top", document.body.scrollTop + 'px') loadMask.css("display", "block") var file = $("[name=file]")[0]; if(file && file.files && file.files[0] && file.files[0].size >0 && file.files[0].size < __MaxFileSize__) { } else { alert('Выберите файл документа!'); loadMask.css("display", "none") return false; } }) $("[name=file]").change(function() { if(this.files && this.files[0] && this.files[0].size > __MaxFileSize__) { alert('Размер файла превышает максимально допустимый ('+Math.round(__MaxFileSize__ / 1024 / 1024)+'Мб)') this.value = ''; } }) })
import React, { PureComponent } from 'react'; import { StyleSheet, KeyboardAvoidingView, Dimensions, Text, View, ActivityIndicator, TouchableOpacity, Image, Button, } from 'react-native'; const WIDTH = Dimensions.get('window').width; // import BottomSheet from 'reanimated-bottom-sheet' import RobotIcon from './assets/robotChat.svg' import Smile from './assets/smile.svg' import ChatMsg from './assets/chatmsg.svg' import Waves from './assets/waves.svg' import Dots from './assets/dots.svg' import { Freshchat, FaqOptions, FreshchatMessage } from 'react-native-freshchat-sdk'; import { FreshchatUser, ConversationOptions } from 'react-native-freshchat-sdk'; import ResponsiveModule from "./constants"; const { responsiveWidth, responsiveHeight, scaleFont } = ResponsiveModule; import messaging, { firebase } from '@react-native-firebase/messaging'; export default class FreeChatScreen extends PureComponent { constructor(props) { super(props); this.state = { showPass: true, press: false, }; this.showPass = this.showPass } componentDidMount() { var freshchatUser = new FreshchatUser(); freshchatUser.firstName = "John"; freshchatUser.lastName = "Doe"; freshchatUser.email = "johndoe@dead.man"; freshchatUser.phoneCountryCode = "+91"; freshchatUser.phone = "1234234123"; Freshchat.setUser(freshchatUser, (error) => { console.log(error); }); Freshchat.getUser((user) => { var restoreId = user.restoreId; console.log("restoreId: " + (user)); }) Freshchat.getFreshchatUserId((data) => { console.log(data); }); Freshchat.getUnreadCountAsync((data) => { console.log('count', data); }); messaging() .getToken() .then(token => { console.log('token', token); if (this._isMounted) { this.setState({ fireToken: token }) } Freshchat.setPushRegistrationToken(token); }); Freshchat.addEventListener( Freshchat.EVENT_UNREAD_MESSAGE_COUNT_CHANGED, () => { console.log("onUnreadMessageCountChanged triggered"); Freshchat.getUnreadCountAsync((data) => { var count = data.count; var status = data.status; if (status) { console.log("Message count: " + count); } else { console.log("getUnreadCountAsync unsuccessful"); } }); } ); // Freshchat.isFreshchatNotification((notification, freshchatNotification) => { // if (freshchatNotification) { // //Freshchat.handlePushNotification(notification); // } else { // // handle your app notification // } // }) } Chat = () => { var conversationOptions = new ConversationOptions(); conversationOptions.tags = ["premium"]; conversationOptions.filteredViewTitle = "Premium Support"; Freshchat.showConversations(conversationOptions) // var freshchatMessage = new FreshchatMessage(); // freshchatMessage.tag = "premium"; // freshchatMessage.message = "text message"; // Freshchat.sendMessage(freshchatMessage); } FAQ = () => { var faqOptions = new FaqOptions(); faqOptions.tags = ["premium"]; faqOptions.filteredViewTitle = "Tags"; faqOptions.filterType = FaqOptions.FilterType.ARTICLE; Freshchat.showFAQs(faqOptions); } render() { return ( <View style={{ backgroundColor: '#5739B2', flex: 1, flexDirection: 'column', }}> <View style={{ justifyContent: 'flex-start', alignSelf: 'center', marginTop: responsiveHeight(50) }}> <View style={{ alignSelf: 'center', borderColor: '#B0A1DE' }}> <View style={{ position: 'absolute', zIndex: 99, alignSelf: 'center' }}> <Text style={{ alignSelf: 'center', color: '#FCCE0D', fontSize: scaleFont(32), fontWeight: 'bold' }}>Hi, {'Amira'}</Text> <View style={{ alignSelf: 'center', flexDirection: 'row' }}> <Text style={{ textAlign: 'center', color: '#1D1D1D', fontSize: scaleFont(16), }}>I’m Robosto your digital assistant{`\n`} to help you shop your groceries in {`\n`}the comfort of your home.{`\n`} Just say <Text style={{ alignSelf: 'flex-end', color: '#FCCE0D', fontSize: scaleFont(16), }}>#Hatly_M3ak</Text> </Text> </View> </View> <ChatMsg width={responsiveHeight(331).toString()} height={responsiveHeight(209).toString()} style={{ alignSelf: 'center', alignItems: 'center' }} /> <RobotIcon width={responsiveHeight(169).toString()} height={responsiveHeight(230).toString()} style={{ position: 'absolute', left: 5, top: responsiveHeight(125), bottom: 0, right: 0, zIndex: 109 }} /> </View> </View> <View style={{ flex: 1, justifyContent: 'flex-end', alignItems: 'flex-end', alignSelf: 'center', }}> <Waves width={responsiveWidth(375).toString()} style={{ zIndex: 109 }} /> </View> <View style={{ position: 'absolute', zIndex: 150, alignSelf: 'center', bottom: 20 }}> <Smile style={{ alignSelf: 'center', marginBottom: responsiveHeight(17) }} /> <TouchableOpacity onPress={()=>this.Chat()} style={{ width: responsiveWidth(325), height: responsiveHeight(45),backgroundColor:'#FFFFFF' ,borderRadius:23}}> <Text style={{top:responsiveHeight(5), textAlign: 'center', color: '#6F58B5', fontSize: scaleFont(22), fontWeight:'bold'}}>Yalla chat</Text> </TouchableOpacity> <TouchableOpacity style={{ marginTop:responsiveHeight(25)}}> <Text style={{ textAlign: 'center', color:'white', fontSize: scaleFont(16), }}>See previous</Text> </TouchableOpacity> </View> </View> ); } } const DEVICE_WIDTH = Dimensions.get('window').width; const DEVICE_HEIGHT = Dimensions.get('window').height; const styles = StyleSheet.create({ container: { //flexDirection: 'column', flex: 1, alignItems: 'center', justifyContent: "center", }, box: { width: 200, height: 50, }, panelContainer: { position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, }, panel: { height: 600, padding: 20, backgroundColor: '#2c2c2fAA', paddingTop: 20, borderTopLeftRadius: 20, borderTopRightRadius: 20, shadowColor: '#000000', shadowOffset: { width: 0, height: 0 }, shadowRadius: 5, shadowOpacity: 0.4, }, header: { width: '100%', height: 50, backgroundColor: 'red' }, panelHeader: { alignItems: 'center', }, panelHandle: { width: 40, height: 8, borderRadius: 4, backgroundColor: '#00000040', marginBottom: 10, }, panelTitle: { fontSize: 27, height: 35, }, panelSubtitle: { fontSize: 14, color: 'gray', height: 30, marginBottom: 10, }, panelButton: { padding: 20, borderRadius: 10, backgroundColor: '#292929', alignItems: 'center', marginVertical: 10, }, panelButtonTitle: { fontSize: 17, fontWeight: 'bold', color: 'white', }, photo: { width: '100%', height: 225, marginTop: 30, }, map: { height: '100%', width: '100%', }, });
var searchData= [ ['jpeg',['JPEG',['../classdomini_1_1algorithm_1_1JPEG.html#ac489916de8505f11b6e29c7206baf3c7',1,'domini.algorithm.JPEG.JPEG(String path, boolean b)'],['../classdomini_1_1algorithm_1_1JPEG.html#ade39a15f3c5722b4975746fcee6ad364',1,'domini.algorithm.JPEG.JPEG(boolean b)']]] ];
export const getResults = () => { return fetch('http://localhost:5000/api/countries/quiz-results/capitals') .then(res => res.json()) } export const postResults = (payload) => { return fetch('http://localhost:5000/api/countries/quiz-results/capitals', { method: 'POST', body: JSON.stringify(payload), headers: { 'Content-type': 'application/json' } }) .then(res => res.json()) } export const deleteResult = (id) => { return fetch('http://localhost:5000/api/countries/quiz-results/capitals/' + id, { method: 'DELETE' }) };
/* eslint-disable no-unused-vars */ import React from 'react'; import { createStore } from 'redux'; import { cleanup, render, screen } from '@testing-library/react'; import { BrowserRouter } from 'react-router-dom'; import { Provider } from 'react-redux'; import '@testing-library/jest-dom/extend-expect'; import Categories from '../pages/categories'; import apiresponse from '../__mocks__/api'; afterEach(cleanup); const startingState = apiresponse; const reducer = (state = startingState, action) => { switch (action.type) { case 'GET_ALL_CHARACTERS': { const newState = Object.keys(action.payload).map((key) => ({ total_count: action.payload[key].info.count, info: action.payload[key].results, })); newState.shift(); return newState; } case 'GET_BY_CATEGORIES': { const newState = { category_index: action.payload, }; return [...state, newState]; } case 'GET_ALL_SPECIES': { const newState = { species_list: action.payload, }; return [...state, newState]; } case 'CLEAR_LIST': { return []; } default: return state; } }; function renderWithRedux( component, { initialState, store = createStore(reducer, initialState) } = {}, ) { return { ...render(<Provider store={store}><BrowserRouter>{component}</BrowserRouter></Provider>), }; } it('Renders with Redux', () => { const { getByText } = renderWithRedux(<Categories />); }); it('Renders "species breakdown" text', () => { const { getByText } = renderWithRedux(<Categories />); expect(screen.getByText('species breakdown')).toBeInTheDocument(); }); it('Renders data from state', () => { const { getByText } = renderWithRedux(<Categories />); expect(screen.getByText('Morty Smith')).toBeInTheDocument(); }); it('Home snapshot test', () => { const { myrender } = renderWithRedux(<Categories />); expect(myrender).toMatchSnapshot(); });
// var items = [5,3,7,6,2,9]; // function swap(items, leftIndex, rightIndex){ // var temp = items[leftIndex]; // items[leftIndex] = items[rightIndex]; // items[rightIndex] = temp; // } // function partition(items, left, right) { // var pivot = items[Math.floor((right + left) / 2)], //middle element // i = left, //left pointer // j = right; //right pointer // while (i <= j) { // while (items[i] < pivot) { // i++; // } // while (items[j] > pivot) { // j--; // } // if (i <= j) { // swap(items, i, j); //sawpping two elements // i++; // j--; // } // } // return i; // } // function quickSort(items, left, right) { // var index; // if (items.length > 1) { // index = partition(items, left, right); //index returned from partition // if (left < index - 1) { //more elements on the left side of the pivot // quickSort(items, left, index - 1); // } // if (index < right) { //more elements on the right side of the pivot // quickSort(items, index, right); // } // } // return items; // } // // first call to quick sort // var sortedArray = quickSort(items, 0, items.length - 1); // console.log(sortedArray); //prints [2,3,5,6,7,9] // Create an array to sort // var array = [9, 2, 5, 6, 4, 3, 7, 10, 1, 12, 8, 11]; // // Basic implementation (pivot is the first element of the array) function quicksort(array) { if (array.length === 0) return []; var left = [], right = [], pivot = array[0]; for (var i = 1; i < array.length; i++) { if (array[i] < pivot) { left.push(array[i]); } else { right.push(array[i]); } } return quicksort(left).concat(pivot, quicksort(right)); } // function pivot(arr, st=0, end=arr.length){ // let pivot = arr[st]; // let swap = st; // for(let i=st+1; i< end; i++){ // if(pivot > arr[i]){ // swap++; // [arr[swap], arr[i]] = [arr[i], arr[swap]]; // } // } // [arr[st], arr[swap]] = [arr[swap], arr[st]]; // return swap; // } console.log(quicksort([2, 0, 0, 0, 1, 0])); // console.log(quicksort(array)); // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
#!/usr/bin/env node process.stdout.write('TOOD :: Implement create-inventory-config.js\n'); process.exit(0);
// const puppeteer = require('puppeteer'); // // document.querySelector('#keyword').addEventListener('keyup', event => { // // // console.log(event.target.value); // // }) // async function scrapeProduct(url){ // const browser = await puppeteer.launch(); // const page = await browser.newPage(); // await page.goto(url); // const[el] = await page.$x('//*[@id="landingImage"]'); // const src = await el.getProperty('src'); // const srcTxt = await src.jsonValue(); // console.log({srcTxt}); // } // scrapeProduct('https://www.amazon.com/Fashion-Business-Minimalism-Leather-Stainless/dp/B07G123WZQ/ref=bbp_bb_939231_st_6EAt_w_12?psc=1&smid=A358LV57IGSQXD');
import { StatusBar } from 'expo-status-bar'; import React, { useState } from 'react'; import { StyleSheet, View, Text, Switch } from 'react-native'; import theme from '../../constants/theme'; import { Input, Button } from 'react-native-elements'; import { useSelector, useDispatch } from 'react-redux'; import { signup, setVisibleFalse } from '../../redux/actions/authentication'; import AppSnackBar from '../../components/snackbar'; import { Alert } from 'react-native'; export default function SignupScreen({ navigation }) { //Constants for snack bar const visible = useSelector(state => state.authReducer.snackBarVisible); const message = useSelector(state => state.authReducer.snackBarMessage); const removeSnackBar = () => dispatch(setVisibleFalse()); //Constants to signup const [newUser, setNewUser] = useState(''); const [isAdmin, setIsAdmin] = useState(false); const dispatch = useDispatch(); const userSignup = (u) => dispatch(signup(u)); const authWithSignup = () => { let role = "USER"; if (isAdmin) role = "ADMIN"; let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w\w+)+$/; if (reg.test(newUser.email) === false) { Alert.alert('Email', 'The email must be correct'); } else { userSignup({ ...newUser, 'role': role }); if (message !== "The email or username is already used") navigation.goBack(); } } return ( <View style={styles.container}> <View style={{ flex: 1, margin: 30 }}> <Text style={styles.title}>Welcome to the exchange students app!</Text> </View> <View style={{ flex: 8, paddingBottom: 40, justifyContent: 'space-between', width: '100%', backgroundColor: theme.colors.cyan, borderTopRightRadius: theme.borderRadius.screen, borderTopLeftRadius: theme.borderRadius.screen, paddingTop: 30, padding: 10 }}> <View style={{ alignItems: 'center' }}> <Input placeholder="Email" style={{ borderWidth: 0, borderRadius: 10, width: '90%', backgroundColor: 'white' }} inputStyle={styles.inputStyle} placeholderTextColor={theme.colors.lightGrey} inputContainerStyle={{ borderBottomWidth: 0 }} onChangeText={value => setNewUser({ ...newUser, 'email': value })} multiline={true} autoFocus={true} keyboardType='email-address' /> <Input placeholder="Username" style={{ borderWidth: 0, borderRadius: 10, width: '90%', backgroundColor: 'white' }} inputStyle={styles.inputStyle} placeholderTextColor={theme.colors.lightGrey} inputContainerStyle={{ borderBottomWidth: 0 }} onChangeText={value => setNewUser({ ...newUser, 'username': value })} multiline={true} autoFocus={true} /> <Input placeholder="Password" style={{ borderWidth: 0, borderRadius: 10, width: '90%', backgroundColor: 'white' }} inputStyle={styles.inputStyle} placeholderTextColor={theme.colors.lightGrey} inputContainerStyle={{ borderBottomWidth: 0 }} onChangeText={value => setNewUser({ ...newUser, 'passwordHash': value })} autoFocus={true} secureTextEntry={true} /> <Input placeholder="Phone number" style={{ borderWidth: 0, borderRadius: 10, width: '90%', backgroundColor: 'white' }} inputStyle={styles.inputStyle} placeholderTextColor={theme.colors.lightGrey} inputContainerStyle={{ borderBottomWidth: 0 }} onChangeText={value => setNewUser({ ...newUser, 'phoneNumber': value })} multiline={true} autoFocus={true} keyboardType='phone-pad' /> <View style={{ flexDirection: 'row', marginTop: -5, marginBottom: 15 }}> <Text style={styles.text}>Tutor</Text> <Switch trackColor={{ false: theme.colors.lightGrey, true: theme.colors.lightBlue }} thumbColor={isAdmin ? theme.colors.blue : theme.colors.grey} ios_backgroundColor="#3e3e3e" onValueChange={() => setIsAdmin(!isAdmin)} value={isAdmin} /> </View> <Button raised={true} buttonStyle={styles.signupButton} titleStyle={styles.signupButtonText} onPress={() => authWithSignup()} containerStyle={{ width: '50%' }} title="SIGNUP" /> </View> <View style={{ alignItems: 'center' }}> <Button raised={true} buttonStyle={styles.loginButton} titleStyle={styles.loginButtonText} onPress={() => navigation.navigate('Login')} containerStyle={{ width: '50%' }} title="LOGIN" /> </View> </View> <AppSnackBar visible={visible} onDismiss={() => removeSnackBar()} message={message} color={theme.colors.blue} /> <StatusBar style="auto" /> </View> ) } const styles = StyleSheet.create({ container: { flex: 1, marginTop: 30, backgroundColor: 'white', alignItems: 'center', justifyContent: 'center', width: '100%', }, title: { fontSize: theme.fontSizes.screenTitle, fontFamily: theme.fonts.bold, textAlign: 'center' }, text: { marginBottom: 10, marginTop: 10, fontSize: theme.fontSizes.buttonText, fontFamily: theme.fonts.regular, color: 'white' }, inputStyle: { color: 'black', fontFamily: theme.fonts.bold, padding: 10, margin: 10, fontSize: theme.fontSizes.cardTitle, }, signupButton: { backgroundColor: 'white', borderRadius: theme.borderRadius.button, }, signupButtonText: { color: theme.colors.cyan, fontFamily: theme.fonts.bold, fontSize: theme.fontSizes.buttonText }, loginButton: { backgroundColor: theme.colors.cyan, borderRadius: theme.borderRadius.button, borderWidth: 1, borderColor: 'white' }, loginButtonText: { color: 'white', fontFamily: theme.fonts.bold, fontSize: theme.fontSizes.buttonText, width: '70%' } });
/** * DomoGeeek v0.1 * https://github.com/ltoinel/domogeeek * * Copyright 2014 DomoGeeek * Released under the Apache License 2.0 (Apache-2.0) * * @desc: MultiPush main app * @author: ltoinel@free.fr */ // Global require var express = require('express'); //Local require var config = require('./config'); // Loading SMS connector if (config.sms.enabled){ var sms = require('../../libs/sms'); } // Loading Mail connector if (config.mail.enabled){ var mail = require('../../libs/mail'); } // Loading OpenKarotz connector if (config.openkarotz.enabled){ var openkarotz = require('../../libs/openkarotz'); } // Init the Express App var app = express(); /** * HTTP GET /multipush */ app.get('/multipush', function (req, resp, next) { var subject = req.query['subject']; var message = req.query['message']; // By default we send a message to all the canal if (req.query['canal'] === undefined){ var canal = ['sms','mail','karotz']; } else { var canal = req.query['canal'].split(','); } // Send multipush multipush(subject, message, canal); resp.status(201).send(); }); /** * Send notification using different channels. * * @param subject The subject of the notification. * @param message The content of the message. */ function multipush(subject,message, canal){ // We send an SMS if (config.sms.enabled && (canal.indexOf("sms") != -1)){ config.sms.phone.forEach(function(phone){ sms.send(config.sms, phone, message); }); } // We send an Email if (config.mail.enabled && (canal.indexOf("mail") != -1)){ config.mail.to.forEach(function(mailto){ mail.send(config.mail, config.mail.from, mailto, "" , subject, message); }); } // We make the Openkarotz talking if (config.openkarotz.enabled && (canal.indexOf("openkarotz") != -1)){ openkarotz.talk(config.openkarotz, message); } } console.info("Starting DomoGeeek MultiPush v%s",config.version); // Starting the REST server app.listen(config.port);
const mongoose = require('mongoose'); const { Schema } = mongoose; const nameSchema = new Schema({ name: String, meaning: String, views: { type: Number, default: 0, }, similar_names: String, gender: { type: String, enum: ['male', 'female', ''], default: '', }, status: { type: String, enum: ['active', 'inactive', 'removed'], default: 'active', }, categories: { type: Array, default: [], }, languages: [ { language_id: { type: Schema.ObjectId, ref: 'Language', }, word: { type: String, default: null, }, }, ], }, { timestamps: true, collation: { locale: 'en_US', strength: 1 } }); module.exports = mongoose.model('Name', nameSchema);
import React from "react"; import PropTypes from "prop-types"; const WidgetHeader = ({title, extra, styleName}) => { return ( <h2 className={`gx-entry-title ${styleName}`}> {title} <span className="gx-text-primary gx-fs-md gx-pointer gx-ml-auto gx-d-none gx-d-sm-block">{extra}</span> </h2> ) }; WidgetHeader.defaultProps = { styleName: '', }; WidgetHeader.propTypes = { title: PropTypes.node, extra: PropTypes.node, }; export default WidgetHeader;
const dogBar = document.querySelector("#dog-bar") const dogInfo = document.querySelector("#dog-info") const filter = document.querySelector("#good-dog-filter") const dogs = [] filter.addEventListener('click', function(e) { let textArray = e.target.innerText.split(" ") if (textArray[3] === "OFF") { e.target.innerText = "Filter good dogs: ON" dogFetch() } else { e.target.innerText = "Filter good dogs: OFF" dogFetch() } }) function dogFetch() { fetch('http://localhost:3000/pups') .then(resp => resp.json()) .then(json => dogFilter(json)) } function dogFilter(json) { let textArray = filter.innerText.split(" ") dogBar.innerHTML = "" if (textArray[3] === "ON") { json.forEach(element => { if (element.isGoodDog === true) { dogBar.innerHTML += `<span>${element.name}</span>` } }) } else { json.forEach(element => { dogBar.innerHTML += `<span>${element.name}</span>` }) } } dogFetch() function dogJSON() { fetch('http://localhost:3000/pups') .then(resp => resp.json()) .then(json => json.forEach(element => { dogs.push(element) })) } dogJSON() dogBar.addEventListener('click', function(e) { dogs.forEach(element => { let isGood = "" if (element.isGoodDog === true) { isGood = "Good Dog!" } else { isGood = "Bad Dog!" } if (element.name === e.target.innerText) { dogInfo.innerHTML = "" dogInfo.innerHTML += ` <img src=${element.image}> <h2>${element.name}</h2> <button>${isGood}</button> ` } }) }) dogInfo.addEventListener('click', function(e) { if (e.target.matches('button')) { dogs.forEach(element => { element.isGoodDog = !element.isGoodDog if (element.name === e.target.previousElementSibling.innerText) { fetch(`http://localhost:3000/pups/${element.id}`, { method: "PATCH", headers: { "Content-Type": "application/json", "Accept": "application/json" }, body: JSON.stringify({ "isGoodDog": element.isGoodDog }) }) .then(resp => resp.json()) .then(json => { if (json.isGoodDog === true) { e.target.innerText = "Good Dog!" } else { e.target.innerText = "Bad Dog!" } }) } }) } })
module.exports = (sequelize, DataTypes) => { return sequelize.define('artifactCoin', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, averse: { type: DataTypes.BLOB, allowNull: true }, reverse: { type: DataTypes.BLOB, allowNull: true }, name: { type: DataTypes.TEXT, allowNull: true }, about: { type: DataTypes.TEXT, allowNull: true }, year: { type: DataTypes.DATE, allowNull: true }, estimated_amount: { type: DataTypes.INTEGER, allowNull: true }, weight: { type: DataTypes.DECIMAL, allowNull: true }, diameter: { type: DataTypes.DECIMAL, allowNull: true }, alloy: { type: DataTypes.TEXT, allowNull: true }, stamp: { type: DataTypes.TEXT, allowNull: true }, nominal: { type: DataTypes.INTEGER, allowNull: true }, currency: { type: DataTypes.TEXT, allowNull: true }, country: { type: DataTypes.TEXT, allowNull: true }, mint: { type: DataTypes.TEXT, allowNull: true }, grading: { type: DataTypes.INTEGER, allowNull: true } }, { tableName: 'artifact_coin', createdAt: false, updatedAt: false }); } // mint, country, currency, shape, need to be deleted it this file and be implemented in sequelize as associations
import template from './view.html'; export default class View { static defaultOptions = { height: 400, width: 400 }; /** * Creates main view elemnt from view template. * * @param {Object} options * @returns {Element} */ static creatView(options) { const div = document.createElement('div'); div.innerHTML = template; const canvas = div.querySelector('canvas'); canvas.height = options.height; canvas.width = options.width; return div.querySelector('.asteroids'); } /** * @param {Object} options */ constructor(options = null) { this._isMounted = false; this._options = { ...View.defaultOptions, ...options }; this.view = View.creatView(this._options); this.canvas = this.view.querySelector('canvas'); this.context = this.canvas.getContext('2d'); } /** * Attaches view to the supplied element, if not already mounted. * * @param {Element} element */ mount(element) { if (element == null) { throw new TypeError('element cannot be null.'); } if (!this._isMounted) { this._isMounted = true; element.appendChild(this.view); } } /** * Detaches view from any element it was mounted on. */ unmount() { if (this._isMounted) { this._isMounted = false; this.view.parentElement.removeChild(this.view); } } }
import _classCallCheck from "@babel/runtime/helpers/classCallCheck"; import _createClass from "@babel/runtime/helpers/createClass"; import _possibleConstructorReturn from "@babel/runtime/helpers/possibleConstructorReturn"; import _getPrototypeOf from "@babel/runtime/helpers/getPrototypeOf"; import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized"; import _inherits from "@babel/runtime/helpers/inherits"; import _defineProperty from "@babel/runtime/helpers/defineProperty"; import styled from "styled-components"; import _ from 'lodash'; import faker from 'faker'; import React, { Component, useState, useEffect } from 'react'; import { Search, Grid, Header, Segment } from 'semantic-ui-react'; var _default = /*#__PURE__*/ function (_React$Component) { _inherits(_default, _React$Component); function _default(props) { var _this; _classCallCheck(this, _default); _this = _possibleConstructorReturn(this, _getPrototypeOf(_default).call(this, props)); _defineProperty(_assertThisInitialized(_this), "state", { data: [] }); _defineProperty(_assertThisInitialized(_this), "resetComponent", function () { return _this.setState({ isLoading: false, results: [], value: '' }); }); _defineProperty(_assertThisInitialized(_this), "handleSearchChange", function (e, _ref) { var value = _ref.value; _this.setState({ isLoading: true, value: value }); setTimeout(function () { if (_this.state.value.length < 1) return _this.resetComponent(); var re = new RegExp(_.escapeRegExp(_this.state.value), 'i'); var isMatch = function isMatch(result) { return re.test(result.title); }; _this.setState({ isLoading: false, results: _.filter(_this.props.data, isMatch) }); }, 300); }); return _this; } _createClass(_default, [{ key: "componentWillMount", value: function componentWillMount() { this.resetComponent(); } }, { key: "handleResultSelect", value: function handleResultSelect(e, _ref2) { var result = _ref2.result, key = _ref2.key; this.props.handleSelectMarker(result); } }, { key: "render", value: function render() { var _this$state = this.state, isLoading = _this$state.isLoading, value = _this$state.value, results = _this$state.results; return React.createElement(Grid, null, React.createElement(Grid.Column, { width: 8 }, React.createElement(Search, { loading: isLoading, onResultSelect: this.handleResultSelect.bind(this), onSearchChange: _.debounce(this.handleSearchChange, 500, { leading: true }), results: results, value: value }))); } }]); return _default; }(React.Component); /*export default({data})=>{ const [list ,setList] = useState([]); const[isLoading,setIsLoading] = useState(false); const[results,setResults] = useState([]); const[val,setVal] = useState(''); useEffect(() => { resetComponent() }, []); function resetComponent(){ setIsLoading(false); setResults([]); setVal(''); } function handleSearchChange(e, { value }){ setIsLoading(true); setVal(value) setTimeout(() => { if (val.length < 1) return resetComponent() const re = new RegExp(_.escapeRegExp(val), 'i') const isMatch = result => re.test(result.title) setIsLoading(false); setResults(_.filter(data, isMatch)) }, 300) } return( <Grid> <Grid.Column width={8}> <Search loading={isLoading} //onResultSelect={this.handleResultSelect.bind(this)} onSearchChange={_.debounce(handleSearchChange, 500, { leading: true })} results={results} value={val} /> </Grid.Column> </Grid> ) } */ export { _default as default }; var SearchStyle = styled.div.withConfig({ displayName: "Search__SearchStyle", componentId: "qnep7e-0" })([".ui.search{float:right;margin-top:20px}"]);
import React from "react"; import {Avatar, Card} from "antd"; const Basic = () => { return ( <Card className="gx-card" title="Basic"> <div className="gx-mb-3"> <Avatar className="gx-mr-2" size="large" icon="user"/> <Avatar className="gx-mr-2" icon="user"/> <Avatar className="gx-mr-2" size="small" icon="user"/> </div> <div className="gx-mb-0"> <Avatar className="gx-mr-2" shape="square" size="large" icon="user"/> <Avatar className="gx-mr-2" shape="square" icon="user"/> <Avatar className="gx-mr-2" shape="square" size="small" icon="user"/> </div> </Card> ); }; export default Basic;
import { useEffect, useRef } from "react"; export const useUpdateEffect = (callback, dependencies) => { const isFirstRender = useRef(true); useEffect(() => { if (isFirstRender.current) { isFirstRender.current = false; } else { return callback(); } }, dependencies); }; export const usePrevious = (value) => { const ref = useRef(); useEffect(() => { ref.current = value; }); return ref.current; };
/** * Created by zhangsu on 2016/5/9. */ MetronicApp.controller('login_controller', function($rootScope, $scope,$state,$stateParams,login_service,filterFilter,$modal, $http, $timeout) { $scope.$on('$viewContentLoaded', function() { // initialize core components App.initAjax(); }); $rootScope.settings.layout.pageBodySolid = true; $rootScope.settings.layout.pageSidebarClosed = false; ComponentsDateTimePickers.init() });
// ========================================= // ** Responsive Menu ** // ========================================= const app = new Vue({ el: '#vue-wrapper', data: { navPull: false, outlineHide: true, categoryReveal: false, }, }); // Allows menu to be closed with escape key document.addEventListener('keyup', evt => { if (evt.keyCode === 27) { app.navPull = false; } }); // Removes outline hiding when tab key is pressed document.addEventListener('keyup', evt => { if (evt.keyCode === 9) { app.outlineHide = false; } }); // *========================================= // ** ScrollMagic ** // *========================================= // * Init ScrollMagic const controller = new ScrollMagic.Controller(); // Collect elements to fade in const fadeUpIn = document.querySelectorAll('.fade-up-in'); // Loop through elements to add animation fadeUpIn.forEach(item => { const sceneOne = new ScrollMagic.Scene({ triggerElement: item, triggerHook: 0.95, reverse: false, }) .setClassToggle(item, 'fade-up-in-reveal') // TODO: Remove indicators .addTo(controller); }); // ********** Footer and contact form ********** const footer = document.querySelector('.main-footer'); const colourChange = document.querySelectorAll('.colour-will-change'); colourChange.forEach(item => { const sceneTwo = new ScrollMagic.Scene({ triggerElement: footer, triggerHook: 0.8, // reverse: false, }) .setClassToggle(item, 'colour-change') // TODO: Remove indicators // .addIndicators({ colorTrigger: '#f00' }) .addTo(controller); }); // ========================================= // ** Menu Scroll Hide ** // ========================================= let scrollPos = 0; const mainNav = document.querySelector('.main-nav'); const iosNavPull = document.querySelector('.ios-nav-pull'); // adding scroll event // eslint-disable-next-line func-names window.addEventListener('scroll', function() { // detects new state and compares it with the new one // eslint-disable-next-line prettier/prettier if ( document.body.getBoundingClientRect().top < scrollPos && !mainNav.classList.contains('nav-reveal') && window.scrollY > 10 ) { mainNav.classList.add('menu-scroll-hide'); } else { mainNav.classList.remove('menu-scroll-hide'); } if (document.body.getBoundingClientRect().top < scrollPos && window.innerWidth <= 700 && window.scrollY > 10) { iosNavPull.classList.add('button-scroll-hide'); } else { iosNavPull.classList.remove('button-scroll-hide'); } // saves the new position for iteration. scrollPos = document.body.getBoundingClientRect().top; }); // *========================================= // ** Cookie Warning ** // *========================================= const cookieBanner = document.querySelector('.cookie-warning-wrapper'); const cookieWarningButton = document.querySelector('.cookie-warning-button'); if (localStorage.getItem('cookieSeen') !== 'shown') { cookieBanner.classList.add('show-cookie-warning'); } else { cookieBanner.style.display = 'none'; } cookieWarningButton.addEventListener( 'click', () => { localStorage.setItem('cookieSeen', 'shown'); cookieBanner.classList.remove('show-cookie-warning'); cookieBanner.addEventListener('transitionend', () => { cookieBanner.style.display = 'none'; }); }, { once: true } ); // ========================================= // ** Lazy load ** // ========================================= const lazyLoadInstance = new LazyLoad({ elements_selector: '.lazy', });
var nav = document.querySelector(".nav"); nav.classList.remove("nav--nojs"); var toggle = document.querySelector(".nav__toggle"); toggle.addEventListener("click", function (evt) { evt.preventDefault(); if (nav.classList.contains("nav--closed")) { nav.classList.remove("nav--closed"); nav.classList.add("nav--opened"); } else { nav.classList.remove("nav--opened"); nav.classList.add("nav--closed"); } }); function initMap() { var mapProp = { center: new google.maps.LatLng(59.938624, 30.323085), zoom: 16, disableDefaultUI: true, }; var map = new google.maps.Map(document.getElementById("map"), mapProp); var coordinates = {lat: 59.938624, lng: 30.323085}; var image = "img/icon-map-marker.svg"; var marker = new google.maps.Marker({ position: coordinates, map: map, icon: image, }); var noPoi = [ { featureType: "poi", stylers: [ { visibility: "off" } ] } ]; map.setOptions({styles: noPoi}); }
import DataType from 'sequelize'; import Model from '../../sequelize'; import { initialize as initializeTransactionStatus } from '../utils'; const TransactionStatus = Model.define('TransactionStatus', { id: { type: DataType.INTEGER(11), allowNull: false, primaryKey: true, autoIncrement: true, }, name: { type: DataType.STRING(45), allowNull: true, }, }); export const initialize = () => { const data = [ { id: 1, name: 'Waiting', }, { id: 2, name: 'Cancelled', }, { id: 3, name: 'Pending', }, { id: 4, name: 'Rejection', }, { id: 5, name: 'BlockchainRejection', }, { id: 6, name: 'Completed', }, ]; initializeTransactionStatus(TransactionStatus, data); }; export default TransactionStatus;
function createBookShopOri(inventory) { return { inventory : inventory, inventoryValue : function() { return this.inventory.reduce((total, book) => total + book.price, 0); }, priceForTitle : function (title) { return this.inventory.find(book => book.title === title).price; } }; } //short form function createBookShop(inventory) { return { inventory, inventoryValue () { return this.inventory.reduce((total, book) => total + book.price, 0); }, priceForTitle (title) { return this.inventory.find(book => book.title === title).price; } }; } const inventory = [ {title : 'harry potter', price : 10}, {title : 'es javascript', price : 15} ]; const bookShop = createBookShop(inventory); console.log( bookShop.inventoryValue() ); console.log( bookShop.priceForTitle('harry potter') );
import React from 'react'; import { Indent, SuperTable, SuperToolbar, Search, ModalWithDrag, Title, SuperPagination} from '../../../../../components'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from '../../EditPage/EditPage.less'; class AddDialog extends React.Component { constructor (props) { super(props); } toSearch = () => { const {filters, searchData, searchConfig, onChange, onSearch, onClick} = this.props; const props = { config: searchConfig, filters, data: searchData, onChange, onSearch, onClick }; return <Search {...props}/> }; toTable = () => { const {cols, items=[], onCheck, tableTitle} = this.props; const props = { cols, items, maxHeight: "300px", callback: {onCheck} }; return (<div> <Title className={s.superTitle} title={tableTitle}/> <Indent> <SuperTable {...props}/> <SuperPagination style={{marginTop: '15px'}} {...this.props}/> </Indent> </div>) }; toFooter = () => { const {buttons, footerBtnClick} = this.props; const props = { size: 'large', buttons, onClick: footerBtnClick }; return <SuperToolbar {...props}/> }; getProps = () => { const {title, afterClose, visible} = this.props; return { title, visible, width: 1000, maskClosable: false, confirmLoading: false, onCancel: afterClose, footer: this.toFooter(), afterClose } }; render() { return ( <ModalWithDrag {...this.getProps()}> <Indent> {this.toSearch()} {this.toTable()} </Indent> </ModalWithDrag> ) } } export default withStyles(s)(AddDialog);
const express = require('express'); const routes = express.Router(); const {findUserByID,read,update} = require("../controller/userController.js"); const { requireSignin,isAuth,isAdmin} = require("../controller/authController"); routes.get("/secret/:userId",requireSignin,isAuth,isAdmin,(req,res)=>{ res.json({ user:req.profile }) }) routes.get('/user/:userId',requireSignin,isAuth,read) routes.put('/user/:userId',requireSignin,isAuth,update) routes.param('userId',findUserByID); module.exports = routes;
let dd = ['cat', 'louis', 'lulu', 'dog'] let [dd1, dd2, dd3, dd4] = dd; console.log(dd1) console.log(dd2) console.log(dd3) let [a,b,c] = [1,2]; console.log(a) console.log(c) console.log('Rest Parameters, Spread syntax=============='); showName = (name) => { console.log(name); } showName('Mike') showName('Mike','Jane') // Mike showName() // undefined // arguments // 함수로 넘어 온 모든 인수에 접근 // 함수내에서 이용 가능한 지역 변수 // length/ index // Array 형태의 객체 - 배열의 내장메서드 없음 function showNameWithArg(name) { console.log(arguments.length) console.log(arguments[0]) console.log(arguments[1]) } showNameWithArg('Mike','Jane') showNameWithRestParam = (...names) => { console.log(names) } showNameWithRestParam('Mike','Jane') add = (...numbers) => { let result = 0 numbers.forEach((num) => (result+=num)); console.log(result); } add(1,2,3,4,5) add(1,2,3,4,5,6,7,8,9,10) function makeUser(name, age, ...skills){ this.name = name; this.age = age; this.skills = skills; } const makeUser1 = new makeUser('Mike', 33, 'html', 'css') const makeUser2 = new makeUser('Kim', 17, 'ES6', 'React', 'html') const makeUser3 = new makeUser('Sergio', 16, 'english') console.log(makeUser1) console.log(makeUser2) console.log(makeUser3) let arr1= [1,2,3]; let arr2= [4,5,6]; let totalArr = [0, ...arr1, ...arr2, 7,8,9]; console.log(`totalArr = ${totalArr}`) // 456123 arr1.forEach((num)=> { arr2.push(num); }) console.log(`pushArr = ${arr2}`) let user = {name:'Park'}; let age = {age:30}; let fe = ['JS','React']; let lang = ['Korean','English']; // user = Object.assign({}, user, age, { // skills : [], // }) // fe.forEach(item => { // user.skills.push(item); // }) user = { ...user, ...age, skills:[...fe, ...lang] } console.log(user)
const db = require('./index'); /** * Get a single user from the database given their email. * @param {String} email The email of the user. * @return {Promise<{}>} A promise to the user. */ const getUserWithEmail = function(email) { const query = { text: ` SELECT * FROM users WHERE email = $1; `, values: [email] }; return new Promise((resolve, reject) => { db.query(query.text, query.values, (err, res) => { if (err) { console.error('query error',err.stack); reject(err); } resolve(res.rows[0]); }); }) } exports.getUserWithEmail = getUserWithEmail; /** * Get a single user from the database given their id. * @param {string} id The id of the user. * @return {Promise<{}>} A promise to the user. */ const getUserWithId = function(id) { const query = { text: ` SELECT * FROM users WHERE id = $1; `, values: [id] }; return new Promise((resolve, reject) => { db.query(query.text, query.values, (err, res) => { if (err) { console.error('query error',err.stack); reject(err); } resolve(res.rows[0]); }); }) } exports.getUserWithId = getUserWithId; /** * Add a new user to the database. * @param {{name: string, password: string, email: string}} user * @return {Promise<{}>} A promise to the user. */ const addUser = function(user) { const query = { text: ` INSERT INTO users (name, email, password) VALUES ($1, $2, $3) RETURNING *; `, values: [user.name, user.email, user.password] }; return new Promise((resolve, reject) => { db.query(query.text, query.values, (err, res) => { if (err) { console.error('query error',err.stack); reject(err); } resolve(res.rows); }); }) } exports.addUser = addUser; /// Reservations /** * Get all reservations for a single user. * @param {string} guest_id The id of the user. * @return {Promise<[{}]>} A promise to the reservations. */ const getAllReservations = function(guest_id, limit = 10) { const query = { text: ` SELECT r.*, p.*, AVG (pr.rating) FROM properties p LEFT OUTER JOIN reservations r ON r.property_id = p.id JOIN property_reviews pr ON pr.property_id = p.id WHERE r.guest_id = $1 GROUP BY r.id, p.id HAVING r.end_date < now()::date ORDER BY r.start_date DESC LIMIT $2; `, values: [guest_id, limit] }; return new Promise((resolve, reject) => { db.query(query.text, query.values, (err, res) => { if (err) { console.error('query error',err.stack); reject(err); } resolve(res.rows); }); }) } exports.getAllReservations = getAllReservations; // Properties /** * Get all properties. * @param {{}} options An object containing query options. * @param {*} limit The number of results to return. * @return {Promise<[{}]>} A promise to the properties. */ const getAllProperties = function(options, limit = 10) { const queryParams = []; // Build necessary query statement let queryString = ` SELECT p.*, avg(pr.rating) as average_rating FROM properties p LEFT OUTER JOIN property_reviews pr ON p.id = pr.property_id `; // Account for search options. Append to query based on set options, in conjunction with other options selected if (options.city) { queryParams.push(`%${options.city}%`); queryString += `WHERE city LIKE $${queryParams.length} `; } if (options.owner_id) { queryParams.push(options.owner_id); queryString += (queryParams.length > 1) ? 'AND ' : 'WHERE ' queryString += `owner_id = $${queryParams.length} ` } if (options.minimum_price_per_night && options.maximum_price_per_night) { queryParams.push(options.minimum_price_per_night, options.maximum_price_per_night); queryString += (queryParams.length > 2) ? 'AND ' : 'WHERE ' queryString += ` cost_per_night > $${queryParams.length - 1} AND cost_per_night < $${queryParams.length} ` } queryString += ` GROUP BY p.id ` if (options.minimum_rating) { queryParams.push(options.minimum_rating); queryString += ` HAVING avg(pr.rating) > $${queryParams.length} ` } queryParams.push(limit); queryString += ` ORDER BY cost_per_night LIMIT $${queryParams.length}; `; // Build query object then return query Promise const query = { text: queryString, values: queryParams }; return new Promise((resolve, reject) => { db.query(query.text, query.values, (err, res) => { if (err) { console.error('query error',err.stack); reject(err); } resolve(res.rows); }); }) } exports.getAllProperties = getAllProperties; /** * Add a property to the database * @param {{}} property An object containing all of the property details. * @return {Promise<{}>} A promise to the property. */ const addProperty = function(property) { let queryParams = [ property.owner_id, property.title, property.description, property.thumbnail_photo_url, property.cover_photo_url, property.cost_per_night, property.street, property.city, property.province, property.post_code, property.country, property.parking_spaces, property.number_of_bathrooms, property.number_of_bedrooms ] let queryStr = ` INSERT INTO properties (owner_id, title, description, thumbnail_photo_url, cover_photo_url, cost_per_night, street, city, province, post_code, country, parking_spaces, number_of_bathrooms, number_of_bedrooms) VALUES ( $1, $2, $3, $4, $5,$6, $7, $8, $9, $10, $11, $12, $13, $14 ) RETURNING *; `; const query = { text: queryStr, values: queryParams }; return new Promise((resolve, reject) => { db.query(query.text, query.values, (err, res) => { if (err) { console.error('query error',err.stack); reject(err); } resolve(res.rows); }); }) } exports.addProperty = addProperty; /** * Add a reservation to the database * @param {{}} reservation An object containing all of the reservation details. * @return {Promise<{}>} A promise to the reservation. */ const addReservation = function(reservation) { let queryParams = [ reservation.guest_id, reservation.start, reservation.end, reservation.property_id ] let queryStr = ` INSERT INTO reservations (guest_id, start_date, end_date, property_id) VALUES ( $1, $2, $3, $4 ) RETURNING *; `; const query = { text: queryStr, values: queryParams }; return new Promise((resolve, reject) => { db.query(query.text, query.values, (err, res) => { if (err) { console.error('query error',err.stack); reject(err); } resolve(res.rows); }); }) } exports.addReservation = addReservation;
import { connect } from 'react-redux'; import {EnhanceLoading} from '../../../../../components/Enhance'; import AddDialog from './AddDialog'; import {postOption, showError, showSuccessMsg, getJsonResult, convert, fuzzySearchEx, fetchJson}from '../../../../../common/common'; import {Action} from '../../../../../action-reducer/action'; import {getPathValue} from '../../../../../action-reducer/helper'; import showPopup from '../../../../../standard-business/showPopup'; import execWithLoading from '../../../../../standard-business/execWithLoading'; const STATE_PATH = ['temp']; const action = new Action(STATE_PATH, false); const URL_LIST = '/api/bill/receiveApply/income_list'; const URL_ADD_APPLY = '/api/bill/receiveApply/addApply'; const getSelfState = (rootState) => { return getPathValue(rootState, STATE_PATH); }; const buildAddDialogState = (list, config, other={}) => { return { ...config, ...other, visible: true, items: list, searchData: {} } }; const changeActionCreator = (keyName, keyValue) => action.assign({[keyName]: keyValue}, 'searchData'); const formSearchActionCreator = (key, filter, control) => async (dispatch, getState) => { const {filters} = getSelfState(getState()); const result = getJsonResult(await fuzzySearchEx(filter, control)); const options = result.data ? result.data : result; const index = filters.findIndex(item => item.key === key); dispatch(action.update({options}, 'filters', index)); }; const searchActionCreator = async (dispatch, getState) => { const {searchData={}} = getSelfState(getState()); if (!searchData['customerId'] || !searchData['tax']) return showError('结算单位与税率必填!'); const list = getJsonResult(await fetchJson(URL_LIST, postOption({maxNumber: 10, ...convert(searchData)}))); dispatch(action.assign({items: list})); }; const resetActionCreator = action.assign({searchData: {}}); // 申请 const onOkActionCreator = () => async (dispatch, getState) => { const {items} = getSelfState(getState()); const checkList = items.filter(o=> o.checked); if(!checkList.length) return showError('请勾选一条数据!'); execWithLoading(async () => { const list = checkList.map(o => convert(o)); if (list.length === 0) return; const params = { currency: list[0]['currency'], customerId: list[0]['customerId'], tax: list[0]['tax'] || 0, ids: list.map(o => o.id) }; const { returnCode, result, returnMsg } = await fetchJson(URL_ADD_APPLY, postOption(params)); if(returnCode !== 0) return showError(returnMsg); showSuccessMsg(returnMsg); dispatch(action.assign({okResult: true})); }); dispatch(action.assign({visible: false})); }; const buttons = { search: searchActionCreator, reset: resetActionCreator }; const clickActionCreator = (key) => { if (buttons.hasOwnProperty(key)) { return buttons[key]; } else { console.log('unknown key:', key); return {type: 'unknown'}; } }; const checkActionCreator = (isAll, checked, rowIndex) => { isAll && (rowIndex = -1); return action.update({checked}, 'items', rowIndex); }; const mapStateToProps = (state) => getSelfState(state); const actionCreators = { onCheck: checkActionCreator, onClick: clickActionCreator, onChange: changeActionCreator, onSearch: formSearchActionCreator, onOk: onOkActionCreator }; const Container = connect(mapStateToProps, actionCreators)(EnhanceLoading(AddDialog)); export default async (params) => { // 新增进去默认不发请求 // const list = getJsonResult(await fetchJson(URL_LIST, postOption({maxNumber: 10}))); const payload = buildAddDialogState([], params); global.store.dispatch(action.create(payload)); await showPopup(Container, {status: 'page'}, true); const state = getSelfState(global.store.getState()); global.store.dispatch(action.create({})); return state.okResult; }
// 构造函数, 用于生成一个dom function Element(tagName, props, children) { if (!(this instanceof Element)) { return new Element(tagName, props, children); } this.tagName = tagName; this.props = props || {}; this.children = children || []; this.key = props ? props.key : undefined; this.id = props ? props.id : undefined; this.node = ''; } //json生成真实dom function render(tree) { const el = document.createElement(tree.tagName); const props = tree.props; for (const propName in props) { el.setAttribute(propName, props[propName]); } tree.children.forEach(child => { const childEl = typeof child == 'object' ? render(child) : document.createTextNode(child); el.appendChild(childEl); }); tree.node = el; return el; }; // 比较入口函数 function diff(oldTree, newTree) { let record = []; if (!diffSame(oldTree, newTree)) { console.log(newTree.tagName + "节点替换"); let obj = { type: '节点替换', oldTagName: oldTree.tagName, newTagName: newTree.tagName, content: '', oldNode: oldTree, newNode: newTree, } record.push(obj); } else { diffPatch(oldTree, newTree, record); } console.log(record); return record; } // 是否是相同节点, 属性不同也算不同阶段,重新生成, key,id,class等等属性 function diffSame(oldTree, newTree) { if (oldTree.tagName == newTree.tagName && oldTree.key == newTree.key) { for (key in oldTree.props) { if (oldTree.props[key] != newTree.props[key]) { console.log(oldTree.tagName + '属性不相同'); return false; } } for (key in newTree.props) { if (oldTree.props[key] != newTree.props[key]) { console.log(oldTree.tagName + '属性不相同'); return false; } } return true; } else { return false; } } // 比较是否是文本节点, 否则比较子节点 function diffPatch(oldTree, newTree, record) { if (typeof newTree.children[0] == "string") { console.log(newTree.tagName + "文本比较"); if (newTree.children[0] !== oldTree.children[0]) { let obj = { type: '文本替换', tagName: oldTree.tagName, content: newTree.children[0], changeNode: oldTree, parentNode: oldTree } record.push(obj); } } else { diffChild(oldTree, oldTree.children, newTree.children, record); } } // 比较子节点 function diffChild(parentNode, oldNodeChild, newNodeChild, record) { let oldStartId = 0; let oldEndId = oldNodeChild.length - 1; let newStartId = 0; let newEndId = newNodeChild.length - 1; let oldStartNode = oldNodeChild[0]; let oldEndNode = oldNodeChild[oldEndId]; let newStartNode = newNodeChild[0]; let newEndNode = newNodeChild[newEndId]; let oldKeyToId let idxInOld let elmToMove let before while (oldStartId <= oldEndId && newStartId <= newEndId) { // 为null情况是, 有key的节点造成了移动,移动过的位置变成null,遇到null就往前移动, 不需要判断,肯定不回相同 if (oldStartNode == null) { oldStartNode = oldNodeChild[++oldStartId]; } else if (oldEndNode == null) { oldEndNode = oldNodeChild[--oldEndId]; } else if (newStartNode == null) { newStartNode = newNodeChild[++newStartId]; } else if (newEndNode == null) { newEndNode = newNodeChild[--newEndId]; } else if (diffSame(oldStartNode, newStartNode)) { console.log("比较开始子节点"); diffPatch(oldStartNode, newStartNode, record); oldStartNode = oldNodeChild[++oldStartId]; newStartNode = newNodeChild[++newStartId]; } else if (diffSame(oldEndNode, newEndNode)) { console.log("比较结尾子节点"); diffPatch(oldEndNode, newEndNode, record); oldEndNode = oldNodeChild[--oldEndId]; newEndNode = newNodeChild[--newEndId]; } else if (diffSame(oldStartNode, newEndNode)) { console.log("比较开始-结尾子节点"); diffPatch(oldStartNode, newEndNode, record); let obj = { type: '移动节点', from: oldStartNode.tagName, to: oldEndNode.tagName, direction: 'after', fromNode: oldStartNode, toNode: oldEndNode, parentNode: parentNode } record.push(obj); oldStartNode = oldNodeChild[++oldStartId]; newEndNode = newNodeChild[--newEndId]; } else if (diffSame(oldEndNode, newStartNode)) { console.log("比较结尾-开始子节点"); let obj = { type: '移动节点', from: oldEndNode.tagName, to: oldStartNode.tagName, direction: 'before', fromNode: oldEndNode, toNode: oldStartNode, parentNode: parentNode } record.push(obj); diffPatch(oldEndNode, newStartNode, record); oldEndNode = oldNodeChild[--oldEndId]; newStartNode = newNodeChild[++newStartId]; } else { // 使用key时的比较 if (oldKeyToId === undefined) { oldKeyToId = createKeyToOldIdx(oldNodeChild, oldStartId, oldEndId) // 有key生成index表 } console.log(oldKeyToId); idxInOld = oldKeyToId[newStartNode.key] if (!idxInOld) { console.log('没有找到, 新建' + newStartNode.tagName); let obj = { type: '新增节点', add: newStartNode.tagName, to: oldStartNode.tagName, direction: 'before', addNode: newStartNode, toNode: oldStartNode, parentNode: parentNode } record.push(obj); } else { elmToMove = oldNodeChild[idxInOld]; if (diffSame(elmToMove, newStartNode)) { diffPatch(elmToMove, newStartNode, record); oldNodeChild[idxInOld] = null; console.log('移动节点'); let obj = { type: '移动节点', from: elmToMove.tagName, to: oldStartNode.tagName, direction: 'before', fromNode: elmToMove, toNode: oldStartNode, parentNode: parentNode }; record.push(obj); } else { console.log('找到, 属性变化, 替换' + newStartNode.tagName); let obj = { type: '新增节点', add: newStartNode.tagName, to: oldStartNode.tagName, direction: 'before', addNode: newStartNode, toNode: oldStartNode, parentNode: parentNode } record.push(obj); } } newStartNode = newNodeChild[++newStartId]; } } if (oldStartId > oldEndId && newStartId <= newEndId) { console.log('批量新增节点'); let before = oldNodeChild[oldEndId + 1] == null ? null : oldNodeChild[oldEndId + 1] let obj = { type: '批量新增节点', add: newNodeChild, to: before ? before.tagName : '', direction: 'before', addNodeArray: newNodeChild, toNode: before, startId: newStartId, endId: newEndId, parentNode: parentNode } record.push(obj); } else if (newStartId > newEndId && oldStartId <= oldEndId) { console.log('批量删除节点'); let obj = { type: '批量删除节点', deleteNodeArray: oldNodeChild, startId: oldStartId, endId: oldEndId, parentNode: parentNode } record.push(obj); } } // 取key存map function createKeyToOldIdx(children, beginIdx, endIdx) { var i, map = {}, key; for (i = beginIdx; i <= endIdx; ++i) { key = children[i].key; if (key != undefined) map[key] = i; } return map; } // 根据判断出来的变化,更新 function showChange(records, oldTree) { records.forEach(record => { // let parent = record.parentNode ? document.getElementById(record.parentNode.id) : ''; let parent = record.parentNode ? record.parentNode.node : ''; // console.log(parent); switch (record.type) { case '节点替换': // let newNode = record.newNode.render(); let newNode = render(record.newNode); document.getElementById('virtualDom').replaceChild(newNode, record.oldNode.node); break; case '文本替换': // document.getElementById(record.newNode.id).textContent = record.content; record.changeNode.node.textContent = record.content; break; case '移动节点': if (record.direction == 'after') { // parent.insertBefore(document.getElementById(record.fromNode.id), document.getElementById(record.toNode.id).nextSibling); parent.insertBefore(record.fromNode.node, record.toNode.node); } else { // parent.insertBefore(document.getElementById(record.fromNode.id), document.getElementById(record.toNode.id)); parent.insertBefore(record.fromNode.node, record.toNode.node); } break; case '新增节点': if (record.direction == 'after') { // parent.insertBefore(record.addNode.render(), record.toNode.node.nextSibling); parent.insertBefore(render(record.addNode), record.toNode.node.nextSibling); } else { // parent.insertBefore(record.addNode.render(), record.toNode.node); parent.insertBefore(render(record.addNode), record.toNode.node); } break; case '批量删除节点': for (let i = record.startId; i <= record.endId; i++) { if (record.deleteNodeArray[i]) { let delNode = record.deleteNodeArray[i].node; if (delNode) { parent.removeChild(delNode); } } } break; case '批量新增节点': for (let i = record.startId; i <= record.endId; i++) { if (record.toNode) { // parent.insertBefore(record.addNodeArray[i].render(), record.toNode.node); parent.insertBefore(render(record.addNodeArray[i]), record.toNode.node) } else { // parent.appendChild(record.addNodeArray[i].render()); parent.appendChild(render(record.addNodeArray[i])); } } break; default: } }); }
var appContext; var authStr = ""; var startTime = null; var store = null; var startTimeRefresh = null; var online = navigator.onLine; /******************************************************************** * Initialize the application * In this case, it will check first of the application has already * registered with the SMP server. If not, it will register the app * then proceed to manage the logon process. ********************************************************************/ function doLogonInit(context, appId) { //Init needs to happen before anything else. console.log("Entering doLogonInit"); jQuery.sap.require("sap.ui.thirdparty.datajs"); //Is there a host address populated? if (context.serverHost.length < 1) { //If not, nothing we can do now console.log("You must set the SMP Server address before you can initialize the server connection."); return; } //Make call to Logon's Init method to get things registered and all setup if (window.sap_webide_companion) { sap.Logon.initPasscodeManager(onLogonInitSuccess, onLogonError, appId); } else { sap.Logon.init(onLogonInitSuccess, onLogonError, appId, context); } console.log("Leaving doLogonInit"); } var onLogonInitSuccess = function(context) { console.log("Entering LogonInitSuccess"); //Make sure Logon returned a context for us to work with if (context) { //Store the context away to be used later if necessary // alert(context); appContext = context; //alert(appContext); //alert(appContext.applicationEndpointURL); console.log("appContext******************************************* "+appContext); //Build the results message which will be written to the log and //displayed to the user //var msg = "Server Returned: " + JSON.stringify(context); //console.log(msg); // authStr = "Basic " + btoa(context.user + ":" + context.password); //start UI5 application // alert(appContext.applicationEndpointURL); startApp(); // readGWONOFF(); // openStore(context); //readGWData(); // openStore(context); } else { //Something went seriously wrong here, context is not populated console.error("context null"); } console.log("Leaving LogonInitSuccess"); }; var onLogonError = function(errObj) { //Generic error function, used as a callback by several of the methods console.error("Entering logonError"); //write the contents of the error object to the console. console.error(JSON.stringify(errObj)); console.error("Leaving logonError"); }; /******************************************************************** * Delete the application's registration information * Disconnects the app from the SMP server ********************************************************************/ function doDeleteRegistration() { console.log("Entering doDeleteRegistration"); if (appContext) { //Call logon's deleteRegistration method sap.Logon.core.deleteRegistration(onDeleteRegistrationSuccess, onLogonError); } else { //nothing to do here, move along... var msg = "The application is not initialized, cannot delete context"; console.log(msg); } console.log("Leaving doDeleteRegistrationU"); } function onDeleteRegistrationSuccess(res) { console.log("Entering unregisterSuccess"); console.log("Unregister result: " + JSON.stringify(res)); //Set appContext to null so the app will know it's not registered appContext = null; //reset the app to its original packaged version //(remove all updates retrieved by the AppUpdate plugin) sap.AppUpdate.reset(); console.log("Leaving unregisterSuccess"); } /******************************************************************** * Lock the DataVault ********************************************************************/ function doLogonLock() { console.log("Entering doLogonLock"); //Everything here is managed by the Logon plugin, there's nothing for //the developer to do except to make the call to lock to //Lock the DataVault sap.Logon.lock(onLogonLockSuccess, onLogonError); console.log("Leaving doLogonLock"); } var onLogonLockSuccess = function() { console.log("Entering logonLockSuccess"); console.log("Leaving logonLockSuccess"); }; /******************************************************************** * Unlock the DataVault ********************************************************************/ function doLogonUnlock() { console.log("Entering doLogonUnlock"); //Everything here is managed by the Logon plugin, there's nothing for //the developer to do except to make the call to unlock. //we'll be using the same success callback as //with init as the signatures are the same and have the same functionality sap.Logon.unlock(onLogonInitSuccess, onLogonError); console.log("Leaving doLogonUnlock"); } /******************************************************************** * Show the application's registration information ********************************************************************/ function doLogonShowRegistrationData() { console.log("Entering doLogonShowRegistrationData"); //Everything here is managed by the Logon plugin, there's nothing for //the developer to do except to make a call to showRegistratioData sap.Logon.showRegistrationData(onShowRegistrationSuccess, onShowRegistrationError); console.log("Leaving doLogonShowRegistrationData"); } function onShowRegistrationSuccess() { console.log("Entering showRegistrationSuccess"); //Nothing to see here, move along... console.log("Leaving showRegistrationSuccess"); } function onShowRegistrationError(errObj) { console.log("Entering showRegistrationError"); console.error(JSON.stringify(errObj)); console.log("Leaving showRegistrationError"); } /******************************************************************** * Update the DataVault password for the user ********************************************************************/ function doLogonChangePassword() { console.log("Entering doLogonChangePassword"); //Everything here is managed by the Logon plugin, there's nothing for //the developer to do except to make the call to changePassword sap.Logon.changePassword(onPasswordSuccess, onPasswordError); console.log("Leaving doLogonChangePassword"); } /******************************************************************** * Change the DataVaule passcode ********************************************************************/ function doLogonManagePasscode() { console.log("Entering doLogonManagePassword"); //Everything here is managed by the Logon plugin, there's nothing for //the developer to do except to make the call to managePasscode sap.Logon.managePasscode(onPasswordSuccess, onPasswordError); console.log("Leaving doLogonManagePassword"); } function onPasswordSuccess() { console.log("Entering passwordSuccess"); //Nothing to see here, move along... console.log("Leaving passwordSuccess"); } function onPasswordError(errObj) { console.error("Entering passwordError"); console.error("Password/passcode error"); console.error(JSON.stringify(errObj)); console.error("Leaving passwordError"); } /******************************************************************** * Read/Write values from the DataVault ********************************************************************/ function doLogonSetDataVaultValue(theKey, theValue) { console.log("Entering doLogonSetDataVaultValue"); //Make sure we have both a key and a value before continuing //No sense writing a blank value to the DataVault if (theKey !== "" && theValue !== "") { console.log("Writing values to the DataVault"); //Write the values to the DataVault sap.Logon.set(onDataVaultSetSuccess, onDataVaultSetError, theKey, theValue); } else { //One of the input values is blank, so we can't continue console.error("Key and/or value missing."); } console.log("Leaving doLogonSetDataVaultValue"); } function onDataVaultSetSuccess() { console.log("Entering dataVaultSetSuccess"); //Clear out the input fields //Cordova alerts are asynchronous, so this code will likely clear the input //fields before the alert dialog displays console.log("Leaving dataVaultSetSuccess"); } function onDataVaultSetError(errObj) { console.error("Entering dataVaultSetError"); console.error("Error writing to the DataVault"); console.error("Leaving dataVaultSetError"); } function doLogonGetDataVaultValue(theKey) { console.log("Entering doLogonGetDataVaultValue"); //Make sure we have a key before continuing if (theKey !== "") { console.log("Reading value for " + theKey + " from the DataVault"); //Read the value from the DataVault sap.Logon.get(onDataVaultGetSuccess, onDataVaultGetError, theKey); } else { //One of the input values is blank, so we can't continue console.error("Value for key missing."); } console.log("Leaving doLogonGetDataVaultValue"); } function onDataVaultGetSuccess(value) { console.log("Entering dataVaultGetSuccess"); console.log("Received: " + JSON.stringify(value)); console.log("Leaving dataVaultGetSuccess"); } function onDataVaultGetError(errObj) { console.error("Entering dataVaultGetError"); console.error(JSON.stringify(errObj)); console.error("Leaving dataVaultGetError"); } function readGWONOFF() { console.log("in read"); // var self = com.hcl.eamoffline.app.SMPController; //this.updateStatus2("read request started"); //self.startTime = new Date(); //this.showScreen("MainDiv"); //this.clearTable("PlantsTable"); /* if (!self.haveAppId()) { return; } */ if(online){ //sap.OData.applyHttpClient(); sap.OData.removeHttpClient(); self.wasOnlineCall = true; }else{ console.log("gga store is open"); // openStore(); self.wasOnlineCall = false; sap.OData.applyHttpClient(); } if(store==null) { openStore(appContext); sap.OData.applyHttpClient(); } // var sURL = self.getEndPointURL() + "PlantSet"; var sURL = "http://us1455saps033.dir.slb.com:8080/com.slb.mobile/WOLIST"; //var sURL = "http://us1455saps033.dir.slb.com:8080/com.hcl.eamoffline/WOLIST"; var oHeaders = {}; oHeaders['Authorization'] = self.authStr; oHeaders['Accept'] = "application/json"; oHeaders['x-csrf-token'] = "Fetch"; //oHeaders['X-SMP-APPCID'] = applicationContext.applicationConnectionId; //this header is provided by the logon plugin // clientCert = new sap.AuthProxy.CertificateFromLogonManager("com.mycompany.logon"); var request = { headers : oHeaders, requestUri : sURL, method : "GET" }; // console.log("read using " + sURL + " with connection id: " + self.applicationContext.applicationConnectionId); //OData.read(request, self.readSuccessCallback, self.errorCallback); //var headers = {"X-SMP-APPCID" : self.applicationContext.applicationConnectionId}; // var m = new sap.ui.model.odata.ODataModel("http://us1455saps033.dir.slb.com:8080/com.hcl.eamoffline/", true, "IMohammed6", "itt123"); OData.read(request, readSuccessCallback1, errorCallback); //var m = new sap.ui.model.odata.ODataModel("http://usphlvm1497.phl.sap.corp:8080/com.hcl.eamoffline/", true, "test", "gga", oHeaders, true); //m.setSizeLimit(1000); //self.plantModel = m; //m.read("/PlantSet", null, null, true, self.readSuccessCallback, self.errorCallback); var bus = sap.ui.getCore().getEventBus(); /* if(isOnline){ m.setSizeLimit(1000); self.plantModel = m; bus.publish("read", "plant", {value:self.plantModel}); }else{ m.setSizeLimit(1000); //OData.read(request, self.readSuccessCallback, self.errorCallback); self.plantModelOffline = m; if(isLocal){ bus.publish("read", "plantChanged", {value:self.plantModelOffline}); }else{ bus.publish("read", "plantOffline", {value:self.plantModelOffline}); } } */ } function readSuccessCallback1(data, response) { // alert("got data yeah!!"); var woList=[]; var woModel = new sap.ui.model.json.JSONModel(); $(data.results).each(function( i, val ) { woList.push({ "WOId" : val.Orderid, "Plant" : val.OrderType, "WOText" :val.ShortText, "RigId": "R2322", "JobId": "J87799", "StartDate": "23-Nov-2014" }); }); woModel.setData(woList); sap.ui.getCore().setModel(woModel,"mastermodel"); oCore.byId("masterlist").fireEvent("drawmaster"); } function readGWData() { var sUrl = appContext.applicationEndpointURL + "/WOLIST?sap-client=330&$format=json"; var uri = appContext.applicationEndpointURL; // var sUrl = appContext.applicationEndpointURL +"?sap-client=330&$format=json"; var headers = {"X-SMP-APPCID" : appContext.applicationConnectionId}; var user = appContext.registrationContext.user; var password = appContext.registrationContext.password; authStr = "Basic " + btoa(user + ":" + password); var oHeaders = {}; oHeaders['Authorization'] = authStr; //oHeaders['X-SMP-APPCID'] = applicationContext.applicationConnectionId; //this header is provided by the logon plugin var request = { headers : oHeaders, requestUri : sUrl, method : "GET" }; if(online) { sap.OData.removeHttpClient(); } else { sap.OData.applyHttpClient(); } OData.read(request, readSuccessCallback, errorCallback); } function readSuccessCallback(data, response) { var woList=[]; var woModel = new sap.ui.model.json.JSONModel(); $(data.results).each(function( i, val ) { woList.push({ "WOId" : val.Orderid, "Plant" : val.OrderType, "WOText" :val.ShortText, "RigId": "R2322", "JobId": "J87799", "StartDate": "23-Nov-2014" }); }); woModel.setData(woList); sap.ui.getCore().setModel(woModel,"mastermodel"); oCore.byId("masterlist").fireEvent("drawmaster"); } function errorCallback(e) { alert("error "+e); alert("An error occurred: " + JSON.stringify(e)); // showScreen("MainDiv"); } function openStore(context) { //startTime = new Date(); // alert("store.open called"); /* "serverHost" : devapp.smpInfo.server, "https" : "false", "serverPort" : devapp.smpInfo.port, "user": "IMohammed6",// ihms612@gmail.com HCPms admin user/ SCN User "password": "itt123", // Hisham@2014 HCPms admin password / SCN Password "serverPort" : devapp.smpInfo.port, //"communicatorId": "REST", "passcode": "password", "unlockPasscode": "password",*/ var properties = { "name": "WOListOfflineStore2", "host": appContext.registrationContext.serverHost, "port": appContext.registrationContext.serverPort, "https": appContext.registrationContext.https, "serviceRoot" : appContext.applicationEndpointURL, //"streamParams" : "custom_header=Content-Type:application/json", "definingRequests" : { "WOListReq2" : "/WOLIST" } }; store = sap.OData.createOfflineStore(properties); store.onrequesterror = errorCallback; //called for each modification error during flush //var options = {}; store.open(openStoreSuccessCallback, errorCallback); //store.open(openStoreSuccessCallback, errorCallback/*, options); } function openStoreSuccessCallback() { var endTime = new Date(); var duration = (endTime - startTime)/1000; // alert("Store opened in " + duration + " seconds"); // refreshStore(); //refreshOnInterval(); } function refreshOnInterval() { var interval = 300000; //5 minutes timerID = setInterval(function () {refreshStore()}, interval); //call refreshStore every interval, //remove timer in pause event, add back in resume } //After calling this the store will receive any changes from the OData producer. function refreshStore() { console.log("REFRESHSTORE"); if (!store) { alert("The store must be open before it can be refreshed"); return; } if (isDeviceOnline()) { startTimeRefresh = new Date(); //updateStatus2("store.refresh called"); store.refresh(refreshStoreCallback, errorCallback); } } function refreshStoreCallback() { var endTime = new Date(); var duration = (endTime - startTimeRefresh)/1000; } function getDeviceStatusString() { if (online) { return alert("Device is ONLINE"); } else { return alert("Device is OFFLINE"); } } function isDeviceOnline() { return online; }
const { attributes } = require("structure"); const Directory = attributes({ id: String, parent: String, name: String, path: String, createdBy: String, updatedBy: String, createdAt: Date, updatedAt: Date, children: Array })( class Directory { } ); module.exports = Directory;
"use strict"; function tlsClient(chan, psk) { const RandomSize = 32; const MasterSecretSize = 48; const MAXFRAG = 16384; const DigestStateSize = 336; const FChangeCipherSpec = 20; const FAlert = 21; const FHandshake = 22; const FApplicationData = 23; const Fragment = Struct([ 'type', U8, 'version', U16, 'fragment', OpaqueVector(U16) ]); const AAD = Struct([ 'recnum', U64, 'type', U8, 'version', U16, 'length', U16 ]); const HClientHello = 1; const ClientHello = Struct([ 'client_version', U16, 'random', Bytes(RandomSize), 'session_id', Vector(U8, U8), 'cipher_suites', Vector(U16, U16), 'compression_methods', Vector(U8, U8), 'extensions', Vector(U16, Struct([ 'type', U16, 'data', Vector(U8, U16) ])) ]); const HServerHello = 2; const ServerHello = Struct([ 'server_version', U16, 'random', Bytes(RandomSize), 'session_id', Vector(U8, U8), 'cipher_suite', U16, 'compression_method', U8, 'extensions', Optional(Vector(U16, Struct([ 'type', U16, 'data', Vector(U8, U16) ]))) ]); const HServerHelloDone = 14; const ServerHelloDone = Struct([]); const HClientKeyExchange = 16; const ClientKeyExchange = Struct([ 'psk_identity', VariableString(U16) ]); const HFinished = 20; const Finished = Struct([ 'verify_data', Bytes(12) ]); const Handshake = Struct([ 'msg_type', U8, null, Length(U24, Select(o => o.msg_type, { 1: ClientHello, 2: ServerHello, 14: ServerHelloDone, 16: ClientKeyExchange, 20: Finished })) ]); let crandom = function(){ var s; s = new Uint8Array(RandomSize); let t = Date.now() / 1000 | 0; s[0] = t >> 24; s[1] = t >> 16; s[2] = t >> 8; s[3] = t; window.crypto.getRandomValues(s.subarray(4)); return s; }(); let srandom; function nullCipher() { } nullCipher.prototype.decrypt = function(f){}; nullCipher.prototype.encrypt = function(f){}; function aeadChacha20Poly1305(mackey, key, iv){ this.iv = iv; this.iv_array = () => Module.HEAPU8.subarray(this.iv, this.iv+12); this.state = C.mallocz(26 * 4, 1); C.setupChachastate(this.state, key, 32, iv, 12, 20); } aeadChacha20Poly1305.mac_key_length = 0; aeadChacha20Poly1305.enc_key_length = 32; aeadChacha20Poly1305.fixed_iv_length = 12; aeadChacha20Poly1305.prototype.decrypt = function(f){ let nonce = new Uint8Array(12); for(var i = 0; i < 12; i++) nonce[i] = f.recnum / 2**(8*(11-i)) & 255 ^ this.iv_array()[i]; C.chacha_setiv(this.state, nonce); f.length -= 16; let aad = pack(AAD, f).data(); f.fragment = withBuf(f.fragment.length, (buf, buf_array) => { buf_array().set(f.fragment); if(C.ccpoly_decrypt(buf, f.length, aad, aad.length, buf + f.length, this.state) < 0) throw new Error("bad MAC"); return buf_array().slice(0, f.length); }); }; aeadChacha20Poly1305.prototype.encrypt = function(f){ let nonce = new Uint8Array(12); for(var i = 0; i < 12; i++) nonce[i] = f.recnum / 2**(8*(11-i)) & 255 ^ this.iv_array()[i]; C.chacha_setiv(this.state, nonce); let aad = pack(AAD, f).data(); f.fragment = withBuf(f.fragment.length + 16, (buf, buf_array) => { buf_array().set(f.fragment); C.ccpoly_encrypt(buf, f.fragment.length, aad, aad.length, buf + f.fragment.length, this.state); return buf_array().slice(); }); }; var handshake = new Packet(); var application = new Packet(); var rxCipher = new nullCipher(); var txCipher = new nullCipher(); var nextTxCipher = null; var nextRxCipher = null; var masterSecret; var sessionKeys; var txRecNum; var rxRecNum; var handhash = C.mallocz(DigestStateSize*2, 1); var closed = false; function calcMasterSecret() { masterSecret = C.mallocz(MasterSecretSize, 1); var n = psk.length; withBuf(2 * n + 4, (buf, buf_array) => withBuf(2 * RandomSize, (seed, seed_array) => { { let a = buf_array(); a[0] = n >> 8; a[1] = n; a[n+2] = n >> 8; a[n+3] = n; a.set(psk, n+4); } seed_array().set(crandom); seed_array().set(srandom, RandomSize); let label = 'master secret'; C.p_sha256(masterSecret, MasterSecretSize, buf, 2 * n + 4, label, label.length, seed, 2 * RandomSize); })); psk.fill(0); } function calcSessionKeys(mac_key_length, enc_key_length, fixed_iv_length) { var n = 2 * mac_key_length + 2 * enc_key_length + 2 * fixed_iv_length; if(sessionKeys !== undefined){ C.memset(sessionKeys.buf, 0, sessionKeys.length); C.free(sessionKeys.buf); } let buf = C.mallocz(n, 1); sessionKeys = { length: n, buf: buf, cMACkey: buf, sMACkey: buf + mac_key_length, cKey: buf + 2 * mac_key_length, sKey: buf + 2 * mac_key_length + enc_key_length, cIV: buf + 2 * mac_key_length + 2 * enc_key_length, sIV: buf + 2 * mac_key_length + 2 * enc_key_length + fixed_iv_length }; let label = 'key expansion'; withBuf(2 * RandomSize, (seed, seed_array) => { seed_array().set(srandom); seed_array().set(crandom, RandomSize); C.p_sha256(sessionKeys.buf, n, masterSecret, MasterSecretSize, label, label.length, seed, 2 * RandomSize); }); } function botch() { throw new Error("TLS botch"); } function alert(f) { var alerts = { 0: 'close notify', 1: 'unexpected message', 20: 'bad record MAC', 22: 'record overflow', 30: 'decompression failure', 40: 'handshake failure', 42: 'bad certificate', 43: 'unsupported certificate', 44: 'certificate revoked', 45: 'certificate expired', 46: 'certificate unknown', 47: 'illegal parameter', 48: 'unknown ca', 49: 'access denied', 50: 'decode error', 51: 'decrypt error', 70: 'protocol version', 71: 'insufficient security', 80: 'internal error', 90: 'user canceled', 100: 'no renegotiation', 110: 'unsupported extension', }; if(f.length != 2) botch(); if(!(f[1] in alerts)) botch(); switch(f[0]){ case 1: console.log('TLS ALERT: WARNING: ' + alerts[f[1]]); break; case 2: throw new Error('TLS ALERT: FATAL: ' + alerts[f[1]]); } } function recvFragment() { function recLen(b) { if(b.length < 5) return -1; return 5 + (b[3] << 8 | b[4]); } chan.read(recLen) .then(b => { if(b === undefined) return; let r = unpack(Fragment, b); if(r.version != 0x0303) botch(); r.recnum = rxRecNum++; r.length = r.fragment.length; rxCipher.decrypt(r); switch(r.type){ case FApplicationData: application.write(r.fragment); break; case FHandshake: handshake.write(r.fragment); break; case FChangeCipherSpec: if(nextRxCipher === null) botch(); rxCipher = new nextRxCipher(sessionKeys.sMACkey, sessionKeys.sKey, sessionKeys.sIV); nextRxCipher = null; rxRecNum = 0; break; case FAlert: if(r.fragment.length == 2 && r.fragment[0] == 1 && r.fragment[1] == 0){ return sendData(new VBuffer(new Uint8Array([1,0]))) .then(() => { handshake.close(); application.close(); chan.close(); }); } alert(r.fragment); break; default: throw new Error("TLS unknown protocol " + r.type.toString()); } return recvFragment(); }); } function recvHandshake() { function handLen(b) { if(b.length < 4) return -1; return 4 + (b[1] << 16 | b[2] << 8 | b[3]); } return handshake.read(handLen).then(b => { if(b[0] != HFinished) C.sha2_256(b, b.length, 0, handhash); return unpack(Handshake, b) }); } function sendData(b, type) { let p = Promise.resolve(); for(var n = 0; n < b.p; n += MAXFRAG){ let i = n; let e = n+MAXFRAG > b.p ? b.p : n+MAXFRAG; p = p.then(() => { var f = { type: type, version: 0x0303, fragment: b.a.subarray(i, e), length: e - i, recnum: txRecNum++ }; txCipher.encrypt(f); return chan.write(pack(Fragment, f).data()); }); } return p; } function sendHandshake(data) { var b = pack(Handshake, data); C.sha2_256(b.data(), b.p, 0, handhash); return sendData(b, FHandshake); } function sendClientHello() { return sendHandshake({ msg_type: HClientHello, client_version: 0x0303, gmx_unix_time: Date.now() / 1000 | 0, random: crandom, session_id: [], cipher_suites: [0xccab], compression_methods: [0], extensions: [] }); } function recvServerHello() { return recvHandshake().then(m => { if(m.msg_type != HServerHello) botch(); if(m.server_version != 0x0303) botch(); if(m.session_id.length != 0) botch(); if(m.cipher_suite != 0xccab) botch(); if(m.compression_method != 0) botch(); srandom = m.random; nextTxCipher = nextRxCipher = aeadChacha20Poly1305; }); } function recvServerHelloDone() { return recvHandshake().then(m => { if(m.msg_type != HServerHelloDone) botch(); }); } function sendClientKeyExchange() { return sendHandshake({ msg_type: HClientKeyExchange, psk_identity: "p9secret" }); } function sendChangeCipherSpec() { var p = new VBuffer(); p.put([1]); return sendData(p, FChangeCipherSpec) .then(() => { if(nextTxCipher === null) botch(); txCipher = new nextTxCipher(sessionKeys.cMACkey, sessionKeys.cKey, sessionKeys.cIV); nextTxCipher = null; txRecNum = 0; }); } function verifyData(label) { return withBuf(32, (hash, hash_array) => withBuf(12, (data, data_array) => { C.memmove(handhash + DigestStateSize, handhash, DigestStateSize); C.sha2_256([], 0, hash, handhash + DigestStateSize); C.p_sha256(data, 12, masterSecret, MasterSecretSize, label, label.length, hash, 32); return data_array().slice(); })); } function sendFinished() { return sendHandshake({ msg_type: HFinished, verify_data: verifyData('client finished') }); } function recvFinished() { return recvHandshake().then(m => { if(m.msg_type != HFinished) botch(); let data = verifyData('server finished'); if(data.length !== m.verify_data.length) botch(); for(var i = 0; i < data.length; i++) if(data[i] != m.verify_data[i]) botch(); }); } function runHandshake() { return sendClientHello() .then(recvServerHello) .then(recvServerHelloDone) .then(sendClientKeyExchange) .then(() => { calcMasterSecret(); calcSessionKeys(nextTxCipher.mac_key_length, nextTxCipher.enc_key_length, nextTxCipher.fixed_iv_length); }) .then(sendChangeCipherSpec) .then(sendFinished) .then(recvFinished); } function TlsConn() { } TlsConn.prototype.read = function(check) { return application.read(check); }; TlsConn.prototype.write = function(b) { if(!(b instanceof VBuffer)) b = new VBuffer(b); return sendData(b, FApplicationData); }; recvFragment(); return runHandshake().then(() => new TlsConn()); }
import { makeStyles } from '@material-ui/core/styles' const useStyles = makeStyles(() => ({ root: { flexGrow: 1, display: 'flex', flexDirection: 'row', justifyContent: 'space-between', backgroundColor: '#FD2A36', borderRadius: 10, fontFamily: 'Barlow', position: 'absolute', }, title: { flexGrow: 1, }, links: { color: 'white', fontSize: '1.5em', width: '10%', padding: 10, textDecoration: 'none', }, logo: { width: '90%', }, appBar: { borderRadius: 20, }, })) export default useStyles
var contador = 0; var correct = 0; var incorrect = 0; var question = document.getElementsByClassName('question') var answer = document.getElementsByClassName('answerPs') var score = document.getElementById('score') var mistake = document.getElementById('mistake') var list = [1, 3, 8, 9, 13, 15, 20, 21, 26, 28] //para ocultar los ejercicios function ocultarEjercicios(){ for(var i = 0; i < question.length; i++){ if( i > 0){ question[i].style.display = "none"; } } } //función que mueve al siguiente ejercicio function nextQuestion(){ if (contador < question.length - 1){ question[contador].style.display = 'none'; contador++; question[contador].style.display = 'block'; } else if (contador === 9){ if (correct === 10){ Swal.fire({ icon: 'success', title: 'EXELENT!! ' + correct.toString() + '/10', text: 'You are the best' }) } else if(correct > 5){ Swal.fire({ icon: 'success', title: 'WELL DONE!! ' + correct.toString() + '/10', text: 'Keep improving' }) } else { Swal.fire({ icon: 'error', title: 'FAIL!! ' + correct.toString() + '/10', text: 'Never give up' }) } } } //función que hace retornar al ejercicio anterior function beforQuestion(){ if (contador != 0){ question[contador].style.display = 'none'; contador--; question[contador].style.display = 'block'; } } //para chequear las respuestas for(var j = 0; j < list.length; j++){ answer[list[j]].addEventListener('click', correctAnswer) } for(var i = 0; i < answer.length; i++){ if(i != 1 & i != 3 & i != 8 & i != 9 & i != 13 & i != 15 & i != 20 & i != 21 & i !=26 & i !=28){ answer[i].addEventListener('click', incorrectAnswer) } } function correctAnswer(){ correct++; score.innerHTML = correct.toString(); Swal.fire({ icon: 'success', title: 'GOOD JOB' }) } function incorrectAnswer(){ incorrect++; mistake.innerHTML = incorrect.toString(); Swal.fire({ icon: 'error', title: 'WRONG' }) }
import launchDarkly from '@busy-web/ember-cli-launch-darkly/services/launch-darkly'; export function initialize(application) { let serviceLookupName = `service:launchDarkly`; application.register(serviceLookupName, launchDarkly); application.inject(serviceLookupName, 'application', 'application:main'); } export default { initialize };
import React from 'react'; import PropTypes from 'prop-types'; import { Box, Grid } from '@chakra-ui/react'; import CardPost from './CardPost.jsx'; const CardList = ({ stateStore }) => ( <div> <Grid templateColumns="repeat(4, 1fr)" gap={6} className="scroll-style"> {/* eslint-disable-next-line operator-linebreak */} {stateStore.listPost.slice(-8).map((p) => ( <Box key={p.id}> <CardPost id={p.id} title={p.title} body={p.body} /> </Box> ))} </Grid> </div> ); CardList.propTypes = { stateStore: PropTypes.objectOf(PropTypes.any).isRequired }; export default CardList;
(function(){ this.utils = { colorWithHex: function(str,alpha) { var alpha = alpha || 1; var color = MSColor.colorWithSVGString(str); color.alpha = alpha; return color; }, generateGUID: function() { return NSUUID.UUID().UUIDString().UTF8String(); }, showRulers: function(show) { if((show && !doc.isRulersVisible()) || (!show && doc.isRulersVisible())) { doc.toggleRulers(); } }, showSelection: function(show) { // FIXME: Selection action is turned off, should be back soon! :) return; var defaults = NSUserDefaults.standardUserDefaults(); var isVisible=defaults.boolForKey("MSNormalEventDrawSelection"); if((show && !isVisible) || (!show && isVisible)) doc.toggleSelection(null); }, rectFromGKRect: function(rect) { return { x: rect.x(), y: rect.y(), width: rect.width(), height: rect.height() }; }, GKRectFromRect: function(rect) { return GKRect.rectWithRect(NSMakeRect(rect.x,rect.y,rect.width,rect.height)); }, currentPage: function(){ return doc.currentPage(); }, createMetaLayer: function(id,data) { var shape=MSShapeGroup.alloc().init(); shape.name = id; shape.isVisible=false; shape.isLocked=true; var metaStorage = MSShapePathLayer.alloc().init(); metaStorage.name = data; shape.addLayers([metaStorage]); return shape; }, deselectAllLayers: function(){ doc.documentData().deselectAllLayers(); }, // Typer. isString: function(obj) { return toString.call(obj)=="[object String]"; }, isNull: function(obj) { }, isDefined: function(obj) { return toString.call(obj)!="[object Undefined]"; }, isUndefined: function(obj) { return toString.call(obj)=="[object Undefined]"; }, isArray: function(obj) { return Array.isArray(obj); }, isFunction: function(obj) { return toString.call(obj)=="[object Function]"; }, isNSObject: function(obj) { return toString.call(obj)=="[object MOBoxedObject]"; }, typeOf: function(obj) { return toString.call(obj); } }; var BorderPosition = { Center: 0, Inside: 1, Outside: 2, Both: 3 }; var Shaper = { rect: function(rect,fill,border,radius) { var shape=MSRectangleShape.alloc().init(); shape.frame().origin=NSMakePoint(rect.x,rect.y); shape.frame().size=NSMakeSize(rect.width,rect.height); if(radius) { if(utils.isString(radius)) { shape.setCornerRadiusFromComponents(radius); } else { shape.cornerRadiusFloat=radius; } } var shapeGroup=MSShapeGroup.alloc().init(); shapeGroup.addLayers([shape]); this.fill(shapeGroup,fill || { color: "#dddddd",alpha: 1}); if(border) this.border(shapeGroup,border); shapeGroup.resizeRoot(true); return shapeGroup; }, fill: function(layer,obj) { var fill = (layer.style().fill()) ? layer.style().fill() : layer.style().fills().addNewStylePart(); fill.color = utils.colorWithHex(obj.color,obj.alpha); }, border: function(layer,obj) { var border = (layer.style().border()) ? layer.style().border() : layer.style().borders().addNewStylePart(); border.color = utils.colorWithHex(obj.color,obj.alpha); border.thickness = utils.isDefined(obj.thickness) ? obj.thickness : border.thickness(); border.position = utils.isDefined(obj.position) ? obj.position : border.position(); } }; var fs = { resolve: function(path) { var root=MSPlugin.pluginsURL().path(); var parts=sketch.scriptPath.split("/"); parts=parts.slice(root.split("/").length); if(parts.length>0) { root=root+"/"+parts[0]; } return root+"/"+path; }, resolveAsset: function(path) { return this.resolve("assets/"+path) }, resolveImageAsset: function(path) { var path2x=path.replace(/.png/g,"@2x.png"); return this.resolveAsset((NSScreen.isOnRetinaScreen() && this.exists(this.resolveAsset(path2x))) ? path2x : path); }, image: function(path) { if(!this.exists(path)) { throw new Error("Specified image file isn't exist at path '"+path+"'"); return null; } return NSImage.alloc().initWithContentsOfFile(path) }, exists: function(path) { return NSFileManager.defaultManager().fileExistsAtPath(path); }, remove: function(path) { NSFileManager.defaultManager().removeItemAtPath_error(path,null); }, writeString: function(obj,path) { return NSString.stringWithString(obj).writeToFile_atomically_encoding_error(path,true,NSUTF8StringEncoding,null); }, readString: function(path) { return NSString.stringWithContentsOfFile_encoding_error(path,NSUTF8StringEncoding,null); }, readJSON: function(path) { var obj=null; try { obj=JSON.parse(this.readString(path)); } catch(e) { throw new Error("Can't parse JSON string!") } return obj; }, writeJSON: function(obj,path) { return this.writeString(JSON.stringify(obj,null,4),path); } }; var View = { centerRect: function(rect,animated) { var animated = animated || true; this.view().centerRect_animated(rect,animated); }, totalRect: function(layers) { return this.view().totalRectForLayers(layers); }, zoomToSelection: function() { this.view().zoomToSelection(); }, centerLayersInCanvas: function() { this.view().centerLayersInCanvas(); }, view: function(){ return doc.currentView(); } }; var Persistent = { storage: function() { return NSThread.currentThread().threadDictionary(); }, setObject: function(key,obj) { this.storage()[key]=JSON.stringify(obj); }, getObject: function(key) { return JSON.parse(this.storage()[key]); } }; this.BorderPosition = BorderPosition; this.Shaper = Shaper; this.View = View; this.fs = fs; this.Persistent = Persistent; }).call(this);
angular.module('ngApp.directBooking').controller('UploadShipmentGuideLineController', function ($scope, DirectBookingService, SessionService, TopCountryService, TopCurrencyService, DbUploadShipmentService, IsCollapedFillExcel) { function init() { var userInfo = SessionService.getUser(); $scope.RoleId = userInfo.RoleId; $scope.CustomerId = userInfo.EmployeeId; $scope.OperationZoneId = userInfo.OperationZoneId; $scope.ModuleType = "Ecommerce"; DirectBookingService.GetInitials($scope.CustomerId).then(function (response) { // Set Country type according to given order $scope.CountriesRepo = response.data.Countries; // Set Currency type according to given order $scope.CurrencyTypes = response.data.CurrencyTypes; $scope.ParcelTypes = response.data.ParcelTypes; $scope.ShipmentMethods = response.data.ShipmentMethods; $scope.CustomerDetail = response.data.CustomerDetail; }); DbUploadShipmentService.GetLogisticServiceCode($scope.OperationZoneId, $scope.CustomerId).then(function (response) { if (response.data.length > 0) { $scope.ServcieCodeDetail = response.data; } }); if (!IsCollapedFillExcel) { $scope.isCollapsed7 = IsCollapedFillExcel; } else { $scope.isCollapsed7 = true; } $scope.GuideLineFillExcel = [ { "name": "From Country" }, { "name": "FromCountryCode" }, { "name": "FromPostCode" }, { "name": "FromContactFirstName" }, { "name": "FromContactLastName" }, { "name": "FromCompanyName" }, { "name": "FromAddress1" }, { "name": "FromAddress2" }, { "name": "FromCity" }, { "name": "FromTelephoneNo" }, { "name": "FromEmail" }, { "name": "ToCountryCode" }, { "name": "ToPostCode" }, { "name": "ToContactFirstName" }, { "name": "ToContactLastName" }, { "name": "ToCompanyName" }, { "name": "ToAddress1" }, { "name": "ToAddress2" }, { "name": "ToCity" }, { "name": "ToTelephoneNo" }, { "name": "ToEmail" }, { "name": "PackageCalculationType" }, { "name": "ParcelType" }, { "name": "Currency" }, { "name": "ShipmentReference" }, { "name": "ShipmentDescription" }, { "name": "TrackingNo" }, { "name": "CourierCompany" }, { "name": "CartonValue" }, { "name": "Length" }, { "name": "Width" }, { "name": "Height" }, { "name": "Weight" }, { "name": "DeclaredValue" }, { "name": "ShipmentContents" } ]; } init(); });
$(document).ready(function() { var l = localStorage.getItem('locale'); if(l) { l = $('[value=' + l + ']') if(l) l.attr('selected', true) } var success = function(data) { if(data.status == 'blocked') { alert('Аккаунт не активирован! Для активации аккаунта перейдите по ссылке в письме.') } else { $.cookie('uid', data.id, {path: '/'}); $.cookie('token', data.token, {path: '/'}); location = "/cabinet/" } } var step2 = function(data) { var p = $("#sesspass").val(); if(p!=null && p!='') { $.post("/Admin.User.loginStepTwo/", { token: data.token, id: data.id, pass: p }, function(r) { if(r && r.response) { success(r.response); } else { alert('Session password error!'); } }, 'JSON'); } } $("#submit").click(function() { var l = $("#login").val(), p = $("#pass").val(); if(l!='' && p!='') { $.post("/Gvsu.modules.users.controller.User.login/", { login: l, pass: p }, function(r) { if(r && r.response) { if(r.response && r.response.dblauth) { $("#step1").css("display","none") $("#step2").css("display","block") $("#submit2").click(function() { step2(r.response); }); } else { success(r.response); } } else { $("#login").val(''); $("#pass").val(''); $("#error").css('display', ''); } }, 'json'); } return false; }); });