text
stringlengths
7
3.69M
import modalForm from '../../../lib/flatfoot_web/static/js/reducers/modal_form'; var initialState = { formValues: undefined, formErrors: undefined }; const SET_FORM_VALUES = 'SET_FORM_VALUES', CLEAR_FORM_VALUES = 'CLEAR_FORM_VALUES', SET_FORM_ERRORS = 'SET_FORM_ERRORS', CLEAR_FORM_ERRORS = 'CLEAR_FORM_ERRORS', ADD_FORM_ERROR = 'ADD_FORM_ERROR', ADD_FORM_VALUE = 'ADD_FORM_VALUE', CLOSE_FORM_MODAL = 'CLOSE_FORM_MODAL'; describe('modalForm', () => { it('should set default state to initialState', () => { expect(modalForm(undefined, {})).to.eql(initialState); }); it('should return current state by default', () => { let state = Object.assign({}, initialState, {formValues: 'asdf'}); expect(modalForm(state, {type: 'NO_LEGIT_TYPE'})).to.eql(state); }); it('should set formValues to the passed form_values object with SET_FORM_VALUES type', () => { expect(modalForm(initialState, {type: SET_FORM_VALUES, form_values: {name: 'dave'}}).formValues).to.eql({name: 'dave'}); }); it('should set formValues to undefined with SET_FORM_VALUES type and no form_values param', () => { expect(modalForm(initialState, {type: SET_FORM_VALUES}).formValues).to.be.undefined; }); it('should add a key value pair to an existing formValues object when provided ADD_FORM_VALUE type, key and value', () => { let startState = Object.assign({}, initialState, {formValues: {name: 'dave'}}); let endState = Object.assign({}, startState, {formValues: {name: 'dave', email: 'd@lively.com'}}); expect(modalForm(startState, {type: ADD_FORM_VALUE, key: 'email', value: 'd@lively.com'})).to.eql(endState); }); it('should not add a new KV pair when provided ADD_FORM_VALUE type and missing either key or value param', () => { let startState = Object.assign({}, initialState, {formValues: {name: 'dave'}}); expect(modalForm(startState, {type: ADD_FORM_VALUE, value: 'd@lively.com'}).formValues).to.eql(startState.formValues); expect(modalForm(startState, {type: ADD_FORM_VALUE, key: 'email'}).formValues).to.eql(startState.formValues); }); it('should set formErrors when passed form_errors object and SET_FORM_ERRORS type', () => { expect(modalForm(initialState, {type: SET_FORM_ERRORS, form_errors: {name: 'Cannot be blank'}}).formErrors).to.eql({name: 'Cannot be blank'}); }); it('should set formErrors to undefined with SET_FORM_ERRORS type and no form_errors param', () => { expect(modalForm(initialState, {type: SET_FORM_ERRORS}).formErrors).to.be.undefined; }); it('should set formErrors to undefined with CLEAR_FORM_ERRORS type', () => { let startState = Object.assign({}, initialState, {formErrors: {name: 'jon smith'}}); expect(startState.formErrors).to.eql({name: 'jon smith'}); expect(modalForm(startState, {type: CLEAR_FORM_ERRORS}).formErrors).to.be.undefined; }); it('should add a KV pair to formErrors with ADD_FORM_ERROR type, key, and value', () => { let startState = Object.assign({}, initialState, {formErrors: {name: 'Cannot be blank'}}); let endState = Object.assign({}, initialState, {formErrors: {name: 'Cannot be blank', email: 'Incorrect format'}}); expect(modalForm(startState, {type: ADD_FORM_ERROR, key: 'email', value: 'Incorrect format'})).to.eql(endState); }); it('should not add a new KV pair when provided ADD_FORM_ERROR type and missing either key or value param', () => { let startState = Object.assign({}, initialState, {formErrors: {name: 'Cannot be blank'}}); expect(modalForm(startState, {type: ADD_FORM_ERROR, value: 'Incorrect format'}).formErrors).to.eql(startState.formErrors); expect(modalForm(startState, {type: ADD_FORM_ERROR, key: 'email'}).formErrors).to.eql(startState.formErrors); }); it('should clear all values and set state to initialState with CLEAR_FORM_VALUES or CLOSE_FORM_MODAL type', () => { let startState = Object.assign({}, initialState, {formValues: 'formValues', formErrors: 'formErrors'}); expect(modalForm(startState, {type: CLEAR_FORM_VALUES})).to.eql(initialState); expect(modalForm(startState, {type: CLOSE_FORM_MODAL})).to.eql(initialState); }); });
import Vue from 'vue' import App from './App.vue' import router from './router/index' import store from './store' import toast from 'components/common/toast/index' // 解决移动端300ms延迟 // 1.npm install fastclick --save // 2.导入 import FastClick from 'fastclick' // 图片懒加载 // 1.npm install vue-lazyload --save // 2.导入 import VueLazyLoad from 'vue-lazyload' // px-to-vm-css // 1.npm install postcss-px-to-viewport --save-dev // 2.修改postcss.config.js Vue.config.productionTip = false // 添加事件总线 Vue.prototype.$bus = new Vue() // 下载toast插件 Vue.use(toast) //3. 解决移动端300ms延迟 FastClick.attach(document.body) // 3.使用图片懒加载 Vue.use(VueLazyLoad, { // 传入占位图 loading: require('assets/img/common/placeholder.png') }) // 4.要使用的地方将src变更为 v-lazy new Vue({ render: h => h(App), router, store }).$mount('#app')
import React from 'react' import { RefreshAction, Toolbar, View } from '@reforma/ui' import { Button } from '@blueprintjs/core' import presidentDS from './presidentDS' class PresidentView extends React.PureComponent { render() { return ( <div style={{ padding: 16 }}> <Toolbar bottomMargin> <Button icon="arrow-left" onClick={this.backToList.bind(this)} > Back to List </Button> <RefreshAction dataSource={presidentDS} /> </Toolbar> <View id={this.props.match.params.id} dataSource={presidentDS} fields={[{name: 'id', label: 'ID'}, 'firstName', 'lastName']} /> </div> ) } backToList() { this.props.history.push('/') } } export default PresidentView
var searchData= [ ['block_5fcluster',['block_cluster',['../classbctree.html#acc45b082bb211c6b9a193bc19bf5f28c',1,'bctree']]] ];
import { connect } from "../../slomux"; import { changeInterval } from "../../actions"; import IntervalComponent from "./component"; const Interval = connect( state => ({ currentInterval: state }), dispatch => ({ changeInterval: value => dispatch(changeInterval(value)) }) )(IntervalComponent); export default Interval;
import axios from "axios"; export const getOrdersAdmin=()=>{ return async dispatch =>{ try{ const response = await axios.get('http://localhost:8888/back/api/read_orders_admin.php') const json = await response.data; dispatch({ type:'GET_ORDERS_ADMIN', payload:json }) console.log(json) } catch(error){ console.log(error); } } }
const express = require('express') const { Socket } = require('socket.io') const app = express() const server = require('http').Server(app) const io = require('socket.io')(server) const PORT = process.env.PORT || 80 const {v4: uuidV4} = require('uuid') app.set('view engine', 'ejs') app.use(express.static('public')) app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); res.header("Access-Control-Allow-Origin", "null") // res.header("Access-Control-Allow-Origin", ) next(); }); app.get('/', (req, res) => { res.redirect( `/${uuidV4()}`) }) app.get('/:room', (req, res) => { res.header('Access-Control-Allow-Origin', '*') res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE") res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept") res.render('room', {roomId: req.params.room}) }) io.on('connection', socket => { socket.on('join-room', (roomId, userId) => { socket.join(roomId) socket.to(roodId).broadcast.emit('user-connected', userId) }) }) server.listen(PORT, () => { console.log("Listnening...") })
var mongoose = require("mongoose"); var Schema = mongoose.Schema; var partySchema = new Schema({ personPosting: Object, host: String, typeOfParty: String, location: { address: { type: String, required: true }, city: { type: String, required: true }, state: String, zip: String }, alcohol: { type: Boolean, required: true }, admission: String, admissionAmount: Number, dateAndTime: String, comments: [String] }); module.exports = mongoose.model("Party", partySchema);
/** * NBTTagByteArray represents a bytes storage * @example * var bb1 = new NBTTagByteArray([1,2,3,10], "tagBytes"); * bb1.size; // 4 * var bb2 = new NBTTagByteArray(); * bb2.size; // 0 * * @memberOf NBT * @augments NBT.NBTArray * @param {Array<number>|ArrayBuffer|String=} value Value of tag * @param {string=} name Name of tag * @constructor */ NBT.NBTTagByteArray = function NBTTagByteArray(value, name){ NBT.NBTArray.call( this, name ); this.setValue( value ); }; extend( NBT.NBTTagByteArray, NBT.NBTArray ); /** * Type of this tag * * @memberOf NBT.NBTTagByteArray * @type {NBT.Type} */ NBT.NBTTagByteArray.prototype.type = NBT.Type.TAG_BYTE_ARRAY; /** * Convert this tag to string * * @memberOf NBT.NBTTagByteArray * @returns {string} String value of this tag */ NBT.NBTTagByteArray.prototype.toString = function(){ return "NBTTagByteArray["+this._value.byteLength+"]"; }; /** * Create clone of this tag * * @memberOf NBT.NBTTagByteArray * @returns {NBT.NBTTagByteArray} Clone of this tag */ NBT.NBTTagByteArray.prototype.clone = function(){ return new NBT.NBTTagByteArray( this._value.slice(0), this._name ); }; /** * Set new value of this tag * * @memberOf NBT.NBTTagByteArray * @param {ArrayBuffer|Array<number>|string} value New value of this tag */ NBT.NBTTagByteArray.prototype.setValue = function(value){ if ( value == null) { this._value = new ArrayBuffer( 0 ); return; } else if ( value instanceof ArrayBuffer ){ this._value = value; return; } else if ( typeof value === "string" ){ value = Utf8Utils.encode( value ); } var length = value.length || value.byteLength; this._value = new ArrayBuffer( length ); var dataView = new DataView( this._value ); for ( var i=0; i<length; i++ ){ dataView.setInt8( i, value[i] ) } }; /** * Get byte at specified position in this array * * @memberOf NBT.NBTTagByteArray * @param {!number} index Index of byte to return * @returns {number} Byte value at the specified position in this array */ NBT.NBTTagByteArray.prototype.get = function(index){ var dataView = new DataView( this._value ); return dataView.getInt8( index ); }; /** * Set new byte in array at specified position * * @memberOf NBT.NBTTagByteArray * @param {number} index Index of byte to replace * @param {number} value Byte to be stored at specified position */ NBT.NBTTagByteArray.prototype.set = function(index, value){ var dataView = new DataView( this._value ); dataView.setInt8( index, value ); }; /** * @virtual * @private * @param {OutputStream=} outputStream */ NBT.NBTTagByteArray.prototype._write = function(outputStream){ outputStream.writeInt32( this._value.byteLength ); outputStream.write( this._value ); }; /** * Number of bytes in this array * * @memberOf NBT.NBTTagByteArray# * @name size * @type {number} * @readonly */ Object.defineProperty( NBT.NBTTagByteArray.prototype, "size", { enumerable: true, get: function(){ return this._value.byteLength; } });
// FB登入 const fbButton = document.querySelector('.FB_login #facebook_login'); fbButton.addEventListener('click', () => { FB.getLoginStatus((response) => { statusChangeCallback(response); }); }); function statusChangeCallback(response) { if (response.status === 'connected') { // user登入了 const { accessToken } = response.authResponse; fetchUSerInfo(accessToken); } else { FB.login((fbResponse) => { const { accessToken } = fbResponse.authResponse; // 拿到accessToken,提供給後端 statusChangeCallback(fbResponse); }, { scope: 'public_profile,email' }); } } function fetchUSerInfo(accessToken) { // 打我們自己的api fetch('/api/v1/user/signin', { method: 'POST', body: JSON.stringify({ provider: 'facebook', access_token: accessToken, }), headers: new Headers({ 'Content-Type': 'application/json', }), }) .then((response) => response.json()) .catch((error) => console.log(error)) .then((info) => { // 前端設定cookie document.cookie = `access_token=${info.data.access_token}`; window.location = '/profile.html'; }); } // 一般登入 const generalLoginBtn = document.querySelector('.general_login .normal_login'); generalLoginBtn.addEventListener('click', () => { const email = document.querySelector('.general_login .user_email').value; const password = document.querySelector('.general_login .user_password').value; fetch('/api/v1/user/signin', { method: 'POST', body: JSON.stringify({ provider: 'native', email, password, }), headers: new Headers({ 'Content-Type': 'application/json', }), }) .then((response) => response.json()) .catch((error) => console.log(error)) .then((info) => { document.cookie = `access_token=${info.data.access_token}`; window.location = '/profile.html'; }); }); // 用戶註冊 const signupBtn = document.querySelector('.user_signup .sign_up'); signupBtn.addEventListener('click', () => { const userName = document.querySelector('.user_signup .signup_name').value; const userEmail = document.querySelector('.user_signup .signup_email').value; const userPassword = document.querySelector('.user_signup .signup_password').value; fetch('/api/v1/user/signup', { method: 'POST', body: JSON.stringify({ name: userName, email: userEmail, password: userPassword, }), headers: new Headers({ 'Content-Type': 'application/json', }), }) .then((response) => response.json()) .catch((error) => console.log(error)) .then((info) => { document.cookie = `access_token=${info.data.access_token}`; window.location = '/profile.html'; }); });
const React = require('react'); const { renderToStream } = require('@react-pdf/renderer'); class PdfTemplate { constructor(Component, getAdditionalProps = null) { this.getAdditionalProps = getAdditionalProps; this.Component = Component; } async render(props) { return renderToStream(await this._render(props)); } async _render(props) { const Component = this.Component; const allProps = props; if (this.getAdditionalProps) { const asyncProps = await Promise.resolve(this.getAdditionalProps(props)); Object.assign(allProps, asyncProps); } return <Component {...allProps} />; } } module.exports = PdfTemplate;
var bikes, database,player, game, form; var playerInfo; var gameState=0 var playerCount=0 var playerNumber=0 var bike1,bike2,bike3,bike4; var bike1Img,bike2Img,bike3Img,bike4Img; var track; function preload(){ bike1Img=loadImage("Sprites/motorcycle.jpg"); bike2Img=loadImage("Sprites/motorcycle.jpg"); bike3Img=loadImage("Sprites/motorcycle.jpg"); bike4Img=loadImage("Sprites/motorcycle.jpg"); track=loadImage("Sprites/track.jpg"); } function setup(){ createCanvas(displayWidth-20,displayHeight-30); database=firebase.database(); game= new Game(); game.getState(); game.start(); } function draw(){ //If player count= 1 or 2 or 3 or 4 then change the GameState to play if(playerNumber===1 && playerCount===1){ game.updateState(1); } else if(playerNumber===2 && playerCount===2){ game.updateState(1); } else if(playerNumber===3 && playerCount===3){ game.updateState(1); } else if(playerNumber===4 && playerCount===4){ game.updateState(1); } //If GameState is 1 then run the play function if(gameState===1){ clear(); game.play(); } }
var pageSize = 25; var boolPassword = true;//secretcopy //簡訊查詢Model Ext.define('gigade.Sms', { extend: 'Ext.data.Model', fields: [ { name: "id", type: "int" }, { name: "order_id", type: "string" }, { name: "mobile", type: "string" }, { name: "subject", type: "string" }, { name: "content", type: "string" }, { name: "send", type: "int" }, { name: "trust_send", type: "string" }, { name: "created", type: "string" }, { name: "estimated_send_time", type: "string" }, { name: "modified", type: "string" }, { name: "modified_time", type: "string" }, { name: "estimated_time", type: "string" }, { name: "created_time", type: "string" } ] }); // //簡訊查詢Store var SmsStore = Ext.create('Ext.data.Store', { autoDestroy: true, pageSize: pageSize, model: 'gigade.Sms', proxy: { type: 'ajax', url: '/Service/SmsList', reader: { type: 'json', root: 'data', totalProperty: 'totalCount' } } }); SmsStore.on('beforeload', function () { Ext.apply(SmsStore.proxy.extraParams, { datequery: Ext.getCmp('datequery').getValue(), time_start: Ext.getCmp('time_start').getValue(), time_end: Ext.getCmp('time_end').getValue(), searchcontent: Ext.getCmp('searchcontent').getValue(), send: Ext.getCmp('send').getValue(), trustsend: Ext.getCmp('trustsend').getValue(), relation_id: "", isSecret: true }) }); var edit_SmsStore = Ext.create('Ext.data.Store', { autoDestroy: true, pageSize: pageSize, model: 'gigade.Sms', proxy: { type: 'ajax', url: '/Service/SmsList', reader: { type: 'json', root: 'data', totalProperty: 'totalCount' } } }); edit_SmsStore.on('beforeload', function () { Ext.apply(edit_SmsStore.proxy.extraParams, { datequery: Ext.getCmp('datequery').getValue(), time_start: Ext.getCmp('time_start').getValue(), time_end: Ext.getCmp('time_end').getValue(), searchcontent: Ext.getCmp('searchcontent').getValue(), send: Ext.getCmp('send').getValue(), trustsend: Ext.getCmp('trustsend').getValue(), relation_id: "", isSecret: false }) }); var datequeryStore = Ext.create('Ext.data.Store', { fields: ['txt', 'value'], data: [ { "txt": '所有時間', "value": "-1" }, { "txt": '建立時間', "value": "0" }, { "txt": '發送時間', "value": "1" } ] }); var SendStore = Ext.create('Ext.data.Store', { fields: ['txt', 'value'], data: [ { "txt": '全部狀態', "value": "-1" }, { "txt": '未發送', "value": "0" }, { "txt": '已发送', "value": "1" }, { "txt": '失敗重發', "value": "2" }, { "txt": '已取消', "value": "3" } ] }); var TrustSendStore = Ext.create('Ext.data.Store', { fields: ['txt', 'value'], data: [ { "txt": '發送中', "value": "0" }, { "txt": '發送完成', "value": "1" } ] }); function Query(x) { var selDate = Ext.getCmp("datequery").getValue(); var start = Ext.getCmp("time_start").getValue(); var end = Ext.getCmp("time_end").getValue(); SmsStore.removeAll(); if ((selDate == -1 || selDate == '' || selDate == null) && (start != null || end != null)) { Ext.Msg.alert(INFORMATION, '請先選擇日期條件'); Ext.getCmp("time_start").reset(); Ext.getCmp("time_end").reset(); } else if ((selDate != -1 ) && (start == null || end == null)) { Ext.Msg.alert(INFORMATION, '請選擇日期'); Ext.getCmp("time_start").reset(); Ext.getCmp("time_end").reset(); } else { Ext.getCmp("SmsView").store.loadPage(1); } } Ext.onReady(function () { var frm = Ext.create('Ext.form.Panel', { id: 'frm', layout: 'anchor', height: 80, flex: 1.5, border: 0, bodyPadding: 10, width: document.documentElement.clientWidth, items: [ { xtype: 'fieldcontainer', combineErrors: true, layout: 'hbox', margin: '10,0,0,0', items: [ { xtype: 'combobox', id: 'datequery', fieldLabel: '日期條件', queryMode: 'local', editable: false, labelWidth: 60, store: datequeryStore, displayField: 'txt', valueField: 'value', value: -1 }, { xtype: 'datefield', id: 'time_start', name: 'time_start', margin: '0,0, 5,40', editable: false, listeners: { 'select': function () { var start = Ext.getCmp("time_start"); var end = Ext.getCmp("time_end"); if (end.getValue() == null) { end.setValue(setNextMonth(start.getValue(), 1)); } else if (start.getValue() > end.getValue()) { Ext.Msg.alert(INFORMATION, "開始時間不能大於結束時間"); end.setValue(setNextMonth(start.getValue(), 1)); } else if (end.getValue() > setNextMonth(start.getValue(), 1)) { end.setValue(setNextMonth(start.getValue(), 1)); } }, specialkey: function (field, e) { if (e.getKey() == e.ENTER) { Query(); } }, focus: function () { var searchType = Ext.getCmp("datequery").getValue(); if (searchType == null || searchType == '' || searchType == '-1') { Ext.Msg.alert(INFORMATION, '請先選擇日期條件'); this.focus = false; } } } }, { xtype: 'displayfield', value: '~' }, { xtype: 'datefield', id: 'time_end', name: 'time_end', margin: '0 5px', editable: false, listeners: { 'select': function () { var start = Ext.getCmp("time_start"); var end = Ext.getCmp("time_end"); var s_date = new Date(start.getValue()); var now_date = new Date(end.getValue()); if (start.getValue() != "" && start.getValue() != null) { if (end.getValue() < start.getValue()) { Ext.Msg.alert(INFORMATION, "結束時間不能小於開始時間"); end.setValue(setNextMonth(start.getValue(), 1)); } else if (end.getValue() > setNextMonth(start.getValue(), 1)) { start.setValue(setNextMonth(end.getValue(), -1)); } } else { start.setValue(setNextMonth(end.getValue(), -1)); } }, specialkey: function (field, e) { if (e.getKey() == e.ENTER) { Query(); } }, focus: function () { var searchType = Ext.getCmp("datequery").getValue(); if (searchType == null || searchType == '' || searchType == '-1') { Ext.Msg.alert(INFORMATION, '請先選擇日期條件'); this.focus = false; } } } } ] }, { xtype: 'fieldcontainer', combineErrors: true, layout: 'hbox', margin: '10,0,0,0', items: [ { xtype: 'combobox', id: 'send', margin: '0,0,0,0', fieldLabel: '發送狀態', queryMode: 'local', editable: false, labelWidth: 60, store: SendStore, displayField: 'txt', valueField: 'value', value: -1, listeners: { "select": function (combo, record) { var send = Ext.getCmp("send"); var trustsend = Ext.getCmp("trustsend"); if (send.getValue() == 1) { trustsend.setDisabled(false); } else { trustsend.clearValue(); trustsend.setDisabled(true); } } } }, { xtype: 'combobox', id: 'trustsend', margin: '0,0, 5,40', fieldLabel: '電信發送狀態', queryMode: 'local', editable: false, disabled: true, labelWidth: 80, store: TrustSendStore, displayField: 'txt', valueField: 'value', value: -1 } ] }, { xtype: 'fieldcontainer', combineErrors: true, layout: 'hbox', items: [{ id: 'searchcontent', xtype: 'textfield', fieldLabel: "編號/訂單編號/行動電話", width: 313, labelWidth: 140, regex: /^\d+$/, regexText: '请输入正確的編號,訂單編號,行動電話進行查詢', name: 'searchcontent', allowBlank: true, value: document.getElementById("SMSID").value, listeners: { specialkey: function (field, e) { if (e.getKey() == e.ENTER) { Query(); } } } }, { xtype: 'button', text: SEARCH, margin: '0,0, 5,40', margin: '0 10 0 20', id: 'btnQuery', iconCls: 'icon-search', handler: Query }, { xtype: 'button', text: RESET, margin: '0 0 0 0', id: 'btn_reset', iconCls: 'ui-icon ui-icon-reset', listeners: { click: function () { Ext.getCmp("datequery").setValue(-1); Ext.getCmp("searchcontent").setValue(''); Ext.getCmp('time_start').reset();//開始時間--time_start Ext.getCmp('time_end').reset();//結束時間--time_end Ext.getCmp('send').setValue(-1), Ext.getCmp('trustsend').clearValue(); Ext.getCmp('trustsend').setDisabled(true); } } } ] }, ] }); var SmsView = Ext.create('Ext.grid.Panel', { id: 'SmsView', store: SmsStore, flex: 8, width: document.documentElement.clientWidth, columnLines: true, frame: true, columns: [ { header: "編號", dataIndex: 'id', width: 60, align: 'center' }, { header: "訂單編號", dataIndex: 'order_id', width: 100, align: 'center' }, { header: "行動電話", dataIndex: 'mobile', width: 130, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) { return "<a href='javascript:void(0);' onclick='SecretLogin(" + record.data.id + ")' >" + value + "</a>" } }, { header: "主旨", dataIndex: 'subject', width: 150, align: 'center' }, { header: "內容", dataIndex: 'content', flex: 1, align: 'center' }, { header: "發送狀態", dataIndex: 'send', width: 100, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) { var sendcontent = record.data.send; switch (record.data.send) { case 0: //sendcontent = "未發送"; sendcontent = "<a href=javascript:onEditClick(" + record.data.id + ")>未發送</a>" break; case 1: sendcontent = "已发送"; break; case 2: sendcontent = "失敗重發"; break; case 3: sendcontent = "已取消"; break; } return sendcontent; } }, { header: "電信發送狀態", dataIndex: 'trust_send', width: 100, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) { var sendcontent = record.data.trust_send; switch (record.data.send) { case 0: sendcontent = "未發送"; break; case 1: sendcontent = "發送失敗"; if (record.data.trust_send == 1) { sendcontent = "發送完成"; } if (record.data.trust_send == 0 || record.data.trust_send == 2) { sendcontent = "發送中"; } break; case 2: sendcontent = "發送失敗"; break; case 3: sendcontent = "已取消"; break; } return sendcontent; } }, { header: "建立時間", dataIndex: 'created_time', width: 150, align: 'center' }, { header: "預計發送時間", dataIndex: 'estimated_time', width: 150, align: 'center' }, { header: "發送時間", dataIndex: 'modified_time', width: 150, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) { if (record.data.send == 0 || record.data.send == 3) { return ''; } else { return record.data.modified_time; } } } , { header: '檢視', dataIndex: 'modified_time', width: 60, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) { if (record.data.send == 1) { return '<a href=javascript:TranToDetial("' + record.data.id + '")>' + "<img hidValue='0' id='reply_ok' src='../../../Content/img/icons/reply.png'/> " + '</a>'; }; } } ], bbar: Ext.create('Ext.PagingToolbar', { store: SmsStore, pageSize: pageSize, displayInfo: true, displayMsg: NOW_DISPLAY_RECORD + ': {0} - {1}' + TOTAL + ': {2}', emptyMsg: NOTHING_DISPLAY }), listeners: { scrollershow: function (scroller) { if (scroller && scroller.scrollEl) { scroller.clearManagedListeners(); scroller.mon(scroller.scrollEl, 'scroll', scroller.onElScroll, scroller); } } } }); Ext.create('Ext.container.Viewport', { layout: 'vbox', items: [frm, SmsView],// renderTo: Ext.getBody(), autoScroll: true, listeners: { resize: function () { SmsView.width = document.documentElement.clientWidth; this.doLayout(); } } }); ToolAuthority(); }); function SecretLogin(rid) {//secretcopy var secret_type = "3";//參數表中的"簡訊查詢列表" var url = "/Service/SmsSearchIndex "; var ralated_id = rid; //點擊機敏信息先保存記錄在驗證密碼是否需要輸入 boolPassword = SaveSecretLog(url, secret_type, ralated_id);//判斷5分鐘之內是否有輸入密碼 if (boolPassword != "-1") {//不准查看 if (boolPassword) {//超過5分鐘沒有輸入密碼 //參數1:機敏頁面代碼,2:機敏資料主鍵,3:是否彈出驗證密碼框,4:是否直接顯示機敏信息6.驗證通過后是否打開編輯窗口 // function SecretLoginFun(type, relatedID, isLogin, isShow, editO, isEdit) { SecretLoginFun(secret_type, ralated_id, true, true, false, url, null, null, null);//先彈出驗證框,關閉時在彈出顯示框 } else { SecretLoginFun(secret_type, ralated_id, false, true, false, url, null, null, null);//直接彈出顯示框 } } } function TranToDetial(SMSID) { var url = '/Service/SendSmsRecord?SMSID=' + SMSID + '&StartTime=' + 1; var panel = window.parent.parent.Ext.getCmp('ContentPanel'); var copy = panel.down('#SmsSearch'); if (copy) { copy.close(); } copy = panel.add({ id: 'SmsSearch', title: '簡訊發送記錄', html: window.top.rtnFrame(url), closable: true }); panel.setActiveTab(copy); panel.doLayout(); } onEditClick = function (rID) { var secret_type = "3";//參數表中的"簡訊查詢查詢列表" var url = "/Service/SmsSearchIndex/Edit "; var ralated_id = rID; boolPassword = SaveSecretLog(url, secret_type, ralated_id);//判斷5分鐘之內是否有輸入密碼 if (boolPassword != "-1") { if (boolPassword) {//驗證 SecretLoginFun(secret_type, ralated_id, true, false, true, url, "", "", "");//先彈出驗證框,關閉時在彈出顯示框 } else { editFunction(ralated_id); } } } function TransToUser(UserMobile) { var url = '/Member/UsersListIndex?UserMobile=' + UserMobile.split('*')[0]; var panel = window.parent.parent.Ext.getCmp('ContentPanel'); var copy = panel.down('#user_detial'); if (copy) { copy.close(); } copy = panel.add({ id: 'user_detial', title: '會員內容', html: window.top.rtnFrame(url), closable: true }); panel.setActiveTab(copy); panel.doLayout(); } setNextMonth = function (source, n) { var s = new Date(source); s.setMonth(s.getMonth() + n); if (n < 0) { s.setHours(0, 0, 0); } else if (n > 0) { s.setHours(23, 59, 59); } return s; }
import React, { useState } from "react"; import { Text ,View} from "react-native" export default function Catalogo() { return ( <View style={{flex:1,backgroundColor:"white"}}> <Text>Catalogo</Text> </View> ) }
export const STATUS_INITIALIZING = 'Initialising'; export const STATUS_READY = 'Ready'; export const STATUS_DISCONNECTED = 'Disconnected'; export const STATUS_CLOSED = 'Closed';
Template.editPanel.onRendered(function() { $('.help-icon').attr({ 'data-toggle': 'tooltip', 'data-placement': 'bottom', 'data-html': true, 'title': '<span style="text-align: center;"><strong>Tips:</strong></span> <br /> ' + '1. Double click circles for more information.<br .> ' + '2. Double click hulls for more information.<br /> ' + '3. Click two consecutive circles to swap them. <br />' + '4. Drag circles to change group arrangements. <br />' + '5. Click backspace on selected circle to remove them.' }); $('.help-icon').tooltip(); $('[data-toggle="tooltip"]').tooltip(); }); Template.editPanel.events({ 'click #resize': function(event) { if ($('#resize').hasClass('glyphicon-resize-full')) { $('#resize').removeClass('glyphicon-resize-full'); $('#resize').addClass('glyphicon-resize-small'); $('#bubble-canvas').css({ 'height': '100%', 'width': '100%' }); setTimeout(function() { $(window).trigger('resize'); }, 1000); $('#filterContainer').css('display', 'block'); $('#filterContainer').css('display', 'none'); } else { $('#resize').removeClass('glyphicon-resize-small'); $('#resize').addClass('glyphicon-resize-full'); $('#bubble-canvas').css({ 'height': 'calc(100% - 50px)', 'width': 'calc(100% - 250px)' }); setTimeout(function() { $(window).trigger('resize'); }, 1000); $('#filterContainer').css('display', 'block'); } } }) Template.bubbles.onRendered(function() { var group = Template.instance().data; // console.log(Template.instance()); buildGroup(group); }); buildGroup = function(group) { buildBubbles(group); var students = group['data']; var filters = group['filters']; $('.bubble').each(function(i, bubble) { var item = group.settings.priorities[Session.get('color_index')]; var attr = students[i][item]; $(bubble).css({ 'background-color': Grouper.colors.get_color(item, attr, filters) }); }); var label = $('#labels').find(':selected').val(); $('.bubble .bubble_text').each(function(i, bubble) { $(bubble).html(students[i][label]); }); }
import tw, { styled } from 'twin.macro' function ThematicBreak(props) { return ( <Container {...props}> <Circle /> <Circle /> <Circle /> </Container> ) } export default styled(ThematicBreak)`` const Circle = styled.div` ${tw`bg-gray-500`} width: 12px; height: 12px; border-radius: 50%; ` const Container = styled.div` ${tw`space-x-4`} width: 100%; display: flex; justify-content: center; `
export const INIT_FIELD_CELLS = 'INIT_FIELD_CELLS'; export const INPUT_CHANGE = 'INPUT_CHANGE'; export const SUBMIT_PLAYER = 'SUBMIT_PLAYER'; export const SUBMIT_STATUS_TEXT = 'SUBMIT_STATUS_TEXT'; export const SET_START_CHIPS = 'SET_START_CHIPS'; export const ADD_NEIGHBORS = 'ADD_NEIGHBORS'; export const STEP_CHIP = 'STEP_CHIP'; export const REVERSE_CHIPS = 'REVERSE_CHIPS'; // export const AUTH_START = 'AUTH_START'; // export const AUTH_SUCCESS = 'AUTH_SUCCESS'; // export const AUTH_FAIL = 'AUTH_FAIL'; // export const AUTH_LOGOUT = 'AUTH_LOGOUT'; // export const SET_AUTH_REDIRECT_PATH = 'SET_AUTH_REDIRECT_PATH';
import React from 'react'; import './App.css'; import axios from 'axios'; class App extends React.Component { constructor() { super(); this.state = { input: "", newBook: [ { title: "", author: [], publisher: "", published: "", description: "", category: "", image: "", infoLink: "" } ], showing: false, } this.handleConvert = this.handleConvert.bind(this) } handleConvert() { axios.get(`https://www.googleapis.com/books/v1/volumes?q=${this.state.input}`) .then(res => { this.setState({ newBook: res.data.items, showing: true }) }) .catch(err => { console.log("Handle Convert Error", err); }) } handleChanges = e => { this.setState({ ...this.state.input, [e.target.name]: e.target.value }) } render() { return ( <div className="appContainer"> <h1>Novel Exploration</h1> <div className="inputBox"> <input type="string" name="input" value={this.state.input} onChange={this.handleChanges} placeholder="Enter book here" /> <button onClick={this.handleConvert}>Explore</button> </div> {this.state.showing ? <div className="bookGridContainer"> {this.state.newBook.map((book) => { if (book.volumeInfo?.authors !== undefined) { return ( <div className="bookGrid"> <a className="row" href={book.volumeInfo?.infoLink} target="_blank" rel="noreferrer"> <div className="bookTitle"> <strong>{book.volumeInfo?.title}</strong> </div> <img src={book.volumeInfo?.imageLinks?.thumbnail} alt="bookcover" /> <div className="sectional2"> <div className="bookAuthor"> <strong>Author:</strong> {book.volumeInfo?.authors[0]} </div> <div className="bookPublisher"> <strong>Publisher:</strong> {book.volumeInfo?.publisher} </div> <div className="bookPublished"> <strong>Published:</strong> {book.volumeInfo?.publishedDate} </div> <div className="bookCat"> <strong>Category:</strong> {book.volumeInfo?.categories[0]} </div> </div> </a> </div> ) } else { return ( <div className="bookGrid"> <a className="row" href={book.volumeInfo?.infoLink} target="_blank" rel="noreferrer"> <div className="bookTitle"> <strong>{book.volumeInfo?.title}</strong> </div> <img src={book.volumeInfo?.imageLinks?.thumbnail} alt="bookcover" /> <div className="sectional2"> <div className="bookPublisher"> <strong>Publisher:</strong> {book.volumeInfo?.publisher} </div> <div className="bookPublished"> <strong>Published:</strong> {book.volumeInfo?.publishedDate} </div> <div className="bookCat"> <strong>Category:</strong> {book.volumeInfo?.categories[0]} </div> </div> </a> </div> ) } })} </div> : <div></div> } </div> ) } } export default App;
import React, { Component } from "react"; import MenuLeft from "../../components/MenuLeft/MenuLeft"; import MenuMain from "../../components/MenuMain/MenuMain"; import MenuRightHeader from "../../components/MenuHeader/MenuRightHeader"; // import MenuRight from "../../components/MenuRight/MenuRight"; // import TaskForm from "../../components/MenuRight/TaskForm"; import routes from "../../router"; import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; // import axios from "axios"; class HomePage extends Component { constructor(props){ super(props); this.state = { tasks : [], keyword : '' } } showContentPage = routes => { var rs = null; if (routes.length > 0) { rs = routes.map((route, index) => { return ( <Route key={index} path={route.path} exact={route.exact} component={route.main} /> ); }); } return <Switch>{rs}</Switch>; }; onSearch =(keyword)=>{ this.setState({ keyword : keyword }); } render() { // var { tasks, keyword} = this.state; return <div className="wrapper"> <Router> <MenuLeft /> <MenuMain onSearch ={this.onSearch} /> <div className= "Menu-right-body"> < MenuRightHeader /> <Switch> {this.showContentPage(routes)} </Switch> </div> </Router> </div>; } } export default HomePage;
import api from 'axios'; export const ACCESS_TOKE = 'token'; const PROTOCOL = 'https'; const HOST_NAME = 'localhost'; const PORT = 44376; const PROD_PROTOCOL = 'https'; const PROD_HOST_NAME = ''; const HOME_URL = '/'; const getApiUrl = () => { let apiUrl = `${PROTOCOL}://${HOST_NAME}:${PORT}`; if (!process || !process.env || process.env.NODE_ENV !== 'development') { apiUrl = `${PROD_PROTOCOL}://${PROD_HOST_NAME}`; } return apiUrl; } export const logIn = (token, redirectUrl) => { localStorage.setItem(ACCESS_TOKE, token); redirectUrl && window.location.replace(redirectUrl); } export const logOut = (homeUrl = '/') => { localStorage.removeItem(ACCESS_TOKE); window.location.replace(homeUrl ? homeUrl : '/'); } export const API_URL = getApiUrl(); export const headerToken = token => { if (token === null) { throw new Error('Token can not be null'); } return { Authorization: `Bearer ${token}` }; } const getPrivateApi = () => { if (localStorage.getItem(ACCESS_TOKE) === null) { window.location.replace(HOME_URL); return api; } else { return api.create({ headers: headerToken(localStorage.getItem(ACCESS_TOKE)) }); } }; export const publicApi = api.create( { baseURL: API_URL } ); export const apiGet = async url => { return getPrivateApi() .get(`${API_URL}${url}`) .then(resp => resp, ({ response }) => { if (response.status === 401) { window.location.replace(HOME_URL); return response; } return Promise.reject(response); }); }; export const apiPost = async (url, body) => { return getPrivateApi() .post(`${API_URL}${url}`, body) .then(resp => resp, ({ response }) => { if (response.status === 401) { window.location.replace(HOME_URL); return response; } return Promise.reject(response); }); }; export const apiPut = async (url, body) => { return getPrivateApi() .put(`${API_URL}${url}`, body) .then(resp => resp, ({ response }) => { if (response.status === 401) { window.location.replace(HOME_URL); return response; } return Promise.reject(response); }); }; export const apiDelete = async url => { return getPrivateApi() .delete(`${API_URL}${url}`) .then(resp => resp, ({ response }) => { if (response.status === 401) { window.location.replace(HOME_URL); return response; } return Promise.reject(response); }); };
import parseUri from './parse-uri' function buildQueryString(keyValues) { const pairs = [] for (let key in keyValues) { const value = keyValues[key] pairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`) } return `?${pairs.join('&')}` } export default function buildUri(parts) { if (typeof parts === 'string') { parts = parseUri(parts) } else if (typeof parts !== 'object') { throw new Error('You need to pass an object or a string') } let uri = '' if (parts.protocol) { uri += `${parts.protocol}://` } if (parts.host) { if (parts.userInfo) { uri += `${parts.userInfo}@` } else if (parts.user) { let userInfo = parts.user if (parts.password) { userInfo += `:${parts.password}` } uri += `${userInfo}@` } uri += parts.host if (parts.port) { uri += `:${parts.port}` } } if (parts.path) { uri += parts.path if (parts.queryKey) { uri += buildQueryString(parts.queryKey) } else if (parts.query) { uri += `?${parts.query}` } } if (parts.anchor) { uri += `#${parts.anchor}` } return uri }
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @param {TreeNode} p * @param {TreeNode} q * @return {TreeNode} */ var lowestCommonAncestor = function (root, p, q) { if (!root) return null; if (!root.left && !root.right) return root.val; const pStack = [root]; // [3, 5] let seen = new Set(); let foundP = false; while (foundP === false) { const currentNode = pStack[pStack.length - 1]; if (currentNode === p) { foundP = true; } else { if (currentNode.right && !seen.has(currentNode.right)) { pStack.push(currentNode.right); seen.add(currentNode.right); } else { if (currentNode.left && !seen.has(currentNode.left)) { pStack.push(currentNode.left); seen.add(currentNode.left); } else { pStack.pop(); } } } } seen = new Set(); if (pStack.includes(q)) return q; const qStack = [root]; // [3, 5, 2, 4] let foundQ = false; while (foundQ === false) { const currentNode = qStack[qStack.length - 1]; if (currentNode === q) { foundQ = true; } else { if (currentNode.right && !seen.has(currentNode.right)) { qStack.push(currentNode.right); seen.add(currentNode.right); } else { if (currentNode.left && !seen.has(currentNode.left)) { qStack.push(currentNode.left); seen.add(currentNode.left); } else { qStack.pop(); } } } } while (qStack.length > 1 && pStack.length > 1) { if (qStack[qStack.length - 1] === pStack[pStack.length - 1]) return pStack[pStack.length - 1]; if (qStack.length > pStack.length) { qStack.pop(); } else { pStack.pop(); } } return root; }; function TreeNode(val) { this.val = val; this.left = this.right = null; } // [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4] const exampleTree = new TreeNode(3); exampleTree.right = new TreeNode(1); exampleTree.right.right = new TreeNode(8); exampleTree.right.left = new TreeNode(0); exampleTree.left = new TreeNode(5); exampleTree.left.left = new TreeNode(6); exampleTree.left.right = new TreeNode(2); exampleTree.left.right.right = new TreeNode(4); exampleTree.left.right.left = new TreeNode(7); console.log(lowestCommonAncestor(exampleTree, 5, 1)); console.log(lowestCommonAncestor(exampleTree, 5, 4)); // if (!root) return null; // if (!root.left && !root.right) return root.val; // const nodeStack = [root]; // let foundP = false; // let foundQ = false; // while (foundP === false && foundQ === false) { // const currentNode = nodeStack[nodeStack.length - 1]; // if (currentNode.val === p) { // foundP === true; // break; // } // if (currentNode.val === q) { // foundQ === true; // break; // } // if (currentNode.right) { // nodeStack.push(currentNode.right); // } // }
import React, { Component } from 'react'; import footerlogo from '../../images/logo-white.png'; export default class Footer extends React.Component { constructor (props) { super(props); this.state = {} } componentDidMount() {} render() { return ( <footer className="sec-block"> <div className="container-fluid text-center py-4"> <code>Designed, developed and broken a thousand times by Parth J. in the year 2019 A.D.</code> <img src={footerlogo} alt="PJ Codes logo" className="mt-5" /> </div> </footer> ) } }
'use strict'; let chai = require('chai'); chai.use(require('chai-as-promised')); chai.should(); describe('Reader', async function() { const { Reader } = require('../'); it('basics', async function() { let reader = new Reader(); reader.input.write(Buffer.from([1, 0, 0])); reader.input.write(Buffer.from([0, 0, 0])); reader.input.write(Buffer.from([0, 2, 3])); reader.input.write(Buffer.from([0])); reader.input.end(); await reader.readUInt32LE().should.eventually.equal(1); await reader.readInt32BE().should.eventually.equal(2); await reader.readFloatLE().should.rejectedWith(Reader.EndOfStream); }); });
import React, {Component} from 'react'; import logo from './logo.svg'; import Header from './components/Header' import './App.css'; export default class App extends Component { state = { user: {}, name: "", apellido: "", age: "" } getDataFromGitHub = () => { fetch('https://api.github.com/users/jsebasct') { } } componentDidMount() { this.getDataFromGitHub() } render() { return ( <div> <Header></Header> </div> ); } } // export default App;
import * as React from 'react' import { Container } from '../../../GlobalStyle' import { FaGithub } from '@react-icons/all-files/fa/FaGithub'; import { FaLinkedinIn } from '@react-icons/all-files/fa/FaLinkedinIn'; import LanguageSelection from '../LanguageSelection'; import { LinksBackground, LinkName, SocialLink, SocialLinks, StyledFooter } from './footer-style'; export default function Footer({lang}) { return ( <StyledFooter> <LanguageSelection lang={lang}/> <LinksBackground> <Container> <SocialLinks> <SocialLink href="https://www.linkedin.com" target="_blank" rel="noreferrer"> <FaLinkedinIn style={{fontSize: '40px'}}/> <LinkName>LinkedIn</LinkName> </SocialLink> <SocialLink href="https://www.github.com" target="_blank" rel="noreferrer"> <FaGithub style={{fontSize: '40px'}}/> <LinkName>GitHub</LinkName> </SocialLink> </SocialLinks> </Container> </LinksBackground> </StyledFooter> ) }
/** * Created by pl on 2017/9/12. */ // var mima2 = document.getElementById('inputpassword2').value(); // var tishi2 = document.getElementById('sure2'); function Display2() {document.getElementById('sure2').style.display = "block";}; function Display3() {document.getElementById('sure3').style.display = "block";}; function Confirm_pw() { var mima1 = document.getElementById('inputpassword1').value; var tishi2 = document.getElementById('sure2'); var len = mima1.length; //获取长度作为判断条件 var reg = new RegExp(/\w/);//匹配合法字符 if (reg.test(mima1)) { if (len>=8&&len<=16) { tishi2.innerHTML = "密码格式正确"; tishi2.style.color = "green"; } else { tishi2.style.color = "red"; tishi2.innerHTML = "密码长度要在8~16字符"; }; } else { tishi2.style.color = "red"; tishi2.innerHTML = "请输入合法字符"; }; }; function Confirm_cpw() { var mima1 = document.getElementById('inputpassword1').value; var mima2 = document.getElementById('inputpassword2').value; var tishi3 = document.getElementById('sure3'); var len = mima2.length; var reg = new RegExp(/\w/);//匹配合法字符 if (reg.test(mima1) && len >= 8 && len <= 16 && mima2 == mima1) { tishi3.innerHTML = "密码格式正确"; tishi3.style.color = "green"; } else { tishi3.innerHTML = "密码格式错误"; tishi3.style.color = "red" ; }; }; function tijiao() { var mima1 = document.getElementById('inputpassword1').value; var mima2 = document.getElementById('inputpassword2').value; var len2 = mima1.length; var len3 = mima2.length; var reg = new RegExp(/\w/);//匹配合法字符 if(len2>=8&&len2<=16&&reg.test(mima1) && reg.test(mima2) && len3 >= 8 && len3 <= 16 && mima2 == mima1) { alert('设置成功!'); var mima1 = $('#inputpassword1').val(); store.update('keyPassword',mima1); store.update('keyAA',true); console.log(mima1); window.location.href="../小米首页/index.html"; console.log(store.get('keyAA')) } else{ alert('请输入正确密码!'); }; };
import React from 'react'; import ReactDOM from 'react-dom'; import Login from './login.jsx'; import RegistrationPage from './RegistrationPage.jsx'; import RiderPage from './rider.jsx'; import DriverPage from './DriverPage.jsx'; class App extends React.Component { constructor() { super(); this.state = { page: 'login', username: '', rider: false, driver: false, startPoint: '', endPoint: '', departureTime: '00:00:00', car: '', seats: 0, schedule: [] // schedule will contain rideId#'s that refer to entries in the rides join table } } render() { return ( <div> {this.state.page === 'login' ? <Login /> : this.state.page === 'registration' ? <Registration /> : this.state.page === 'driver' ? <Driver /> : <Rider /> } </div> ) } } ReactDOM.render(<App />, document.getElementById('app'));
const express = require('express'); const app = express(); const fs = require('fs'); const path = require('path'); const mainRouterAr = require('./routes/mainAr'); const mainRouterEn = require('./routes/mainEn'); const mainRouter = require('./routes/main'); app.use(require('body-parser').urlencoded({ extended: false })); ////////////// View Engine : EJS ////////////// app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views')); ////////////// PUBLIC ////////////// app.use(express.static(path.join(__dirname, '../public'))); ////////////// Routers ////////////// app.use('/', mainRouter); app.use('/en', mainRouter); app.use('/ar', mainRouter); ////////////// Routers con POST ////////////// let newsletter = fs.readFileSync(path.join(__dirname ,'./database/newsletter.json'), 'utf8'); newsletter = JSON.parse(newsletter) console.log(newsletter) app.post('/', function (req, res){ newsletter.push(req.body); fs.writeFileSync(path.join(__dirname ,'./database/newsletter.json'), JSON.stringify(newsletter, null , 4) ); let saludo = req.body.name.split(' ')[0]; return res.send(`Muchas gracias ${saludo}, estaremos enviandote novedades pronto!!`); console.log(newsletter) }); ////////////// Puerto: 3000 ////////////// app.listen(process.env.PORT || 3000, function(){ console.log('Server running at http://localhost:3000/') }) module.exports = app
// redux reducer // interprits what to do with actions function counter(state, action){ if (state == null) { return { count: 0}; } var count = state.count; switch(action.type) { case "increase": return {count: ++count}; case "decrease": return {count: --count}; default: return state; } } export default counter;
var next = $(".next i"); var prev = $(".prev i"); // funzione click di destra, quindi next next.click(function(){ // assegno ad una variabile l'immagine attiva var immagineAttiva = $("img.active"); // rimuovo dall'immagine la classe active, // quindi l'immagine non è più attiva immagineAttiva.removeClass("active"); // assegno all'immagine fratello successiva di destra // (con .next) la classe active. immagineAttiva.next().addClass("active"); // faccio la stessa cosa per i tre puntini blu var cerchioAttivo = $("i.active"); cerchioAttivo.removeClass("active"); cerchioAttivo.next().addClass("active"); // usa if per far riniziare il ciclo delle immagini. if (immagineAttiva.hasClass("last")) { immagineAttiva = $("img.first") immagineAttiva.addClass("active"); } // stessa cosa per i puntini. if (cerchioAttivo.hasClass("last")) { cerchioAttivo = $("i.first") cerchioAttivo.addClass("active"); } }); // funzione click di sinistra, quindi prev prev.click(function(){ var immagineAttiva = $("img.active"); immagineAttiva.removeClass("active"); immagineAttiva.prev().addClass("active"); var cerchioAttivo = $("i.active"); cerchioAttivo.removeClass("active"); cerchioAttivo.prev().addClass("active"); if (immagineAttiva.hasClass("first")) { immagineAttiva = $("img.last") immagineAttiva.addClass("active"); } if (cerchioAttivo.hasClass("first")) { cerchioAttivo = $("i.last") cerchioAttivo.addClass("active"); } }); // BONUS: funzione al click del pallino andare avanti e indietro. var pallino = $(".nav > i"); var immagini = $("img").siblings().get(); //array delle immagini pallino.click(function(){ // trova indice elemento var pallinoIndex = $(this).index(); // seleziono il pallino corrente. var pallinoAttivo = $(this); // tolgo la classe e la riaggiungo ai pallini. pallino.removeClass("active"); pallinoAttivo.addClass("active") // tolgo la classe active all'immagine attiva del corrispettivo puntino. $("img.active").removeClass("active"); // aggiungo la classe acitve all'immagine attiva del corrispettivo puntino. $(immagini[pallinoIndex]).addClass("active"); }); // funzione per andare avanti e indietro con le arrow.
const list = require("prompt-list") exports.run = () => { const player = new list({ name: "Main Menu", message: "You see a minecraft crEEper. WHat do you DO??", choices: [ "run away liek a baby", "attacc", "nothing" ] }) player.ask((choice) => { if(choice.startsWith("run")) { console.log("You ran away like a baby. go cry to yo mama") } else if(choice === "attacc") { console.log("you attacc but you no protecc so you get bent. you a ded boi") } else { console.log("well you did nothing so you ded") } }) }
import React,{Component} from 'react' const textWraperStyle = { fontFamily: 'PingFangSC-Light', fontSize: '50px', color: '#FFFFFF', letterSpacing: 0, lineHeight: '40px', position: 'absolute', top: '41.8%', left: '15.5%' } const btnWraperStyle = { height:'44px', width:'140px', border:'2px solid #FFFFFF', borderRadius:'4px', fontFamily: 'PingFangSC-Regular', fontSize: '20px', color: '#FFFFFF', letterSpacing: 0, textAlign: 'center', lineHeight: '44px', position: 'absolute', top:'59.1%', left:'17.5%', zIndex:5000 } const TextWraper = ({text,style}) => { return ( <div style={Object.assign({},textWraperStyle,style)} > {text} </div> ) } class BtnWraper extends Component{ clickHandle () { } render () { return ( <div style={btnWraperStyle} onClick={this.clickHandle.bind(this)}> <a style={{display:'block',width:'100%',height:'100%'}}>了解详情</a> </div> ) } } class InnerWraper extends Component{ constructor(props){ super(props) } render () { return ( <div style={{height:'100%',position:'relative'}}> <TextWraper text={this.props.text} style={this.props.style} /> </div> ) } } export default InnerWraper
import React from "react"; import {connect} from "react-redux"; import Users from "../Users/Users" import reloaderPhoto from "../../Common/img/reload.gif" import userAvatar from "../../Common/img/auto_avatar.jpg" import {NavLink} from "react-router-dom"; import { deleteFollowThunkCreator, addFollowThunkCreator, getUsersThunkCreator } from "../../redux/reducer/Users-reducer"; class UsersContainerAPI extends React.Component { constructor(props) { super(props); } render() { let pageCount = Math.ceil(this.props.totalPageCount / this.props.pageSize) let pages = [] for (let i = 1; i <= pageCount; i++) { pages.push(i) } const newPages = pages.map(el => <span onClick={() => this.onPageChanged(el)}> {el === this.props.currentPage ? <strong>{el}</strong> : el} </span>) const newMas = this.props.users.users.map(el => <div> <span> <div> <NavLink to={`profile/${el.id}`}><img src={el.photos.small != null ? el.photos.small : userAvatar}/></NavLink> </div> <div> {el.followed ? <button disabled={this.props.followingInProgress.some(id => id===el.id)} onClick={() => { this.props.deleteFollowThunkCreator(el.id) }}>Unfollow</button> : <button disabled={this.props.followingInProgress.some(id => id===el.id)} onClick={() => { this.props.addFollowThunkCreator(el.id) }}>Follow</button>} </div> </span> <span> <span> <div>{el.name}</div> <div>{el.id}</div> <div>{el.status}</div> </span> </span> </div>) return (<> {this.props.isFetch ? null : <img src={reloaderPhoto}/>} <div> <Users newMas={newMas} newPages={newPages}/> </div> </> ) } componentDidMount() { this.props.getUsersThunkCreator(this.props.currentPage, this.props.pageSize) } onPageChanged = (pageNumber) => { this.props.getUsersThunkCreator(pageNumber, this.props.pageSize) } } const mapStateToProps = (state) => { return { users: state.usersPage, pageSize: state.usersPage.pageSize, totalPageCount: state.usersPage.totalUsersCount, currentPage: state.usersPage.currentPage, isFetch: state.usersPage.isFetch, followingInProgress: state.usersPage.followingInProgress } } const UserContainer = connect(mapStateToProps, { getUsersThunkCreator, deleteFollowThunkCreator, addFollowThunkCreator })(UsersContainerAPI) export default UserContainer
angular.module('myApp', ['ngMaterial', 'ngMessages', 'md.data.table']);
import React, { Component } from 'react'; import './App.less'; import { Button } from 'antd'; class App extends Component { // 路由跳转 toHome(){ this.props.history.push('/home') } render() { return ( <div className="App"> <h1>app</h1> <Button type="primary" onClick={() => {this.toHome()}}>app to home</Button> </div> ); } } export default App;
// @flow import React, { Component } from 'react'; export type ScreenViewType<T> = { viewComponent: typeof Component, initialProps: ?T, viewProps: ?T, to: (string, T) => void }; const ScreenView = <T>({ viewComponent: View, initialProps, viewProps, ...others }: ScreenViewType<T>) => <View {...others} {...initialProps} {...viewProps} />; export default ScreenView;
module.exports = { fetchAllFriends(userId, success){ $.ajax({ url: `api/users/${userId}/friends`, success(resp){ success(resp); } }); }, createFriend(data, success){ $.ajax({ url: `api/friends`, method: "POST", data: {friend: data}, success(resp){ success(resp); } }); }, updateFriend(id, success){ $.ajax({ url: `api/friends/${id}`, method: "PATCH", data: {friend: {status: "accepted"}}, success(resp){ success(resp); } }); }, removeFriend(id, success){ $.ajax({ url: `api/friends/${id}`, method: "DELETE", success(resp){ success(resp); } }); } };
/** * Copyright IBM Corp. 2021 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ export default function getCssPropertyForRule(rule, prop, sheets) { const slen = sheets.length; for (let i = 0; i < slen; i++) { let rules; try { rules = sheets[i].cssRules; } catch (e) { continue; } const rlen = rules.length; for (let j = 0; j < rlen; j++) { if (rules[j].selectorText === rule) { return rules[j].style[prop]; } } } }
const modifyNewComment = (contact_id, comment_id, value) => { const CommentContainer = document.querySelector(`.comments-${contact_id}`); const tempContainer = document.createElement("div"); tempContainer.className = `comment comment-${comment_id}`; /* comment wrapper */ const commentWrapper = document.createElement("div"); commentWrapper.className = 'comment__wrapper'; commentWrapper.innerHTML = `<div class="comment__item">` + `<div class="comment__writer-img">` + `<img src="${userImage}">` + `</div>` + `<div class="comment__content">` + `<div class="comment__top-info">` + `<span class="comment__writer">${writer}</span>` + `<span class="comment__date">` + "방금 전" + `</span>` + `</div>` + `<span class="comment__text">${value}</span>` + `</div>` + `</div>` + `<input class="comment__delete-btn comment-btn" onclick="onClickDeleteComment(${comment_id})" type="submit" value="삭제">`; CommentContainer.appendChild(tempContainer); tempContainer.appendChild(commentWrapper); /* 가장 위에 최신 댓글 삽입 */ CommentContainer.insertBefore(tempContainer, CommentContainer.firstChild); } const onClickNewComment = async (id) => { try { const url = `/contact/comment_create/`; const value = document.querySelector(`.createComment-${id} .comment__value`); const value_text = value.value const { data } = await axios.post(url, { id, value: value_text }) if (data.login_required === true) { alert('로그인 후 이용 가능합니다.'); } else { modifyNewComment(id, data.comment_id, data.value); const cmt = document.querySelector('.comment__value') cmt.value = '' } } catch (error) { console.log(error) } } const modifyDeleteComment = (comment_id) => { const targetCommentContainer = document.querySelector(`.comment-${comment_id}`); targetCommentContainer.remove(); } const onClickDeleteComment = async (commentId) => { if (confirm("댓글을 삭제하시겠습니까?")) { const url = `/contact/comment_delete/`; const { data } = await axios.post(url, { commentId }) modifyDeleteComment(data.comment_id); } else { return; } }
Meteor.publish("folios",function(params){ return Folios.find(params); }); Meteor.publish("foliosPanel",function(params){ return Folios.find(params, {fields: { _id:1 ,folio:1 ,nombre:1 ,fecha:1 ,zona_id:1 ,plan:1 ,prioridad:1 ,analista_id:1 ,verificador_id:1 ,domicilio:1 ,telefono:1 ,ubicacion:1 ,razon:1 ,verificacionRazon:1 ,verificacionEstatus:1 ,folioEstatus:1 ,referencia:1 ,EsLlamado:1 }}); }); Meteor.publish("buscarFolio",function(options){ let selector = { folio: { '$regex' : '.*' + options.where.folio || '' + '.*', '$options' : 'i' } } return Folios.find(selector, {fields: { _id:1 ,folio:1 ,nombre:1 ,fecha:1 ,zona_id:1 ,plan:1 ,prioridad:1 ,analista_id:1 ,verificador_id:1 ,domicilio:1 ,telefono:1 ,ubicacion:1 ,razon:1 ,verificacionRazon:1 ,verificacionEstatus:1 ,folioEstatus:1 ,referencia:1 }},options.options); }); Meteor.publish("buscarNombre",function(options){ let selector = { nombre: { '$regex' : '.*' + options.where.nombre || '' + '.*', '$options' : 'i' } } return Folios.find(selector, {fields: { _id:1 ,folio:1 ,nombre:1 ,fecha:1 ,zona_id:1 ,plan:1 ,prioridad:1 ,analista_id:1 ,verificador_id:1 ,domicilio:1 ,telefono:1 ,ubicacion:1 ,razon:1 ,verificacionRazon:1 ,verificacionEstatus:1 ,folioEstatus:1 ,referencia:1 }},options.options); });
import { getSchema } from 'Test/factories' import createViewProps from '../ViewProps' describe('ViewProps', () => { test('createViewProps', () => { const schema = getSchema() const props = createViewProps({ schema, columns: [{ name: 'firstName', caption: 'Name' }, 'age'], id: 1 }) expect(props.schema).toBe(schema) expect(props._isViewProps).toBe(true) expect(props.columns).toHaveLength(1) expect(props.columns[0].field.name).toBe('firstName') expect(props.columns[0].caption).toBe('Name') expect(props.recordDataSource.modelId).toBe('1') }) })
import Image from 'next/image' import Link from 'next/link' import HeadMetadata from '../components/HeadMetadata' function about() { return (<> <HeadMetadata title='About me (cent) | Cent Blog' metaDescription="About me (cent)" /> <main className="parent"> <div className="left"></div> <div className="middle posts"> <center><h2>Paul Innocent David (cent)</h2></center> <div className="centImg"> <Image src="/cent.jpg" alt="Paul Innocnet David (cent)" width="300px" height="350px" /> </div> <br /> <h4>Hi, I&#39;m Paul Innocent.</h4> <p>I help people understand software development. I love pets too and tech stuff</p> <p>I&#39;m a full stack software developer. I write about modern Node.js, JavaScript, and development.</p> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Saepe consequatur tempora, deserunt reprehenderit minus rerum tempore dicta commodi quod nostrum.</p> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Fugiat blanditiis voluptate mollitia nulla culpa deserunt adipisci? Ullam praesentium distinctio voluptatem corporis, ratione soluta architecto alias exercitationem pariatur, odit quis nisi rem dolores amet obcaecati error ex eius dolorem, assumenda ipsum.</p> <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Illo, quas possimus eligendi a doloribus in aperiam asperiores velit architecto ipsum, labore doloremque! Beatae hic nulla cum, natus omnis nobis voluptate fugit debitis mollitia voluptatibus quisquam impedit! Mollitia rerum aliquid reiciendis quae, tenetur explicabo repudiandae, sapiente consequatur eaque facere similique officiis omnis. Aliquam magnam qui excepturi.</p> <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Similique sed mollitia provident facere exercitationem fugiat.</p> <div>social handles & tel</div> <center><Link href="/contact"><a><button className="btnSolid">contact me</button></a></Link></center> </div> </main> <br /> <br /> </>) } export default about
var express = require("express"), app = express(), port = process.env.PORT || 3000, bodyParser = require('body-parser'), handlebars = require("express-handlebars"), mysql = require('mysql'); var db = require("./models"); app.engine('handlebars', handlebars({defaultLayout: 'main'})); app.set('view engine', 'handlebars'); var routing = require("./routes/html")(app); db.sequelize.sync({}) .then(function () { app.listen(port, function () { console.log("App is starting at port", port); }); }) .catch(function (err) { console.log(err); });
//return const sum = (a = 3) => a + 5 sum(5) arr.map( el => el + 2 ) //ciało funkcji rozbudowane (a = 3) => { return a + 5 } //zwraca obiekt (a = ()=>{}) => ({ value : a }) function(a = 3){ return { value: a} }
define(['backbone', 'marionette'], function(Backbone, Marionette) { return Backbone.Marionette.AppRouter.extend({ initialize: function(options) { console.log("Wavity login router initialize called"); }, // all routes need to be defined in controller appRoutes: { '': 'login' } }); }); // EOF
import { BASE_PATH_FRAGMENT, PROPERTY_ID_PATH_FRAGMENT } from '../constants'; export const RESOURCE_NAME = 'roomtype'; export const PATHNAME_TEMPLATE = `${BASE_PATH_FRAGMENT}/${RESOURCE_NAME}${PROPERTY_ID_PATH_FRAGMENT}`;
import React, { Component } from 'react' import importcss from 'importcss' @importcss(require('./Layout.global.css')) export default class Layout extends Component { constructor() { super() } render() { return <div styleName="layout" className="app-inner2"> {this.props.children} </div> } }
_.isDate = function(value){ return value && typeof value === 'object' && toString.call(value) === '[object Date]'; }
import React,{Component} from 'react' import HomeModal from '../../components/home' import {toggleQRcode,toggleShopCode} from '../../actions/navbar' import {connect} from 'react-redux' class Home extends Component{ render(){ const {isQRcode,isShopCode,dispatch} = this.props return( <HomeModal qrcode={()=>dispatch(toggleQRcode(!isQRcode))} shopcode={()=>dispatch(toggleShopCode(!isShopCode))} /> ) } } const mapStateToProps = state => { const { isQRcode,isShopCode } = state.navbarReducer return { isQRcode,isShopCode } } export default connect(mapStateToProps)(Home);
import React from "react"; import Dropdown from "./Dropdown"; import AuthComponent from "./AuthComponent"; import Logo from "./logo.png"; function NavBar(props) { return ( <nav className="navbar fixed-top navbar-light"> <div> <div id="navHeader" className="navbar-brand" onClick={props.onClick}> <img src={Logo} height="30" width="30" className="d-inline-block align-top" alt="" ></img> <span className="desktop">Random recipe generator</span> </div> </div> <div className="navbar-button-block"> {props.state.loaded ? ( <div className="navbar-button-block"> <p id="hitabutton" className="desktop"> Hit a button to get one of the delicious recipes </p> <Dropdown handleClick={props.handleClick} classNameButton="btn btn-primary btn-sm dropdown-toggle" direction="dropdown" /> </div> ) : null} <AuthComponent onAccountClick={props.onAccountClick} /> </div> </nav> ); } export default NavBar;
import { SET_CURRENT_USER, GET_ERRORS, GET_ASSOCIATE_ID, ADD_ASSOCIATE_OBJECT, GET_DESTINATION, LOGOUT_USER } from '../constants'; import axios from "axios"; import setAuthToken from "../utils/setAuthToken"; import jwt_decode from "jwt-decode"; export const registerUser = (userData, history, userType) => dispatch => { axios .post("http://localhost:5000/api/users/register", userData) .then(res => history.push(`/${userType}/login`)) .catch(err => dispatch({ type: GET_ERRORS, payload: err.response.data }) ); }; export const loginUser = userData => dispatch => { axios .post("http://localhost:5000/api/users/login", userData) .then(res => { const { token } = res.data; localStorage.setItem("jwtToken", token); setAuthToken(token); const decoded = jwt_decode(token); dispatch(setCurrentUser(decoded)) }) .catch(err => dispatch({ type: GET_ERRORS, payload: err.response.data }) ); }; export const setCurrentUser = decoded => { return { type: SET_CURRENT_USER, payload: decoded } }; export const logout = () => dispatch => { dispatch({ type: LOGOUT_USER, payload: {} }) } export const logoutUser = () => dispatch => { localStorage.removeItem("jwtToken"); setAuthToken(false); dispatch(setCurrentUser({})); logout(); }; export const addAssociate = (userId, newUser) => async dispatch => { console.log(newUser); await axios.put(`http://localhost:5000/api/users/${userId}`, newUser) .then(res => { const { token } = res.data; localStorage.setItem("jwtToken", token); setAuthToken(token); const decoded = jwt_decode(token); dispatch(setCurrentUser(decoded)) }) .catch(err => dispatch({ type: GET_ERRORS, payload: err.response.data }) ); } export const changeFunds = (currentId, newCurrent) => async dispatch => { console.log(newCurrent.id); await axios.put(`http://localhost:5000/api/users/${currentId}`, newCurrent) .then(res => { const { token } = res.data; localStorage.setItem("jwtToken", token); setAuthToken(token); const decoded = jwt_decode(token); dispatch(setCurrentUser(decoded)) }) .catch(err => dispatch({ type: GET_ERRORS, payload: err.response.data }) ); } export const sendFunds = (currentUser, acceptingUser) => async dispatch => { console.log('hello'); console.log(acceptingUser.funds); console.log(currentUser.funds); await axios.put(`http://localhost:5000/api/users/${acceptingUser._id}`, acceptingUser) changeFunds(currentUser._id, currentUser); } export const getDestinationUser = (destinationId, fundsToSend) => async dispatch => { console.log('get destination'); await axios.get(`http://localhost:5000/api/users/${destinationId}`) .then(res => { let newUser = {...res.data.data, funds: res.funds + fundsToSend} dispatch({ type: GET_DESTINATION, payload: newUser , funds: fundsToSend}) }) .catch(err => { dispatch({ type: GET_ERRORS, payload: err.response.data }) }) } export const setAssociateObject = (associateId) => async dispatch => { await axios.get(`http://localhost:5000/api/users/${associateId}`) .then(res => { console.log(res.data.data) dispatch({ type: GET_ASSOCIATE_ID, payload: res.data.data }) }) .catch(err => { dispatch({ type: GET_ERRORS, payload: err.response.data }) }) } export const addAssociateObject = (associateId) => async dispatch => { await axios.get(`http://localhost:5000/api/users/${associateId}`) .then(res => { console.log(res.data.data) dispatch({ type: ADD_ASSOCIATE_OBJECT, payload: res.data.data }) }) .catch(err => { dispatch({ type: GET_ERRORS, payload: err.response.data }) }) }
import React, { useState, useContext } from "react"; import { View, Text, StyleSheet } from "react-native"; import { Input, Button } from "react-native-elements"; import AuthContext from "../context/authContext"; const AuthForm = (props) => { const { buttonTitle, onPress } = props; const { data } = useContext(AuthContext); const { isAuthenticating, errorMessage } = data; const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const onChangeEmailHandler = (newEmail) => { // validation setEmail(newEmail); }; const onChangePasswordHandler = (newPassword) => { // validation setPassword(newPassword); }; return ( <View style={styles.container}> <Input label="Email" placeholder="email" autoCapitalize="none" autoCorrect={false} value={email} onChangeText={onChangeEmailHandler} errorMessage={errorMessage} /> <Input label="Password" placeholder="password" autoCorrect={false} autoCapitalize="none" secureTextEntry value={password} onChangeText={onChangePasswordHandler} /> <Button title={buttonTitle} onPress={() => { onPress(email, password); }} disabled={email.length === 0 || password.length === 0} raised loading={isAuthenticating} /> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: "center", borderColor: "red", borderWidth: 1, padding: 10, }, }); export default AuthForm;
// Author of the project - SAYANI SASHA // ---------- Урок № 6 - Преобразование типов ---------- // В JS есть автоматическая конвертация типов, что означает если интерпретатор ожидает увидеть в каком-то месте программы значение определенного типа, то любое значение будет приведено к этому типу. // Например если одним из операндов оператора + является строка то другой операнд также преобразуется в строку console.log(5+"5"); console.log(typeof(5+"5")); // Оператор умножения будет пытаться преобразовать любые значения в числа console.log("5"*"6"); console.log(typeof("5"*"6")); // если преобразование выполнить невозможно то получим Nan console.log("5"*"hi"); console.log(typeof("5"*"hi")); // Автоматическое преобразование типов происходит также когда используется оператор сравнения равенства console.log("5" == 5); console.log(typeof("5" == 5)); // И по этому мы можем сравнивать значение разных типов console.log(""); // ------ Явные преобразования(Explicit Conversions) // При помощи конструктора number можно перевести любое значение в числовой тип console.log(Number("444")); console.log(typeof(Number("444"))); // При помощи конструктора string можно перевести любое значение в строковый тип console.log(String("6666")); console.log(typeof(String("6666"))); // Для перевода в булевой тип используется конструктор Boolean console.log(Boolean(1)); console.log(Boolean(0)); console.log(""); // Есть более короткие записи преобразования типов // преобразования числа в логический тип console.log(!!6); console.log(!!0); // !!- сокращенная запись , преобразования числа в логический тип // преобразования значения в строку console.log(333+""); console.log(typeof(333+"")); // преобразования значения в число , можно использовать унарный + console.log(+"334"); console.log(typeof(+"334")); // Еще 1 метод преобразования значения строку toSting // var number = 122; // console.log(typeof number.toSting()); console.log(""); // Также мы можем преобразовать число в строку с помощью parseInt and parseFloat console.log(typeof(parseInt("3 px"))); // также строка может содержать другие символы какие будут просто игнорироваться console.log(typeof(parseInt("3.332"))); console.log(""); // Какие значение можно получить в результате различных преобразований console.log(String(Infinity)); //Infinity console.log(typeof(String(Infinity))); //String console.log(String(NaN)); //NAN console.log(typeof(String(NaN))); //String console.log(+"");//0 console.log(""); // Преобразование простых значений в обьекты // когда интерпретатор ожидает увидеть где-то в программе обьект , но видет там обычное значение то он просто преобразует это знавчение в обьект используя его обьект обвертку var n =5; console.log(n.value); // мы обратились к несуществующему свойству объекту value в результате чего получили undefined // Когда мы обращемся к не существующему свойствам обьекту выдаст undefined // по этому то что мы получили undefined говорит о том что переменная n была пероразована в обьект
import { FullScreen, useFullScreenHandle } from "react-full-screen"; import { Rnd } from "react-rnd"; import { AiOutlineClose } from "react-icons/ai"; import { BiWindow, BiWindows, BiFullscreen } from "react-icons/bi"; import { FaRegWindowMinimize } from "react-icons/fa"; import { TiInfoLarge } from "react-icons/ti"; import { Content, Titlebar, Buttons, Frame } from "../styles/Window.styles"; import useWindow from "../hooks/useWindow"; import AppInfo from "./AppInfo"; export default function Window({ id }) { const { rndRef, rndStart, resizeStop, dragStop, height, width, x, y, frameRef, zIndex, isMaximized, maximize, isMinimized, minimize, close, showInfo, focus, toggleShowInfo, title, url, } = useWindow(id); const fullscreenHandler = useFullScreenHandle(); return ( <Rnd ref={rndRef} size={{ width, height }} position={{ x, y }} style={{ display: isMinimized ? "none" : "block", background: "var(--primary-dark)", backdropFilter: "blur(5px)", zIndex, }} onDragStart={rndStart} onDragStop={dragStop} onResizeStart={rndStart} onResizeStop={resizeStop} disableDragging={isMaximized} enableResizing={!isMaximized} bounds="#boundary" minWidth={400} cancel="#frame, .window-menu-btn" > <Content> {!fullscreenHandler.active && ( <Titlebar> <span title={title}>{title}</span> <Buttons> <button title="How This Was Made" id="info" className="window-menu-btn" onClick={toggleShowInfo} > <TiInfoLarge /> </button> <button title="Fullscreen" className="window-menu-btn" onClick={() => { focus(); fullscreenHandler.enter(); }} > <BiFullscreen /> </button> <button title="Minimize" className="window-menu-btn" onClick={minimize}> <FaRegWindowMinimize /> </button> <button title="Maximize" className="window-menu-btn" onClick={maximize}> {isMaximized ? <BiWindows /> : <BiWindow />} </button> <button title="Close" className="window-menu-btn" onClick={close}> <AiOutlineClose /> </button> </Buttons> </Titlebar> )} <FullScreen handle={fullscreenHandler}> {showInfo && <AppInfo id={id} />} <Frame showInfo={showInfo} id="frame" ref={frameRef} onClick={focus}> {url ? ( <iframe title={id} src={url} frameBorder="0" allowFullScreen></iframe> ) : ( <h1>Native App</h1> )} </Frame> </FullScreen> </Content> </Rnd> ); }
/** * A mini calendar allowing the user to select a single date. */ P.views.calendar.Mini = P.views.Item.extend({ templateId: 'calendar.mini.layout', className: 'v-miniCal', events: { 'click .js-day': 'select', 'click .js-month-after': 'monthAfter', 'click .js-month-before': 'monthBefore', 'click .js-today': 'today' }, initialize: function(options) { options = options || {}; this.collection = new Backbone.Collection(); this.cal = new P.models.Calendar(); if (options.selectedDate) { this.selectedDate = options.selectedDate; } this.moment = moment(); if (options.moment) { this.moment = options.moment; } if (options.targetEl) { this.$text = options.targetEl; options.targetEl.on('change', this.onChange.bind(this)); } }, /** * Reset selected dates. */ clear: function() { this.selectedDate = null; this.render(); }, /** * Test if date is selected by calendar. */ isSelected: function(isodate) { return isodate === this.selectedDate; }, /** * Navigate to the next month. */ monthAfter: function() { this.moment.add(1, 'months'); this.render(); }, /** * Navigate to the previous month. */ monthBefore: function() { this.moment.add(-1, 'months'); this.render(); }, onChange: function(event) { var date = this.$text.val(), err = P.helpers.Time.validateDate(date); if (err) { return; } this.setDate(date); }, /** * Event handler when a day is clicked. */ select: function(event) { var date = $(event.currentTarget).data('date'); this.setDate(date); this.$el.trigger('select', [date]); }, serializeData: function() { var start = this.moment.date(1), weeks = this.cal.loadWeeks(start.clone(), 6), displayWeeks = [], dw, iso, i, j, d; for (i = 0; i < weeks.length; i++) { dw = []; for (j = 0; j < weeks[i].length; j++) { d = weeks[i][j].moment; iso = d.format('YYYY-MM-DD'); dw.push({ otherMonth: !d.isSame(start, 'month'), day: d.format('D'), iso: iso, isToday: d.isSame(new Date(), 'day'), isSelected: this.isSelected(iso) }); } displayWeeks.push(dw); } return { month: this.moment.format('MMMM'), year: this.moment.format('YYYY'), isSameMonth: this.moment.isSame(new Date(), 'month'), weekdays: this.cal.weekdays('ddd'), weeks: displayWeeks }; }, setDate: function(date) { var selectedClass = 'calMini-selectedCell', $target = this.$('.js-day[data-date="' + date + '"]'); if ($target.length === 0) { console.warn('Can not set date', date); } this.selectedDate = date; this.$('.' + selectedClass).removeClass(selectedClass); $target.addClass(selectedClass); }, /** * Navigate the calendar to the current month. */ today: function() { this.moment = moment(); this.render(); }, /** * Unselect the date. */ unselect: function(date) { if (this.selectedDate === date) { this.selectedDate = null; this.render(); } } });
//NPM Packages const request = require( "request" ); const forecast = ( lat, long, callback ) => { const url = `https://api.darksky.net/forecast/5dbb8aceac436233245ecf1a4aa27213/${ lat }, ${ long }`; request( { url, json: true }, ( err, res ) => { const { daily, currently, code } = res.body; if( err ) { callback( `Unable to connect to the internet. Double check your internet connection.` ); } else if( code === 400 || code === 404 ) { callback( `Unable to find the location provided. Please double check your spelling or try another location.` ); } else { callback( "No error", `${ daily.data[0].summary } It is currently, ${ currently.temperature }℉ , Moreover, there is a ${ currently.humidity }% chance of rain today.` ); } }); }; module.exports = forecast;
var word = (prompt("Enter a message, four letters or longer")); while (word.length < 4) word = (prompt("Try again.")); alert("You entered: " + word); alert(word + " has " + word.length + " characters"); alert("The third character is \'" + word.charAt(2) + "\'"); alert(word + " to uppercase is: " + word.toUpperCase(word)); alert(word + " to lowercase is: " + word.toLowerCase(word)); alert("Here is " + word + " in a sentence"); alert("subword: " + word.substring(1,4));
"use strict"; import { getQueryVar } from "./getQueryVar.js"; let problemCount; window.onload = function () { problemCount = Number(getQueryVar("problemCount")); const problemNum = Number(getQueryVar("problem")); RefreshActionBar(problemNum); document.getElementById("title").innerHTML = getQueryVar("title"); document.getElementById("problem").src = getQueryVar("baseUrl") + "/problem" + problemNum + ".html"; }; function RefreshActionBar(problemNum) { const actionButtonArray = document.getElementsByClassName("action-button"); if (1 == problemNum) { actionButtonArray[0].classList.remove("action-button-active"); actionButtonArray[1].classList.remove("action-button-active"); actionButtonArray[2].classList.add("action-button-active"); actionButtonArray[3].classList.add("action-button-active"); } else if (problemCount == problemNum) { actionButtonArray[0].classList.add("action-button-active"); actionButtonArray[1].classList.add("action-button-active"); actionButtonArray[2].classList.remove("action-button-active"); actionButtonArray[3].classList.remove("action-button-active"); } else { actionButtonArray[0].classList.add("action-button-active"); actionButtonArray[1].classList.add("action-button-active"); actionButtonArray[2].classList.add("action-button-active"); actionButtonArray[3].classList.add("action-button-active"); } } window.ProblemSelect = function (problem) { const elemProblem = document.getElementById("problem"); const problemSrcSplit = elemProblem.contentWindow.location.href.split("/"); const pageSplit = problemSrcSplit[problemSrcSplit.length - 1].split("."); let problemNum = Number(pageSplit[0].replace(/problem/, "")); if ( ("last" == problem && problemNum == problemCount) || ("first" == problem && 1 == problemNum) ) return; if (problem.substring) { if ("next" == problem) problemNum++; else if ("prev" == problem) problemNum--; else if ("first" == problem) problemNum = 1; else if ("last" == problem) problemNum = problemCount; } else if (problem.toFixed) { problemNum = Number(problem); } if (1 > problemNum || problemCount < problemNum) return; RefreshActionBar(problemNum); const url = problemSrcSplit[problemSrcSplit.length - 3] + "/" + problemSrcSplit[problemSrcSplit.length - 2] + "/" + "problem" + problemNum + "." + pageSplit[1]; elemProblem.contentWindow.location.replace(url); };
var Splash = function () {}; Splash.prototype = { preload: function(){ }, create: function(){ console.log('Hi, this is the splash screen'); }, update: function(){ } };
const prices = { pepperonnis: 1, mushrooms: 1, greenPepper: 1, whiteSauce: 3, glutenFreeCrust: 5 } /*******************************/ /********* PEPPERONNI *********/ /*******************************/ const pepperonniButton = document.querySelector('.btn-pepperonni') const pepperonnis = document.querySelectorAll('.pep') pepperonniButton.onclick = () => { // Recorre el array de pepperonnis y "togglea" la clase hide pepperonnis.forEach(pepperonni => { pepperonni.classList.toggle('hide') }) // Togglea la clase active del botón, si incluye o no el ingrediente pepperonniButton.classList.toggle('active') // Muestra u oculta el precio si el botón tiene la clase active showPrice(pepperonniPrice, pepperonniButton, pepperonnis) updatePrices() } /*******************************/ /********* GREEN PEPPER *********/ /*******************************/ const greenPepperButton = document.querySelector('.btn-green-peppers') const greenPeppers = document.querySelectorAll('.green-pepper') greenPepperButton.onclick = () => { // Recorre el array de green peppers y "togglea" la clase hide greenPeppers.forEach(greenPepper => { greenPepper.classList.toggle('hide') }) // Togglea la clase active del botón, si incluye o no el ingrediente greenPepperButton.classList.toggle('active') // Muestra u oculta el precio si el botón tiene la clase active showPrice(greenPepperPrice, greenPepperButton, greenPepper) updatePrices() } /*******************************/ /********* MUSHROOMS *********/ /*******************************/ const mushroomButton = document.querySelector('.btn-mushrooms') const mushrooms = document.querySelectorAll('.mushroom') mushroomButton.onclick = () => { // Recorre el array de mushrooms y "togglea" la clase hide mushrooms.forEach(mushroom => { mushroom.classList.toggle('hide') }) // Togglea la clase active del botón, si incluye o no el ingrediente mushroomButton.classList.toggle('active') // Muestra u oculta el precio si el botón tiene la clase active showPrice(mushroomPrice, mushroomButton, mushrooms) updatePrices() } /*******************************/ /*********** SAUCE ***********/ /*******************************/ const sauceElement = document.querySelector('.sauce') const sauceButton = document.querySelector('.btn-sauce') sauceElement.classList.remove('sauce-white') // Removes sauce when document loads sauceButton.classList.remove('active') // Since the sauce white option is not selected by default, the button is also not active sauceButton.onclick = () => { // Togglea la clase sauce-white sauceElement.classList.toggle('sauce-white') // Togglea la clase active del botón, si incluye o no el ingrediente sauceButton.classList.toggle('active') // Muestra u oculta el precio si el botón tiene la clase active showPrice(whiteSaucePrice, sauceButton, whiteSauce) updatePrices() } /*******************************/ /*********** GLUTEN ***********/ /*******************************/ const glutenElement = document.querySelector('.crust-gluten-free') const glutenButton = document.querySelector('.btn-crust') glutenElement.classList.remove('crust-gluten-free') // Removes gluten when document loads glutenButton.classList.remove('active') // Since the gluten-free option is not selected by default, the button is also not active glutenButton.onclick = () => { // Togglea la clase crust-gluten-free glutenElement.classList.toggle('crust-gluten-free') // Togglea la clase active del botón, si incluye o no el ingrediente glutenButton.classList.toggle('active') // Muestra u oculta el precio si el botón tiene la clase active showPrice(glutenFreePrice, glutenButton, glutenFreeCrust) updatePrices() } /*******************************/ /************ PRICE ************/ /*******************************/ // Getting all the prices const pepperonniPrice = document.querySelector('#pepperoni-price') const mushroomPrice = document.querySelector('#mushroom-price') const greenPepperPrice = document.querySelector('#pepper-price') const whiteSaucePrice = document.querySelector('#white-sauce-price') const glutenFreePrice = document.querySelector('#gluten-free-price') // If the ingredient button is active, the pizza includes the ingredient // If the pizza includes the ingredient, it must show the price for that ingredient const showPrice = (ingredientPrice, ingredientButton, ingredient) => { if (ingredientButton.classList.contains('active')) { ingredientPrice.classList.remove('hide') } else { ingredientPrice.classList.add('hide') prices.ingredient = 0 } } showPrice(pepperonniPrice, pepperonniButton) showPrice(mushroomPrice, mushroomButton) showPrice(greenPepperPrice, greenPepperButton) showPrice(whiteSaucePrice, sauceButton) showPrice(glutenFreePrice, glutenButton) /*********************************/ /******* UPDATING THE PRICE *******/ /*********************************/ const totalPrice = document.querySelector('#total-price') totalPrice.innerHTML = 'Aprende algo dinero'
import React, { useContext, useEffect } from 'react'; import ListItem from './ListItem'; import { globalState } from '../context/GlobalState'; import { v4 as uuidv4 } from 'uuid'; const History = () => { const globalstate = useContext(globalState); useEffect(() => { globalstate.getInitialData(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return ( <div className="history"> <h3>History</h3> <ul className="transaction-list"> {globalstate.transactions.map((transaction) => ( <ListItem key={transaction._id} transactionDetails={transaction} /> ))} </ul> </div> ) } export default History;
import React from 'react'; import {StyleSheet, Text, View, FlatList} from 'react-native'; import {ms} from 'react-native-size-matters'; import {connect} from 'react-redux'; import WeatherCard from '../Components/WeatherCard'; import Spinner from 'react-native-loading-spinner-overlay'; function Weather(props) { // const weatherArrays = props.ListData.map(x => x.weather.map(y => y.description)) renderItem = ({item}) => { return ( <WeatherCard date={item.dt} icName={item.weather[0].icon} metric={item.main.temp} weather={item.weather[0].description} /> ); }; console.log('okwdoko', props.ListData[0].weather[0].icon); return ( <View style={styles.cover}> <FlatList data={props.ListData} keyExtractor={item => item.dt} renderItem={renderItem} showsVerticalScrollIndicator={false} /> <Spinner visible={props.isLoading} textContent={"Loading"} textStyle={{ color: "white" }} /> </View> ); } const styles = StyleSheet.create({ cover: { backgroundColor: '#ffde03', paddingVertical: ms(20), paddingHorizontal: ms(20), width: '100%', height: '100%', }, }); const mapStateToProps = state => ({ ListData: state.dataReducer.ListData, isLoading: state.dataReducer.isLoading, }); const mapDispatchToProps = {}; export default connect(mapStateToProps, mapDispatchToProps)(Weather);
require('dotenv').config(); const express = require('express'); const router = express.Router(); const moment = require('moment') const mapbox = require('@mapbox/mapbox-sdk/services/geocoding'); const axios = require('axios'); const geocodingClient = mapbox({ accessToken: process.env.MAPBOX_PUBLIC_KEY }) router.get('/', (req, res) => { res.json({type: 'success', message: 'You access the protected API route'}); }); // get /api/address?address= query router.get('/address', (req, res) => { let address = req.query.address; console.log('address is ', address); geocodingClient.forwardGeocode({ query: address }).send().then(function(response) { let result = { center: response.body.features[0].center, neighborhood: response.body.features[0].context[0].text, zipcode: response.body.features[0].context[1].text, city: response.body.features[0].context[2].text, state: response.body.features[0].context[3].short_code.substring(3) } console.log(result); res.json(result) }) }) // get /api/disasters?state=zipcode= router.get('/disasters', (req, res) => { let startdate = moment().subtract(10, 'years'); axios.get(`https://www.fema.gov/api/open/v1/DisasterDeclarationsSummaries?$filter=state%20eq%20%27${req.query.state}%27%20and%20declarationDate%20gt%20%27${startdate}%27`).then(response => { let disasters = response.data.DisasterDeclarationsSummaries; // console.log(disasters); let disastersSummary = { total: 0, score: 0, unit: 'instances', rank: '', details: { Fire: 0, Flood: 0, 'Landslide': 0, Earthquake: 0, Tornado: 0, Hurricane: 0 } }; disasters.forEach(disaster => { if (disaster.placeCode === req.query.zipcode) { console.log(disaster.incidentType); if (disastersSummary['details'][disaster.incidentType]==='Mud/Landslide') { disastersSummary['details']['Landslide']++; } else { disastersSummary['details'][disaster.incidentType]++; } disastersSummary['total']++; } }) switch(true) { case disastersSummary.total <= 2: disastersSummary.rank = 'Low'; disastersSummary.score = disastersSummary.total/10; break; case disastersSummary.total < 10: disastersSummary.rank = 'Medium'; disastersSummary.score = disastersSummary.total/10; break; case disastersSummary.total >= 10: disastersSummary.rank = 'High'; disastersSummary.score = disastersSummary.total/10; break; } console.log(disastersSummary); res.json(disastersSummary) }) }) // get /api/airquality?city= router.get('/airquality', (req, res) => { let city = req.query.city; console.log('get air quality for', city) const url = `https://api.waqi.info/feed/${city}/?token=${process.env.AIR_QUALITY_KEY}` axios.get(url).then(result => { let airResponse = result.data let aqi = airResponse.data.aqi; let rank =''; if(!aqi){ rank = ''; } else if(aqi <= 50){ rank = "Good"; }else if(aqi > 50 && aqi <= 100){ rank = "Moderate"; }else{ rank = "Unhealthy" } let details = {} for (let key in airResponse.data.iaqi) { details[key] = airResponse.data.iaqi[key].v } let air = { total: airResponse.data.aqi, rank, unit: 'AQI', score: airResponse.data.aqi/100, details: { CO: details.co, NO2: details.no2, O3: details.o3, SO2: details.so2, 'PM2.5': details.pm25 } } console.log(air); res.json(air); }) }) // get /api/crime?neighborhood= router.get('/crime', (req, res) => { const API_URL = 'https://data.seattle.gov/resource/4fs7-3vj5.json'; let neighborhood = req.query.neighborhood; let startDate = moment('2000-01-01', 'YYYY-MM-DD'); console.log(startDate); console.log('get crime record for ', neighborhood); axios.get(API_URL).then(response => response.data) .then((data) => { let crimeData = { total: 0, rank: '', unit: 'instances', score: 0, details: { Theft: 0, Robbery: 0, Burglary: 0, 'Sex Offense': 0, Drug: 0, Murder: 0 } } let temp = {}; data.forEach(crime => { if (crime.neighborhood.toLowerCase().includes(neighborhood.toLowerCase())) { if (temp[crime.crime_subcategory]) { temp[crime.crime_subcategory]++; } else { temp[crime.crime_subcategory] = 1; } crimeData.total++; } }) for (let key in temp) { switch(true) { case key.includes('THEFT'): crimeData.details.Theft += temp[key]; break; case key.includes('ROBBERY') || key === 'CAR PROWL': crimeData.details.Robbery += temp[key]; break; case key.includes('BURGLARY'): crimeData.details.Burglary += temp[key]; break; case key.includes('SEX') || key === 'RAPE': crimeData.details['Sex Offense'] += temp[key]; break; case key === 'NARCOTIC': crimeData.details.Drug += temp[key]; break; case key === 'HOMICIDE': crimeData.details.Murder += temp[key]; break; } } switch(true) { case crimeData.total <= 25: crimeData.rank = 'Good'; break; case crimeData.total <= 50: crimeData.rank = 'OK'; break; case crimeData.total <= 75: crimeData.rank = 'Bad'; break; case crimeData.total <= 100: crimeData.rank = 'Danger'; break; case crimeData.total > 100: crimeData.rank = 'Move'; break; } crimeData.score = crimeData.total/50 console.log(crimeData); res.json(crimeData); }) }) module.exports = router;
export const Search = () => null
var express = require('express'); //var Blob = require('blob'); var router = express.Router(); const axios = require('axios'); const bodyParser = require('body-parser'); router.use(bodyParser.urlencoded({ extended: true })); router.use(bodyParser.json()); router.use(bodyParser.raw()); const ApiBaseUrl = 'https://workshop4-oce0002.cec.ocp.oraclecloud.com/content/management/api/v1.1/'; const token = 'eyJ4NXQjUzI1NiI6IlVUdWFCZmRaVmppVHNFNDFubkJuN0YwdVZyWVV2Q3NPbjJCd2JxT0NzWE0iLCJ4NXQiOiJqX0E2bVpiRzNLMmNhb1ZtVWM5RlJnei1HX3MiLCJraWQiOiJTSUdOSU5HX0tFWSIsImFsZyI6IlJTMjU2In0.eyJ1c2VyX3R6IjoiQW1lcmljYVwvQ2hpY2FnbyIsInN1YiI6IkhPTC1BVS0wMSIsInVzZXJfbG9jYWxlIjoiZW4iLCJpZHBfbmFtZSI6ImxvY2FsSURQIiwidXNlci50ZW5hbnQubmFtZSI6ImlkY3MtYTllMGYxMTllM2QwNGVlZmFkODI4N2I1ODRiMTAzNTQiLCJpZHBfZ3VpZCI6ImxvY2FsSURQIiwiYW1yIjpbIlVTRVJOQU1FX1BBU1NXT1JEIl0sImlzcyI6Imh0dHBzOlwvXC9pZGVudGl0eS5vcmFjbGVjbG91ZC5jb21cLyIsInVzZXJfdGVuYW50bmFtZSI6ImlkY3MtYTllMGYxMTllM2QwNGVlZmFkODI4N2I1ODRiMTAzNTQiLCJjbGllbnRfaWQiOiJFNTc5NTVCRTc4RjU0NDMwOUZBQjVFNERBMEJBQ0UzQV9BUFBJRCIsInN1Yl90eXBlIjoidXNlciIsInNjb3BlIjoib2ZmbGluZV9hY2Nlc3MgdXJuOm9wYzpjZWM6YWxsIiwiY2xpZW50X3RlbmFudG5hbWUiOiJpZGNzLWE5ZTBmMTE5ZTNkMDRlZWZhZDgyODdiNTg0YjEwMzU0IiwidXNlcl9sYW5nIjoiZW4iLCJleHAiOjE1OTI4MDgwNDksImlhdCI6MTU5MjIwMzI0OSwiY2xpZW50X2d1aWQiOiJhNzNjODlkYjlmZjE0ZGY4YWM5M2RjZGY0MjkyNGU3ZiIsImNsaWVudF9uYW1lIjoiQ0VDU0FVVE9fd29ya3Nob3A0Q0VDU0FVVE8iLCJpZHBfdHlwZSI6IkxPQ0FMIiwidGVuYW50IjoiaWRjcy1hOWUwZjExOWUzZDA0ZWVmYWQ4Mjg3YjU4NGIxMDM1NCIsImp0aSI6IjMwNzFjMGRjLTI2MDctNDM0Zi05NTM1LTkwNTFjMmY2NjZiOCIsInVzZXJfZGlzcGxheW5hbWUiOiJIT0wgVXNlciIsInN1Yl9tYXBwaW5nYXR0ciI6InVzZXJOYW1lIiwicHJpbVRlbmFudCI6dHJ1ZSwidG9rX3R5cGUiOiJBVCIsImNhX2d1aWQiOiJjYWNjdC03MTQzMDU3YzYyZDc0YWUxOTk1OWM5YzdhMjZjOTRhNCIsImF1ZCI6WyJodHRwczpcL1wvRTU3OTU1QkU3OEY1NDQzMDlGQUI1RTREQTBCQUNFM0EuY2VjLm9jcC5vcmFjbGVjbG91ZC5jb206NDQzXC9kb2N1bWVudHNcL2ludGVncmF0aW9uXC9zb2NpYWwiLCJ1cm46b3BjOmxiYWFzOmxvZ2ljYWxndWlkPUU1Nzk1NUJFNzhGNTQ0MzA5RkFCNUU0REEwQkFDRTNBIiwiaHR0cHM6XC9cL0U1Nzk1NUJFNzhGNTQ0MzA5RkFCNUU0REEwQkFDRTNBLmNlYy5vY3Aub3JhY2xlY2xvdWQuY29tOjQ0M1wvb3NuXC9zb2NpYWxcL2FwaSIsImh0dHBzOlwvXC9FNTc5NTVCRTc4RjU0NDMwOUZBQjVFNERBMEJBQ0UzQS5jZWMub2NwLm9yYWNsZWNsb3VkLmNvbTo0NDNcLyJdLCJ1c2VyX2lkIjoiMzE3NTcyNWJiMDkzNDQ3OGFjMjYzN2M4N2FhMmEzNTYiLCJ0ZW5hbnRfaXNzIjoiaHR0cHM6XC9cL2lkY3MtYTllMGYxMTllM2QwNGVlZmFkODI4N2I1ODRiMTAzNTQuaWRlbnRpdHkub3JhY2xlY2xvdWQuY29tIn0.kjzxqCkIIphVn5-5N1ThUQplv48j-roY7n4hKOYVMlPUewJQsKqvJMbIvSoGtcM7_WQ4WQkgONRh3mRAc9luO3GflvLW5N5nzKnY4UMY1iBvSY8owrilZIUDltxzf7Bgcsu9rJsG5w2PuZ7iPf4VBsRrnolNeCtkKUwCZlK6BfTZVlN4-0kRpN8iT25BT-yRBFjamt0d_0ntYs09BLDdOQ9EU-AAQSSZ_hYu4Y7F93PkF_Oq6TLpfOZVu2LpIWNen9lS69dLTAm6OXlhkc7Sahy9S1FVQ0brpxeJ_P4KPQ9kWFe78vOdpjgYadEG3sS4RhRnVPMpv7cQBDjG8LJWYg'; const Fs = require('fs') var ContentId = ''; var fileName=""; const repositoryId = '4B7DBFA4F8ED4504A65C023486C81455'; var contentData =''; /* GET home page. */ router.post('/', (req, res) => { console.log('post'); if(req.body.event.name === 'DIGITALASSET_CREATED' && repositoryId === req.body.entity.repositoryId) { ContentId = req.body.entity.id; downloadContent(res) } // } else if(req.body.event.name === 'CONTENTITEM_CREATED' && repositoryId === req.body.entity.repositoryId){ // var ContentItemId = req.body.entity.id; // getContentDetails(ContentItemId); // } else { res.sendStatus(200) } }); router.get('/', (req, res) => { //downloadContent(res) res.sendStatus(200) }); function getContentDetails(ContentItemId) { var contentApiUrl = ApiBaseUrl + 'items/' + ContentItemId + '/'; var header = { headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json', }, responseType: 'application/json' } axios.get(contentApiUrl, header, { responseType: 'stream' }) .then(response => { //console.log(response.header); //console.log(response.data); if(response.data.type === 'StaticSite') { contenDdata = response.data downloadThumbnail(contenDdata.fields.thumbnail.id); createSite(contentData); } else { res.sendStatus(200) return; } }) .catch(error => { console.log(error); res.status(400).send({ Error: error }); return; }); } function downloadThumbnail(thumbnailId) { } async function createSite(contentData) { siteName = contentData.name; siteTemplate = 'StarterTemplate'; siteUrl = ApiBaseUrl + '/sites'; var payload = { "name" : siteName, "template" : siteTemplate, "thumbnail" : { "url" : "", "imageType" : "thumbnail" } } var header = { headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' } } } async function downloadContent(res) { var imageApiUrl = ApiBaseUrl + 'assets/' + ContentId + '/native'; var header = { headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json', }, responseType: 'stream' } await axios.get(imageApiUrl, header, { responseType: 'stream' }) .then(response => { //console.log(response.data); resContentType = response.headers['content-type']; if (resContentType.indexOf('image/') > -1) { var ext = resContentType.replace('image/', ''); fileName = ContentId + "." + ext; var writer = Fs.createWriteStream(fileName); } else { console.log("Content is not image"); res.status(400).send({ Error: 'Content is not an image!' }); return; } var stream = response.data.pipe(writer) stream.on('finish', () => { quickstart(res, fileName); }) //imageNode.src = imgUrl }) .catch(error => { console.log(error); res.status(400).send({ Error: error }); return; }); } async function quickstart(res, fileName) { console.log("calling google api") // const description = 'WELCOME TO\n' + // 'WORLD\n' + // 'CONGRESS\n' + // 'BOSTON\n' + // 'July 28–31, 2019\n' + // 'NCMA\n' + // 'NATIONAL CONTRACT MANAGEMENT ASSOCIATION\n' + // 'CONNECTING TO\n' + // "CREATE WHAT'S NEXT\n" + // 'MAYOR MARTIN J. WALSH\n' //Imports the Google Cloud client library const vision = require('@google-cloud/vision'); // Creates a client const client = new vision.ImageAnnotatorClient(); // Performs label detection on the image file const [result] = await client.textDetection(fileName) const detections = result.textAnnotations; console.log('Text:'); //console.log(detections[0].description) //console.log(detections.description) //detections.forEach(text => console.log(text)); var description = detections[0].description; var splitedText = description.split('\n') splitedText.pop(); updateContent(splitedText, res); } function updateContent(splitedText, res) { const contentUrl = ApiBaseUrl + 'bulkItemsOperations'; var tags = {}; tags = splitedText.map(text => { return { 'name': text } }) //console.log(tags); var payload = { "q": "id eq \"" + ContentId + "\"", "operations": { "addTags": { "tags": tags } } } var header = { headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' } } //console.log(contentUrl); //console.log(payload); axios.post(contentUrl, payload, header) .then(function (response) { //console.log(response); Fs.unlink(fileName, (err) => { if (err) throw err; console.log('successfully deleted '+fileName); }); res.sendStatus(200) }) .catch(function (error) { console.log(error); }); } module.exports = router;
// Começa o comando gerar memes. module.exports.run = async (bot, message, args) => { // kk burro var Discord = require('discord.js'); //Define que talvez usaremos discord.js nisso aqui. var fs = require('fs'); // Define que talvez usaremos fs (controle de diretórios, pastas) aqui. message.channel.send(`✅ Olá, este comando está em desenvolvimento.`); let dbmems = JSON.parse(fs.readFileSync("./memes.json", "utf8")); dbmems[bot.user.id] = { dbmems: args[0] } fs.writeFile("./memes.json", JSON.stringify(dbmems), (err) => { if (err) console.log(err) }); } module.exports.config = { name: "genmemes", aliases: ["gerarmems"] };
class Paddle{ constructor(x, y){ this.loc = createVector(0, -1) this.clr = (random(255), random(255), random(255)) this.loc.x = x this.loc.y = y } run(){ this.render() this.update() } render(){ fill(this.clr) rect(this.x, this.y, 20, 20) } update(){ var mouseLoc = createVector(mouseX, 700); this.loc = p5.Vector.lerp(this.loc, mouseLoc, 0.09); } }
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsHighlight = { name: 'highlight', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M6 14l3 3v5h6v-5l3-3V9H6zm5-12h2v3h-2zM3.5 5.875L4.914 4.46l2.12 2.122L5.62 7.997zm13.46.71l2.123-2.12 1.414 1.414L18.375 8z"/></svg>` };
import axios from 'axios'; import Config from 'react-native-config'; export const getTipoReceitasAsync = async () => { const response = await axios.get(Config.APP_URL_BASE + '/tipoReceita'); return response; } export const getTodasReceitasAsync = async (receitaId) => { const response = await axios.get(Config.APP_URL_BASE + '/receita', { params: { tipoReceita: receitaId.toString() } }); return response; } export const inserirNovaReceita = async (Receita) => { const response = await axios.put(Config.APP_URL_BASE + '/receita', Receita); return response; }
var path = require('path') var proc = require('child_process') module.exports = function getUntracked (repoPath, cb) { if (typeof repoPath === 'function') { cb = repoPath repoPath = process.cwd() } proc.exec('cd ' + repoPath + ' && git ls-files --others --exclude-standard', function (err, result) { if (err) return cb(err) var absPaths = result.trim().split('\n') .map(function (p) { return path.resolve(repoPath, p) }) return cb(null, absPaths) }) }
const express = require('express'); const exphbs = require('express-handlebars'); const path = require('path'); const app = require('./app'); const environment = (app) => { app.engine('.hbs', exphbs({ defaultLayout: 'main', extname: '.hbs', layoutsDir: path.join(__dirname, './../views/layouts'), partialsDir: path.join(__dirname, './../views/partials') })) app.set('view engine', '.hbs') app.set('views', path.join(__dirname,'./../views')) app.use(express.static(__dirname + './../assets')); } module.exports = environment;
const express = require("express"); const app = express(); const port = process.env.PORT || 8080; app.use(express.static("public")); let customers = [ { id: 1, name: "Jack" }, { id: 2, name: "Tina" }, ]; let database = [ { id: 1, latitude: 60, longitude: 70 }, { id: 2, latitude: 40, longitude: 80 }, ]; var str = JSON.stringify(database, null, 2) // HTTP GET http://localhost:8080/api/customers app.get("/api/customers", (req, res) => { res.send(customers); }); // HTTP GET http://localhost:8080/api/locations app.get('/api/locations', function (req, res) { //res.json('fetch all locations') //res.json(database) res.type("application/json") res.send(str) //res.send(JSON.stringify(database, null, 2)) }) app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`); });
import './Option.css' const Option = (data) =>{ const {displayNum, optNum, setOption} = data; const optionClicked = () =>{ setOption(optNum) } return ( <div className="Option"> <button className="Option-Button" onClick={optionClicked}> {displayNum} </button> </div> ); } export default Option;
//text recall /*------------------------------------------------------------------------------------------------------------------*/ var myInput = document.getElementById('input'); var myInput1 = document.getElementById('input1'); myInput.onfocus = function () { 'use strict'; //store place holder Attr in back Attr this.setAttribute('data-place', this.getAttribute('placeholder')); this.setAttribute('placeholder', ''); }; myInput.onblur = function () { 'use strict'; //store place holder Attr in back Attr this.setAttribute('placeholder', this.getAttribute('data-place')); this.setAttribute('data-place', ''); }; myInput1.onfocus = function () { 'use strict'; //store place holder Attr in back Attr this.setAttribute('place', this.getAttribute('placeholder')); this.setAttribute('placeholder', ''); }; myInput1.onblur = function () { 'use strict'; //store place holder Attr in back Attr this.setAttribute('placeholder', this.getAttribute('place')); this.setAttribute('place', ''); }; /*--------------------------------------------------------------------------------------------------------------------------*/ //text animation /*--------------------------------------------------------------------------------------------------------------------------*/ var welcomeText = 'Welcome to my website I hope you a good time', i = 0; window.addEventListener("load", function (evt) { 'use strict'; var welcomewriter = setInterval(function () { document.getElementById('welcomeStatement').textContent += welcomeText[i];//.innerHTML == .textContent i = i + 1; if (i > welcomeText.length - 1) { clearInterval(welcomewriter); } }, 100); }); /*--------------------------------------------------------------------------------------------------------------------------*/ //password desigin var mypass = document.getElementById('pass'), mypassicon = document.getElementById('passicon'); mypassicon.onclick = function () { 'use strict'; if (this.className === 'fa fa-eye') { mypass.setAttribute('type', 'text'); this.className = 'fa fa-eye-slash'; } else { mypass.setAttribute('type', 'password'); this.className = 'fa fa-eye'; } }; /*--------------------------------------------------------------------------------------------------------------------------*/ //scroll up /*--------------------------------------------------------------------------------------------------------------------------*/ var myupButton = document.getElementById('up'); window.onscroll = function () { 'use strict'; if (window.pageYOffset >= 400) { myupButton.style.display = 'block'; } else { myupButton.style.display = 'none'; } }; myupButton.onclick = function () { 'use strict'; window.scrollTo(0, 0); }; /*--------------------------------------------------------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------------------------------------------------------*/ //change class randomly var slidelist = ["slider", "slider1", "slider2"], randomimg = Math.floor(Math.random() * slidelist.length); document.getElementById('slideimg').setAttribute('class', slidelist[randomimg]); /*--------------------------------------------------------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------------------------------------------------------*/ //live preview /*document.getElementById('').onKeyup = function(){ document.getElementById('').innerHTML = this.value; } */ /*--------------------------------------------------------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------------------------------------------------------*/ //prevent contextmenu document.addEventListener('contextmenu', function (e) { 'use strict'; e.preventDefault(); }); /*--------------------------------------------------------------------------------------------------------------------------*/ //clock preview /*--------------------------------------------------------------------------------------------------------------------------*/ function showTime() { 'use strict'; var now = new Date(), hours = now.getHours(), minutes = now.getMinutes(), seconds = now.getSeconds(); if (hours < 10) {hours = '0' + hours; } if (minutes < 10) {minutes = '0' + minutes; } if (seconds < 10) {seconds = '0' + seconds; } document.getElementById('clock').textContent = hours + ':' + minutes + ':' + seconds; } window.addEventListener("load", function (evt) { 'use strict'; setInterval(showTime, 500); }); /*--------------------------------------------------------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------------------------------------------------------*/ // slide show var slideimg = document.getElementById('slideimg'), Images = [ "http://admusicfuel.com/wp-content/uploads/Music-Fuel-358-1700x600.jpg", "Images/man.jpg", "Images/train.jpg", "Images/buildings.jpg" ]; function imageSlide() { 'use strict'; setInterval(function () { var rand = Math.floor(Math.random() * Images.length); slideimg.src = Images[rand]; }, 3000); } imageSlide(); /*--------------------------------------------------------------------------------------------------------------------------*/ //hash identifier /*if (window.location.hash){ if (window.location.hash.indexof('mohamed') === 1){ console.log("it is here"); }else{ console.log("oops"); } } */ /*--------------------------------------------------------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------------------------------------------------------*/ //redirect link /*function redirect(url){ //<button onclick ="redirect('google.com')">click to go </button> window.location = url; }*/ /*--------------------------------------------------------------------------------------------------------------------------*/
//DayHeaderView Object constructor //This view constructs a view for each day, it put out the initial starttime from the model, // get the endtime and totaltime from the model //it also creats an activitylist view to hold the dragables var DayView = function(container, model, dayId) { this.container = container.clone(); this.container.insertBefore($("#addDayButton")); this.container.attr("id", container.attr("id")+dayId); this.dayName = this.container.find("#dayName"); this.endTime = this.container.find("#endTime"); this.totalTime = this.container.find("#totalTime"); this.dayScheduleView = null; this.inputStartTime = this.container.find("#inputStartTime"); this.chart = this.container.find("#chart"); this.pPart = this.container.find("#pPart"); this.gwPart = this.container.find("#gwPart"); this.dPart = this.container.find("#dPart"); this.bPart = this.container.find("#bPart"); this.breakP = this.container.find("#breakP"); //breakdiv is the div which the class making the line marking 30% breaks will be appended var breakdiv = $("<div>"); this.chart.append(breakdiv); this.dayId = dayId; model.addObserver(this); //In the uptadet view function all parts of the day view that will be updated is placed. this.updateView = function() { // When day is created it creates a activitylist view where activities can be dropped if (this.dayScheduleView == null) { this.dayScheduleView = this.container.find("#dayScheduleView"); window.viewsMap["day"+dayId+"List"] = new ActivityListView(this.dayScheduleView, model, dayId); window.controllersMap["day"+dayId+"List"] = new ActivityListViewController(window.viewsMap["day"+dayId+"List"], model); window.dragAndDropLists.push("#"+this.dayScheduleView.attr("id")); window.linkDragAndDropLists(); } //When the view updates the endtime and total time is emptied //The breack paragraph also gets emtied this.endTime.empty(); this.totalTime.empty(); this.breakP.empty(); //Setting day title, start time, end time and total time from model this.dayName.html("Day "+ (+dayId + 1)); this.inputStartTime.attr("value", "0" + model.days[dayId].getStart() + "0"); this.endTime.append("End time: "+ model.days[dayId].getEnd()); this.totalTime.append("Total time: " + model.days[dayId].getTotalLength() + " min"); //Sets the width of the diffrent div for showing the total amount of presentaion, //group work, discussion and break activities //it's donr by dividing the total amount of every type of activity and then dividing with the //total time of the day //they are not showed from begining becouse width = 0% this.pPart.css("width", (model.days[dayId].getLengthByType(0)/model.days[dayId].getTotalLength())*100 + "%"); this.gwPart.css("width", (model.days[dayId].getLengthByType(1)/model.days[dayId].getTotalLength())*100 + "%"); this.dPart.css("width", (model.days[dayId].getLengthByType(2)/model.days[dayId].getTotalLength())*100 + "%"); this.bPart.css("width", (model.days[dayId].getLengthByType(3)/model.days[dayId].getTotalLength())*100 + "%"); /* The styling class minBreak is added to the breakdiv for showing the total time isn't 0*/ if( model.days[dayId].getTotalLength()!=0){ breakdiv.addClass("minBreak"); //If breaks are less then 30 % a text shows up, this is also dependent on that there actually is // a total time if((model.days[dayId].getLengthByType(3)/model.days[dayId].getTotalLength())*100 < 30){ this.breakP.html("Not enough breaks!").attr("style","color:red"); } //Else if there is 30% or more there will be a text showing that there is 30% or more breaks else{ this.breakP.html("You're day have 30% or more breaks, great!").attr("style","color:black"); } } else{ breakdiv.removeClass("minBreak"); } this.container.show(); } this.updateView(); this.update = function(args) { this.updateView(); } }
var searchData= [ ['board_152',['Board',['../_interface_8h.html#a6b9d49fc70cadab85447f14c584095b3',1,'Board():&#160;Interface.h'],['../_player_8h.html#aff2077940e775ff7cb8a2c704b3a6174',1,'Board():&#160;Player.h']]] ];
function runTest() { FBTest.setPref("showXMLHttpRequests", true); FBTest.openNewTab(basePath + "console/spy/5049/issue5049.html", function(win) { FBTest.openFirebug(function() { FBTest.enableConsolePanel(function(win) { var options = { tagName: "div", classes: "logRow logRow-spy loaded", counter: 2 }; waitForDisplayedElementAsync("console", options, function(row) { var panel = FBTest.getPanel("console"); var root = panel.panelNode; var statuses = root.querySelectorAll(".spyRow .spyStatus"); if (FBTest.compare(2, statuses.length, "There must be two statuses")) { FBTest.ok(statuses[0].textContent, "There must be a status info: " + statuses[0].textContent); FBTest.ok(statuses[1].textContent, "There must be a status info: " + statuses[1].textContent); } var times = root.querySelectorAll(".spyRow .spyTime"); FBTest.compare(2, times.length, "There must be two time fields"); { FBTest.ok(times[0].textContent, "There must be a time info: " + times[0].textContent); FBTest.ok(times[1].textContent, "There must be a time info: " + times[1].textContent); } FBTest.testDone(); }); // Execute test implemented on the test page. FBTest.click(win.document.getElementById("testButton")); }); }); }); } function waitForDisplayedElementAsync(panelName, config, callback) { FBTest.waitForDisplayedElement(panelName, config, function(element) { setTimeout(function(element) { callback(element); }, 1000); }); }
import axios from 'axios'; import { normalize } from 'normalizr'; import * as schema from './schema'; import withUser from '../utils/withUser'; import { UPDATE_FRAME, } from './types'; const updateFrame = data => ({ type: UPDATE_FRAME, payload: data, }); export const setThrow = (id, ball, pins) => (dispatch, getState) => { const data = withUser({ ball, pins }, getState()); return axios.patch(`/frames/${id}`, data) .then((res) => { const normalizedData = normalize(res.data.data, schema.game); dispatch(updateFrame(normalizedData)); return res.data.data; }); };
const getters = { getTableSize(state) { return state.table.size; }, getTableValues(state) { return state.table.values; } }; export default getters
import React from 'react'; import ClientFolder from './ClientFolder'; import store from '../store'; export default React.createClass({ render() { let clientFolders; if(!this.props.client.clientFolders) { clientFolders = <div />; } else { clientFolders = this.props.client.clientFolders.map((clientFolder, i, arr) => { return <ClientFolder key={i} clientFolder={clientFolder} session={this.props.session}/> }); } return ( <ul className ="secondary-container"> {clientFolders} </ul> ); } });
/* eslint-disable import/prefer-default-export */ export { default as promiseWhile } from './promiseWhile'; /* eslint-enable import/prefer-default-export */
var tokki = angular.module("homeController", []); tokki.config(["$stateProvider", "$urlRouterProvider", function($stateProvider, $urlRouterProvider){ $stateProvider .state('system.home', { url: "/home", templateUrl: "pages/home/home.html", controller: 'Home', resolve: { tokkiData: ["$q", "tokkiApi", function($q, tokkiApi){ var deferred = $q.defer(); var boletas = tokkiApi.query({action: 'boletas', control: 'latest'}); var cafs = tokkiApi.query({action: 'cafs', control: 'latest'}); $q.all([boletas.$promise, cafs.$promise]). then(function(response) { deferred.resolve(response); }); return deferred.promise; } ] } }) }] ); tokki.controller("Home", ['$scope', '$rootScope', '$state', 'tokkiApi', 'tokkiData', function($scope, $rootScope, $state, tokkiApi, tokkiData) { $rootScope.navigation = 'home'; $scope.boletas = tokkiData[0]; $scope.cafs = tokkiData[1]; $scope.pedidos = tokkiData[2]; //$scope.cafs = tokkiData; $scope.viewboleta = function(dte, id){ $state.go('system.viewboleta', {dte: dte, id: id}); } $scope.viewdte = function(dte, id){ $state.go('system.viewdte', {dte: dte, id: id}); } } ]);
import Vue from 'vue' import Router from 'vue-router' import Home from '@/views/Home.vue' import SaveAnswers from '@/views/SaveAnswers.vue' import Play from '@/views/Play.vue' import Winners from '@/views/Winners.vue' import Admin from '@/views/Admin.vue' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'home', component: Home }, { path: '/save-answers', name: 'save-answers', component: SaveAnswers }, { path: '/play', name: 'play', component: Play }, { path: '/winners', name: 'winners', component: Winners }, { path: '/admin', name: 'admin', component: Admin }, ] })
import Link from "next/link"; import { useRouter } from "next/router"; import { useState, useEffect } from "react"; export default function Layout({ children }) { //* Rendering JQuery useEffect(() => { "use strict"; // Start of use strict // Toggle the side navigation $("#sidebarToggle, #sidebarToggleTop").on("click", function (e) { $("body").toggleClass("sidebar-toggled"); $(".sidebar").toggleClass("toggled"); if ($(".sidebar").hasClass("toggled")) { $(".sidebar .collapse").collapse("hide"); } }); // Close any open menu accordions when window is resized below 768px $(window).resize(function () { if ($(window).width() < 768) { $(".sidebar .collapse").collapse("hide"); } // Toggle the side navigation when window is resized below 480px if ($(window).width() < 480 && !$(".sidebar").hasClass("toggled")) { $("body").addClass("sidebar-toggled"); $(".sidebar").addClass("toggled"); $(".sidebar .collapse").collapse("hide"); } }); // Prevent the content wrapper from scrolling when the fixed side navigation hovered over $("body.fixed-nav .sidebar").on( "mousewheel DOMMouseScroll wheel", function (e) { if ($(window).width() > 768) { var e0 = e.originalEvent, delta = e0.wheelDelta || -e0.detail; this.scrollTop += (delta < 0 ? 1 : -1) * 30; e.preventDefault(); } } ); // Scroll to top button appear $(document).on("scroll", function () { var scrollDistance = $(this).scrollTop(); if (scrollDistance > 100) { $(".scroll-to-top").fadeIn(); } else { $(".scroll-to-top").fadeOut(); } }); // Smooth scrolling using jQuery easing $(document).on("click", "a.scroll-to-top", function (e) { var $anchor = $(this); $("html, body") .stop() .animate( { scrollTop: $($anchor.attr("href")).offset().top, }, 1000, "easeInOutExpo" ); e.preventDefault(); }); }, []); // ? Defining Objects const router = useRouter(); // ? Defining Variables const [admin, setadmin] = useState(""); // ? Setting Up Variables useEffect(() => { setadmin( localStorage.getItem("user_name") ? JSON.parse(localStorage.getItem("user_name")).user_name : "" ); }, []); //? Components const Logo = () => ( <img src={require("../public/img/feasta.jpeg")} width={47} height={47} /> ); // ? Defining Metods const handleLogout = () => { var locallogin = JSON.stringify({ login: false }); localStorage.setItem("login", locallogin); router.push("/login"); }; return ( <div> {/* <Head> </Head> */} <main> <div className="App"> <div id="wrapper"> {/* Sidebar */} <ul className="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar" > {/* Sidebar - Brand */} <Link href="/dashboard"> <a className="sidebar-brand d-flex align-items-center justify-content-center"> <div> <Logo /> </div> <div className="sidebar-brand-text mx-3">FEASTA</div> </a> </Link> {/* Divider */} <hr className="sidebar-divider my-0" /> {/* Nav Item - Dashboard */} <li className="nav-item active"> <Link href="/dashboard"> <a className="nav-link"> <i className="fas fa-fw fa-tachometer-alt" /> <span>Dashboard</span> </a> </Link> </li> {/* Divider */} <hr className="sidebar-divider" /> {/* Heading */} <div className="sidebar-heading">Interface</div> <li className="nav-item"> <a className="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseUtilities" aria-expanded="true" aria-controls="collapseUtilities" > {/*<i class="fas fa-fw fa-wrench"></i>*/} <span>Menu</span> </a> <div id="collapseUtilities" className="collapse" aria-labelledby="headingUtilities" data-parent="#accordionSidebar" > <div className="bg-white py-2 collapse-inner rounded"> <h6 className="collapse-header">Utilities:</h6> <Link href="/dashboard/menu"> <a className="collapse-item">Menu Updation</a> </Link> <Link href="/dashboard/add/category"> <a className="collapse-item">Add Category</a> </Link> <Link href="/dashboard/add/item"> <a className="collapse-item">Add Item</a> </Link> </div> </div> </li> {/* Divider */} <hr className="sidebar-divider" /> {/* Heading */} <div className="sidebar-heading">Report</div> {/* Nav Item - Dashboard */} <li className="nav-item active"> <Link href="report/"> <a className="nav-link"> <span>Stats</span> </a> </Link> </li> <div className="text-center d-none d-md-inline"> <button className="rounded-circle border-0" id="sidebarToggle" /> </div> </ul> {/* End of Sidebar */} {/* Content Wrapper */} <div id="content-wrapper" className="d-flex flex-column"> {/* Main Content */} <div id="content"> {/* Topbar */} <nav className="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow"> {/* Sidebar Toggle (Topbar) */} <button id="sidebarToggleTop" className="btn btn-link d-md-none rounded-circle mr-3" > <i className="fa fa-bars" /> </button> {/* Topbar Search */} <form className="d-none d-sm-inline-block form-inline mr-auto ml-md-3 my-2 my-md-0 mw-100 navbar-search"> <div className="input-group"> <input type="text" className="form-control bg-light border-0 small" placeholder="Search for..." aria-label="Search" aria-describedby="basic-addon2" /> <div className="input-group-append"> <button className="btn btn-primary" type="button"> <i className="fas fa-search fa-sm" /> </button> </div> </div> </form> {/* Topbar Navbar */} <ul className="navbar-nav ml-auto"> {/* Nav Item - Search Dropdown (Visible Only XS) */} <li className="nav-item dropdown no-arrow d-sm-none"> <a className="nav-link dropdown-toggle" href="#" id="searchDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" > <i className="fas fa-search fa-fw" /> </a> {/* Dropdown - Messages */} <div className="dropdown-menu dropdown-menu-right p-3 shadow animated--grow-in" aria-labelledby="searchDropdown" > <form className="form-inline mr-auto w-100 navbar-search"> <div className="input-group"> <input type="text" className="form-control bg-light border-0 small" placeholder="Search for..." aria-label="Search" aria-describedby="basic-addon2" /> <div className="input-group-append"> <button className="btn btn-primary" type="button"> <i className="fas fa-search fa-sm" /> </button> </div> </div> </form> </div> </li> {/* Nav Item - User Information */} <li className="nav-item dropdown no-arrow"> <a className="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" > <span className="mr-2 d-none d-lg-inline text-gray-600 small"> FEASTA welcomes you,{" "} <span style={{ color: "Orange", fontWeight: "700", fontSize: "14px", }} > {" " + admin} </span> </span> <img className="img-profile rounded-circle" src="https://source.unsplash.com/QAB-WJcbgJk/60x60" /> </a> {/* Dropdown - User Information */} <div className="dropdown-menu dropdown-menu-right shadow animated--grow-in" aria-labelledby="userDropdown" > <a className="dropdown-item" href="#"> <i className="fas fa-user fa-sm fa-fw mr-2 text-gray-400" /> Profile </a> <div className="dropdown-divider" /> <Link href="/login"> <button className="dropdown-item" data-toggle="modal" data-target="#logoutModal" onClick={handleLogout} > <i className="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400" /> Logout </button> </Link> </div> </li> </ul> </nav> {/* End of Topbar */} {/* Begin Page Content */} <div className="container-fluid"> {/* CONTENT */} {children} {/* FOOTER */} <footer className="sticky-footer bg-white"> <div className="container my-auto"> <div className="copyright text-center my-auto"> <span>Copyright © FEASTA 2020</span> </div> </div> </footer> {/* End of Footer */} </div> {/* End Page Content */} </div> {/* End of Content Wrapper */} </div> </div> </div> </main> </div> ); }
import React from 'react' function PageDetail(props) { // console.log(props) return ( <div> <div> 我是PageDetail</div> <h2>{props.match.path}</h2> {/*<h2>{props.match.url}</h2>*/} {/*<h2>{props.match.params.id}</h2>*/} </div> ) } export default PageDetail
var _ = require("underscore"); module.exports = {}; module.exports.slack = new function(username){ var token = process.env.SLACK_TOKEN; var WebClient = require('@slack/client').WebClient; var client = new WebClient(token); client.users.list(null, function usersCb(err, res) { if (err) { console.log('Error:', err); } else { console.log('Team Info:', res.members); var user = findUser(res.members, username); return parseSlackProfile(user); } }); } module.exports.json = new function(username){ var usersData = require('./users_data'); return usersData[name]; } function findUser(users, username){ return _.findWhere(users, {name: username}); } function parseSlackProfile(user){ if (!user){ return "User not found."; } return "The slack profile for this user says: \n" + user; }
class Card { constructor(name, order) { this.name = name this.order = order } getFullName() { return `${this.name} (${this.order})` } } const DATA_COLLECTION = [ { name: "Avalon" }, { name: "Bahamut" }, { name: "Charizard" }, { name: "Drogon" }, { name: "Ender" }, { name: "Fang" } ] const cards = DATA_COLLECTION.map((item, index) => { return new Card(item.name, index + 1) }) console.log(cards) cards.forEach(item => { console.log(item.getFullName()) })
import React from 'react'; import { Image, ScrollView, StyleSheet, View, } from 'react-native'; import { widthPercentageToDP as wp, heightPercentageToDP as hp, } from 'react-native-responsive-screen'; // 현재 배너와 열어본 상품을 여기에 함께 정의해 놓았음 const MainBannerLinks = () => ( <View style={[styles.primeContainer]}> <ScrollView horizontal style={styles.container}> <Image style={styles.recommendedImages} source={{ uri: 'http://i.imgur.com/k1yVI.jpg', width: wp('70%'), height: hp('40%') }} /> <Image style={styles.recommendedImages} source={{ uri: 'http://i.imgur.com/k1yVI.jpg', width: wp('70%'), height: hp('40%') }} /> <Image style={styles.recommendedImages} source={{ uri: 'https://i.imgur.com/k1yVI.jpg', width: wp('70%'), height: hp('40%') }} /> </ScrollView> </View> ); const styles = StyleSheet.create({ primeContainer: { flex: 1, }, container: { flex: 1, marginLeft: 10, marginTop: 10, }, recommendedImages: { marginLeft: 10, marginRight: 10, borderRadius: 10, marginTop: 10, marginBottom: 10, }, }); export default MainBannerLinks; /* <View style={[styles.box, styles.box2]}> <View style={[styles.smallBox, styles.box3]}> <Image source={{ uri: 'http://i.imgur.com/k1yVI.jpg', width: 75, height: 80 }} /> <Text>몽골진간장</Text> <Image source={{ uri: 'http://i.imgur.com/k1yVI.jpg', width: 75, height: 80 }} /> <Text>몽골진간장</Text> </View> </View> */
import React, { Component } from 'react'; import { WhiteSpace,WingBlank,Toast} from 'antd-mobile'; import { Text, View, TouchableNativeFeedback, FlatList, Image } from 'react-native'; import getServices from '../../fetch/fetch'; import api from '../../api/api'; import MenuCard from '../../component/menuCard'; export default class DetailsScreen extends React.Component { constructor(props) { super(props); this.state = { data: [] }; } static navigationOptions = ({ navigation, navigationOptions }) => { const { params } = navigation.state; return { headerTitle:'我的收藏', headerLeft:null, }; }; componentDidMount(){ this.getData(); } getData = () =>{ Toast.loading('请稍等',0); const uid = this.props.navigation.getParam('data')[0].uid; getServices(`${api.getCollection}?uid=${uid}`,data=>{ if(data.success === 1){ Toast.hide(); this.setState({data:data.data}); }else{ Toast.hide(); Toast.fail(data.msg); } }) } render() { const { params } = this.props.navigation.state; const name = params ? params.name : null; const {data} = this.state; return ( <View style={{flex:1}}> {/* <WingBlank style={{ alignItems: 'center', justifyContent: 'center' }}> */} <FlatList data={data} renderItem={({item,k}) => <MenuCard data={item} key={item.cid} getData={this.getData} navigation={this.props.navigation} type="collection"/>} onRefresh={()=>{this.getData()}} refreshing={false} /> {/* </WingBlank> */} </View> ); } }
import gql from "graphql-tag"; export const LAUNCH_TILE_DATA = gql` fragment LaunchTile on Launch { id isBooked rocket { id name } mission { name missionPatch } } `; export const getLaunchesQuery = gql` query launchList($after: String) { launches(after: $after) { cursor hasMore launches { ...LaunchTile } } } ${LAUNCH_TILE_DATA} `; export const getLaunchDetailsQuery = gql` query LaunchDetails($launchId: ID!) { launch(id: $launchId) { isInCart @client site rocket { type } ...LaunchTile } } ${LAUNCH_TILE_DATA} `;
var exec = require('child_process').exec module.exports = function(){ var packerCmd = {} //Build the command, pass the options appropriately, return the feedback packerCmd.command = function(command, file, options){ if(typeof file == 'object'){ options = file file = null } var cmd = 'packer ' + command + ' -machine-readable ' if(file){ cmd += file + ' ' } if(options){ Object.keys(options).forEach(function(option){ var value = '-' + options[option] if(options[option] instanceof 'array'){ value = '=' + options[option].join(',') + ' ' } else if(options[option] !== true){ value = '=' + options[option] + ' ' } else { cmd += '-' + option + '=' + options[option] } }) } return cmd } packerCmd.build = function(file, options, cb){ var self = this, outputType; if(!options){ options = { outputType: 'results' }; } //If options aren't passed in, use default options if(typeof options == 'function'){ cb = options options = {} outputType = 'results' } else { outputType = options.outputType delete options.outputType } exec(self.command('build', file, options), { maxBuffer: 1024 * 1000 }, function(err, stdout, stderr){ if(err || stderr){ cb(err || stderr) } else { if(outputType == 'raw'){ cb(null, stdout) return } //Format the output outputArr = stdout.split('\n') //Go through each, formatting it into a more workable format outputArr.forEach(function(result, index){ //Split each result item into an array using the comma delimiter outputArr[index] = result.split(',') //Replace all instances of %!(PACKER_COMMA) with a , //Yes, the innerIndex is ugly, I'm sorry. outputArr[index].forEach(function(item, innerIndex){ outputArr[index][innerIndex] = outputArr[index][innerIndex].replace('%!(PACKER_COMMA)', ',') }) }) if(outputType == 'delimited'){ cb(null, outputArr) return } var results = {}, errors //Now go through the output, line by line, and build the results object outputArr.forEach(function(line){ var builder = line[1], type = line[2], data = line.length > 4 ? line.slice(3, line.length) : line[3] //We only care about lines length 4 or more if(line.length < 4){ return } //We also only care about messages for builders, not packer if(builder == ''){ return } if(!results[builder]){ results[builder] = { } } if(type == 'error-count'){ if(!errors){ errors = {} } if(!errors[builder]){ errors[builder] = {} } errors[builder]['error-count'] = data } else if(type == 'error'){ if(!errors){ errors = {} } if(!errors[builder]){ errors[builder] = {} } if(!errors[builder].error){ errors[builder].error = data } else { if(!(results[builder].error instanceof Array)){ results[builder].error = [results[builder].error] } results[builder].error.push(data) } } else if(type =='artifact-count'){ results[builder]['artifact-count'] = data } else if(type == 'artifact'){ var artifactIndex = data[0], dataDescriptor = data[1] if(!results[builder].artifacts){ results[builder].artifacts = {} } if(!results[builder].artifacts[artifactIndex]){ results[builder].artifacts[artifactIndex] = {} } if(data.length > 2){ results[builder].artifacts[artifactIndex][dataDescriptor] = data.length > 4 ? data.splice(2, data.length) : data[2] } if(dataDescriptor == 'id'){ results[builder].artifacts[artifactIndex].image = data[2].split(':')[1] results[builder].artifacts[artifactIndex].region = data[2].split(':')[0] } } }) Object.keys(results).forEach(function(builder){ var artifacts = [] Object.keys(results[builder].artifacts).forEach(function(artifactIndex){ artifacts.push(results[builder].artifacts[artifactIndex]) }) results[builder].artifacts = artifacts }) if(outputType == 'all'){ cb(null, { raw: stdout, delimited: outputArr, results: results }) } else { cb(null, results) } } }) } return packerCmd }
require('babel-register')({ sourceMaps: true }); const logFactory = require('log-factory'); logFactory.init({ console: true, log: process.env.LOG_LEVEL || 'info' }); global.testLogger = logFactory.getLogger('TEST'); global.logSpy = (s) => { testLogger.info('logSpy: ', s); for (var i = 0; i < s.callCount; i++) { global.testLogger.info('call: ', i, ': ', JSON.stringify(s.getCall(i).args)); } }
require('./db/connection') const express = require('express') const cors = require('cors') const { Record } = require("./models/Records") const { recordRouter } = require("./routes/records") const { userRouter } = require("./routes/user") const port = process.env.PORT || 5000 const app = express() app.use(cors()) app.use(express.json()) app.use(recordRouter) app.use(userRouter) app.get("/health", (req, res) => { res.status(200).send({ message: "Backend Working"}) }) app.listen(port, () => { console.log(`Server is listening on port ${port}`) })
import React from "react"; function Footer() { const instagram = process.env.REACT_APP_INSTAGRAM; const facebook = process.env.REACT_APP_FACEBOOK; const youtube = process.env.REACT_APP_YOUTUBE; const twitter = process.env.REACT_APP_TWITTER; const github = process.env.REACT_APP_GITHUB; const linkedin = process.env.REACT_APP_LINKEDIN; return ( <> <footer className="footer"> <div className="social_links"> <a href={{ instagram }}> <span className="fa-stack fa-lg ig combo"> <i className="fa fa-circle fa-stack-2x circle"></i> <i className="fa fa-instagram fa-stack-1x fa-inverse icon"></i> </span> </a> <a href={{ facebook }}> <span className="fa-stack fa-lg fb combo"> <i className="fa fa-circle fa-stack-2x circle"></i> <i className="fa fa-facebook fa-stack-1x fa-inverse icon"></i> </span> </a> <a href={{ youtube }}> <span className="fa-stack fa-lg yt combo"> <i className="fa fa-circle fa-stack-2x circle"></i> <i className="fa fa-youtube-play fa-stack-1x fa-inverse icon"></i> </span> </a> <a href={{ twitter }}> <span className="fa-stack fa-lg tw combo"> <i className="fa fa-circle fa-stack-2x circle"></i> <i className="fa fa-twitter fa-stack-1x fa-inverse icon"></i> </span> </a> <a href={{ github }}> <span className="fa-stack fa-lg gt combo"> <i className="fa fa-circle fa-stack-2x circle"></i> <i className="fa fa-codepen fa-stack-1x fa-inverse icon"></i> </span> </a> <a href={{ linkedin }}> <span className="fa-stack fa-lg tw combo"> <i className="fa fa-circle fa-stack-2x circle"></i> <i className="fa fa-linkedin fa-stack-1x fa-inverse icon"></i> </span> </a> </div> </footer> </> ); } export default Footer;
define(['model/query.model'], function (query) { 'use strict'; var Select_Template_View = function () { var btn_query_report=$(document).find('#btn-query-report'); var outData = $(document).find("#outdata"); var submitQuery = function () { /* var iframe = $(window.frames["iframe-outdata"].document);*/ var templateName = $(document).find('#template-name').val(); var otype = $(document).find('#otype').val(); var eid = $(document).find('#eid').val(); var firstDate = $(document).find('#first-date').val(); var secondDate = $(document).find('#second-date').val(); var ruleTemplate = $(document).find('#rule-name').val(); var data = { reporttemplate:templateName, otype:otype, eid:eid, firstdate:firstDate, seconddate:secondDate, ruletemplate:ruleTemplate } query.ajax('/submit', 'GET', data, function (r) { if (r.result === 'ok') { console.log(r.data); console.log(r.link); outData.html(''); var link = r.link.split('/'); var filelink = '/'+link[link.length-2]+'/'+link[link.length-1]; outData.append( $('<li class="out-data-item list-group-item"></li>').append( $('<span class="item-casename"></span>').html('Case Name'), $('<span class="item-outdata"></span>').html("Output Data") )); var i; for(i = 0; i < r.data.length; i += 1){ outData.append( $('<li class="out-data-item list-group-item"></li>').append( $('<span class="item-casename"></span>').html(r.data[i][0]), $('<span class="item-outdata"></span>').html(r.data[i][1]) )); } outData.append($('<a></a>').html('Download File').addClass('download-link').attr('href',filelink)); } else { console.log('err'); } }, this); }; this.init = function () { btn_query_report.on('click',submitQuery); }; }; return new Select_Template_View(); });
$(function () { // 好友店商品ajax无限滚动加载 var loading = false; // 最多可加载的条目 var maxItems = 60; $.detachInfiniteScroll($('.infinite-scroll')); // 每次加载添加多少条目 var itemsPerLoad = 20; function addItems(number, lastIndex) { // 生成新条目的HTML var html = ''; for (var i = lastIndex + 1; i <= lastIndex + number; i++) { html += '<li>' + '<a href="#" class="item-link1 item-content">' + '<div class="item-media">' + '<img src="http://image.59store.com/Food/r31.jpg!small" style="width: 4rem;">' + '</div>' + '<div class="item-inner">' + '<div class="item-title-row">' + '<div class="item-title">韩国进口 海飘 即食烤海苔袋装 2g/包</div>' + '<!-- <div class="item-after">$15</div> -->' + '</div>' + '<div class="item-title-row">' + '<span style="color:#F9A502">¥1.00</span>' + '</div>' + '<div class="item-title-row">' + '<span class="color-gray text-small" style="line-height:1.25rem;">库存:36 销量:435</span>' + '<i class="icon icon-cart"></i>' + '</div>' + '</div>' + '</a>' + '</li>'; } // 添加新条目 $('#haou-store-show-content ul').append(html); } //预先加载20条 addItems(itemsPerLoad, 0); // 上次加载的序号 var lastIndex = 20; // 注册'infinite'事件处理函数 $(document).on('infinite', '#haou-store-show-content',function() { // 如果正在加载,则退出 if (loading) return; // 设置flag loading = true; if (lastIndex >= maxItems) { // 加载完毕,则注销无限加载事件,以防不必要的加载 $.detachInfiniteScroll($('.infinite-scroll')); // 删除加载提示符 $('.infinite-scroll-preloader').remove(); return; } // 模拟1s的加载过程 setTimeout(function() { // 重置加载flag loading = false; console.log('lastIndex'); console.log(lastIndex); console.log('maxItems'); console.log(maxItems); if (lastIndex >= maxItems) { // 加载完毕,则注销无限加载事件,以防不必要的加载 $.detachInfiniteScroll($('.infinite-scroll')); // 删除加载提示符 $('.infinite-scroll-preloader').remove(); return; } // 添加新条目 addItems(itemsPerLoad, lastIndex); // 更新最后加载的序号 lastIndex = $('#haou-store-show-content ul li').length; //容器发生改变,如果是js滚动,需要刷新滚动 $.refreshScroller(); }, 1000); }); $.init(); });
var image = document.images[0]; var buttons = document.getElementsByTagName("button"); var i; for (i = 0; i < buttons.length; i++) { buttons[i].addEventListener("click", function() { if (this.id == "field") { image.src = "images/field.jpg"; } else if (this.id == "tree") { image.src = "images/tree.jpg"; } else { image.src = "images/stone.jpg"; } }); }
import React from 'react' import './FooterControls.css' import MicOffIcon from '@material-ui/icons/MicOff' import StopIcon from '@material-ui/icons/Stop' import SecurityIcon from '@material-ui/icons/Security' import PeopleIcon from '@material-ui/icons/People' import ChatIcon from '@material-ui/icons/Chat' function FooterControls() { return ( <div className="controls"> <div class="controls__block"> <div class="controls__button"> <MicOffIcon /> <span>Mute</span> </div> <div class="controls__button"> <StopIcon /> <span>Stop Video</span> </div> </div> <div class="controls__block"> <div class="controls__button"> <SecurityIcon /> <span>Security</span> </div> <div class="controls__button"> <PeopleIcon /> <span>Participants</span> </div> <div class="controls__button"> <ChatIcon /> <span>Chat</span> </div> </div> <div class="controls__block"> <div class="controls__button"> <span class="leave_meeting">Leave Meeting</span> </div> </div> </div> ) } export default FooterControls