text
stringlengths
7
3.69M
/* Adding listener for 'add' button click. Also setting gobal variables for the table, a runtime function for random which will generate a variable between 5 and 10. Followed by a timer which will execute the removeTable() function at every rand second interval*/ document.getElementById("add").addEventListener("click", addTable); var table = document.getElementById("formData"); var rand = random(); var timer = setInterval(function() { removeTable() }, (rand * 1000)); var tableValues = []; /* Created a function called addTable() which will store the values of the initializer row and pass them to an entirely new row which an x button at the end which has an innerHTML that executes the removeRow() function when clicked. In order to create a new row, first we call the checkDuplicates() function which will check if the exact form data already exists in the table. If not, we call areThereBlanks() which will check to see if any fields are empty. No new tables will be created unless both tests pass. After creating a new row with the values in the initalizer row, the clearInitRow() function is called which clears the values the user has added to the initializer row to set the user up for the next addition. */ function addTable() { var firstName = document.getElementById("firstName").value; var lastName = document.getElementById("lastName").value; var email = document.getElementById("email").value; var buttonStr = "<button type='button' id='remove' onclick='removeTable()'><span class='glyphicon glyphicon-remove'></span></button>"; var combined = firstName + lastName + email; if (checkDuplicates(tableValues, combined) === true) { if (areThereBlanks(firstName, lastName, email) === false) { tableValues.push(combined); var row = table.insertRow(1); row.class = "added"; var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); var cell3 = row.insertCell(2); var cell4 = row.insertCell(3); cell1.innerHTML = firstName; cell2.innerHTML = lastName; cell3.innerHTML = email; cell4.innerHTML = buttonStr; } } clearInitRow(); } /* removes the first table row as long as it's one of the rows that has been added by the user, not the initalizer row */ function removeTable() { if (table.rows[1].class === "added") { var removalStr = ""; for (var i = 0; i < 3; i++) { removalStr += table.rows[1].cells[i].innerHTML; } var index = tableValues.indexOf(removalStr); if (index > -1) { tableValues.splice(index, 1); } table.deleteRow(1); } } //Generates and returns a random number between 1 and 10 and rounds down to the nearest whole number. function random() { return Math.floor(Math.random() * (10 - 5) + 5); } //sets up initializer row with empty values making it easier for the user to enter new information. function clearInitRow() { document.getElementById("firstName").value = ""; document.getElementById("lastName").value = ""; document.getElementById("email").value = ""; } //checks to see if the information the user is trying to add already exists inside the table. function checkDuplicates(arr, string) { if (arr.indexOf(string) === -1) { return true; } else { alert("You cannot have duplicate input field values!!!"); } } //Checks if any of the required fields are blank and will stop the fields from being added if so. function areThereBlanks(firstName, lastName, email) { if (firstName === "" || lastName === "" || email === "") { alert("You must fill out all of the input fields!"); return true; } else { return false; } }
const initialState = { loanType: 'Home Purchase', propertyType: 'Single Family Home', city: '', propToBeUsedOn: '', found: 'false', realEstateAgent: 'false', cost: 0, downPayment: 0, credit: '', history: '', addressOne: '', addressTwo: '', addressThree: '', firstName: '', lastName: '', email: '' } const UPDATE_LOAN_TYPE = 'UPDATE_LOAN_TYPE' const UPDATE_PROPERTY_TYPE = 'UPDATE_PROPERTY_TYPE' const UPDATE_CITY = 'UPDATE_CITY' const UPDATE_PROP = 'UPDATE_PROP' const UPDATE_FOUND = 'UPDATE_FOUND' const UPDATE_AGENT = 'UPDATE_AGENT' const UPDATE_COST = 'UPDATE_COST' const UPDATE_PAYMENT = 'UPDATE_PAYMENT' const UPDATE_CREDIT = 'UPDATE_CREDIT' const UPDATE_HISTORY = 'UPDATE_HISTORY' const UPDATE_ADDRESS_ONE = 'UPDATE_ADDRESS_ONE' const UPDATE_ADDRESS_TWO = 'UPDATE_ADDRESS_TWO' const UPDATE_ADDRESS_THREE = 'UPDATE_ADDRESS_THREE' const UPDATE_FIRST_NAME = 'UPDATE_FIRST_NAME' const UPDATE_LAST_NAME = 'UPDATE_LAST_NAME' const UPDATE_EMAIL = 'UPDATE_EMAIL' export function updateEmail(email) { return { type: UPDATE_EMAIL, payload: email } } export function updateLastName(lastName) { return { type: UPDATE_LAST_NAME, payload: lastName } } export function updateFirstName(firstName) { return { type: UPDATE_FIRST_NAME, payload: firstName } } export function updateAddressTwo(addressTwo) { return { type: UPDATE_ADDRESS_TWO, payload: addressTwo } } export function updateAddressThree(addressThree) { return { type: UPDATE_ADDRESS_THREE, payload: addressThree } } export function updateAddressOne(addressOne) { return { type: UPDATE_ADDRESS_ONE, payload: addressOne } } export function updateHistory(history) { return { type: UPDATE_HISTORY, payload: history } } export function updateCredit(credit) { return { type: UPDATE_CREDIT, payload: credit } } export function updatePayment(payment) { return { type: UPDATE_PAYMENT, payload: payment } } export function updateCost(cost) { return { type: UPDATE_COST, payload: cost } } export function updateAgent(agent) { return { type: UPDATE_AGENT, payload: agent } } export function updateFound(found) { return { type: UPDATE_FOUND, payload: found } } export function updateProp(prop) { return { type: UPDATE_PROP, payload: prop } } export function updateLoanType(type) { return { type: UPDATE_LOAN_TYPE, payload: type } } export function updateCity(city) { return{ type: UPDATE_CITY, payload: city } } export function updatePropertyType(type) { return { type: UPDATE_PROPERTY_TYPE, payload: type } } export default function reducer(state = initialState, action){ switch( action.type ) { case UPDATE_PROP: return {...state, propToBeUsedOn: action.payload} case UPDATE_LOAN_TYPE: return {...state, loanType: action.payload} case UPDATE_PROPERTY_TYPE: return {...state, propertyType: action.payload} case UPDATE_CITY: return {...state, city: action.payload} case UPDATE_AGENT: return {...state, realEstateAgent: action.payload} case UPDATE_COST: return {...state, cost: action.payload} case UPDATE_PAYMENT: return {...state, downPayment: action.payload} case UPDATE_CREDIT: return {...state, credit: action.payload} case UPDATE_HISTORY: return {...state, history: action.payload} case UPDATE_ADDRESS_ONE: return {...state, addressOne: action.payload} case UPDATE_ADDRESS_TWO: return {...state, addressTwo: action.payload} case UPDATE_ADDRESS_THREE: return {...state, addressThree: action.payload} case UPDATE_FIRST_NAME: return {...state, firstName: action.payload} case UPDATE_LAST_NAME: return {...state, lastName: action.payload} case UPDATE_EMAIL: return {...state, email: action.payload} default: return state } }
'use strict' const Theme = require('../models/theme') function createTheme(req, res) { let theme = new Theme() theme.title = req.body.title theme.description = req.body.description theme.img_theme = req.body.img_theme theme.category = req.body.category theme.save((err, themeStored) => { if (err) res.status(500).send({ message: `error saving to database: ${err}` }) res.status(201).send({ theme: themeStored }) }) } function getAllThemes(req, res) { Theme.find({}, (err, themes) => { if (err) return res.status(500).send({ message: `request error: ${err}` }) res.status(200).send({ themes }) }) } function getTheme(req, res) { let themeId = req.params.themeId Theme.findById(themeId, (err, theme) => { if (err) return res.status(500).send({ message: `request error: ${err}` }) if (!theme) return res.status(404).send({ message: 'the theme dont exist' }) res.status(200).send({ theme }) }) } function updateTheme(req, res) { let themeId = req.params.themeId let update = req.body Theme.findByIdAndUpdate(themeId, update, (err, themeUpdated) => { if (err) res.status(500).send({ message: `error updating image: ${err}` }) res.status(200).send({ theme: themeUpdated }) }) } function deleteTheme(req, res) { let themeId = req.params.themeId Theme.findByIdAndRemove(themeId, (err, theme) => { if (err) res.status(500).send({ message: `error deleting theme: ${err}` }) res.status(200).send({ message: 'the theme has been deleted' }) }) } // not used function getIds(req, res) { Theme.find({}, "_id", (err, idsthemes) => { if (err) res.status(500).send({ message: `request error: ${err}` }) //return idsthemes res.status(200).send({ idsthemes }) }) } module.exports = { createTheme, getAllThemes, getTheme, getIds, updateTheme, deleteTheme }
/** * Created by az on 2017/7/24. */ import React, { Component } from 'react'; import './qb-component/_default.scss'; import QbLayout from './qb-component/QbLayout'; import { QbDatePicker, QbTimePicker } from './qb-component/QbDatePicker'; import QbRateStar from './qb-component/QbRateStar'; import QbButton from './qb-component/QbButton'; import QbHighlight from './qb-component/QbHighlight'; import QbScore from './qb-component/QbScore'; import QbStar from './qb-component/QbStar'; import QbImgSection from './qb-component/QbImgSection'; import { QbCheckBox, QbRadio, QbInput, QbSwitcher } from './qb-component/QbInput'; import { QbModalBody, QbModalHeader, QbModalFooter, QbModal } from './qb-component/QbModal'; import { QbDropDown, QbDropDownDivider, QbDropDownItem } from './qb-component/QbDropDown'; import QbSlider from './qb-component/QbSlider'; import { QbCard } from './qb-component/QbCard'; import CloseIcon from './qb-component/assets/image/icon/x-icon@3x.png'; import SearchIcon from './qb-component/assets/image/icon/search.svg'; import CalendarIcon from './qb-component/assets/image/icon/calendar.svg'; import { QbTabs, QbTab } from './qb-component/QbTabs'; import QbCollapse from './qb-component/QbCollapse'; import Collapse from 'rc-collapse'; import QbMessageCard from './qb-component/QbMessageCard'; import QbProgressBar from './qb-component/QbProgressBar'; import 'rc-collapse/assets/index.css'; import { QbAvatar } from './qb-component/QbHeader'; import QbAlert from './qb-component/QbAlert'; import { QbNavLeft, QbNavDDL } from './qb-component/QbNavLeftDDL'; import Rheostat from 'rheostat'; import QbEClassCardTemplate from './qb-component/QbEClassCardTemplate'; import 'rheostat/css/slider.css'; import 'rheostat/css/slider-horizontal.css'; const Panel = Collapse.Panel; export default class Test extends Component { constructor(props) { super(props); this.state = { show: false, switchState: true, showCard: true, numlist: ['yahaha'], showModal: false, showAlert: false, showSpin: false, expand: false, singleDate: null, startDate: null, endDate: null, btnDropDownValue: { label:"Start time", value: "date" }, inputDropDownValue: null, inputValue: '', price: { low: 0, high: 15, }, time: { hour: 0, minute: 0, periods: 'AM', }, isValid: true } } toggleModal() { this.setState({ show: !this.state.show }); console.log('Tag show is, ', this.state.show); } switchHandler() { console.log('Tag click'); this.setState((prevState, props) => ({ switchState: !prevState.switchState })); } messageToggle() { this.setState((prevState, props) => ({ showCard: !prevState.showCard })); } sliderChange(lowPrice, highPrice) { this.setState({price: { low: lowPrice, high: highPrice, }}); } buttonIconClick() { alert('icon cliasc'); } datesChange(start, end) { this.setState({ startDate: start, endDate: end, }) } dateChange(date) { this.setState({ singleDate: date, }) } add() { console.log('Tag before numlist:', this.state.numlist); let a = this.state.numlist; a.push('another one'); this.setState({ numlist: a }) } alertMessage() { QbAlert.error('hi', 'click<a href="http://stg.quesbook.com/api/v1/user/password?email=gzhang%2B3%40quesbook.com">Resend the email</a>', 300); QbAlert.info('hi', 'hello', 300); QbAlert.warning('hi', 'hello', 300); QbAlert.success('hi', 'hello', 300); } handleClickLoad = () => { let self = this; self.setState({ showSpin: true }, () => { setTimeout(() => { self.setState({ showSpin: false }) }, 600) }) } onClickCard = () => { this.setState({ expand: !this.state.expand }) } render() { const dropDownContent = [{ label: 'abc', value: 'abc', }, { label: 'bcd', value: 'bcd', }, { label: 'cde', value: 'cde', }, { label: 'def', value: 'def', }]; let list = this.state.numlist.map((data, index) => { return <div key={index}>{data}</div> }); console.log('Tag numlist:', this.state.numlist); let collapseContent = [{ header: <div> <img src="" /> <div style={{ color: '#ffffff' }}>hello</div> </div>, content: <div>hi</div>, }, { header: <div> <img src="" /> <div>god</div> </div>, content: <div>like</div> }]; const classCardData = { btnText: 'Finished', compClass: null, compStyle: { width: '450px', margin: 30 }, expand: false, disabled: false, sectionName: 'math', courseName: 'E-Class for Opening, Transitional & Closing Sentences', startsAt: 'Jan. 15th at 5PM', description: 'Take this e-class to learn the important elements that go into writing and identifying effective paragraphs made up of opening, transitional and closing sentences. This class will teach you how to master this skill for the ACT', skillName: 'Analyzing Function' }; const classCardData2 = { ...classCardData, expand: true, btnText: 'Join Class' } let paramQbNav = { itemList: [ { "key": "item01", "value": "Item 01", "href": "/", "isRedirect": false }, { "key": "item02", "value": "Item 02", "href": "/", "isRedirect": false } ], queryStrName: 'keyNav', }; return ( <div> <QbEClassCardTemplate compStyle={{ margin: 30 }} expand={this.state.expand} cardClickHandler={this.onClickCard} sectionName={'math'} courseName={'E-Class for Opening, Transitional & Closing Sentences'} startsAt={'Jan. 15th at 5PM'} description={'Take this e-class to learn the important elements that go into writing and identifying effective paragraphs made up of opening, transitional and closing sentences.'} skillName={'Analyzing Function'} > <div> 明月几时有?把酒问青天。不知天上宫阙,今夕是何年。 我欲乘风归去,又恐琼楼玉宇,高处不胜寒。起舞弄清影,何似在人间。 转朱阁,低绮户,照无眠。不应有恨,何事长向别时圆? 人有悲欢离合,月有阴晴圆缺,此事古难全。但愿人长久,千里共婵娟。 </div> </QbEClassCardTemplate> <p>可以选择过去的时间</p> <QbDatePicker displayFormat="MM/DD/YY" orientation={'vertical'} allowPastDays startDateId="startDateId" endDateId="endDateId" startDate={this.state.startDate} endDate={this.state.endDate} option={{ icon: <img alt="icon" src={CalendarIcon} />, style: {marginBottom: 30}, small: true }} onDatesChange={this.datesChange.bind(this)} onDateChange={this.dateChange.bind(this)} /> <QbDatePicker allowPastDays id="testSingle" singleDate = {this.state.singleDate} option={{ singlePicker: true, placeHolder: "2012-1-1" }} onDateChange={this.dateChange.bind(this)} /> <button onClick={() => { this.setState({ startDate: null, endDate: null, singleDate: null, time: null, price: null, btnDropDownValue: null, inputDropDownValue: null, inputValue: null, }); }}>reset</button> <p>不能选择过去的时间</p> {/* <QbDatePicker startDateId="startDateId" endDateId="endDateId" option={{ icon: <img alt="icon" src={CalendarIcon} />, small: true }} onDatesChange={this.datesChange.bind(this)} onDateChange={this.dateChange.bind(this)} /> <QbDatePicker id="testSingle" option={{ singlePicker: true, placeHolder: "2012-1-1" }} onDateChange={this.dateChange.bind(this)} /> <QbDatePicker id="testSingle" option={{ icon: <img alt="icon" src={CalendarIcon} />, singlePicker: true, placeHolder: "today(2012-1-1)", small: true }} onDateChange={this.dateChange.bind(this)} /> */} <QbRateStar /> <QbRateStar rate={3.3} compStyle={{ width: 'maxContent' }} /> <QbRateStar starWidth={31.1} starHeight={30} rate={'3.75'} gap={8} /> <QbRateStar starWidth={31.1} starHeight={30} rate={undefined} gap={8} /> <QbNavLeft params={paramQbNav} /> {/* <QbClassCard {...classCardData} /> */} <QbNavDDL params={paramQbNav} /> <QbSwitcher switchState={this.state.switchState} clickHandler={this.switchHandler.bind(this)} /> <QbSlider maxMark="$10+" minMark="Free!" maxPrice={15} value={this.state.price} style={{ height: 100, width: 300 }} changeHandler={this.sliderChange.bind(this)} /> <QbDropDown value={this.state.btnDropDownValue} option={{ inputType: "button", btnStyle: { width: 350, textAlign: 'left' }, style: { position: 'relative', width: 400, height: 52 }, dropdownStyle: { width: '100%' } }} content={dropDownContent} onChange={(data) => { this.setState({ btnDropDownValue: data}); }} /> <QbButton label="hello" isSubmit="true" className="btn btn-secondary btn-sm" iconClick={this.buttonIconClick.bind(this)} dataTarget="#azmodal" dataToggle='modal'> <img src={CloseIcon} style={{ height: 'inherit', width: 'inherit' }} /> </QbButton> <QbDropDown value={this.state.inputDropDownValue} option={{ placeHolder: 'e.g. Apostrophes', inputType: "input", btnStyle: { width: 350, textAlign: 'left' }, style: { position: 'relative', width: 400, height: 52 }, dropdownStyle: { width: '100%' }, icon: <img alt="icon" src={CalendarIcon} /> }} content={dropDownContent} onChange={(data) => { console.log('TAg data:', data); this.setState({ inputDropDownValue: data }); }} /> <QbTimePicker id="endPicker" onPickerClose={(time) => this.setState({time: time})} time={this.state.time} option={{ btnStyle: { width: 150, height: 52, fontSize: 20, justifyContent: 'center' }, displayMinute: true }} /> <QbButton label="talksndonoadn3oqnwodnqowndoqnodiqhwpir" style={{ width: 100 }} className="btn btn-primary btn-lg" clickHandler={() => this.setState({ showAlert: !this.state.showAlert })} /> <QbCheckBox label="hello" id="hello" value={1} changeHandler={(value) => console.log('hello', value)} fontStyle={{ fontSize: 16 }} /> <QbCheckBox label="hi" id="hi" value={2} changeHandler={(value) => console.log('hi', value)} fontStyle={{ fontSize: 16 }} /> <QbRadio label="hello" id='r1' name="1" value={1} changeHandler={(value) => console.log('hello', value)} fontStyle={{ fontSize: 16 }} /> <QbRadio label="hi" id='r2'name='1' value={2} changeHandler={(value) => console.log('hello', value)} fontStyle={{ fontSize: 16 }} /> <QbButton label={'改变输入框的文本合法性'} clickHandler={()=>{this.setState({isValid: !this.state.isValid})}}/> <QbInput placeHolder='e.g. math' size="small" value={this.state.inputValue} isValid={this.state.isValid} errorMsg={'输入的文本格式不对'} changeHandler={(value) => this.setState({ inputValue: value })}> <img alt="icon" src={SearchIcon} /> </QbInput> <button onClick={this.alertMessage.bind(this)}>add</button> <QbModal target="azmodal" show={this.state.show} afterHidden={() => { this.setState({ show: false }) }} afterShown={() => { this.setState({ show: true }) }}> <QbModalHeader> <div>headerssss</div> </QbModalHeader> <QbModalBody> <div> <QbSwitcher switchState={this.state.switchState} clickHandler={this.switchHandler.bind(this)} /> </div> </QbModalBody> <QbModalFooter> <QbButton label="close" dataTarget="#modal" dataToggle='modal' /> </QbModalFooter> </QbModal> <QbTimePicker id="startPicker" onPickerClose={(time) => console.log('Tag time is:', time)} option={{ btnStyle: { width: 100, height: 52, fontSize: 20 }, style: { width: 100 } }} /> {/*/!* <QbClassCard {...classCardData2} /> *!/*/} {/* <QbAvatar user={{ name: 'Tom Zhu', avatar: '' }} size='big'></QbAvatar> <QbProgressBar compStyle={{ margin: '50px 0' }} percentage={'100%'} /> <QbProgressBar showProgressText={true} compStyle={{ margin: '50px 0' }} percentage={'35%'} /> <QbImgSection sectionType="English" style={{ 'height': '200px' }}></QbImgSection> <QbImgSection sectionType="science"></QbImgSection> <QbStar num="33"></QbStar> <QbScore score="1"></QbScore> <QbScore score="99"></QbScore> <QbScore score="1" content="over all" style={{ 'borderColor': '#b9cff3', 'color': '#b9cff3', 'fontSize': '40px' }}></QbScore> <QbScore score="32" content="over all" style={{ 'borderColor': '#b9cff3', 'color': '#b9cff3', 'fontSize': '40px' }}></QbScore> <h1> My StudyPlan <QbHighlight content="Quesbook Web"></QbHighlight> </h1> npm <QbSwitcher switchState={this.state.switchState} clickHandler={this.switchHandler.bind(this)} /> <QbButton label="show message" className="btn btn-lg btn-primary" clickHandler={this.messageToggle.bind(this)} /> <QbMessageCard option={option} title="hello!" content="ha lou a !" onCancelClick={this.messageToggle.bind(this)} /> <QbCard cardStyle={{ height: 120, width: 500 }} avatarSrc={CloseIcon} rate={3.5} /> <QbTabs> <QbTab ref="hlo"> {list} </QbTab> <QbTab ref="bin"> <div>asd</div> </QbTab> <QbTab ref="ho" className="new" style={{ height: 50, overflowY: 'scroll' }}> <div>xixiix</div> <div>xixiix</div> <div>xixiix</div> <div>xixiix</div> <div>xixiix</div> <div>xixiix</div> <div>xixiix</div> <div>xixiix</div> <div>xixiix</div> </QbTab>` </QbTabs> <QbCollapse content={collapseContent} panelStyle={{ color: '#ffffff', background: '#203a62' }} /> <button onClick={() => { QbAlert.error('title', (<div>hello inhao jodhqwhbdlsjcn ijbib2ekwnijwienf l</div>), 100, { fontWeight: 'bold' }); }}> booooo {/*</button> *!/*/} </div> ) } }
'use strict'; var fs=require('fs'); const express = require('express'); // Constants const PORT = 8080; var path=require('path'); // App const app = express(); app.set('views',__dirname + '/views'); app.use(express.static(path.join(__dirname, 'public'))); app.get('/start', function(req,res) { res.sendFile(__dirname + '/views/index.html'); }); app.listen(PORT); console.log('Running on http://localhost:' + PORT);
// Higher order component that force updates component on themer change // and passes down theme through props import React, { Component } from 'react' import { isValidElementType } from 'react-is' import PropTypes from 'prop-types' import themer from './index' import { cleanConfig, themePropTypes } from './utils' function withTheme(options = {}) { // This allows us to maintain backwards compatibility with withTheme(Component) // while supporting withTheme(options)(Component) if (isValidElementType(options)) { return withTheme()(options) } return function wrapWithTheme(WrappedComponent) { class WithTheme extends Component { static displayName = `withTheme(${WrappedComponent.name || WrappedComponent.displayName || 'Component'})` static propTypes = { forwardedRef: PropTypes.oneOfType([ PropTypes.func, PropTypes.shape({ current: PropTypes.any }), ]), snacksTheme: themePropTypes, } componentDidMount() { this.unsubscribe = themer.subscribe(this.onThemeChange) this.validateSnacksTheme() } componentWillUnmount() { this.unsubscribe() } onThemeChange = () => { this.forceUpdate() } themeIsValid() { const { snacksTheme } = this.props return Boolean(snacksTheme) && typeof snacksTheme === 'object' } validateSnacksTheme() { if (process.env.NODE_ENV !== 'production') { // eslint-disable-line no-undef const { snacksTheme } = this.props const themeIsBad = snacksTheme && !Object.keys(cleanConfig(snacksTheme)).length if (themeIsBad) { throw new Error( `Recieved an invalid snacksTheme Prop. Expected undefined or an object and instead got ${typeof snacksTheme}` ) } } } render() { const { snacksTheme, forwardedRef, ...rest } = this.props const theme = this.themeIsValid() ? snacksTheme : themer.themeConfig return <WrappedComponent ref={forwardedRef} snacksTheme={theme} {...rest} /> } } if (options.forwardRef) { const withThemeForwardRef = (props, ref) => { return <WithTheme {...props} forwardedRef={ref} /> } // gives us ForwardRef(withTheme(ComponentName)) in dev tools and snapshots withThemeForwardRef.displayName = WithTheme.displayName return React.forwardRef(withThemeForwardRef) } return WithTheme } } export default withTheme
// given a binary search tree and level k // find the maximum value at level k function maxAtLevelK(root, k) { var maxLeft, maxRight; if (k > 0) { if (root) { if (root.right !== null) { maxRight = maxAtLevelK(root.right, k - 1); } if (root.left !== null) { maxLeft = maxAtLevelK(root.left, k - 1); } } if (!!maxRight) { return maxRight; } else if (!!maxLeft) { return maxLeft; } else { return null; } } else { return root; } } exports.maxAtLevelK = maxAtLevelK;
Blockly.Blocks['inserisci_numero'] = { init: function() { this.appendValueInput("NAME") .setCheck("Number") .appendField("ins numero:"); this.setColour(300); this.setTooltip(""); this.setHelpUrl(""); } };
const usuarios = [ { nome: 'Diego', idade: 23, empresa: 'Rocketseat' }, { nome: 'Gabriel', idade: 15, empresa: 'Rocketseat' }, { nome: 'Lucas', idade: 30, empresa: 'Facebook' } ]; /* 2.1 */ const map = usuarios.map(({ idade }) => idade); /* 2.2 */ const filter = usuarios.filter(({ idade, empresa }) => idade > 18 && empresa === 'Rocketseat'); /* 2.3 */ const find = usuarios.find(({ empresa }) => empresa === 'Google'); /* 2.4 */ const novaIdade = duplicaIdade(usuarios); const novaIdadeFilter = novaIdade.filter((value) => value.idade <= 50); function duplicaIdade(arr) { return arr.map((value) => { value.idade *= 2; return value; }); } console.log(map); console.log(filter); console.log(find); console.log(novaIdade); console.log(novaIdadeFilter);
$(function(){ var process_map = {}; $(".project").live("watch:start", startWatchingProject); $(".project").live("watch:stop", stopWatchingProject); $(".projects").live("processes:killAll", killWatchingProcesses); air.NativeApplication.nativeApplication.addEventListener(air.Event.EXITING, killWatchingProcesses); function startWatchingProject(evnt, data) { var nativeProcessStartupInfo = new air.NativeProcessStartupInfo(); nativeProcessStartupInfo.executable = javaDir(); var processArgs = new air.Vector["<String>"](); processArgs.push( '-jar', jruby_complete_jar(), // '-r' + jar('vendor/scout.jar'), '-S', compassExecutable(), "watch", data.project.projectDir, "--require", "ninesixty", "--require", "yui", "--require", "compass-h5bp", "--sass-dir", data.project.sassDir, "--css-dir", data.project.cssDir, "--images-dir", data.project.imagesDir, "--javascripts-dir", data.project.javascriptsDir, "--environment", data.project.environment, "--output-style", data.project.outputStyle, "--trace" ); if(data.project.configFile){ processArgs.push("--config", data.project.configFile); } //air.trace(processArgs); nativeProcessStartupInfo.arguments = processArgs; process = new air.NativeProcess(); process.addEventListener(air.ProgressEvent.STANDARD_OUTPUT_DATA, outputDataHandler); process.addEventListener(air.ProgressEvent.STANDARD_ERROR_DATA, errorDataHandler); process.addEventListener(air.NativeProcessExitEvent.EXIT, onExit); process.start(nativeProcessStartupInfo); $('.project[data-key='+data.project.key+']').trigger(':started'); function onExit(evnt) { $('.project[data-key='+data.project.key+']').trigger('watch:stop'); } function outputDataHandler(evnt) { var bytes = process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable); $('.project_details[data-key='+data.project.key+']').trigger(':newLogOutput', bytes.toString()); } function errorDataHandler(evnt) { var bytes = process.standardError.readUTFBytes(process.standardError.bytesAvailable); $('.project_details[data-key='+data.project.key+']').trigger(':newLogOutput', bytes.toString()); } process_map[data.project.key] = process; } function stopWatchingProject(evnt, data) { var project_key = $(this).attr('data-key'); var process = process_map[project_key]; if(process){ stopProcess(process); delete process_map[project_key]; $('.project[data-key='+project_key+']').trigger(':stopped'); } } function killWatchingProcesses() { for (var i in process_map) { stopProcess(process_map[i]); } } function stopProcess(process){ var forcibly_exit = true; process.exit(forcibly_exit); } function compassExecutable() { return air.File.applicationDirectory.resolvePath('bin/compass').nativePath; } function jruby_complete_jar() { return air.File.applicationDirectory.resolvePath('vendor/jruby-complete.jar').nativePath; } function jar(path) { // air.trace(path); // var app_path = air.File.applicationDirectory.resolvePath('.'); // air.trace(app_path); // var jar_path = air.File.applicationDirectory.resolvePath(path); // air.trace(jar_path); // air.trace(app_path.getRelativePath(jar_path)); // return app_path.getRelativePath(jar_path); return air.File.applicationDirectory.resolvePath(path).nativePath; } function javaDir() { if(air.Capabilities.os.match(/Windows/)) { path = air.File.applicationDirectory.resolvePath("C:\\Program Files\\Java\\jre7\\bin\\java.exe"); if(!path.exists){ path = air.File.applicationDirectory.resolvePath("C:\\Program Files (x86)\\Java\\jre7\\bin\\java.exe"); if(!path.exists){ path = air.File.applicationDirectory.resolvePath("C:\\Program Files\\Java\\jre6\\bin\\java.exe"); } } return path; } else { return air.File.applicationDirectory.resolvePath("/usr/bin/java"); } } });
import babelpolyfill from 'babel-polyfill' import Vue from 'vue' import App from './App' import ElementUI from 'element-ui' import VueRouter from 'vue-router' import store from './vuex/store' import routes from './routes' import 'element-ui/lib/theme-chalk/index.css' import 'font-awesome/css/font-awesome.min.css' Vue.use(ElementUI); Vue.use(VueRouter); const router = new VueRouter({routes:routes}); router.beforeEach((to, from, next) => { if (to.path == '/login') sessionStorage.removeItem('token'); let token = JSON.parse(sessionStorage.getItem('token')); if (!token && to.path != '/login') { next({ path: '/login' }) } else { next() } }); new Vue({ router, store, render: h => h(App) }).$mount('#app')
const { ObjectId } = require('mongodb'); const { Incident } = require('../../models'); /** * resolve incident */ async function incident(__, { id }) { if (!ObjectId.isValid(id)) { throw new Error(`Incident ${id} is not valid`); } const incident = await Incident.findById(ObjectId(id)); return incident; } incident.type = 'Query'; module.exports = { incident };
"use strict"; /*global alert: true, ODSA, console */ (function ($) { var jsav; // for JSAV library object // create a new settings panel and specify the link to show it var settings = new JSAV.utils.Settings($(".jsavsettings")); // Initialize the arraysize dropdown list ODSA.AV.initArraySize(5, 12, 8); // Process About button: Pop up a message with an Alert function about() { var mystring = "Quicksort Algorithm Visualization\nWritten by Daniel Breakiron\nCreated as part of the OpenDSA hypertextbook project.\nFor more information, see http://opendsa.org.\nWritten during Summer, 2012\nLast update: July, 2012\nJSAV library version " + JSAV.version(); alert(mystring); } // Execute the "Run" button function function runIt() { var arrValues = ODSA.AV.processArrayValues(); // If arrValues is null, the user gave us junk which they need to fix if (arrValues) { ODSA.AV.reset(true); jsav = new JSAV($(".avcontainer"), {settings: settings}); // Initialize the original array var arr = jsav.ds.array(arrValues, {indexed: true}); jsav.displayInit(); // BEGIN QUICKSORT IMPLEMENTATION // Save the left edge of the original array so sublists can be positioned relative to it // leftEdge = parseFloat(arr.element.css("left")); leftEdge = 200; // Hack because arr.element.css is returning "auto" instead of position var level = 1; var leftOffset = 0; quicksort(arr, level, leftOffset); // END QUICKSORT IMPLEMENTATION jsav.umsg("Done sorting!"); jsav.recorded(); // mark the end } } // The space required for each row to be displayed var leftEdge = 0; function quicksort(arr, level, leftOffset) { var left = 0; var right = arr.size() - 1; // Correctly position the array setPosition(arr, level, leftOffset); jsav.umsg("Select the pivot"); var pivotIndex = Math.floor((left + right) / 2); arr.highlightBlue(pivotIndex); jsav.step(); jsav.umsg("Move the pivot to the end"); arr.swapWithStyle(pivotIndex, right); jsav.step(); jsav.umsg("Partition the subarray"); arr.setLeftArrow(left); arr.setRightArrow(right - 1); jsav.step(); // finalPivotIndex will be the final position of the pivot var finalPivotIndex = partition(arr, left, right - 1, arr.value(right)); jsav.umsg("When the right bound crosses the left bound, all elements to the left of the left bound are less than the pivot and all elements to the right are greater than or equal to the pivot"); jsav.step(); jsav.umsg("Move the pivot to its final location"); arr.toggleArrow(finalPivotIndex); arr.swapWithStyle(right, finalPivotIndex); arr.markSorted(finalPivotIndex); jsav.step(); // Create and display sub-arrays // Sort left partition var subArr1 = arr.slice(left, finalPivotIndex); if (subArr1.length === 1) { jsav.umsg("Left sublist contains a single element which means it is sorted"); arr.toggleArrow(finalPivotIndex - 1); jsav.step(); arr.toggleArrow(finalPivotIndex - 1); arr.markSorted(left); } else if (subArr1.length > 1) { var avSubArr1 = jsav.ds.array(subArr1, {indexed: true, center: false}); jsav.umsg("Call quicksort on the left sublist"); jsav.step(); quicksort(avSubArr1, level + 1, leftOffset); } // Sort right partition var subArr2 = arr.slice(finalPivotIndex + 1, right + 1); if (subArr2.length === 1) { jsav.umsg("Right sublist contains a single element which means it is sorted"); arr.toggleArrow(finalPivotIndex + 1); jsav.step(); arr.toggleArrow(finalPivotIndex + 1); arr.markSorted(finalPivotIndex + 1); } else if (subArr2.length > 1) { var avSubArr2 = jsav.ds.array(subArr2, {indexed: true, center: false}); jsav.umsg("Call quicksort on the right sublist"); jsav.step(); quicksort(avSubArr2, level + 1, leftOffset + finalPivotIndex + 1); } } function partition(arr, left, right, pivotVal) { var origLeft = left; while (left <= right) { // Move the left bound inwards jsav.umsg("Move the left bound to the right until it reaches a value greater than or equal to the pivot"); jsav.step(); while (arr.value(left) < pivotVal) { jsav.umsg("Step right"); arr.clearLeftArrow(left); left++; arr.setLeftArrow(left); jsav.step(); } arr.highlight(left); jsav.umsg("That is as far as we go this round"); jsav.step(); // Move the right bound inwards jsav.umsg("Move the right bound to the left until it crosses the left bound or finds a value less than the pivot"); jsav.step(); // If its desirable to have the right bound continue into sorted sections, replace origLeft with 0 while ((right > origLeft) && (right >= left) && (arr.value(right) >= pivotVal)) { jsav.umsg("Step left"); arr.clearRightArrow(right); right--; arr.setRightArrow(right); jsav.step(); } if (right > left) { arr.highlight(right); jsav.umsg("That is as far as we go this round"); jsav.step(); // Swap highlighted elements jsav.umsg("Swap the selected values"); arr.swap(left, right); jsav.step(); arr.unhighlight([left, right]); } else { jsav.umsg("Bounds have crossed"); arr.unhighlight(left); jsav.step(); break; } } // Clear the arrows and mark the final position of the pivot arr.clearLeftArrow(left); arr.clearRightArrow(right); arr.toggleArrow(left); // Return first position in right partition return left; } /** * Calculates and sets the appropriate 'top' and 'left' CSS values based * on the specified array's level of recursion and number of blocks the array should be offset from the left * * arr - the JSAV array to set the 'top' and 'left' values for * level - the level of recursion, the full-size array is level 1 * leftOffset - the number of blocks from the left the array should be positioned */ function setPosition(arr, level, leftOffset) { console.log("In setPosition with level " + level + " and leftOffset " + leftOffset + ". Also, leftEdge is " + leftEdge); var blockWidth = 46; var rowHeight = 80; var left = leftEdge + leftOffset * blockWidth; var top = rowHeight * (level - 1); console.log("Position for array: " + left + ", " + top); // Set the top and left values so that all arrays are spaced properly arr.element.css({"left": left, "top": top}); } // Connect action callbacks to the HTML entities $('#about').click(about); $('#run').click(runIt); $('#reset').click(ODSA.AV.reset); }(jQuery));
var mod = angular.module('mediaService', []); /* * This service is designed to handle local media. There are a few cross-platform * quirks that we want to centralize so that we don't need to handle the same * thing all over the place. */ mod.factory('MediaService', ['Environment', function(Environment) { var mediaService = {}; var playOptions = { playAudioWhenScreenIsLocked : false }; mediaService.isNative = function isNative() { return typeof window.Media != 'undefined'; } // src here is intended to be the www-relative source. So if something is in // www/img/goal.mp3, the source should be img/goal.mp3 mediaService.loadMedia = function loadMedia(src, elementId, statusCallback) { var prefix = ''; if (!src.startsWith('http') && window.device && window.device.platform && window.device.platform.toLowerCase() == 'android') { prefix = '/android_asset/www/'; } if (window.Media) { return new Media(prefix + src, function getMediaSuccess() { console.log("Loaded Media: " + src); }, function getMediaFailure() { console.log("Failed Loading Media: " + src); }, statusCallback); } else if (elementId) { var el = document.getElementById(elementId); el.src = src; return el; } } mediaService.setVolume = function setVolume(media, volume) { if (media.setVolume) { media.setVolume(volume); } else { media.volume = volume; } } mediaService.replayMedia = function replayMedia(media, options) { if (!mediaService.isNative()) { media.load(); media.play(); } else { if (!options) options = playOptions; media.play(options); } } return mediaService; }]);
/* При помощи цикла for выведите чётные числа от 2 до 10. */ for(let i = 2; i <=10; i++) { if (i%2 !== 0) continue; alert(i); }
cordova.define('cordova/plugin_list', function(require, exports, module) { module.exports = [ { "file": "plugins/phonegap-plugin-barcodescanner/www/barcodescanner.js", "id": "phonegap-plugin-barcodescanner.BarcodeScanner", "pluginId": "phonegap-plugin-barcodescanner", "clobbers": [ "cordova.plugins.barcodeScanner" ] }, { "file": "plugins/cordova-plugin-geolocation/www/Coordinates.js", "id": "cordova-plugin-geolocation.Coordinates", "pluginId": "cordova-plugin-geolocation", "clobbers": [ "Coordinates" ] }, { "file": "plugins/cordova-plugin-geolocation/www/PositionError.js", "id": "cordova-plugin-geolocation.PositionError", "pluginId": "cordova-plugin-geolocation", "clobbers": [ "PositionError" ] }, { "file": "plugins/cordova-plugin-geolocation/www/Position.js", "id": "cordova-plugin-geolocation.Position", "pluginId": "cordova-plugin-geolocation", "clobbers": [ "Position" ] }, { "file": "plugins/cordova-plugin-geolocation/www/geolocation.js", "id": "cordova-plugin-geolocation.geolocation", "pluginId": "cordova-plugin-geolocation", "clobbers": [ "navigator.geolocation" ] }, { "file": "plugins/com.unarin.cordova.beacon/www/lib/underscore-min-1.6.js", "id": "com.unarin.cordova.beacon.underscorejs", "pluginId": "com.unarin.cordova.beacon", "runs": true }, { "file": "plugins/com.unarin.cordova.beacon/www/lib/q.min.js", "id": "com.unarin.cordova.beacon.Q", "pluginId": "com.unarin.cordova.beacon", "runs": true }, { "file": "plugins/com.unarin.cordova.beacon/www/LocationManager.js", "id": "com.unarin.cordova.beacon.LocationManager", "pluginId": "com.unarin.cordova.beacon", "merges": [ "cordova.plugins" ] }, { "file": "plugins/com.unarin.cordova.beacon/www/Delegate.js", "id": "com.unarin.cordova.beacon.Delegate", "pluginId": "com.unarin.cordova.beacon", "runs": true }, { "file": "plugins/com.unarin.cordova.beacon/www/model/Region.js", "id": "com.unarin.cordova.beacon.Region", "pluginId": "com.unarin.cordova.beacon", "runs": true }, { "file": "plugins/com.unarin.cordova.beacon/www/Regions.js", "id": "com.unarin.cordova.beacon.Regions", "pluginId": "com.unarin.cordova.beacon", "runs": true }, { "file": "plugins/com.unarin.cordova.beacon/www/model/CircularRegion.js", "id": "com.unarin.cordova.beacon.CircularRegion", "pluginId": "com.unarin.cordova.beacon", "runs": true }, { "file": "plugins/com.unarin.cordova.beacon/www/model/BeaconRegion.js", "id": "com.unarin.cordova.beacon.BeaconRegion", "pluginId": "com.unarin.cordova.beacon", "runs": true }, { "file": "plugins/cordova-plugin-inappbrowser/www/inappbrowser.js", "id": "cordova-plugin-inappbrowser.inappbrowser", "pluginId": "cordova-plugin-inappbrowser", "clobbers": [ "cordova.InAppBrowser.open", "window.open" ] } ]; module.exports.metadata = // TOP OF METADATA { "cordova-plugin-whitelist": "1.3.1", "cordova-plugin-compat": "1.1.0", "cordova-plugin-crosswalk-webview": "2.1.0", "phonegap-plugin-barcodescanner": "6.0.4", "cordova-plugin-geolocation": "2.4.1", "com.unarin.cordova.beacon": "3.4.0", "cordova-plugin-inappbrowser": "1.6.1" } // BOTTOM OF METADATA });
import { DELETE_SUCCESS, GET_PERMISSIONS_SUCCESS, UPDATE_PERMISSIONS_SUCCESS, SHARE_SUCCESS, GET_HISTORY_SUCCESS, GET_RECORD_SUCCESS, REQUEST_SUCCESS, SEARCH_SUCCESS, VIEW_SUCCESS, CANCEL_REQUEST_SUCCESS, MEDHIS_INSERTED_SUCCESS, FIRST_HISTORY_SUCCESS, RECORD_INSERTED_SUCCESS, GET_ALL_RECORD_SUCCESS, ACCEPT_REQUEST_SUCCESS } from "./types"; import axios from "axios"; import { tokenConfig } from "./authActions"; import { returnErrors } from "./errorActions"; //Insert record of patient export const insertRecord = (record, viewId, shareToken) => ( dispatch, getState ) => { const token = getState().auth.token; // Headers const config = { headers: { "Content-type": "application/json" } }; if (token) { config.headers["x-auth-token"] = token; } // If token, add to headers if (shareToken) { config.headers["x-auth-token1"] = shareToken; } const { bloodPressure, pulseRate, respiratoryRate, temperature, heent, heart, lungs, abdomen, extremities, completeBloodCount, urinalysis, fecalysis, chestXray, isihiraTest, audio, psychologicalExam, drugTest, hepatitisBTest, complaints, diagnosis, treatment, remarks } = record; const body = { bloodPressure, pulseRate, respiratoryRate, temperature, heent, heart, lungs, abdomen, extremities, completeBloodCount, urinalysis, fecalysis, chestXray, isihiraTest, audio, psychologicalExam, drugTest, hepatitisBTest, complaints, diagnosis, treatment, remarks }; axios .post(`/api/clinician/addRecord/${viewId}`, body, config) .then((res) => dispatch({ type: RECORD_INSERTED_SUCCESS, payload: res.data }) ) .catch((err) => dispatch( returnErrors( err.response.data, err.response.status, "RECORD_INSERTED_FAIL" ) ) ); }; //Update history of patient export const insertHistory = (history, viewId, shareToken) => ( dispatch, getState ) => { const token = getState().auth.token; // Headers const config = { headers: { "Content-type": "application/json" } }; // If token, add to headers if (token) { config.headers["x-auth-token"] = token; } if (shareToken) { config.headers["x-auth-token1"] = shareToken; } const { pastIllness, famIllness, immunization, hospitalizations, operations, allergies, medication, bloodType, height, weight, bodyArt, habits, visualAcuity, menarchYear, menarchAge, mensDuration, dysmennorrhea } = history; const body = { pastIllness, famIllness, immunization, hospitalizations, operations, allergies, medication, bloodType, height, weight, bodyArt, habits, visualAcuity, menarchYear, menarchAge, mensDuration, dysmennorrhea }; axios .post(`/api/clinician/addHistory/${viewId}`, body, config) .then((res) => dispatch({ type: MEDHIS_INSERTED_SUCCESS, payload: res.data }) ) .catch((err) => dispatch( returnErrors( err.response.data, err.response.status, "MEDHIS_INSERTED_FAIL" ) ) ); }; //View patient medical record export const view = (_id, shareToken) => (dispatch, getState) => { const token = getState().auth.token; // Headers const config = { headers: { "Content-type": "application/json" } }; // If token, add to headers if (token) { config.headers["x-auth-token"] = token; } if (shareToken) { config.headers["x-auth-token1"] = shareToken; } axios .get(`/api/clinician/${_id}`, config) .then((res) => dispatch({ type: VIEW_SUCCESS, payload: res.data }) ) .catch((err) => { dispatch( returnErrors(err.response.data, err.response.status, "VIEW_FAIL") ); }); }; //Cancel request access to patient export const cancelRequest = (_id) => (dispatch, getState) => { const body = {}; axios .post(`/api/clinician/cancelRequest/${_id}`, body, tokenConfig(getState)) .then((res) => dispatch({ type: CANCEL_REQUEST_SUCCESS, payload: res.data }) ) .catch((err) => dispatch( returnErrors( err.response.data, err.response.status, "CANCEL_REQUEST_FAIL" ) ) ); }; //Request access to patient export const request = ({ _id, reason, message, duration, isRequested }) => ( dispatch, getState ) => { const body = JSON.stringify({ reason, message, duration, isRequested }); console.log(body); axios .post(`/api/clinician/request/${_id}`, body, tokenConfig(getState)) .then((res) => dispatch({ type: REQUEST_SUCCESS, payload: res.data }) ) .catch((err) => dispatch( returnErrors(err.response.data, err.response.status, "REQUEST_FAIL") ) ); }; //Search for patients export const search = (search) => (dispatch, getState) => { axios .get(`/api/clinician/search/${search}`, tokenConfig(getState)) .then((res) => dispatch({ type: SEARCH_SUCCESS, payload: res.data }) ) .catch((err) => { dispatch( returnErrors(err.response.data, err.response.status, "SEARCH_FAIL") ); }); }; //Get specific record for patient export const getRecord = (record) => (dispatch, getState) => { axios .get(`/api/patient/getRecord/${record}`, tokenConfig(getState)) .then((res) => dispatch({ type: GET_RECORD_SUCCESS, payload: res.data }) ) .catch((err) => { dispatch( returnErrors(err.response.data, err.response.status, "GET_RECORD_FAIL") ); }); }; //Get specific record for clinician export const specificCRecord = (patient, record, shareToken) => ( dispatch, getState ) => { const token = getState().auth.token; // Headers const config = { headers: { "Content-type": "application/json" } }; if (token) { config.headers["x-auth-token"] = token; } // If token, add to headers if (shareToken) { config.headers["x-auth-token1"] = shareToken; } axios .get(`/api/clinician/specificRecord/${patient}/${record}`, config) .then((res) => dispatch({ type: GET_RECORD_SUCCESS, payload: res.data }) ) .catch((err) => { dispatch( returnErrors(err.response.data, err.response.status, "GET_RECORD_FAIL") ); }); }; //Get all records of patient for clinician export const allCRecords = (patient, shareToken) => (dispatch, getState) => { const token = getState().auth.token; // Headers const config = { headers: { "Content-type": "application/json" } }; if (token) { config.headers["x-auth-token"] = token; } // If token, add to headers if (shareToken) { config.headers["x-auth-token1"] = shareToken; } axios .get(`/api/clinician/allRecords/${patient}`, config) .then((res) => dispatch({ type: GET_ALL_RECORD_SUCCESS, payload: res.data }) ) .catch((err) => { dispatch( returnErrors( err.response.data, err.response.status, "GET_ALL_RECORD_FAIL" ) ); }); }; //Get all records of patient export const allRecords = () => (dispatch, getState) => { const token = getState().auth.token; // Headers const config = { headers: { "Content-type": "application/json" } }; if (token) { config.headers["x-auth-token"] = token; } axios .get(`/api/patient/allRecords`, config) .then((res) => dispatch({ type: GET_ALL_RECORD_SUCCESS, payload: res.data }) ) .catch((err) => { dispatch( returnErrors( err.response.data, err.response.status, "GET_ALL_RECORD_FAIL" ) ); }); }; //Get specific history for patient export const getHistory = (id) => (dispatch, getState) => { axios .get(`/api/patient/specificHistory/${id}`, tokenConfig(getState)) .then((res) => dispatch({ type: GET_HISTORY_SUCCESS, payload: res.data }) ) .catch((err) => { dispatch( returnErrors(err.response.data, err.response.status, "GET_HISTORY_FAIL") ); }); }; //Get medical history for clinician export const getCHistory = (patient, medHis, shareToken) => ( dispatch, getState ) => { const token = getState().auth.token; // Headers const config = { headers: { "Content-type": "application/json" } }; if (token) { config.headers["x-auth-token"] = token; } // If token, add to headers if (shareToken) { config.headers["x-auth-token1"] = shareToken; } axios .get(`/api/clinician/specificHistory/${patient}/${medHis}`, config) .then((res) => dispatch({ type: GET_HISTORY_SUCCESS, payload: res.data }) ) .catch((err) => { dispatch( returnErrors(err.response.data, err.response.status, "GET_HISTORY_FAIL") ); }); }; //Get the first medical history of patient export const firstHistory = (patient, medHisId, shareToken) => ( dispatch, getState ) => { const token = getState().auth.token; // Headers const config = { headers: { "Content-type": "application/json" } }; if (token) { config.headers["x-auth-token"] = token; } // If token, add to headers if (shareToken) { config.headers["x-auth-token1"] = shareToken; } axios .get(`/api/clinician/firstHistory/${patient}/${medHisId}`, config) .then((res) => dispatch({ type: FIRST_HISTORY_SUCCESS, payload: res.data }) ) .catch((err) => { dispatch( returnErrors( err.response.data, err.response.status, "FIRST_HISTORY_FAIL" ) ); }); }; //Share patient record to clinician export const share = ({ email, expiration, canPrint, canInsert }) => ( dispatch, getState ) => { const body = JSON.stringify({ email, expiration, canPrint, canInsert }); axios .post("/api/patient/share", body, tokenConfig(getState)) .then((res) => dispatch({ type: SHARE_SUCCESS, payload: res.data }) ) .catch((err) => dispatch( returnErrors(err.response.data, err.response.status, "SHARE_FAIL") ) ); }; //Get all permissions for patient export const getPermissions = () => (dispatch, getState) => { localStorage.removeItem("permissions"); axios .get("/api/patient/permissions", tokenConfig(getState)) .then((res) => dispatch({ type: GET_PERMISSIONS_SUCCESS, payload: res.data }) ) .catch((err) => { dispatch( returnErrors( err.response.data, err.response.status, "GET_PERMISSIONS_FAIL" ) ); }); }; //Get all permissions for clinician export const getPermissionsC = () => (dispatch, getState) => { localStorage.removeItem("permissions"); axios .get("/api/clinician/permissions", tokenConfig(getState)) .then((res) => dispatch({ type: GET_PERMISSIONS_SUCCESS, payload: res.data }) ) .catch((err) => { dispatch( returnErrors( err.response.data, err.response.status, "GET_PERMISSIONS_FAIL" ) ); }); }; //Update permission of clinician export const updatePermission = (id, { canView, canPrint, canInsert }) => ( dispatch, getState ) => { const body = { canView, canPrint, canInsert }; axios .post(`/api/patient/update/permissions/${id}`, body, tokenConfig(getState)) .then((res) => dispatch({ type: UPDATE_PERMISSIONS_SUCCESS, payload: res.data }) ) .catch((err) => dispatch( returnErrors( err.response.data, err.response.status, "UPDATE_PERMISSION_FAIL" ) ) ); }; //Cancel the request of clinician export const cancel = (clinicianId, id) => (dispatch, getState) => { const body = {}; axios .post( `/api/patient/cancelRequest/${clinicianId}/${id}`, body, tokenConfig(getState) ) .then((res) => dispatch({ type: CANCEL_REQUEST_SUCCESS, payload: res.data }) ) .catch((err) => dispatch( returnErrors( err.response.data, err.response.status, "CANCEL_REQUEST_FAIL" ) ) ); }; //Accept the request of clinician export const accept = (clinicianId, duration, id) => (dispatch, getState) => { const body = {}; axios .post( `/api/patient/accept/${clinicianId}/${duration}/${id}`, body, tokenConfig(getState) ) .then((res) => dispatch({ type: ACCEPT_REQUEST_SUCCESS, payload: res.data }) ) .catch((err) => { dispatch( returnErrors( err.response.data, err.response.status, "ACCEPT_REQUEST_FAIL" ) ); }); }; export const deleteRecords = (record) => (dispatch, getState) => { dispatch({ type: DELETE_SUCCESS }); };
$(document).ready(function(){ var star; var question; var comment; var status; var data_id; var course; // var batch; $('.submit_click').attr('disabled','disabled'); question=$('.question').val(); course=$('.course').val(); $(document).on('click','.star_click',function(){ star=$(this).val(); $('.star_val').val(star); data_id=$(this).attr('data-id'); $('.faChkRnd').removeClass('check_status'); $('.submit_click').attr('disabled','disabled'); $.ajax({ url:"option_block_fac.php", method:"POST", data:{question:question,data_id:data_id,star:star,course:course}, success:function(response){ // $('.optionBlock').html(''); $('#'+data_id+'_block').html(response); $('.submit_click').removeAttr('disabled'); //var click_id =$() } }); }); $(document).on('click','.action_click',function(){ var action_val=$(this).attr('data-attr'); var action; var data_id; var batch=$('.batch').val(); var question=$('.question').val(); var star=$('.star_val').val(); var comments=$('.comment').val(); var cand_id=$('.cand_id').val(); var city_id=$('.city').val(); var cat_val=$('.cat_val').val(); //alert(action_val); if(action_val=='next') { action=0; var options="null"; star=0; data_id=0; comments=0; } else{ data_id=$(this).attr('data-id'); //alert(data_id); action=1; //alert('proceed'); checked = $(".check_status"+data_id+":checked").length; if(!checked) { alert("You must check at least one checkbox."); return false; } else{ // else{ var options=[]; $('.check_status'+data_id).each(function(){ if($(this).is(":checked")) { options.push($(this).val()); } }); options = options.toString(); window.location.replace('sample.php?id='+new_val); } } //alert(options); $.ajax({ // url:"action_pages/ajax/feedNextAjax.php", // method:"POST", // data:{question:question, // cand_id:cand_id, // city_id:city_id, // cat_val:cat_val, // star:star, // options:options, // comments:comments, // action:action, // data_id:data_id, // course:course, // batch:batch // }, // success:function(response){ // //alert(response); // var status_1=response.split('_'); // var status1=status_1[0]; // var new_val=status_1[1]; // //console.log(new_val); // if(status_1[0].includes("faculty")){ // $('.star'+data_id).attr('disabled','disabled'); // $('#'+data_id+'_block').hide(); // } // else if(status_1[0].includes("next")){ // window.location.replace('http://52.66.108.174/MilesFeedback/sample.php?id='+new_val); // } // else{ // window.location.replace('http://52.66.108.174/MilesFeedback/thankyou.php'); // } // } }); }); })
import React, { useState, useEffect } from 'react'; const TasksContainer = () => { // let alarms = []; const [alarms, setAlarmsList] = useState([]); useEffect(() => console.log("IN COMPONENT DID MOUNT")); chrome.alarms.getAll((alarmsList) => { console.log('lalarms', alarmsList); // alarms = alarmsList; if (JSON.stringify(alarmsList) != JSON.stringify(alarms)) { setAlarmsList(alarmsList); } }) const removeAlarm = (name) => { if (alarms.length) { setAlarmsList(alarms.filter(alarm => alarm.name !== name)); chrome.alarms.clear(name); } } return ( <div className="tasks-container"> <ul> { alarms.length ? alarms.map((alarm, index) => { let scheduledTimeInMillS = alarm.scheduledTime; let date = String(new Date(scheduledTimeInMillS)); return ( <> <li key={index}> {alarm.name} at {date.slice(date.indexOf(new Date().getFullYear()) + 5, date.indexOf('GMT') - 1)} <img src="../delete.svg" onClick={(e) => {e.preventDefault(); removeAlarm(alarm.name)}} className="cross-button"/> {/* <span onClick={(e) => {e.preventDefault(); removeAlarm(alarm.name)}} className="cross-button">X</span> */} </li> </> ) }) : '' } </ul> </div> ); }; export default TasksContainer;
/** * Calculates the number of days between start and end dates */ function daysBetween(start, end) { return Math.floor((end - start) / (1000 * 60 * 60 * 24)) + 1; } /** * Returns a date in format MM-DD-YYYY */ function niceDate(d) { return (d.getMonth() + 1) + '-' + d.getDate() + '-' + d.getFullYear(); } /** * Retrieves GET parameters from the URL */ function getUrlParameter(sParam) { var sPageURL = decodeURIComponent(window.location.search.substring(1)), sURLVariables = sPageURL.split('&'), sParameterName, i; for (i = 0; i < sURLVariables.length; i++) { sParameterName = sURLVariables[i].split('='); if (sParameterName[0] === sParam) { return sParameterName[1] === undefined ? true : sParameterName[1]; } } } /** * Returns true if d is a valid date */ function isValid(d) { return !isNaN(d.getTime()); } /** * Define custom String.format() */ String.prototype.format = function() { var args = arguments; return this.replace(/{(\d+)}/g, function(match, number) { return typeof args[number] != 'undefined' ? args[number] : match ; }); };
// 对象的函数解构 let json = { a: '张三', b: '李四', }; function func({ a, b = 'hi' }) { console.log(a, b); } func(json); // 数组解构 let arr = ['a', 'b']; function func2(a, b) { console.log(a, b); } func2(...arr); // in 的用法 let obj = { a: '张三', b: '李四', }; console.log('c' in obj); // false let arr2 = ['a', , ,]; console.log(0 in arr2); // true console.log(1 in arr2); // false /** * 数组遍历 */ let arr3 = ['a', 'b', 'c']; arr3.forEach((val, index) => { console.log(index, val); }); arr3.filter((x) => console.log(x)); arr3.some((x) => console.log(x)); let newArr = arr3.map((x) => (x = 'web')); console.log(newArr); /** * 数组转字符串 */ console.log(arr3.toString()); console.log(arr3.join('|'));
$.Transform = function (x, y) { this.position = new $.Vector(x, y) }
import React, { Component } from 'react'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; import Switch from 'react-router-dom/Switch'; import './App.css'; // Imports of ./Components import Header from './Components/Partials/Header'; import Footer from './Components/Partials/Footer'; import Home from './Components/Home/Home'; import About from './Components/About/About'; import Register from './Components/Register/Register'; import Login from './Components/Login/Login'; import Chat from './Components/Chat/Chat'; import NotFound from './Components/NotFound/NotFound'; import Contact from './Components/Contact/Contact'; // Font Awesome Library import { library } from '@fortawesome/fontawesome-svg-core'; import { faShare, faToolbox, faSmile } from '@fortawesome/free-solid-svg-icons'; library.add(faShare, faToolbox, faSmile); class App extends Component { render() { return ( <React.Fragment> <Header /> <Router> <div className="App"> <Switch> <Route exact path={"/"} component={Home} /> <Route path={"/chat"} component={Chat} /> <Route path={"/about"} component={About} /> <Route path={"/contact"} component={Contact} /> <Route path={"/login"} component={Login} /> <Route path={"/register"} component={Register} /> <Route component={NotFound} /> </Switch> </div> </Router> <Footer /> </React.Fragment> ); } } export default App;
import Race from './Race'; import raceTemplates from './raceTemplates'; export default class Aasimar extends Race { constructor(subKey) { super('aasimar'); this.subKey = subKey; this.statMods.charisma = 2; } }
import React from "react"; import styled from "styled-components"; import PropTypes from "prop-types"; import theme from "styled-theming"; const defaultColor = theme("mode", { light: "rgb(20, 23, 26)", dark: "rgb(255, 255, 255)" }); // const primaryColor = theme('mode', { // light: 'rgb(27, 149, 224)', // dark: 'rgb(27, 149, 224)', // }); const secondaryColor = theme("mode", { light: "rgb(101, 119, 134)", dark: "rgb(136, 153, 166)" }); // const warningColor = theme('mode', { // ligit: 'rgb(224, 36, 94);', // dark: 'rgb(224, 36, 94)', // }) const StyledText = styled.span` line-height: 1.3125; font-weight: ${props => (props.bold ? "700" : "400")}; color: ${props => { if (props.secondary) { return secondaryColor; } if (props.primary) { return "rgb(27, 149, 224)"; } if (props.warning) { return "rgb(224, 36, 94)"; } return defaultColor; }}; font-size: ${props => { if (props.small) return "12px"; if (props.large) return "18px"; if (props.xlarge) return "21px"; return "14px"; }}; `; export default function Text({ children, bold, secondary, primary, warning, small, large, xlarge }) { return ( <StyledText bold={bold} secondary={secondary} primary={primary} warning={warning} small={small} large={large} xlarge={xlarge} > {children} </StyledText> ); } Text.propTypes = { children: PropTypes.node, bold: PropTypes.bool, secondary: PropTypes.bool, primary: PropTypes.bool, warning: PropTypes.bool, small: PropTypes.bool, large: PropTypes.bool, xlarge: PropTypes.bool }; Text.defaultProps = { children: "", bold: false, secondary: false, primary: false, warning: false, small: false, large: false, xlarge: false }; /* color: ${props => props.secondary ? 'rgb(101, 119, 134)' : props.primary ? 'rgb(27, 149, 224)' : props.warning ? 'rgb(224, 36, 94)' : 'rgb(20, 23, 26)' }; */
/*****************Object cloning************* */ // first method var obj={"name":"abc","age":23} var obj2={} Object.assign( obj2, obj) console.log("obj2 : ", obj2) console.log("===============================================") // second method var obj={"name":"abc","age":23} Object.assign( {}, obj) console.log("obj2 : ", obj2)
// 只能存对象 // WeakSet值时唯一的 // 主要用来 let a = new WeakSet(), b = {}; // add(),has()和set的使用方法一样 a.add( b ); // a.add( b ); console.log( a.has( b ) ); // true
import { reactive, onMounted } from 'vue'; const useQuestionsAndAnswers = () => { const questions = reactive([]) const getQuestionsAndAnswers = async () => { const response = await fetch(`https://peaceful-hamlet-45136.herokuapp.com/questions`) const fetchedData = await response.json(); if(response.status === 200) { fetchedData.data.forEach(obj => questions.push(obj)) } else { console.log('Something went wrong') } }; onMounted(() => { getQuestionsAndAnswers(); }); return { questions } } export default useQuestionsAndAnswers;
var express = require('express'); var router = express.Router(); var goodModel = require('../model/goods'); var cateModel =require('../model/cates') var articleModel = require('../model/article') //新增商品 router.post('/addGood',function(req, res, next){ let { name, img, price, desc, hot, cate,id,create_time} = req.body var good = { hot:(hot ? hot :false), name, img, price, desc, cate, create_time:Date.now() } if (id) { goodModel.updateOne({_id:id},good).then(()=>{ res.json({err:0,msg:'修改成功'}) }) }else{ goodModel.insertMany([good]).then(()=>{ res.json({err:0,msg:'添加成功'}) }) } }) //删除 router.get('/del',function(req,res){ var {id} = req.query goodModel.deleteOne({_id:id}).then(()=>{ res.json({err:0,msg:'删除成功'}) }) }) // 获取全部品类 router.get('/getAllCates', function(req, res, next) { // 1 由小到大 cateModel.find({}).then(arr=>{ // console.log(arr) res.json({err:0,msg:'success',data:arr}) }).catch(err=>{ res.json({err:1,msg:'fail',err}) }) }) //商品详情 router.get('/detail',function(req,res){ var {good_id} = req.query goodModel.find({_id:good_id}).then(arr=>{ res.json({err:0,msg:'success',data:arr[0]}) }).catch(()=>{ res.json({err:1,msg:'没有找到当前商品'}) }) }) //文章 router.post('/create',function(req,res){ var {title,content} = req.body var article ={ title, content, author:'zhp', create_time:Date.now() } articleModel.insertMany([article]).then(()=>{ res.json({err:0,msg:'success'}) }) }) // 查询 router.get('/list',function(req,res){ var {page,size,name,hot,cate,max_price,min_price,brand,shop_id,create_time} = req.query //非必填数据处理 page = parseInt(page ? page : 1) size = parseInt(size ? size : 2) var params = { hot: hot ? hot :false, cate: cate ? cate : false, } if (!params.hot) delete params.hot if (!params.cate) delete params.cate goodModel.count().then(total=>{ goodModel.find(params).skip((page-1)*size).limit(size).sort({create_time:-1}).then(arr=>{ res.json({err:0,msg:'success',data:{ total:total, list:arr }}) }) }) }) module.exports = router;
import React, { Component } from 'react' import { Route, withRouter } from 'react-router-dom' import * as BooksAPI from './BooksAPI' import './App.css' import Shelf from './Shelf' import Search from './Search' class BooksApp extends Component { state = { currentlyReading: [], wantToRead: [], read: [] } componentDidMount() { BooksAPI.getAll() .then( (books) => { this.setState((currentState) => ({ currentlyReading: books.filter(b => b.shelf === 'currentlyReading'), wantToRead: books.filter(b => b.shelf === 'wantToRead'), read: books.filter(b => b.shelf === 'read'), })) } ) } onChangeShelf = (book, newShelfName) => { const oldShelfName = book.shelf BooksAPI.update(book, newShelfName) /* Em todos os casos, deve-se remover o livro da prateleira antiga */ this.setState((currentState) => ({ [oldShelfName]: currentState[oldShelfName].filter(b => b.id !== book.id) })) if (newShelfName !== 'none') { /* No caso da remoção de livros das estantes, não é necessário adicioná-lo em uma lista de nome 'none'. A aplicação nem salva os livros sem prateleira para poupar recursos e priorizar a performance. */ this.setState((currentState) => ({ [newShelfName]: currentState[newShelfName].concat(book), })) } /* Setando o atributo 'shelf' do livro, para que o select marque o valor correspondente à nova prateleira. */ book.shelf = newShelfName } render() { return ( <div className="app"> <Route path='/search' render={() => ( <Search onChangeShelf={this.onChangeShelf} currentlyReadingBooks={this.state.currentlyReading} wantToReadBooks={this.state.wantToRead} readBooks={this.state.read} /> )} /> <Route exact path='/' render={() => ( <div className="list-books"> <div className="list-books-title"> <h1>MyReads</h1> </div> <div className="list-books-content"> <div> <Shelf title='Currently Reading' books={this.state.currentlyReading} onChangeShelf={this.onChangeShelf} /> <Shelf title='Want to Read' books={this.state.wantToRead} onChangeShelf={this.onChangeShelf} /> <Shelf title='Read' books={this.state.read} onChangeShelf={this.onChangeShelf} /> </div> </div> <div className="open-search"> <button onClick={() => this.props.history.push('/search')}>Add a book</button> </div> </div> )} /> </div> ) } } export default withRouter(BooksApp)
let l = 400; let rain = []; let dropMax = 40; let sizeX = 4; let sizeY = 16; let offset = l; let layers; let fps; function setup() { fps = Math.floor(windowHeight/12); l = windowWidth-20; h = windowHeight-20; dropMax = l*h/4000; dropMax = Math.floor(dropMax); layers = Math.floor(fps/25)+1; createCanvas(l, h); frameRate(fps); alert(fps+" fps, "+layers+" layers, "+dropMax+" drops"); } function draw() { background(50); frameRate(fps); for (var i=0; i< dropMax; i++) { if (!rain[i]) { rain[i] = new Drop(); } else { rain[i].show(); } if (rain[i].posY > h) { rain[i] = false; } else { rain[i].fall(rain[i].vel, 0); } } } function Drop() { this.posX = Math.floor(Math.random()*l); this.posY = -(Math.floor(Math.random()*offset)); this.vel = Math.floor(Math.random()*layers)+1; this.fall = function(a, b) { this.posY += a; this.posX += b; } this.show = function() { fill(200/layers*this.vel, 200/layers*this.vel, 255); noStroke(); rect(this.posX, this.posY,sizeX,sizeY); } }
import React, { Component } from 'react'; import Question from './AnswerQuestion/Question'; export default class ExerciceDisplayer extends Component { render() { const { title, questions } = this.props.exercice; const { showScale, copy } = this.props; return ( <div> <div className="box notification is-info"> <div className="title">{title}</div> </div> {questions.map((question, index) => ( <Question key={question._id} question={question} showScale={showScale} index={index} copy={copy} /> ))} <div className="steps-actions"> <div className="buttons field is-grouped columns"> <div className="is-4 is-offset-8 column text-right"> <a href="#/" data-nav="next" className="button is-info is-outlined is-medium is-4 is-offset-8" onClick={this.props.handleNext} > <span className="icon"> <i className="fas fa-arrow-right"></i> </span> <span>Suivant</span> </a> </div> </div> </div> </div> ); } }
'use strict'; const { smart } = require('webpack-merge'); const config = require('../package.json'); const path = require('path'); const webpack = require('webpack'); const baseWebpackConfig = require('./webpack.base.js'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const utils = require('./utils/loaderConfig.js'); const { getIp } = require('./utils/nodeUtils.js'); const assetsRoot = config.buildConfig && config.buildConfig.base && config.buildConfig.base.assetsRoot ? "../" + config.buildConfig.base.assetsRoot : "../dist"; const port = config.buildConfig && config.buildConfig.dev && config.buildConfig.dev.port ? parseInt(config.buildConfig.dev.port) : 4444; const open = config.buildConfig && config.buildConfig.dev && config.buildConfig.dev.open === false ? config.buildConfig.dev.open : true; const localPublicPath = config.buildConfig && config.buildConfig.base && config.buildConfig.base.localPublicPath ? config.buildConfig.base.localPublicPath : config.buildConfig && config.buildConfig.dev && config.buildConfig.dev.localPublicPath ? config.buildConfig.dev.localPublicPath : '/'; const ifHttp = (config.buildConfig && config.buildConfig.dev && config.buildConfig.dev.https === true) ? config.buildConfig.dev.https : false const host = config.buildConfig && config.buildConfig.base && config.buildConfig.base.host ? config.buildConfig.base.host : config.buildConfig && config.buildConfig.dev && config.buildConfig.dev.host ? config.buildConfig.dev.host : 'localhost'; const sourceMap = config.buildConfig && config.buildConfig.base && config.buildConfig.base.sourceMap ? config.buildConfig.base.sourceMap : config.buildConfig && config.buildConfig.dev && config.buildConfig.dev.sourceMap ? config.buildConfig.dev.sourceMap : false; let imgAssetsPublicPath = config.buildConfig && config.buildConfig.base && config.buildConfig.base.imgAssetsPublicPath ? config.buildConfig.base.imgAssetsPublicPath : config.buildConfig && config.buildConfig.dev && config.buildConfig.dev.imgAssetsPublicPath ? config.buildConfig.dev.imgAssetsPublicPath : '/'; const proxyConfig = config.proxyConfig ? config.proxyConfig : {}; for (let i in proxyConfig) { proxyConfig[i].bypass = function (req, res, proxyOptions) { if (/.+\.webpack-hot-update\.json$/.test(req.url) || /favicon\.ico$/.test(req.url)) return false; // ----------------- if (config.buildConfig.dev.mode === 'history' && proxyOptions.context === '/**') throw new Error('history模式下请配置具体的代理匹配!'); // ----------------- res.setHeader("x-proxy-by", "luo-proxy"); res.setHeader("x-proxy-match", proxyOptions.context); res.setHeader("x-proxy-target", proxyOptions.target); res.setHeader("x-proxy-target-path", proxyOptions.target + req.url); } } const ip = getIp(1); module.exports = smart(baseWebpackConfig, { mode: 'development', output: { publicPath: localPublicPath === '/' ? '/' : localPublicPath.replace(/\/$/g, '') + '/', hotUpdateChunkFilename: 'hot/[hash].webpack-hot-update.js', hotUpdateMainFilename: 'hot/[hash].webpack-hot-update.json' }, devServer: { public: (host === 'localhost' ? ip : host) + (port === 80 ? '' : (':' + port)), host: '0.0.0.0', port, https: ifHttp, progress: true, inline: true, hotOnly: true, contentBase: path.resolve(__dirname, assetsRoot), open, overlay: { warnings: true, errors: true }, publicPath: localPublicPath === '/' ? localPublicPath : localPublicPath + "/", openPage: localPublicPath === '/' ? '' : localPublicPath.replace('/', '') + '/', proxy: proxyConfig, disableHostCheck: true, }, watch: true, watchOptions: { poll: 1000, aggregateTimeout: 500, ignored: /node_modules/ }, module: { rules: [ ...utils.cssLoaders(MiniCssExtractPlugin, sourceMap), utils.imgLoaders(imgAssetsPublicPath) ] }, devtool: sourceMap ? ((typeof sourceMap === 'string') ? sourceMap : 'source-map') : 'none', plugins: [ new HtmlWebpackPlugin({ favicon: path.join(__dirname, '../public', 'favicon.ico'), template: "./src/index.html", filename: "index.html", hash: true, }), new webpack.NamedModulesPlugin(), new webpack.HotModuleReplacementPlugin(), new MiniCssExtractPlugin({ filename: '[name]_[chunkhash].css' }), ] });
game.resources = [ /* Resources * these have all the sources for my game my background tiles, my meta, * my mario,mytitle screen, my slime, and my mushroom */ {name: "background-tiles", type:"image", src: "data/img/background-tiles.png"}, {name: "meta-tiles", type:"image", src: "data/img/meta-tiles.png"}, {name: "mario", type:"image", src: "data/img/player1.png"}, {name: "title-screen", type:"image", src: "data/img/title-screen.png"}, {name: "slime", type:"image", src: "data/img/slime-spritesheet.png"}, {name: "mushroom", type:"image", src: "data/img/mushroom.png"}, /* Atlases * @example * {name: "example_tps", type: "tps", src: "data/img/example_tps.json"}, */ /* Maps. *and these are the sources for my two maps */ {name: "level04", type: "tmx", src: "data/map/level04.tmx"}, {name: "level05", type: "tmx", src: "data/map/level05.tmx"}, /* Background music. * @example * {name: "example_bgm", type: "audio", src: "data/bgm/"}, */ /* Sound effects. * @example * {name: "example_sfx", type: "audio", src: "data/sfx/"} */ ];
function getDuplicates() { searchfield = $('[data-duplicate-searchfield]').attr('data-duplicate-searchfield'); if (searchfield) { var solrURL = webApplicationBaseURL + "/servlets/solr/select?q=*%3A*&rows=0&fl=id&wt=json&indent=true&facet=true&facet.field=" + searchfield; $.ajax({ method: "GET", url: solrURL, dataType: "json" }) .done(function( json ) { var html="<ul>"; var i = 0; var facets=json['facet_counts']['facet_fields']['recordIdentifier']; while (facets[i] && facets[i+1]) { ppn=facets[i]; count=facets[i+1]; link= webApplicationBaseURL + "/servlets/solr/select?q=%2BobjectType%3A%22mods%22+%2BrecordIdentifier%3A%22" + ppn + "%22&fl=*%2Cscore&rows=20"; if (count > 1) { html += '<li> <a href="' + link + '">' + ppn + '-' + count + '</a> </li>'; } i=i+2; } html+="</ul>"; $('[data-duplicate-searchfield]').html(html); }) .fail(function( jqXHR, ajaxOptions, thrownError ) { if(jqXHR.status==404) { var html='<div style="text-align:center;color:red;" >'+jqXHR.responseText+'</div>'; $('[data-duplicate-searchfield]').html(html); } else { $('[data-duplicate-searchfield]').html("Unknown Error during get FacetSearch"); } }); } }; $(document).ready( function() { //var $("[data-duplicate-searchfield]"); //if ($('#PPN')) getDuplicates(); });
var express = require('express'); var router = express.Router(); var dataModel = require('../model/data.model'); var config = require ('../config.js'); var fs = require ('fs'); router.get('/', function(req, res) { res.render('index', { title: 'Express' }); }); router.get('/help', function(req, res) { res.render('help', { title: 'Express' }); }); router.get('/import_temp', function(req, res) { res.render('import_temp', { title: 'Express' }); }); router.post('/import_data', function(req, res) { var data = req.param('data'); var data1 = JSON.parse(data); dataModel.import_rule(data1,function(returndata){ res.send(JSON.stringify({result:'ok',data: returndata})); }); /* var otype = req.query.otype; var eid = req.query.eid; var firstdate = req.query.firstdate; var seconddate = req.query.seconddate; var ruletemplate = req.query.ruletemplate;*/ /* dataModel.run_cmd(reporttemplate, otype, eid, firstdate, seconddate, ruletemplate, function (outdata) { if(!outdata){ res.send(JSON.stringify({result: 'err', data:''})); } else { res.send(JSON.stringify({result: 'ok', data: outdata})); } } );*/ }); router.get('/submit', function(req, res) { var reporttemplate = req.query.reporttemplate; var otype = req.query.otype; var eid = req.query.eid; var firstdate = req.query.firstdate; var seconddate = req.query.seconddate; var ruletemplate = req.query.ruletemplate; dataModel.run_cmd(reporttemplate, otype, eid, firstdate, seconddate, ruletemplate, function (outdata) { if(!outdata){ res.send(JSON.stringify({result: 'err', data:''})); } else { dataModel.createOutFile( outdata ,function (result){ res.send(JSON.stringify({result: 'ok', data: outdata, link:result})); }); } } ); }); module.exports = router;
const express = require('express'); const router = express.Router(); const pool = require('../database'); const { isLoggedIn } = require('../lib/auth'); // add maquina router.get('/add',isLoggedIn,(req,res) => { res.render ('equipos/add'); }); router.post('/add', async (req, res)=>{ const { equipo,tipo, codificacion, marca, modelo, serial, funcionamiento, observaciones} = req.body; const newlink ={ equipo, codificacion, tipo, marca, modelo, serial, funcionamiento, observaciones, user_id: req.user.id }; await pool.query('INSERT INTO lista_maquinas set ?',[newlink]); req.flash('success','Equipo Registrado') res.redirect('/equipos'); }); router.get('/', isLoggedIn, async (req,res) =>{ const equipos = await pool.query('SELECT * FROM lista_maquinas WHERE user_id = ?',[req.user.id]); res.render('equipos/lista_maquinas',{equipos}); }); // delete maquina router.get('/delete/:id', async (req,res) =>{ const {id} = req.params; await pool.query('DELETE FROM lista_maquinas WHERE ID= ?',[id]); req.flash('success','Equipo Borrado') res.redirect('/equipos'); }); // edit maquina router.get('/edit/:id',isLoggedIn, async (req,res) =>{ const {id} = req.params; const equipos = await pool.query('SELECT * FROM lista_maquinas WHERE ID= ?',[id]); res.render('equipos/edit',{link:equipos[0]}); }); router.post('/edit/:id',isLoggedIn, async (req, res)=>{ const {id}= req.params; const { equipo,tipo, codificacion, marca, modelo, serial, funcionamiento, observaciones} = req.body; const newlink ={ equipo, codificacion, tipo, marca, modelo, serial, funcionamiento, observaciones, user_id: req.user.id }; await pool.query('UPDATE lista_maquinas set ? WHERE ID= ?',[newlink, id]) req.flash('success','Equipo Editado') res.redirect('/equipos') }) // detalles router.get('/detalles/:id',isLoggedIn, async (req,res) =>{ const {id} = req.params; const equipo = await pool.query('SELECT * FROM lista_maquinas WHERE id= ?',[id]); res.render('equipos/detalles',{link:equipo[0]}); }); // serviciop tecmico module.exports = router;
$(function () { var data = [{ name: 'Tokyo', data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6] }, { name: 'New York', data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5] }, { name: 'Berlin', data: [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0] }, { name: 'London', data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8] }]; var categories = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; ChartsRendering.renderColumn('#container', data, categories); ChartsRendering.renderColumn('#container2', data, categories); ChartsRendering.renderColumn('#container3', data, categories); });
#!/usr/bin/env node "use strict"; var fs = require("fs"); var path = require("path"); var yargs = require("yargs"); var pkg = require("../package.json"); var ObsidianPackFile = require("obsidian-pack"); function getPackIndex(pack) { var index = {}; var assetList = pack.assetList; for (var i = 0 ; i < assetList.length ; i++) { var assetName = assetList[i]; index[assetName] = pack.getAssetRecord(assetName); } return index; } var argv = yargs .option("output", { describe: "Output file (print to stdout if not defined)", alias: "o", nargs: 1, normalize: true }) .option("pretty-print", { describe: "Makes the output JSON human-readable", alias: "p", type: "boolean" }) .version(pkg.version).alias("version", "v") .usage("Usage: obsidian-catalog [options] <packFiles>") .help().alias("help", "h") .example("obsidian-catalog assets1.opak assets2.opak") .example("obsidian-catalog -o catalog.json assets.opak") .locale("en") .argv; var catalog = { packages: {} }; for (var i = 0 ; i < argv._.length ; i++) { var packPath = argv._[i]; var packBin = fs.readFileSync(packPath); var pack = new ObsidianPackFile(packBin); catalog.packages[pack.packName] = { url: path.basename(packPath), assets: getPackIndex(pack) }; } var catalogStr = JSON.stringify(catalog, null, argv["pretty-print"] ? 2 : 0); if (argv.output) { fs.writeFileSync(argv.output, catalogStr); } else { console.log(catalogStr); }
define(["jquery"], function ($) { /** * Добавить задачу * @returns {} */ function addCase() { var task = { Name: $("#name-input").val(), Description: $("#description-input").val(), StartDate: $("#startDate-input").val(), EndDate: $("#endDate-input").val() }; $.ajax({ url: "api/values/", type: "POST", data: JSON.stringify(task), contentType: "application/json;charset=utf-8", success: function (id) { // При получении положительного ответа отрисовать на странице addCaseToUI(task, id); }, error: function () { alert("add error"); } }); } /** * Заполнение списка задач * @returns {} */ function getCases() { //$(function() { $.ajax({ url: "api/values", type: "GET", dataType: "json", success: function (data) { $.each(data, function (index, book) { addCaseToUI(book, book.Id); }); } }); //}); } /** * Удалить задачу * @param {} id - id задачи * @returns {} */ function removeCase(id) { $.ajax({ url: "api/values/" + id, type: "DELETE", contentType: "application/json;charset=utf-8", success: function () { // При получении положительного ответа убрать задачу со страницы removeCaseFromUI(id); }, error: function () { alert("remove case error"); } }); } /** * Удалить все задачи * @returns {} */ function removeAll() { $.ajax({ url: "api/values/", type: "DELETE", contentType: "application/json;charset=utf-8", success: function () { // При получении положительного ответа убрать все задачи // со страницы removeAllFromUI(); }, error: function () { alert("remove all error"); } }); } /** * Убирает задачу со страницы * @param {number} index - id задачи * @returns {} */ function removeCaseFromUI(index) { var tr = $("#" + index); tr.hide(1000); setTimeout(function () { tr.remove(); }, 1000); } /** * Убирает все задачи со страницы * @returns {} */ function removeAllFromUI() { var raws = $("#cases-table").find("tr"); var count = raws.length; while (--count > 0) { var index = raws[count].id; removeCaseFromUI(index); } } /** * Добавляет задачу на страницу * @param {Object} task задача * @param {number} index индекс задачи * @returns {} */ function addCaseToUI(task, index) { var tr = $("<tr>", { id: index }); $("<td>" + task.Name + "</td>").appendTo(tr); $("<td>" + task.Description + "</td>").appendTo(tr); $("<td>" + task.StartDate.split("T")[0] + "</td>").appendTo(tr); $("<td>" + task.EndDate.split("T")[0] + "</td>").appendTo(tr); var removeButton = $("<input />", { text: "Remove", type: "button", value: "Remove", id: "remove-btn-" + index }); $("<td>").append(removeButton).appendTo(tr); tr.show(1000).appendTo("#cases-table"); $("#remove-btn-" + index).click(function (event) { event.preventDefault(); removeCase(index); }); } return { addCase: addCase, removeCase: removeCase, removeAll: removeAll, removeCaseFromUI: removeCaseFromUI, addCaseToUI: addCaseToUI, removeAllFromUI: removeAllFromUI, getCases: getCases } });
'use strict'; var bcrypt = require('bcrypt'); var mongoose = require('mongoose'); var utils = require('../../utils'); /** * Schema defining the 'user' model. Note that there is no model for 'guest'. */ var UserSchema = module.exports = new mongoose.Schema({ /** * User type. Either temporary (guest) or standard (authenticated with a provider). */ account_type: { type: String, enum: ['temporary', 'standard'], required: true, default: 'temporary' }, /** * Nickname of the user. */ name: { type: String, required: true }, /** * URL path to the user's image */ avatar: { type: String, default: null }, /** * User's different possible authentication providers */ providers: { basic: { email: { type: String, match: /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/ }, password: { type: String } }, github: { id: String, token: String, name: String, avatar: String }, google: { id: String, token: String, email: String, name: String } }, /** * Timestamp for the user creation date */ created_at: { type: Date }, /** * Timestamp for the last time the user was edited */ edited_at: { type: Date } }); if(!UserSchema.options.toJSON) UserSchema.options.toJSON = { } if(!UserSchema.options.toObject) UserSchema.options.toObject = { } // Remove the sensitive stuff from 'user' when JSONized. UserSchema.options.toJSON.transform = function(doc, ret) { // ret.id = doc.id; // ret.type = 'user'; // ret.username = doc.email; //delete ret._id; //delete ret.__v; // delete ret.token; // delete ret.password; if (doc.providers) { if (doc.providers.basic) { doc.providers.basic.password = ''; } } return { 'id': doc.id, 'avatar': doc.avatar, 'username': doc.name, 'account_type': doc.account_type, 'providers': doc.providers } } /** * BUG See 'config/schemas/board.js' for details. */ UserSchema.options.toObject.transform = UserSchema.options.toJSON.transform; /** * Validates password with regexp. * Reference: https://kb.wisc.edu/page.php?id=4073 */ UserSchema.path('providers.basic.password').validate(function() { var user = this; if(!user.isModified('providers.basic.password')) { return true; } return /^[a-zA-Z0-9!"#$%&'()*+,-.\/:;<=>?@\[\]^_`{|}~]{8,36}$/.test(user.providers.basic.password); }, null); /** * Hash the users password using 'bcrypt' if modified. */ UserSchema.pre('save', function hashPassword(next) { var user = this; user.edited_at = Date.now(); if(!user.isModified('providers.basic.password')) { return next(); } var SALT_FACTOR = 10; bcrypt.genSalt(SALT_FACTOR, function(err, salt) { if(err) { return next(utils.error(500, err)); } bcrypt.hash(user.providers.basic.password, salt, function(err, hash) { if(err) { return next(utils.error(500, err)); } user.providers.basic.password = hash; return next(); }); }); }); /** * Compare the given plaintext password with the stored (hashed) password. */ UserSchema.methods.comparePassword = function(password, callback) { bcrypt.compare(password, this.providers.basic.password, callback); }
import React, { Component } from "react"; import juiceHead from "../images/juiceHead.png"; import pachaMama from "../images/pachaMama.png"; import glasBasix from "../images/glasBasix.png"; import naked from "../images/naked.png"; import twist from "../images/twist.png"; export default function Ejuice() { return ( <div className="ejuice-wrapper"> <div className="product-link-wrapper"> <h2>Juice Head</h2> <div className="juiceHead-wrapper"> <img src={juiceHead} width={200} height={300}></img> </div> <h2>Pacha Mama</h2> <div className="pachaMama-wrapper"> <img src={pachaMama} width={200} height={100}></img> </div> <h2>Glas Basix</h2> <div className="glasBasix-wrapper"> <img src={glasBasix}></img> </div> <h2>Naked</h2> <div className="naked-wrapper"> <img src={naked}></img> </div> <h2>Twist</h2> <div className="twist-wrapper"> <img src={twist}></img> </div> </div> </div> ) }
// TODO add error handling for incorrect requests module.exports = collectionName => ({ get: async (req, res) => { res.json(await req.storage.get(collectionName)); }, post: async (req, res) => { try { const result = await req.storage.add(collectionName, req.body); res.json(result); } catch (err) { console.log(err); res.status(400); res.json({ error: err }); } }, getById: async (req, res) => { try { const result = await req.storage.get(collectionName, req.params.id); res.json(result); } catch (err) { console.log(err); if (err instanceof ReferenceError) { res.status(404); res.json({ error: 'ID not found: ' + req.params.id }); return; } res.status(400); res.json({ error: err }); } }, postById: async (req, res) => { try { const result = await req.storage.set(collectionName, req.params.id, req.body); res.json(result); } catch (err) { console.log(err); if (err instanceof ReferenceError) { res.status(404); res.json({ error: 'ID not found: ' + req.params.id }); return; } res.status(400); res.json({ error: err }); } }, deleteById: async (req, res) => { try { await req.storage.delete(collectionName, req.params.id); res.json({count: 1}); } catch (err) { console.log(err); if (err instanceof ReferenceError) { res.status(404); res.json({ error: 'ID not found: ' + req.params.id }); return; } res.status(400); res.json({ error: err }); } } });
'use strict'; //counting sheep function sheepCounter(sheep){ if(sheep === 0){ console.log('All sheep jumped over the fence'); return; } console.log(`${sheep}: Another sheep jumps over the fence`); return sheepCounter(sheep - 1); } sheepCounter(6);
var gulp = require('gulp'); var csso = require('gulp-csso'); var uglify = require('gulp-uglify'); var jshint = require('gulp-jshint'); var stylus = require('gulp-stylus'); var template = require('gulp-template'); var htmlmin = require('gulp-htmlmin'); var autoprefixer = require('gulp-autoprefixer'); var md5File = require('md5-file'); gulp.task('contrast-css', function () { gulp.src([dirname + '/app/contrast/contrast.styl']) .pipe(stylus()) .pipe(autoprefixer({ browsers: ['last 2 versions'] })) .pipe(csso()) .pipe(gulp.dest(dirname + '/public/contrast')); }); gulp.task('contrast-js', function () { gulp.src([dirname + '/app/contrast/contrast.js']) .pipe(jshint()) .pipe(jshint.reporter('default')) .pipe(uglify()) .pipe(gulp.dest(dirname + '/public/contrast')); }); gulp.task('contrast-production', ['contrast-css', 'contrast-js'], function () { gulp.src([dirname + '/app/contrast/contrast.html']) .pipe(template({ hashContrastCss: md5File(dirname + '/public/contrast/contrast.css').substring(0, 10), hashContrastJs: md5File(dirname + '/public/contrast/contrast.js').substring(0, 10) })) .pipe(htmlmin({ collapseWhitespace: true, removeComments: true, minifyCSS: true })) .pipe(gulp.dest(dirname + '/public/contrast')); }); gulp.task('contrast-js-dev', function () { gulp.src([dirname + '/app/contrast/contrast.js']) .pipe(jshint()) .pipe(jshint.reporter('default')) .pipe(gulp.dest(dirname + '/public/contrast')); }); gulp.task('contrast', ['contrast-css', 'contrast-js-dev'], function () { gulp.src([dirname + '/app/contrast/contrast.html']) .pipe(template({ hashContrastCss: md5File(dirname + '/public/contrast/contrast.css').substring(0, 10), hashContrastJs: md5File(dirname + '/public/contrast/contrast.js').substring(0, 10) })) .pipe(gulp.dest(dirname + '/public/contrast')); });
const mongoose = require("mongoose"); const chatSchema = new mongoose.Schema ({ msgFrom: { type: String, default: "", required: true }, msgTo: { type: String, default: "", required: true }, msg: { type: String, default: "", required: true }, room: { type: String, default: "", required: true }, createdOn: { type: Date, default: Date.now } }); mongoose.model("Chat", chatSchema);
var langEngine = require(process.cwd() + '/engine/translates/langs.js') ,async = require('async'); var Passport = null; var Travelelogue = null; var pgClient = null; module.exports = { /** * * @param server * @param Hapi */ $init : function(server, Hapi){ Travelelogue = server.plugins.travelogue; pgClient = server.pgClient; } // get Hapi Config ,$getConfig : function(){ return { auth:'passport', get_get : { auth:false, params : '{params*}' }, index_get : { auth : 'passport' },stat_get : { auth : 'passport' },import_post : { params : '{params*}' },langs_get:{ auth : false } } }, langs_get : function(request){ var dataContainer = { lang_of_names : 'en' }; langEngine.getlangs(pgClient, ['lang','name','translate','status'], dataContainer, function(err,data){ response(request, err, {'langs':data}); }); }, addlang_post : function(request){ // var dataContainer = { // lang : 'cz', // name : 'Czech', // lang_of_name: 'en' // }; var dataContainer = request.payload; dataContainer.lang_of_name = 'en'; langEngine.addlang(pgClient, dataContainer, function(err){ response(request, err, 'ok'); }); }, get_get : function(request){ // http://localhost:8080/admin/translates/get/en/second/?fields=data,description,link,key&type=api&group=1 // note : #get-type - default angular-static // type = angular-static - output in json for angular static // api - standard output for editor // csv - output in csv format with ';' // second : second language if is the primary not available - mostly english // group : specify just the group of translates var data = request.params.params.split('/'); var dataContainer = { lang: data[0] }; if(data.length > 1){ dataContainer.second = data[1]; } if(data.length > 1){ dataContainer.page = data[1]; } else { dataContainer.page = false; } // note : #get-type var type = 'angular-static'; if(request.query.type){ type = request.query.type; } var fields = ['link']; // angular-static have just key and data if(type == 'angular-static') { fields = ['key','data']; }else if(type == 'csv') { fields = ['link','data']; dataContainer.byLinkId = true; }else if(request.query.fields){ fields = request.query.fields.split(',') ; } if(request.query.lastUpdateFirst && request.query.lastUpdateFirst=='true'){ dataContainer.lastUpdateFirst = true; } if(!isNaN(request.query.group)){ dataContainer.group = request.query.group; } console.log(fields, dataContainer); langEngine.get(pgClient, fields, dataContainer, function(err,data){ if(err || type == 'api'){ response(request, err, {page: dataContainer.page, trans:data, lang:dataContainer.lang}); } else if(type=='csv'){ var out = ''; data.forEach(function(trans){ out += trans.link.toString() + ';' + (trans.data ? trans.data.split('\n').join(' ') : '') +"\n"; }); request.reply(out).type('text/plain'); } else { var out = {}; data.forEach(function(trans){ out[trans.key] = trans.data; }); request.reply(out); } }); },add_post : function(request){ var dataContainer = request.payload; if(!dataContainer.lang){ response(request, 'field \'lang\' missing'); return ; } if(!dataContainer.key){ response(request, 'field \'key\' missing'); return ; } if(!dataContainer.desc){ response(request, 'field \'desc\' missing'); return ; } langEngine.addtranslate(pgClient, dataContainer, function(err,data){ response(request, err, data); }); },update_post : function(request){ var dataContainer = request.payload; if(!dataContainer.lang){ response(request, 'field \'lang\' missing!'); return ; } if(!dataContainer.link){ response(request, 'field \'link\' missing!'); return ; } if(!dataContainer.data){ response(request, 'field \'data\' missing!'); return ; } langEngine.translate(pgClient, dataContainer, function(err,data){ response(request, err, data); }); },updatedesc_post : function(request){ var dataContainer = request.payload; if(!dataContainer.key){ response(request, 'field \'key\' missing!'); return ; } if(!dataContainer.link){ response(request, 'field \'link\' missing!'); return ; } if(!dataContainer.desc){ response(request, 'field \'desc\' missing!'); return ; } langEngine.updatedesc(pgClient, dataContainer, function(err,data){ response(request, err, data); }); },import_post : function(request){ console.log('req3432', request.payload); if(!request.payload.csv){ response(request, 'csv missing'); return ; } var params = request.params.params.split('/'); var lang = params[0]; var funcs = []; var lines = request.payload.csv.split('\n'); var errorApear = lines.some(function(line, idx){ if(line && !isBlank(line)){ funcs.push(function(icb){ // issue if(line.indexOf(';') < 0){ response(request, 'line: '+idx+' missing separator for link and data'); return true; } var linkData = line.split(';'); var linkT = linkData.shift(); var link = parseInt(linkT.trim()); if(isNaN(link)){ response(request, 'line: '+idx+' link is not a number'); return true; } var data = linkData.join(';').trim(); var dataContainer = { lang: lang, link : link, data : data } console.log('translate', dataContainer); langEngine.translate(pgClient, dataContainer, icb); }); } }); if(!errorApear){ async.parallel(funcs, function(err, data){ response(request, err, 'ok'); }); } // } } function isBlank(str) { return (!str || /^\s*$/.test(str)); } function response(request, err, data){ if(err){ request.reply({error:err, success:-1}).code(400); } else { request.reply({success:1,error:'',response:data}); } }
import React, { useEffect, useState } from "react"; import Header from "./Header"; // this below component is for typing and adding new item import Additem from "./Additem"; // this component is each list item. map is used to use it multiple times. import Item from "./Item"; function App(){ // for storing all the to do list const [listArray,setListArray]=useState([]); // for local starage purpose (used inside deleteFunc) var tempArray = []; // for getting data from local storage (if any) during the reload useEffect(()=>{ const temp1 = localStorage.getItem("data"); if(temp1!==null){ console.log("probe"); setListArray(JSON.parse(temp1)); } },[]) // the input that is fed to this function gets added to the list array // this function is passed down to components as props function addToList(input){ setListArray(previous=>{ localStorage.setItem("data",JSON.stringify([...previous,input])); return [...previous,input]; }) } // the array item of index that is fed to this function gets deleted // this is also passed down to components. function deleteFunc(index){ setListArray(previous=>{ tempArray = previous.filter((item,ind)=>{ return (ind!==index) }) localStorage.setItem("data",JSON.stringify(tempArray)); return tempArray; }) } return <div> <Header /> <Additem addToList={addToList} /> {listArray.map((item,index)=>{ return <Item item={item} key={index} id={index} deleteFunc={deleteFunc} /> })} </div> } export default App;
/* * * BasketCardsRenderer constants * */ export const DEFAULT_ACTION = 'app/BasketCardsRenderer/DEFAULT_ACTION';
import React from "react"; import { Container, Row, Col, Form, Input, Modal, ModalBody, ModalHeader, ModalFooter, FormGroup, Label, NavLink, Button, Alert } from "reactstrap"; import { insertRecord } from "../../actions/blockchainActions"; import { connect } from "react-redux"; import CircularProgress from "@material-ui/core/CircularProgress"; import { clearErrors } from "../../actions/errorActions"; class InsertMedicalRecords extends React.Component { state = { msg: "", loading: false, modal2: false, bloodPressure: "", pulseRate: "", respiratoryRate: "", temperature: "", heent: "", heart: "", lungs: "", abdomen: "", extremities: "", completeBloodCount: "", urinalysis: "", fecalysis: "", chestXray: "", isihiraTest: "", audio: "", psychologicalExam: "", drugTest: "", hepatitisBTest: "", complaints: "", diagnosis: "", treatment: "", remarks: "", shareToken: "" }; componentDidMount() { const { permissions, viewId } = this.props.medrec; this.setState({ shareToken: permissions[permissions.findIndex((per) => per.patientId === viewId)] .shareToken }); } componentDidUpdate(prevProps) { const { error } = this.props; if (error !== prevProps.error) { if (error.id === "RECORD_INSERTED_FAIL") { this.setState({ msg: error.msg.msg, loading: false }); } else { this.setState({ msg: null }); } } } toggle2 = () => { this.setState({ modal2: !this.state.modal2 }); this.props.clearErrors(); }; onChange = (e) => { this.setState({ [e.target.name]: e.target.value }); }; onSubmit = (e) => { e.preventDefault(); this.setState({ loading: true }); const { bloodPressure, pulseRate, respiratoryRate, temperature, heent, heart, lungs, abdomen, extremities, completeBloodCount, urinalysis, fecalysis, chestXray, isihiraTest, audio, psychologicalExam, drugTest, hepatitisBTest, complaints, diagnosis, treatment, remarks } = this.state; const record = { bloodPressure, pulseRate, respiratoryRate, temperature, heent, heart, lungs, abdomen, extremities, completeBloodCount, urinalysis, fecalysis, chestXray, isihiraTest, audio, psychologicalExam, drugTest, hepatitisBTest, complaints, diagnosis, treatment, remarks }; this.props.insertRecord( record, this.props.medrec.viewId, this.state.shareToken ); }; render() { if (this.props.medrec.msg === "RECORD_INSERTED_SUCCESS") { window.location.assign("/records"); } return ( <Form> <Container> <h2 className="dataDesign">Insert Record</h2> <Label> <h5 className="dataDesign">Physical Examination Findings</h5> </Label> <Container className="div2"> <Row style={{ borderBottomStyle: "solid", paddingTop: "10px" }}> <Col lg="2"> <FormGroup className="dataDesign">Vital Signs</FormGroup> </Col> <Col lg="8"> <Row> <Col> <Row> <Col lg="5"> <Label for="bloodPressure">Blood Pressure</Label> </Col> <Col> <FormGroup> <Input onChange={this.onChange} type="text" id="bloodPressure" name="bloodPressure" placeholder="Enter blood pressure" /> </FormGroup> </Col> </Row> </Col> <Col> <Row> <Col lg="5"> <Label for="pulseRate">Pulse Rate</Label> </Col> <Col> <FormGroup> <Input onChange={this.onChange} type="text" id="pulseRate" name="pulseRate" placeholder="Enter pulse rate" /> </FormGroup> </Col> </Row> </Col> </Row> <Row> <Col> <Row> <Col lg="5"> <Label for="respiratoryRate">Respiratory Rate</Label> </Col> <Col> <FormGroup> <Input onChange={this.onChange} type="text" id="respiratoryRate" name="respiratoryRate" placeholder="Enter respiratory rate" /> </FormGroup> </Col> </Row> </Col> <Col> <Row> <Col lg="5"> <Label for="temperature">Temperature</Label> </Col> <Col> <FormGroup> <Input onChange={this.onChange} type="text" id="temperature" name="temperature" placeholder="Enter temperature" /> </FormGroup> </Col> </Row> </Col> </Row> </Col> </Row> <Row style={{ borderBottomStyle: "solid", paddingTop: "10px" }}> <Col lg="2"> <FormGroup className="dataDesign"> Physical Examination </FormGroup> </Col> <Col> <Row> <Col lg="4"> <FormGroup> <Label for="heent">HEENT</Label> <Input onChange={this.onChange} type="textarea" name="heent" id="heent" /> </FormGroup> </Col> <Col lg="4"> <FormGroup> <Label for="heart">Heart</Label> <Input onChange={this.onChange} type="textarea" name="heart" id="heart" /> </FormGroup> </Col> <Col lg="4"> <FormGroup> <Label for="lungs">Lungs</Label> <Input onChange={this.onChange} type="textarea" name="lungs" id="lungs" /> </FormGroup> </Col> </Row> <Row> <Col lg="4"> <FormGroup> <Label for="abdomen">Abdomen</Label> <Input onChange={this.onChange} type="textarea" name="abdomen" id="abdomen" /> </FormGroup> </Col> <Col lg="4"> <FormGroup> <Label for="extremities">Extremities</Label> <Input onChange={this.onChange} type="textarea" name="extremities" id="extremities" /> </FormGroup> </Col> </Row> </Col> </Row> <Row style={{ paddingTop: "10px" }}> <Col lg="2"> <FormGroup className="dataDesign">Laboratory Workups</FormGroup> </Col> <Col> <Row> <Col lg="4"> <FormGroup> <Label for="completeBloodCount"> Complete Blood Count(CBC) </Label> <Input onChange={this.onChange} type="textarea" name="completeBloodCount" id="completeBloodCount" /> </FormGroup> </Col> <Col lg="4"> <FormGroup> <Label for="urinalysis">Urinalysis</Label> <Input onChange={this.onChange} type="textarea" name="urinalysis" id="urinalysis" /> </FormGroup> </Col> <Col lg="4"> <FormGroup> <Label for="fecalysis">Fecalysis</Label> <Input onChange={this.onChange} type="textarea" name="fecalysis" id="fecalysis" /> </FormGroup> </Col> </Row> <Row> <Col lg="4"> <FormGroup> <Label for="chestXray">Chest X-ray(CXR)</Label> <Input onChange={this.onChange} type="textarea" name="chestXray" id="chestXray" /> </FormGroup> </Col> <Col lg="4"> <FormGroup> <Label for="isihiraTest">Ishihara Test</Label> <Input onChange={this.onChange} type="textarea" name="isihiraTest" id="isihiraTest" /> </FormGroup> </Col> <Col lg="4"> <FormGroup> <Label for="audio">Audio</Label> <Input onChange={this.onChange} type="textarea" name="audio" id="audio" /> </FormGroup> </Col> </Row> <Row> <Col lg="4"> <FormGroup> <Label for="psychologicalExam">Psychological Exam</Label> <Input onChange={this.onChange} type="textarea" name="psychologicalExam" id="psychologicalExam" /> </FormGroup> </Col> <Col lg="4"> <FormGroup> <Label for="drugTest">Drug Test</Label> <Input onChange={this.onChange} type="textarea" name="drugTest" id="drugTest" /> </FormGroup> </Col> <Col lg="4"> <FormGroup> <Label for="hepatitisBTest">Hepatitis B Test</Label> <Input onChange={this.onChange} type="textarea" name="hepatitisBTest" id="hepatitisBTest" /> </FormGroup> </Col> </Row> </Col> </Row> </Container> <br /> <Container className="div2" style={{ paddingTop: "10px" }}> <Row> <Col lg="6"> <FormGroup> <Label className="dataDesign" for="complaints"> Complaints </Label> <Input onChange={this.onChange} type="textarea" name="complaints" id="complaints" /> </FormGroup> </Col> <Col lg="6"> <FormGroup> <Label className="dataDesign" for="diagnosis"> Diagnosis </Label> <Input onChange={this.onChange} type="textarea" name="diagnosis" id="diagnosis" /> </FormGroup> </Col> </Row> <Row> <Col lg="6"> <FormGroup> <Label className="dataDesign" for="treatment"> Treatment </Label> <Input onChange={this.onChange} type="textarea" name="treatment" id="treatment" /> </FormGroup> </Col> <Col lg="6"> <FormGroup> <Label className="dataDesign" for="remarks"> Remarks </Label> <Input onChange={this.onChange} type="textarea" name="remarks" id="remarks" /> </FormGroup> </Col> </Row> </Container> <div> <Button className="fixedright1" color="primary" style={{ marginTop: "1.5rem", borderRadius: "40px", width: "100px" }} onClick={this.toggle2} > <b>Insert</b> </Button> <Modal style={{ textAlign: "center" }} centered isOpen={this.state.modal2} modalTransition={{ timeout: 700 }} backdropTransition={{ timeout: 1300 }} toggle2={this.toggle2} size="md" > <ModalHeader style={{ justifyContent: "center" }}> <h2 className="dataDesign">Insert Record?</h2> </ModalHeader> <ModalBody> {this.state.msg ? ( <Alert color="danger"> {this.state.msg}</Alert> ) : null} <h5> You can't edit this record once you click insert. Are you sure? </h5> </ModalBody> <ModalFooter style={{ justifyContent: "center" }}> <Button color="secondary" style={{ fontWeight: "bold", height: "40px", borderRadius: "20px", width: "100px" }} onClick={this.toggle2} > <b>Go back</b> </Button> <Button color="primary" style={{ fontWeight: "bold", borderRadius: "20px", width: "100px", height: "40px" }} onClick={this.onSubmit} disabled={this.state.loading} > {this.state.loading ? ( <CircularProgress color="light" size="25px" /> ) : ( "Insert" )} </Button> </ModalFooter> </Modal> <NavLink href="/records" className="logout"> <b>Cancel</b> </NavLink> </div> </Container> </Form> ); } } const mapStateToProps = (state) => ({ medrec: state.medrec, error: state.error }); export default connect(mapStateToProps, { insertRecord, clearErrors })( InsertMedicalRecords );
import React from 'react'; import { Form, FormGroup, Label, Input, FormFeedback, Button } from 'reactstrap'; import { Fade } from 'react-reveal'; export class ContactForm extends React.Component { constructor(props) { super(props); this.state = { email: false, idea: false, description: false, name: false, emailValue: '', ideaValue: '', descriptionValue: '', nameValue: '', mailto: '', }; this.checkInput = this.checkInput.bind(this); this.handleInputChange = this.handleInputChange.bind(this); } handleInputChange(event) { const target = event.target; const value = target.value; const name = target.name; this.setState({ [name]: value }); } checkInput() { let valid = true; if (this.state.descriptionValue.length < 20) { this.setState({ description: true }) valid = false; } else { this.setState({ description: false }) } if (this.state.ideaValue.length < 5) { this.setState({ idea: true }) valid = false; } else { this.setState({ idea: false }) } if (!(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(this.state.emailValue))) { this.setState({ email: true }) valid = false; } else { this.setState({ email: false }) } if (this.state.nameValue.length < 2) { this.setState({ name: true }) valid = false; } else { this.setState({ name: false }) } if (valid) { let mailtoString = "mailto:imandrewh@outlook.com" + "?subject=" + this.state.ideaValue + "&body=" + "Dear TwoForLoops Crew,%0D%0A%0D%0A" + this.state.descriptionValue + "%0D%0A%0D%0ASincerely,%0D%0A" + this.state.nameValue +"%0D%0A" +this.state.emailValue; this.setState({ mailto: mailtoString, }); let x = window.open(mailtoString); x.close(); } } render() { return ( <Form> <Fade top cascade> <FormGroup> <Label>Name*</Label> <Input placeholder="John Doe" value={this.state.nameValue} invalid={this.state.name} onChange={this.handleInputChange} name="nameValue" /> <FormFeedback>{this.props.nameError}</FormFeedback> </FormGroup> <FormGroup> <Label>Email*</Label> <Input placeholder="example@example.com" value={this.state.emailValue} invalid={this.state.email} onChange={this.handleInputChange} name="emailValue" /> <FormFeedback>{this.props.emailError}</FormFeedback> </FormGroup> <FormGroup> <Label>Idea*</Label> <Input placeholder="Mobile Application" value={this.state.ideaValue} invalid={this.state.idea} onChange={this.handleInputChange} name="ideaValue" /> <FormFeedback>{this.props.ideaError}</FormFeedback> </FormGroup> <FormGroup> <Label>Tell Us More*</Label> <Input placeholder="I want to make Tinder, but for animals" invalid={this.state.description} value={this.state.descriptionValue} type="textarea" onChange={this.handleInputChange} name="descriptionValue" /> <FormFeedback>{this.props.descriptionError}</FormFeedback> <div className="small text-muted">This will open an email client since this is a hosted template</div> </FormGroup> </Fade> <Fade bottom> <div className="text-right"> <Button onClick={this.checkInput} href={this.state.mailto}>Send</Button> </div> </Fade> </Form> ); } } ContactForm.defaultProps = { ideaError: "Please enter an idea", emailError: "Please enter a valid email", descriptionError: "Please give a little more detail", nameError: "Please enter a name", }
import React from "react"; const PersonForm = ({ handleAddAndUpdate, handleName, handleNumber, newName, newNumber, }) => { return ( <form onSubmit={handleAddAndUpdate}> <div> name: <input name="name" onChange={handleName} value={newName} /> </div> <div> number: <input name="number" onChange={handleNumber} value={newNumber} /> </div> <div> <button type="submit">add</button> </div> </form> ); }; export default PersonForm;
export formProgress from './formProgress'; export auth from '../../pages/auth/ducks/auth';
var arr = [1,2,3,4,5,6,7,8,9,"Vitalik"] function findElement(array, value) { for(var i = 0; i < arr.length; i++){ if(value === arr[i]){ return i; } } return -1; } console.log(findElement(arr, "Vitalik"));
import { request } from "./base"; export const getWorkspaces = () => { return request('/api/workspaces'); }; export const getChannels = () => { return request('/api/channels') } export const getMessages = (channelId) => { return request(`/api/channels/${channelId}/messages`); } export const sendMessage = (body, channel) => { return request('/api/messages', { ...body, channel, }, 'POST'); }
const $ = jQuery = jquery = require ("jquery") const common = require ("cloudflare/common") const notification = require ("cloudflare/core/notification") const modal = require ("cloudflare/core/modal") function filterResults ( term, results ) { let searchTerm = ( term + "" ).toLowerCase ().trim () return results.filter ( entry => { return ( entry.notes + "" ).toLowerCase ().indexOf ( searchTerm ) > -1 || ( entry.configuration.value + "" ).toLowerCase ().indexOf ( searchTerm ) > -1 }) } function sortResults ( section, results ) { let pivot = $(section).find (".sort-asc, .sort-desc") if ( pivot.length > 0 ) { let access = ( obj, path ) => { return path.reduce ( ( o, i ) => o [ i ], obj ) } let attribute = $(pivot).data ("sort").split (".") let isAsc = $(pivot).hasClass ("sort-asc") === true results = results.sort ( ( a, b ) => { let aValue = (access ( a, attribute ) + "").toLowerCase () let bValue = (access ( b, attribute ) + "").toLowerCase () if ( isAsc ) { if ( aValue < bValue ) return -1 if ( aValue > bValue ) return 1 return 0 } else { if ( aValue > bValue ) return -1 if ( aValue < bValue ) return 1 return 0 } }) } return results } function sortResults ( section, results ) { let pivot = $(section).find (".sort-asc, sort-desc") if ( pivot.length > 0 ) { let access = ( obj, path ) => { return path.reduce ( ( o, i ) => o [ i ], obj ) } let attribute = $(pivot).data ("sort").split (".") results = results.sort ( ( a, b ) => { let aValue = (access ( a, attribute ) + "").toLowerCase () let bValue = (access ( b, attribute ) + "").toLowerCase () if ( $(pivot).hasClass ("sort-desc") ) { if ( aValue > bValue ) return -1 if ( aValue < bValue ) return 1 return 0 } else { if ( aValue < bValue ) return -1 if ( aValue > bValue ) return 1 return 0 } }) } return results } function populateResult ( section ) { let results = $(section).data ("result") || [] results = filterResults ( $(section).find (".search").val (), results ) results = sortResults ( section, results ) let table = $(section).find ("table > tbody") $(section).data ( "item-count", results.length ) let itemCount = $(section).data ("item-count") let page = $(section).data ("page") let pageSize = $(section).data ("page-size") let pageCount = Math.ceil ( itemCount / pageSize ) let from = pageSize * ( page - 1 ) + 1 if ( itemCount == 0 ) from = 0 let to = Math.min ( pageSize * page, itemCount ) $(section).find (".pagination_container .pages").html ("") $(section).find (".pagination_container .showing").html (`${from} - ${to} of ${itemCount} rules`) let pages = $(section).find (".pagination_container .pages") let createPage = ( number ) => { return $(`<span class="page" >`) .addClass ( number == page ? "" : "trigger" ) .addClass ( number == page ? "current" : "" ) .data ( "target", "page" ) .data ( "page", number ) .text ( number ) } if ( pageCount > 7 ) { $(pages).append ( createPage ( 1 ) ) if ( pageCount > 7 && page > 4 ) { $(pages).append ( $(`<span>`).text ("...") ) } let start = Math.max ( 2, page - 3 ) let end = Math.min ( pageCount - 1, page + 3 ) if ( page - 4 < 0 ) end += Math.abs ( page - 4 ) if ( page + 3 > pageCount ) start -= page + 3 - pageCount if ( pageCount <= 7 && page < 4 ) end -= 1 if ( pageCount <= 7 && page > 4 ) start += 1 for ( let i = start; i <= end; i++ ) { $(pages).append ( createPage ( i ) ) } if ( pageCount > 7 && page < pageCount - 3 ) { $(pages).append ( $(`<span>`).text ("...") ) } $(pages).append ( createPage ( pageCount ) ) } else { for ( let i = 1; i <= pageCount; i++ ) { $(pages).append ( createPage ( i ) ) } } if ( page == 1 ) { $(section).find (".previous").addClass ("disabled") } else { $(section).find (".previous").removeClass ("disabled") } if ( page == pageCount ) { $(section).find (".next").addClass ("disabled") } else { $(section).find (".next").removeClass ("disabled") } $(table).html ("") let appended = 0 for ( let i = 0; i < results.length; i++ ) { if ( i >= ( page - 1 ) * pageSize && i < page * pageSize ) { let entry = results [ i ] $(table).append ( $(`<tr>`) .append ( $(`<td>`) .text ( entry.configuration.value ) .append ( $(`<span>`).text ( entry.notes ) ) .css ({ width: "100%" }) ) .append ( $(`<td>`).text ("This website") ) .append ( $(`<td>`).css ( "display", "flex" ) .html ( modal.createSelect ( "mode", [ { "label": "Block", "value": "block", selected: entry.mode == "block" }, { "label": "Challenge", "value": "challenge", selected: entry.mode == "challenge" }, { "label": "Whitelist", "value": "whitelist", selected: entry.mode == "whitelist" }, { "label": "JavaScript Challenge", "value": "js_challenge", selected: entry.mode == "js_challenge" } ]) .css ({ minWidth: "200px" }) .addClass ("trigger-select") .data ( "target", "mode" ) .data ( "id", entry.id ) ) .append ( modal.createIconButton ( "trigger edit", "&#xF013;" ) .data ( "id", entry.id ) .data ( "note", entry.notes ) .data ( "target", "edit" ) ) .append ( modal.createIconButton ( "trigger delete", "&#xF01A;" ) .data ( "id", entry.id ) .data ( "target", "delete" ) ) ) ) } } if ( results.length == 0 ) { $(table).append ( $("<tr>").append ( $("<td colspan='6' >").text ("No access rules found.") ) ) } } $(document).on ( "cloudflare.firewall.access_rules.initialize", function ( event, data ) { $(data.section).data ( "result", data.response.result ) populateResult ( data.section ) $(data.section).removeClass ("loading") }) $(document).on ( "cloudflare.firewall.access_rules.sort", function ( event, data ) { $(data.section).data ( "page", 1 ) $(data.section).data ( "sort", $(data.trigger).data ("sort") ) if ( $(data.trigger).hasClass ("sort-asc") ) { $(data.trigger).siblings ().removeClass ("sort-asc").removeClass ("sort-desc") $(data.trigger).removeClass ("sort-asc").addClass ("sort-desc") $(data.section).data ( "direction", "desc" ) } else if ( $(data.trigger).hasClass ("sort-desc") ) { $(data.trigger).siblings ().removeClass ("sort-asc").removeClass ("sort-desc") $(data.trigger).removeClass ("sort-asc").removeClass ("sort-desc") $(data.section).data ( "direction", "" ) } else { $(data.trigger).siblings ().removeClass ("sort-asc").removeClass ("sort-desc") $(data.trigger).addClass ("sort-asc") $(data.section).data ( "direction", "asc" ) } populateResult ( data.section ) }) $(document).on ( "cloudflare.firewall.access_rules.search", function ( event, data ) { $(data.section).data ( "page", 1 ) let table = $(data.section).find ("table > tbody") $(table).children ().remove () populateResult ( data.section ) }) $(document).on ( "cloudflare.firewall.access_rules.add", function ( event, data ) { $(data.section).addClass ("loading") var value = $(data.section).find ("[name='value']").val () var mode = $(data.section).find ("[name='mode']").val () var note = $(data.section).find ("[name='note']").val () var target = "" switch ( true ) { case /^[a-z]{2}$/i.test ( value ): target = "country" break case /AS[0-9]+/.test ( value ): target = "asn" break case /\//.test ( value ): target = "ip_range" break default: target = "ip" } $.ajax ({ url: data.form.endpoint, type: "POST", data: { "form_key": data.form.key, "target": target, "value": value, "mode": mode, "note": note }, success: function ( response ) { notification.showMessages ( response ) $(data.section).addClass ("loading") $(data.section).find ("[name='value']").val ("") $(data.section).find ("[name='mode']").val ("block") $(data.section).find ("[name='note']").val ("") common.loadSections (".access_rules") } }) common.loadSections (".access_rules") }) $(document).on ( "cloudflare.firewall.access_rules.delete", function ( event, data ) { var confirm = new modal.Modal () confirm.addTitle ("Confirm") confirm.addElement ( $("<p>").text (`Are you sure you want to delete this rule?`) ) confirm.addButton ({ label: "OK", callback: ( components ) => { confirm.close () $(data.section).addClass ("loading") var id = $(data.trigger).data ("id") $.ajax ({ url: data.form.endpoint, type: "POST", data: { "form_key": data.form.key, "id": id }, success: function ( response ) { notification.showMessages ( response ) common.loadSections (".access_rules") } }) }}) confirm.addButton ({ label: "Cancel", class: "gray", callback: confirm.close }) confirm.show () }) $(document).on ( "cloudflare.firewall.access_rules.mode", function ( event, data ) { $(data.section).addClass ("loading") var id = $(data.trigger).data ("id") var mode = $(data.trigger).val () $.ajax ({ url: data.form.endpoint, type: "POST", data: { "form_key": data.form.key, "id": id, "mode": mode }, success: function ( response ) { notification.showMessages ( response ) common.loadSections (".access_rules") } }) }) $(document).on ( "cloudflare.firewall.access_rules.edit", function ( event, data ) { let notes = modal.createTextarea ( "notes", "", $(data.trigger).data ("note") ).css ({ margin: "22.5px 22.5px 0 22.5px", width: "calc(100% - 45px)", fontSize: "1.1em" }) let edit = new modal.Modal ( 800 ) edit.addTitle ("Edit notes") edit.addElement ( notes ) edit.addButton ({ label: "Close", class: "gray", callback: edit.close }) edit.addButton ({ label: "Save", callback: ( components ) => { edit.close () $(data.section).addClass ("loading") $.ajax ({ url: data.form.endpoint, type: "POST", data: { "form_key": data.form.key, "id": $(data.trigger).data ("id"), "note": notes.val () }, success: function ( response ) { notification.showMessages ( response ) common.loadSections (".access_rules") } }) }}) edit.show () }) $(document).on ( "cloudflare.firewall.access_rules.page", function ( event, data ) { $(data.section).data ( "page", $(data.trigger).data ("page") ) populateResult ( data.section ) }) $(document).on ( "cloudflare.firewall.access_rules.next_page", function ( event, data ) { if ( $(data.section).data ("page") + 1 <= Math.ceil ( $(data.section).data ("item-count") / $(data.section).data ("page-size") ) ) { $(data.section).data ( "page", $(data.section).data ("page") + 1 ) populateResult ( data.section ) } }) $(document).on ( "cloudflare.firewall.access_rules.previous_page", function ( event, data ) { if ( $(data.section).data ("page") - 1 > 0 ) { $(data.section).data ( "page", $(data.section).data ("page") - 1 ) populateResult ( data.section ) } })
// JScript File // Da includere come ultimo elemento javascript /// <summary> /// Costanti per tipologia allegati /// </summary> var C_TIPO_ALLEGATO_PRENOTAZIONE_VIAGGIO = 1; var C_TIPO_ALLEGATO_NOTA_SPESA = 3; /* window.onload = function() { //disabilita combinazione tasti (CTRL+"n") //disableCtrlModifer(); if (parent.frames.length > 1) { //Il controllo sull'esistenza del divLoading è necessario per pagine come l'Help if (top.document.getElementById('divLoading')) { top.displayLoading(0); } if (parent.document.getElementById('hViewMenu')) { if (parent.document.getElementById('hViewMenu').value == "0") { if (document.getElementById('testataViaggiatore') || document.getElementById('dettaglioFatturato') || document.getElementById('testataEvento')) { self.parent.viewHideMenu(0, 0); } else if (document.getElementById('tblEventi')) { //Questo elseif serve per nascondere il menu e visualizzare la TOP per il profilo eventi. } } else self.parent.viewHideMenu(1, 1); } //Nel caricamento della pagina controllo se sono nella pagina del Report if (parent.document.getElementById("divBack")) { parent.document.getElementById("divBack").style.display = "none"; } } $(document).ready(function() { $('#boxRicercaAvanzata').keypress(function(e) { if (e.keyCode == 13) { $('#btnCerca').click(); } }); }); } */ //+---------------------------------------------------------------------------- // // Codice eseguito sempre al caricamento della pagina // // Description: Disabilito Hystory della pagina // //----------------------------------------------------------------------------- window.history.forward(0); //+---------------------------------------------------------------------------- // // Codice eseguito sempre al caricamento della pagina // // Description: Disabilito tasto destro del mouse // //----------------------------------------------------------------------------- //try //{ // $(document).bind("contextmenu",function(e){return false;}); //} //catch ( e ) //{ //} //+---------------------------------------------------------------------------- // // disableCtrlModifer // // Description: Disabilito combinazione tasti // //----------------------------------------------------------------------------- function disableCtrlModifer() { $(document).bind('keydown', 'Ctrl+c', function () { alert('copy anyone?'); }); //$(document).bind('keydown', 'Ctrl+t', false); //apri nuovo tab //$(document).bind('keydown', 'ctrl+n', false); //apri nuova pagina } function trim(str) { // Legenda RegExp: //(\s = spazio, * = zero o più occorrenze, ^ = inizio input, & = fine input) // Il primo replace toglie tutti gli spazi partendo dal primo carattere // Il secondo replace toglie poi gli spazi partendo dall'ultimo carattere if (str) return str.replace(/^\s*/, '').replace(/\s*$/, ''); else return ""; } function Replace(StringToReplace, StringToChange, StringChangedIn) { var re = new RegExp(StringToChange, "ig"); StringToReplace = StringToReplace.replace(re, StringChangedIn); return StringToReplace; } function viewHideSearch() { if ($('#boxRicercaAvanzata').is(':visible')) $("#boxRicercaAvanzata").hide(); else $("#boxRicercaAvanzata").show(); } //Questa funzione serve per nascondere o visualizzare il div che viene visualizzato quando //una pagina sta caricando qualcosa o salvando. function displayLoading(val) { if (top.document.getElementById('divLoading')) { if (val == 1) top.document.getElementById('divLoading').style.display = 'block'; else top.document.getElementById('divLoading').style.display = 'none'; } } //+---------------------------------------------------------------------------- // // Function: base_Js_ApriPopup // // Description: Funzione che apre una nuova finestra // // Arguments: // // Returns: // // //----------------------------------------------------------------------------- var wnd = null; function Js_ApriPopup(percorso, nomewin, toolbar, location, directories, status, menubar, scrollbars, resizable, left, top, width, height) { if (nomewin == "newAddressWindow") { uniqueName = new Date(); nomewin = uniqueName.getTime(); } if (wnd != null) { if (wnd.closed || wnd.name != nomewin) { wnd = window.open(percorso, nomewin, 'toolbar=' + toolbar + ',location=' + location + ',directories=' + directories + ',status=' + status + ',menubar=' + menubar + ',scrollbars=' + scrollbars + ',resizable=' + resizable + ',left=' + left + ',top=' + top + ',width=' + width + ',height=' + height + ''); } else { if (wnd.document.getElementById('fieldChanged').value == 0) { wnd.location.href = percorso; } else { //SGA nota: da rendere in lingua... spostare in basepage! if (confirm('Dati modificati. \nOK= apri nuova scheda e perdi modifiche \nCancel=apri scheda esistente mantenendo le modifiche')) { wnd.location.href = percorso; } } wnd.focus(); } } else { wnd = window.open(percorso, nomewin, 'toolbar=' + toolbar + ',location=' + location + ',directories=' + directories + ',status=' + status + ',menubar=' + menubar + ',scrollbars=' + scrollbars + ',resizable=' + resizable + ',left=' + left + ',top=' + top + ',width=' + width + ',height=' + height + ''); } } //AR Funzioni per gestione popup Report // Script Js ApriReport var winReport = null; function apriReport(percorso) { percorso = percorso.replace(/\xA3/gi, "\'"); percorso = percorso.replace(/\xE7/gi, "\\"); winReport = window.open(percorso, 'newreport', 'toolbar=0,location=0,directories=0,status=1,menubar=1,scrollbars=1,resizable=1,left=0, top=0,width=1020,height=700'); //Aspetta e poi chiude la maschera del report //////////AR commentato per test remoto setTimeout(chiudiReport, 100); return false; } function chiudiReport() { if (winReport.document.body) { //winReport.document.body.style.border='10px solid green'; winReport.document.onmouseover = function () { winReport.close(); }; //winReport.close() } else { setTimeout(chiudiReport, 100); } } //Aggiunta da SVA per test. function pausecomp(millis) { var date = new Date(); var curDate = null; do { curDate = new Date(); } while (curDate - date < millis); } function viewPages(idName, objLink) { var elArr = getElementsByClassName("panel"); //Pulisco gli attributi 'selected' su tutto il menu var menuArr = getElementsByClassName("menuItem"); for (var i = 0; i < menuArr.length; i++) { menuArr[i].className = menuArr[i].className.replace("selected", ""); } //Metto l'attributo 'selected' sul link relativo al div visualizzato for (var i = 0; i < elArr.length; i++) { with (elArr[i]) { var id = elArr[i].id; if (id == idName) { document.getElementById(id).style.display = "block"; objLink.className += " selected"; document.getElementById("panelName").value = id; } else { document.getElementById(id).style.display = "none"; } } } } /* Developed by Robert Nyman, http://www.robertnyman.com Code/licensing: http://code.google.com/p/getelementsbyclassname/ PARAMETERS className: One or several class names, separated by space. Multiple class names demands that each match have all of the classes specified. Mandatory. tag: Specifies the tag name of the elements to match. Optional. elm: Reference to a DOM element to look amongst its children for matches. Recommended for better performance in larger documents. Optional. CALL EXAMPLES ---To get all elements in the document with a “info-links” class--- getElementsByClassName("info-links"); ---To get all div elements within the element named “container”, with a “col” class--- getElementsByClassName("col", "div", document.getElementById("container")); ---To get all elements within in the document with a “click-me” and a “sure-thang” class--- getElementsByClassName("click-me sure-thang"); */ var getElementsByClassName = function (className, tag, elm) { if (document.getElementsByClassName) { getElementsByClassName = function (className, tag, elm) { elm = elm || document; var elements = elm.getElementsByClassName(className), nodeName = (tag) ? new RegExp("\\b" + tag + "\\b", "i") : null, returnElements = [], current; for (var i = 0, il = elements.length; i < il; i += 1) { current = elements[i]; if (!nodeName || nodeName.test(current.nodeName)) { returnElements.push(current); } } return returnElements; }; } else if (document.evaluate) { getElementsByClassName = function (className, tag, elm) { tag = tag || "*"; elm = elm || document; var classes = className.split(" "), classesToCheck = "", xhtmlNamespace = "http://www.w3.org/1999/xhtml", namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace) ? xhtmlNamespace : null, returnElements = [], elements, node; for (var j = 0, jl = classes.length; j < jl; j += 1) { classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]"; } try { elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null); } catch (e) { elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null); } while ((node = elements.iterateNext())) { returnElements.push(node); } return returnElements; }; } else { getElementsByClassName = function (className, tag, elm) { tag = tag || "*"; elm = elm || document; var classes = className.split(" "), classesToCheck = [], elements = (tag === "*" && elm.all) ? elm.all : elm.getElementsByTagName(tag), current, returnElements = [], match; for (var k = 0, kl = classes.length; k < kl; k += 1) { classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)")); } for (var l = 0, ll = elements.length; l < ll; l += 1) { current = elements[l]; match = false; for (var m = 0, ml = classesToCheck.length; m < ml; m += 1) { match = classesToCheck[m].test(current.className); if (!match) { break; } } if (match) { returnElements.push(current); } } return returnElements; }; } return getElementsByClassName(className, tag, elm); }; /* Funzioni di base (originariamente nella BasePage) */ //+---------------------------------------------------------------------------- // // Function: base_Js_ShowErrorMessage // // Description: Apertura popup per messaggio errore // // Arguments: message = messaggio da visualizzare // // Returns: // //----------------------------------------------------------------------------- function ShowErrorMessage(message) { alert(message); } //+---------------------------------------------------------------------------- // // Function: closeWindowOpenerRefresh // // Description: Effettua il refresh della maschera chiamante e chiude la finestra corrente // // Arguments: // // Returns: // //----------------------------------------------------------------------------- function closeWindowOpenerRefresh() { window.opener.location.reload(true); self.close(); } //+---------------------------------------------------------------------------- // // Function: closeWindowOpenerSubmit // // Description: Effettua il submit del form della maschera chiamante e chiude la finestra corrente // // Arguments: // // Returns: // //----------------------------------------------------------------------------- function closeWindowOpenerSubmit() { window.opener.document.form1.submit(); self.close(); } //+---------------------------------------------------------------------------- // // Function: windowOpenerSubmit // // Description: Effettua il submit del form della maschera chiamante // // Arguments: // // Returns: // //----------------------------------------------------------------------------- function windowOpenerSubmit() { window.opener.document.form1.submit(); } //+---------------------------------------------------------------------------- // // Function: closeWindowConRefresh // // Description: Chiude il Thickbox ricaricando la pagina chiamante (chiamare da Thickbox) // ATTENZIONE! Assicurarsi che la pagina chiamante abbia form1!!!!!! // Arguments: percorso = percorso della maschera chiamante relativo alla pagina corrente // // Returns: // //----------------------------------------------------------------------------- function closeWindowConRefresh(percorso) { //self.parent.document.location.href = percorso; self.parent.document.form1.submit(); } //+---------------------------------------------------------------------------- // // Function: windowRefresh // // Description: Ricarica la pagina corrente (chiamare da Thickbox) // // Arguments: percorso = percorso della maschera corrente // // Returns: // //----------------------------------------------------------------------------- function windowRefresh(percorso) { //window.location.href=percorso; self.document.location.href = percorso; } //+---------------------------------------------------------------------------- // // Function: closeThickBoxConRefresh // // Description: Chiude il Thickbox ricaricando la pagina chiamante (chiamare da Thickbox) // ATTENZIONE! Assicurarsi che la pagina chiamante abbia form1!!!!!! // Arguments: percorso = percorso della maschera chiamante relativo alla pagina corrente // // Returns: // //----------------------------------------------------------------------------- function closeThickBoxConRefresh(percorso) { self.parent.document.location.href = percorso; //self.parent.document.form1.submit(); } //+---------------------------------------------------------------------------- // // Function: ativaOptionsDisabled // // Description: Visualizza i campi disabilitati dei DropDown in colore diverso e ne impedisce la selezione all'onChange() // // Arguments: // // Returns: // // P.S. Aggiungere nella head della pagina contenente combobox contenente anche elementi disabilitati il seguente codice javascript // // <!--[if lte IE 7]> // addEvent(window, 'load', ativaOptionsDisabled); // <![endif]--> // P.S. 2 Se si tratta di una pagina caricata con ThickBox, il codice sopra non funziona; basta aggiungere // $(document).ready(function(){ // ativaOptionsDisabled() // }); //----------------------------------------------------------------------------- function ativaOptionsDisabled() { var sels = document.getElementsByTagName('select'); for (var i = 0; i < sels.length; i++) { // AR Ci sono problemi ad aggiungere l'onchange a tutti i combo (si cancellano gli altri eventi onchange) // Per il momento ci si limita a considerare solo i combo che possono avere campi disabilitati e ad imporre // questo solo evento onchange. In futuro indagare su una soluzione definitiva. if (sels[i].className.indexOf("DropWithDisabled") != -1) { sels[i].onchange = function () { if (this.options[this.selectedIndex].disabled) { // AR Decommentando questo codice, quando viene selezionato un valore disabilitato, // viene selezionato il primo valore non disabilitato fra quelli successivi al selezionato // var initial_index = this.selectedIndex; // var found = false; // while (this.selectedIndex < this.options.length - 1) { // this.selectedIndex++; // if (!this.options[this.selectedIndex].disabled) { // found = true; // break; // } // } // if (!found) { // this.selectedIndex = initial_index; // while (this.selectedIndex > 0) { // this.selectedIndex--; // if (!this.options[this.selectedIndex].disabled) { // found = true; // break; // } // } // } // if (!found) // AR Se ci si muove su un valore disabilitato, va selezionato il primo (vuoto) this.selectedIndex = -1; } } } if (sels[i].options[sels[i].selectedIndex].disabled) { //se l'item selezionato è disabilitato, chiamo onchange() - AR non deve fare nulla //sels[i].onchange(); } for (var j = 0; j < sels[i].options.length; j++) { if (sels[i].options[j].disabled) { sels[i].options[j].style.color = '#888'; } } } } // //Script che evita che l'utente clicchi più volte su un bottone // var __oldDoPostBack = null; try { __oldDoPostBack = __doPostBack; __doPostBack = newDoPostback; } catch (e) { //donothing } var postbacking = false; var submitting = false; var oldSubmit = null; if (document.forms[0] != null) { oldSubmit = document.forms[0].onsubmit; document.forms[0].onsubmit = NewSubmit; } function NewSubmit() { if (submitting) { return false; } else { submitting = true; if (oldSubmit != null) { window.setTimeout(freePostbackAndSubmit, 1000); return oldSubmit(); } else { return true; } } } function newDoPostback(eventTarget, eventArgument) { if (postbacking) { return false; } else { postbacking = true; window.setTimeout(freePostbackAndSubmit, 1000); return __oldDoPostBack(eventTarget, eventArgument); } } function freePostbackAndSubmit() { postbacking = false; submitting = false; } function safeParam(param) { /// <summary> /// Utilizzata per l'utilizzo della funzione SyncPageMethod per le variabili stringa /// </summary> /// <param name="param" type="string"></param> if (param != null) { param = param.replace(/\\/g, "/#"); param = param.replace(/'/g, "\\'"); } return param; } //+---------------------------------------------------------------------------- // // Function: SyncPageMethod // // Description: Funzione che utilizza ajax per chiamare un webmetod in modo sincrono // // Arguments: methodName, dataParameters, pageName // dataParameters format: "{chiave:'valore',secondachiave:'secondoValore'}" // Returns: string -- "OK" o messaggio di errore // //----------------------------------------------------------------------------- function SyncPageMethod(methodName, dataParameters, pageName) { var path = document.location.pathname; if (pageName != undefined) { path = pageName; } var rval = $.ajax({ type: "POST", url: path + "/" + methodName, data: dataParameters, contentType: "application/json; charset=utf-8", dataType: "json", async: false }); try { var response = eval('(' + rval.responseText + ')'); if (response.hasOwnProperty("d")) return response.d; else return response; } catch (err) { //document.write("<script type='text/javascript'>" + rval.responseText + "<\script>"); document.write(rval.responseText); document.location.href = document.location.href; return "OK"; } } //+---------------------------------------------------------------------------- // // getParameterByName // // Description: Legge la QueryString "name" // // //----------------------------------------------------------------------------- function getParameterByName(name) { name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regexS = "[\\?&]" + name + "=([^&#]*)"; var regex = new RegExp(regexS); var results = regex.exec(window.location.href); if (results == null) return ""; else return results[1]; } /* WindowUtilities File Da includere nella head delle pagine che utilizzano WebDialogWindow 14/01/2011 : SVA */ //+---------------------------------------------------------------------------- // // openDefaultEditor // // Description: open editor in new mode // //----------------------------------------------------------------------------- function openDefaultEditor() { var strURL = "?MODALITA=NEW"; if (document.location.href.lastIndexOf("?") != -1) { strURL = document.location.href.substring(document.location.href.lastIndexOf("/") + 1, document.location.href.lastIndexOf("?")).replace("_MSB_", "_MSE_") + strURL; } else { strURL = document.location.href.substr(document.location.href.lastIndexOf("/") + 1).replace("_MSB_", "_MSE_") + strURL; } openEditor(strURL); } //+---------------------------------------------------------------------------- // // openDefaultEditor // // Description: open editor in Edit mode // //----------------------------------------------------------------------------- var msgConfUscita = ""; function onCompletegetDizionarioUI(result) { msgConfUscita = result; } function openEditor(strURL, IdDialog) { //Verifico se la URL ha già la redirezione. Dovrebbe succedere solo per: //1) Chiamata dal pulsante "M" - modifica dei Browser //2) Chiamata da un browser secondario della maschera (struttura Master/Detail) if (strURL.indexOf("../") == -1) { //estraggo il nome della cartella contenente Browser/Editor var pathEditor = top.frames['frameContent'].document.location.href; var col_array = pathEditor.split("/"); var strFolder = col_array[col_array.length - 2]; strURL = "../" + strFolder + "/" + strURL } var d = new Date(); var rs = d.getTime(); if (strURL.indexOf("?") != -1) { strURL += "&rs=" + rs; } else { strURL += "?rs=" + rs; } var dialogWindow = $(top).find('editorDialog'); var dialogFrame = $(top).find('frameEditorDialog'); if (dialogWindow) { if (dialogFrame) { $('#frameEditorDialog').attr("src", strURL); } $('#editorDialog').dialog("option", "height", 400); $('#editorDialog').dialog("option", "width", 600); $("#editorDialog").dialog("option", "closeOnEscape", false); $('#editorDialog').dialog("open"); } } //function showDialog() { // windowResize(); // $('#editorDialog').dialog("open"); //} function hideEditorDialog(IdDialog) { if (IdDialog == undefined) IdDialog = "editorDialog"; var dialogWindow = $(top).find('editorDialog'); var dialogFrame = $(top).find('frameEditorDialog'); if (dialogFrame) { $('#frameEditorDialog').attr("src", "/Web/Home/blank.aspx"); } if (dialogWindow) { $('#editorDialog').dialog("close"); } } function windowResize(newWidth, newHeight) { //var newHeight = $("#frameEditorDialog").contents().find("#dialogHeight").val(); //var newWidth = $("#frameEditorDialog").contents().find("#dialogWidth").val(); //Nel caso che risulti "undefined" metto un default if (newHeight == undefined) newHeight = 500 if (newWidth == undefined) newWidth = 600 var dialog = $(top).find("editorDialog"); if (dialog != null) { $('#editorDialog').dialog("option", "height", newHeight); $('#editorDialog').dialog("option", "width", newWidth); $('#editorDialog').dialog("option", "position", "center"); $("#editorDialog").dialog("option", "closeOnEscape", false); } } //Questa parte di codice serve per gestire il refresh dei browser. function refreshBrowser() { $('#btnRefresh').click(); } //+---------------------------------------------------------------------------- // // openDefaultEditor // // Description: open editor in Edit mode // //----------------------------------------------------------------------------- function AutomaticRowSave(e) { var targ; if (!e) var e = window.event; if (e.target) targ = e.target; else if (e.srcElement) targ = e.srcElement; if (targ) if (targ.nodeType == 3) // defeat Safari bug targ = targ.parentNode; // targ rappresenta l'oggetto che ha scatenato l'evento var idtxt = targ.id; var idBtn = String(idtxt).replace('dummy', 'btnUpd'); document.getElementById(idBtn).click(); } //+---------------------------------------------------------------------------- // // EndRequestHandler // // Description: utilizzata nei browser con Update Panel e ToolkitScriptManager // //----------------------------------------------------------------------------- function EndRequestHandler(sender, e) { if (e.get_error()) { e.set_errorHandled(true); } } //+---------------------------------------------------------------------------- // Name: openHelp // Description: apre il contenuto dell'Help in una nuova finestra // La soluzione con iFrame è stata scartata per evitare problemi con gli Editor //----------------------------------------------------------------------------- function openHelp(pagina) { pagina = "/Web/Help/frm_HLP.aspx?PAGINA=" + pagina; window.open(pagina); } //+---------------------------------------------------------------------------- // Name: loadIframeDetail // Description: apre il contenuto del dettaglio Browser in un iFrame ed eseguo lo scroll della pagina. //----------------------------------------------------------------------------- function loadIframeDetail(pagina) { //Carico iFrame $("#boxBrowserDetail").html("<iframe frameborder='0' name='iframeBrowserDetail' id='iframeBrowserDetail' src='" + pagina + "'></iframe>"); //Scroll dela pagina fino alla posizione del "boxBrowserDetail" var destination = $("#boxBrowserDetail").offset().top; $("html:not(:animated)").animate({ scrollTop: destination }, 500); } //+---------------------------------------------------------------------------- // Name: closeHelp // Description: nascondo l'Help //----------------------------------------------------------------------------- function closeHelp() { parent.document.getElementById('boxHelp').innerHTML = ''; } //+---------------------------------------------------------------------------- // Name: PrintPage // Description: //----------------------------------------------------------------------------- function PrintPage() { window.print(); } //--- // Name: addRowInMyGridView // Description: alla pressione del pulsante Nuovo nella toolbar dei browser, // effettuo il click sul pulsante New presente nella prima riga della MyGridView. // Per identificarlo utilizzo la classe che deve essere ".btnAdd". //--- function addRowInMyGridView() { $('.btnAdd').click(); } //--- // Name: openPopUp // Description: //--- function openPopUp(idRiga) { parent.parent.openEditor(percorsoEdit + idRiga); } //--- // Name: openPopUpNewRecord // Description: apro la popUp in modalità NEW //--- function openPopUpNewRecord() { parent.parent.openEditor(percorsoNew); } //--- // Name: substituteBrowser // Description: //--- function substituteBrowser(idRiga) { document.location.href = percorsoEdit + idRiga; } //--- // Name: substituteBrowserNewRecord // Description: apro il record in modalità NEW sostituendo la pagina //--- function substituteBrowserNewRecord() { document.location.href = percorsoNew; } //--- // Name: closeSubstituteEditor // Description: chiude l'editor nel caso di SubstituteBrowser //--- function closeSubstituteEditor(percorso) { document.location.href = percorso; } //----------------------------------------------------------------------------- // // Function: GetFromDictionary // Description: Funzione che restituisce il testo di una chiave del dizionario // Arguments: chiave // Returns: string // //----------------------------------------------------------------------------- function GetFromDictionary(chiave) { var rval = $.ajax({ type: "POST", url: document.location.pathname + "/getDizionarioUI", data: "{key:'" + chiave + "'}", contentType: "application/json; charset=utf-8", dataType: "json", async: false }); var response = eval('(' + rval.responseText + ')'); if (response.hasOwnProperty("d")) return response.d; else return response; } //--- // // Funzioni per Allegati // //--- function GetAllegati(idRichiesta, idServizio, tipoAllegato) { /// <summary> /// Recupera gli allegati della pratica nel momento in cui apro la richiesta viaggio. /// </summary> /// <param name="idRichiesta" type="Int">Id richiesta</param> /// <param name="idServizio" type="Int">Id prenotazione nota spesa o altro tipo di servizio</param> /// <param name="tipoAllegato" type="String">Tipo allegato</param> var paramIdRichiesta = idRichiesta; if (idServizio != "") paramIdRichiesta = idServizio; var r = SyncPageMethod("getAllegati", "{idRichiesta:" + paramIdRichiesta + ", tipoAllegato:" + tipoAllegato + "}", "../WebServices/WSAllegati.asmx"); if (tipoAllegato == C_TIPO_ALLEGATO_NOTA_SPESA) { var idCliente = $("#hIdCliente", parent.document).val(); for (var i = 0; i < r.length; i++) { // Produzione $("#imgScontrino").attr("src", "../../images_fatture/" + idCliente + "/" + idRichiesta + "/" + idServizio + "/" + r[i].Value); // Test locale //$("#imgScontrino").attr("src", "C:\\tmp\\" + idCliente + "\\" + idRichiesta + "\\" + r[i].Value); } } else { var strHTML = "<div class='tblEditorRichiesta' id='tblRiepilogoAllegati'>"; var nomeFile = ""; var idCliente = 1; for (var i = 0; i < r.length; i++) { nomeFile = r[i].Value; strHTML += "<div class='mt-1'>"; strHTML += "<i class='btn btn-secondary btn-sm fa fa-times' title='Elimina file' data-toggle='tooltip' id='span" + r[i].Id + "' onclick='javascript:if (confirm(\"Sei sicuro di voler eliminare il file selezionato?\")){DeleteFile(" + r[i].Id + ",\"" + nomeFile + "\", " + idRichiesta + "," + idCliente + ");GetAllegati(" + idRichiesta + "," + idRichiesta + "," + tipoAllegato + ");}'></i> "; strHTML += "<a href='#' title='Scarica file' data-toggle='tooltip' onclick='downloadFile(\"" + r[i].Value + "\");'><small>" + r[i].Value + "</small></a>"; strHTML += "</div>"; } strHTML += "</div>"; $("#divAllegati_" + tipoAllegato).html(strHTML); } } function DeleteFile(idAllegato, fileName, idRichiesta, idCliente) { /// <summary> /// Eliminazione file allegato /// </summary> /// <param name="idAllegato" type="Int">Id allegato</param> /// <param name="fileName" type="String">Nome file</param> /// <param name="idRichiesta" type="String">Id Richiesta</param> /// <param name="idCliente" type="String">Id Cliente</param> var stato = document.getElementById("hIdStato").value; if (stato == "") return false; else var r = SyncPageMethod("DeleteAllegato", "{idAllegato:" + idAllegato + ",nomeFile:'" + fileName + "',idRichiesta:" + idRichiesta + ",idCliente:" + idCliente + "}", "../WebServices/WSAllegati.asmx"); if (r != "1") alert("Ci sono stati dei problemi durante l'eliminazione del file."); else alert("Eliminazione completata."); } function downloadFile(fileName) { /// <summary> /// Scarico il file allegato /// </summary> /// <param name="fileName" type="String">Nome file</param> $("#hFileToDownload").val(fileName); // Nel caso di mobile apro una nuova finestra per non perdere la navigazione. if ($("#hMobile").val() == "1") { var idCliente = $("#hIdCliente").val(); var idRichiesta = $("#hIdRichiesta").val(); window.open("../AllegaFile/Download.aspx?FILENAME=" + fileName + "&CLI=" + idCliente + "&REQ=" + idRichiesta); return false; } else { $("#btnDownload").click(); } } function SendFile(idAllegato) { /// <summary> /// Invio il File Allegato via email. /// </summary> var r = SyncPageMethod("SendAllegato", "{idAllegato:" + idAllegato + "}", "../WebServices/WSAllegati.asmx"); if (r != "1") alert("Ci sono stati dei problemi durante l'invio del file, riprovare più tardi."); else alert("Allegato inviato correttamente."); } function checkRequiredField(idGriglia) { /// <summary> /// Controllare i campi obbligatori delle griglie senza il MaskeEditValidator. /// </summary> var elements = $('#' + idGriglia + ' .required'); var canSave = true; elements.each(function () { id = String($(this).attr("id")); if ($("#" + id).val() == "") { $("#" + id).addClass("MaskedEditError"); canSave = false; } }); return canSave; } function enableField(obj, setFocus) { /// <summary> /// Abilita un campo di Tipo data. Funzione centralizzata per evitare problemi con versioni diverse di Jquery o Cross-Browser. /// Valido per classi (es: ".class input"), tag (es: "input"), id ("es: "#id"). /// </summary> /// <param name="obj" type="String">Identificativo del campo</param> /// <param name="setFocus" type="Bool">True:passa il focus al campo / False:non passa il focus</param> if (!$(obj).hasClass("accessoRead")) { $(obj).removeAttr('disabled'); if (setFocus) $(obj).focus(); } } function disableField(obj) { /// <summary> /// Disabilita un campo. Funzione centralizzata per evitare problemi con versioni diverse di Jquery o Cross-Browser /// Valido per classi (es: ".class input"), tag (es: "input"), id ("es: "#id"). /// </summary> /// <param name="obj" type="String">Oggetto da modificare</param> $(obj).attr("disabled", true); } function writeError(e, pageJs, functionName) { /// <summary> /// 30/01/2017 - test gestione errore JS /// /// Reference: http://www.w3schools.com/js/js_errors.asp /// ----------------------------------------------------------------- /// Error Name | Description /// ----------------------------------------------------------------- /// EvalError | An error has occurred in the eval() function /// RangeError | An number out of range error has occurred /// ReferenceError | An illegal reference has occurred /// SyntaxError | A syntax error has occurred /// TypeError | A type error has occurred /// URIError | An error in encodeURI() has occurred /// ----------------------------------------------------------------- /// /// </summary> /// <param name="e" type="Object">Oggetto errore</param> /// <param name="pageJs" type="String">Nome del file .js</param> /// <param name="functionName" type="String">Nome della function</param> // Recupera il messaggio dei web Method se valorizzato if (e.Message != "") { e.message = e.Message; } if (pageJs == undefined) pageJs = ""; if (functionName == undefined) functionName = ""; alert(GetFromDictionary("ERR_MSG_ERROR_JS")); // Visualizzazione errore nella console del browser. console.error; console.log(e.message); // https://developer.mozilla.org/en-US/docs/Web/API/Console var browser = window.navigator.userAgent; // Registrazione errore nel DB. var url = location.href; //////////////var r = SyncPageMethod("writeError", "{message:'" + e.message + "', name:'" + e.name + "', url:'" + url + "', urljs:'" + pageJs + "', functionName:'" + functionName + "', browser:'" + browser + "'}", "../WebServices/WSErrori.asmx"); //////////////if (r.hasOwnProperty("Message") || r.toString() == "") { ////////////// alert(GetFromDictionary("ERR_MSG_WEB_METHOD") + r.Message); //////////////} } function documentReadyEditorBO() { $("#ButtonAnnulla").click(function (e) { $("#iframeEditorModal", parent.document).attr("src", ""); $("#btnCloseModal", parent.document).click(); return false; }); $("#ButtonSalva").click(function (e) { if (!$('#form1').valid()) { return false; } }); $('#form1').FormObserve({ changeClass: "changed" }); $('#form1').validate({ errorPlacement: function (error, element) { } }); ////////////////// ????? SE: serve?????? coomentata con SV: ativaOptionsDisabled(); } function genericDocumentReady() { $(".bt-switch input[type='checkbox'], .bt-switch input[type='radio']").bootstrapSwitch(); $(".btnClose").click(function (e) { $("#iframeNewService", parent.document).attr("src", ""); if ($("#hMobile").val() != "1") { $("#btnCloseServizio", parent.document).click(); // chiudo la modal } return false; }); $("#btnPreSalva").click(function (e) { save(); }); // Mask $('.money').mask('000.000.000.000.000,00', { reverse: true }); $('.time').mask('00:00'); $(".datepicker").mask("99/99/9999", { placeholder: 'gg/mm/aaaa' }); $(".datepicker").blur(function () { checkYear($(this).attr("id")); }); //$(".datepicker").datepicker($.datepicker.regional["it"]); $.validator.addClassRules({ "datepicker": { dateMaskedITA: true } }); $.validator.addClassRules({ "time": { minuteMaskedITA: true } }); $.validator.addClassRules({ "consecutiveDate": { validConsecutiveDate: true } }); $.validator.methods.validConsecutiveDate = function (value, element, param) { return compareConsecutiveDate(element); }; $('form').validate({ errorPlacement: function (error, element) { } }); $("#form1").FormObserve({ changeClass: "changed" }); !function ($) { "use strict"; var SweetAlert = function () { }; SweetAlert.prototype.init = function () { }, //init $.SweetAlert = new SweetAlert, $.SweetAlert.Constructor = SweetAlert }(window.jQuery), //initializing function ($) { "use strict"; $.SweetAlert.init() }(window.jQuery); $('.datepicker').datepicker({ showOn: 'button', buttonImage: "../Images/calendar.gif", buttonImageOnly: false }); $(".ui-datepicker-trigger").addClass("fa fa-calendar-alt"); } function closeParentModal() { /// <summary> /// Chiude la finestra modale. Utilizzata principalmente nei sottobrower del backoffice. /// </summary> parent.$('#modalPage').modal('toggle'); } function clearSearchSelectedAPI(str, table, id) { /// <summary> /// Rimozione tag di formattazione. /// </summary> /// <param name="str" type="String">Stringa da aggiornare</param> try { if (str != "" && str != undefined) { if (str.length > 0) { str = str.replace(/<b>/g, ""); str = str.replace(/<\/b>/g, ""); } } return str; } catch (e) { writeError(e, "JScript.js", "clearSearchSelectedAPI-" + table); } } function loadSearchAPI(id, table, character) { /// <summary> /// Carica la tendina con i primi 5 risultati caricati dall'API in funzione della ricerca . /// </summary> /// <param name="id" type="Int">Id servizio</param> try { var idDiv = "#search-" + id; var pathAPI = ""; if (character.which == 40 && character.which == 38 && character.which == 13) alert(character.which); if (character.which != 40 && character.which != 38 && character.which != 13) { if ($("#" + id).val().length) { $(idDiv).show(); if (table == "LoadAirportSearch") { pathAPI = $("#hPathAPI").val() + 'airport/autofill?designator=' + safeParam($("#" + id).val()) + '&api-version=1.0'; var r = SyncPageMethod("callAPI", "{path:'" + pathAPI + "'}", "../WebServices/WSApiSearch.asmx"); } else if (table == "LoadRailSearch") { if ($("#" + id).val().length > 2) { pathAPI = $("#hPathAPI").val() + 'railstation/autofill?stationName=' + safeParam($("#" + id).val()) + '&api-version=1.0'; var r = SyncPageMethod("callAPI", "{path:'" + pathAPI + "'}", "../WebServices/WSApiSearch.asmx"); } else return false; } else if (table == "LoadHotelSearch") { if ($("#" + id).val().length > 2) { pathAPI = $("#hPathAPI").val() + 'hotellocation/autofill?designator=' + safeParam($("#" + id).val()) + '&api-version=1.0'; var r = SyncPageMethod("callAPI", "{path:'" + pathAPI + "'}", "../WebServices/WSApiSearch.asmx"); } else return false; } if (r.hasOwnProperty("Message")) { alert(r.toString()); } else { var data = JSON.stringify(r.toString()); var n = SyncPageMethod(table, "{json:" + data + "}", "../WebServices/WSApiSearch.asmx"); if (n.hasOwnProperty("Message")) { alert(n.toString()); } else { $(idDiv).html(n.toString()); } } $(idDiv + " li").click(function () { var idLi = $(this).attr('id'); var idLiVal = $("#" + idLi.toString() + " .ddlId").html(); var idLiText = $("#" + idLi + " .ddlText").html(); //setto il codice iata per la ricerca dei voli nel campo hidden setAirIataCode(id, idLiVal); $("#" + id).val(clearSearchSelectedAPI(idLiText, table, idLiVal)); $("#h" + id).val(idLiVal); $(idDiv).hide(); }); } else { $(idDiv).hide(); } } else if (character.which == 40)//freccia in giù { if ($(idDiv + " li.selected").length == 0) { $(idDiv + " li").first().addClass("selected"); } else { var idSelectedLi = $(idDiv + " li.selected").attr("id"); if ($("#" + idSelectedLi).next().length > 0) { $("#" + idSelectedLi).next().addClass("selected"); $("#" + idSelectedLi).removeClass("selected"); } } } else if (character.which == 38)//freccia in su { if ($(idDiv + " li.selected").length == 0) { $(idDiv + " li").first().addClass("selected"); } else { var idSelectedLi = $(idDiv + " li.selected").attr("id"); if ($("#" + idSelectedLi).prev().length > 0) { $("#" + idSelectedLi).prev().addClass("selected"); $("#" + idSelectedLi).removeClass("selected"); } } } else if (character.which == 13)//Invio { $(idDiv + " li.selected").click(); } } catch (e) { writeError(e, "JScript.js", "loadSearchAPI-" + table); } } function setSearchDefaultAPI(id, table) { /// <summary> /// Creazione nuovo servizio. /// Il timeout serve per non escludere l'evento click che arriverebbe sempre dopo il blur. /// </summary> /// <param name="id" type="Int">Id servizio</param> try { setTimeout(function () { var idDiv = "#search-" + id; if ($(idDiv).is(":visible")) { var liVal = ($(idDiv + " li.selected").length > 0) ? $(idDiv + " li.selected .ddlText").html() : $(idDiv + " li .ddlText").first().html(); var liId = ($(idDiv + " li.selected").length > 0) ? $(idDiv + " li.selected .ddlId").html() : $(idDiv + " li .ddlId").first().html(); //setto il codice iata per la ricerca dei voli nel campo hidden (solo per la pagina AIR) setAirIataCode(id, liId); if (liVal != undefined) { $("#" + id).val(clearSearchSelectedAPI(liVal, table, liId)); if (id == "txtEVT_AEROPORTO_DA" || id == "txtEVT_AEROPORTO_A") $("#h" + id).val(liVal); else $("#h" + id).val(liId); $(idDiv).hide(); } else $(idDiv).hide(); } }, 200); } catch (e) { writeError(e, "JScript.js", "setSearchDefaultAPI-" + table); } } function setAirIataCode(id, value) { ///<summary> ///setto il codice itala per la ricerca dei voli nel campo hidden ///</summary> if (id == "txtPRA_DA") $("#hPra_da_code").val(value); else if (id == "txtPRA_A") $("#hPra_a_code").val(value); else if (id == "txtPRH_CITTA") $("#htxtPRH_CITTA").val(value); } function selezionaStelle(number, idAcrn) { ///<summary> /// Faccio il show del numero di stelle che mi arriva e nascondo le altre /// idAcrn serve per generalizzare il metodo aggiungendo un accronimo (nel caso si volessero utilizzare le stelle nella stessa pagina) ///</summary> ///<param name="id" type="Int">numero della stella selezionata</param> ///<param name="id" type="String">Accronimo della pagina dalla quale si chiama il metodo</param> //idAcr == 'Hot' -> Filtro iniziale di ricerca //idAcr == 'Try' -> Filtro iniziale di ricerca della pagina frm_mse_try var stella1Select = "#1StellaSelect" + idAcrn; var stella2Select = "#2StellaSelect" + idAcrn; var stella3Select = "#3StellaSelect" + idAcrn; var stella4Select = "#4StellaSelect" + idAcrn; var stella5Select = "#5StellaSelect" + idAcrn; var stella1 = "#1Stella" + idAcrn; var stella2 = "#2Stella" + idAcrn; var stella3 = "#3Stella" + idAcrn; var stella4 = "#4Stella" + idAcrn; var stella5 = "#5Stella" + idAcrn; // default $(stella1Select).show(); // sempre visibile $(stella2Select).hide(); $(stella3Select).hide(); $(stella4Select).hide(); $(stella5Select).hide(); $(stella1).hide(); $(stella2).hide(); $(stella3).hide(); $(stella4).hide(); $(stella5).hide(); if(typeof number == 'number') number = number.toString(); switch (number) { case '1': $(stella2).show(); $(stella3).show(); $(stella4).show(); $(stella5).show(); break; case '2': $(stella2Select).show(); $(stella3).show(); $(stella4).show(); $(stella5).show(); break; case '3': $(stella2Select).show(); $(stella3Select).show(); $(stella4).show(); $(stella4).show(); break; case '4': $(stella2Select).show(); $(stella3Select).show(); $(stella4Select).show(); $(stella5).show(); break; case '5': $(stella2Select).show(); $(stella3Select).show(); $(stella4Select).show(); $(stella5Select).show(); break; } $("#hStelleMassime").val(number); }
import styles from "./secondPanel.module.css" import BusinessCenterIcon from '@material-ui/icons/BusinessCenter'; import LanguageIcon from '@material-ui/icons/Language'; import MonetizationOnIcon from '@material-ui/icons/MonetizationOn'; import AssessmentIcon from '@material-ui/icons/Assessment'; import ParallaxCustom from "./parallaxCustom"; import { Background, Parallax } from "react-parallax"; import Image from "next/image"; const SecondPanel = () => { return ( <Parallax className={styles.container} strength={400} bgStyle={{background:"center"}}> <Background bgClassName={styles.background}> <Image layout="fixed" width={2299} height={1527} alt="building skyline" src="/images/buildingBackground2.jpg" /> </Background> <div className={styles.textContainer}> <h1 className={styles.title}>Voulez-vous donner une nouvelle dimension à votre entreprise ? </h1> <h2 className={styles.title}>Sophia est la solution tout-en-un pour votre entreprise.</h2> <p className={styles.text}> Grâce à notre expérience et à notre passion pour les affaires et la technologie, nous vous aiderons à développer votre entreprise au maximum de son potentiel. Que ce soit pour préparer votre entreprise à une plus grande croissance, pour la gérer plus efficacement ou pour améliorer votre présence en ligne, nous pouvons vous aider. </p> <div className={styles.iconContainer}> <div className={styles.iconSingleContainer}> <LanguageIcon className={styles.icon} /> <p> Transformation Numérique </p> </div> <div className={styles.iconSingleContainer}> <MonetizationOnIcon className={styles.icon} /> <p>Optimisez vos décisions financières</p> </div> <div className={styles.iconSingleContainer}> <AssessmentIcon className={styles.icon} /> <p> Obtenez des perspectives stratégiques</p> </div> <div className={styles.iconSingleContainer}> <BusinessCenterIcon className={styles.icon}/> <p>Implémentez les meilleures pratiques</p> </div> </div> </div> </Parallax> ) } export default SecondPanel
const http=require('http'); const server=http.createServer((req,res)=>{ res.statusCode=200; res.setHeader('Content-Type','text/plain'); res.end('hello world'); }); let port=8877; let host='127.0.0.1'; server.listen(port,host,()=>{ console.log('the sever ${host}:${port} is working'); })
"use strict"; const burgerBtn = document.querySelector(".burger"); const menu = document.querySelector(".navmenu"); burgerBtn.addEventListener("click", (event) => { event.preventDefault(); if (!menu.classList.contains("active")) { menu.classList.toggle("active"); burgerBtn.classList.add("burger-active") } else { menu.classList.remove("active"); burgerBtn.classList.remove("burger-active") } });
import './style.css'; import 'bootstrap/dist/css/bootstrap.min.css'; import {storage} from './storage'; import {projectModuleDOM} from './projectRender'; import {projectModuleLOG} from './projectLogic'; import { taskModuleLOG } from './taskLogic'; import {checkerModule} from './checker'; //load data from localstorage storage.loadDefault(); //check all tasks in projects and count their priorities checkerModule.infoprovider(storage.projects); //call project logic projectModuleLOG.projectAI(storage.projects); //call task logic taskModuleLOG.taskAI(storage.projects);
Module.register("wd-weatherforecast", { defaults: { units: config.units, language: config.language, animationSpeed: 1000, showDailyPrecipitationChance: true, showIndoorTemperature: false, showTextSummary: true, showWind: false, showSunriseSunset: true, showForecast: true, fadeForecast: false, forecastTableFontSize: 'medium', maxDaysForecast: 7, // maximum number of days to show in forecast tempDecimalPlaces: 0, apiBase: "https://api.weather.gov", debug: false }, ONE_DAY_IN_MS: 86400000, getTranslations: function () { return false; }, getScripts: function () { return [ 'moment.js' ]; }, getStyles: function () { return [ "font-awesome.css", "weather-icons.css", "weather-icons-wind.css", "wd-weatherforecast.css" ]; }, start: function () { Log.info("Starting module: " + this.name); // Set locale. moment.locale(config.language); this.weatherData = null; }, getDayFromTime: function(measurement) { var dt = new Date(Date.parse(measurement.endTime)); return moment.weekdaysShort(dt.getDay()); // + " " + (measurement.isDaytime?"&nbsp;":"night"); }, processWeather: function () { if (this.weatherData === null ){ Log.log("We don't have all the data we need for a weather update; waiting..."); return; } var data = this.weatherData; if (this.config.debug) { console.log('weather data', data); } this.loaded = true; this.updateDom(this.config.animationSpeed); }, notificationReceived: function(notification, payload, sender) { // Log.log("noaaforecast RECV: " + notification + " from: " + JSON.stringify(sender.name)); switch(notification) { case "DOM_OBJECTS_CREATED": break; case "WEATHER_REFRESHED": this.weatherData = payload; Log.log("RECV: " + notification); this.processWeather(); break; } }, getDom: function() { var wrapper = document.createElement("div"); if (!this.loaded) { wrapper.innerHTML = this.translate('LOADING'); wrapper.className = "dimmed light small"; return wrapper; } wrapper.appendChild(this.renderWeatherForecast()); return wrapper; }, renderForecastRow: function (data, min, max, addClass) { const total = max - min; const interval = 100 / total; const rowMinTemp = Math.round(parseFloat(data.temp.min)); const rowMaxTemp = Math.round(parseFloat(data.temp.max)); const row = document.createElement("tr"); row.className = "forecast-row" + (addClass ? " " + addClass : ""); const dayTextSpan = document.createElement("span"); dayTextSpan.className = "forecast-day" dayTextSpan.innerHTML = moment(data.dt * 1000).format("ddd"); var iconClass = data.weather[0].weatherClass; if ( iconClass != null ){ iconClass = iconClass[0]; if ( !iconClass.startsWith('wi-') ){ iconClass = 'wi-day-' + iconClass; } } var icon = document.createElement("span"); icon.className = 'wi weathericon ' + iconClass; var wind = document.createElement("div"); wind.className = "small dimmed wind"; var windBearing = document.createElement("span"); windBearing.className = "wi wi-wind from-" + data.windDirection.toLowerCase(); wind.appendChild(windBearing); var cardinalDirection = data.windDirection; var windSpeed = document.createElement("span"); if (this.weatherData.config.units === 'metric') { var windSpeedUnit = "m/s"; } else { var windSpeedUnit = "mph"; } windSpeed.innerHTML = " " + cardinalDirection + " " + Math.round(parseFloat(data.wind_speed)) + windSpeedUnit; wind.appendChild(windSpeed); var dayPrecipProb = document.createElement("span"); dayPrecipProb.className = "forecast-precip-prob"; var precipProbability = Math.round(data.pop * 100); // if (precipProbability > 0) { dayPrecipProb.innerHTML = precipProbability + "%"; // } // else { // dayPrecipProb.innerHTML = "&nbsp;"; // } var forecastBar = document.createElement("div"); forecastBar.className = "forecast-bar"; var minTemp = document.createElement("span"); minTemp.innerHTML = rowMinTemp + "&deg;"; minTemp.className = "temp min-temp"; var maxTemp = document.createElement("span"); maxTemp.innerHTML = rowMaxTemp + "&deg;"; maxTemp.className = "temp max-temp"; var bar = document.createElement("span"); bar.className = "bar"; bar.innerHTML = "&nbsp;"; var barWidth = Math.round(interval * (rowMaxTemp - rowMinTemp)); bar.style.width = barWidth + '%'; var leftSpacer = document.createElement("span"); leftSpacer.style.width = (interval * (rowMinTemp - min)) + "%"; var rightSpacer = document.createElement("span"); rightSpacer.style.width = (interval * (max - rowMaxTemp)) + "%"; forecastBar.appendChild(leftSpacer); forecastBar.appendChild(minTemp); forecastBar.appendChild(bar); forecastBar.appendChild(maxTemp); forecastBar.appendChild(rightSpacer); var forecastBarWrapper = document.createElement("td"); forecastBarWrapper.appendChild(forecastBar); row.appendChild(dayTextSpan); row.appendChild(icon); if (this.config.showDailyPrecipitationChance) { row.appendChild(dayPrecipProb); } if (this.config.showWind) { row.appendChild(wind); } row.appendChild(forecastBarWrapper); return row; }, renderWeatherForecast: function () { const numRows = this.config.maxDaysForecast; const filteredRows = this.weatherData.daily.filter( function(d, i) { return (i < numRows); }); let min = Number.MAX_VALUE; let max = -Number.MAX_VALUE; for (let i = 0; i < filteredRows.length; i++) { const row = filteredRows[i]; max = Math.max(max, row.temp.max); min = Math.min(min, row.temp.min); } min = Math.round(min); max = Math.round(max); const display = document.createElement("table"); display.className = this.config.forecastTableFontSize + " forecast"; for (i = 0; i < filteredRows.length; i++) { const day = filteredRows[i]; let addClass = ""; if(this.config.fadeForecast) { if(i+2 == filteredRows.length) { addClass = "dark"; } if(i+1 == filteredRows.length) { addClass = "darker"; } } const row = this.renderForecastRow(day, min, max, addClass); display.appendChild(row); } return display; }, // Round the temperature based on tempDecimalPlaces roundTemp: function (temp) { var scalar = 1 << this.config.tempDecimalPlaces; temp *= scalar; temp = Math.round( temp ); temp /= scalar; return temp; }, });
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; import { BrowserRouter as Router} from 'react-router-dom'; import { Provider } from "react-redux"; import { MuiThemeProvider } from "@material-ui/core/styles"; import createMuiTheme from "@material-ui/core/styles/createMuiTheme"; // import { createFirestoreInstance } from "redux-firestore"; import Appstore from './redux/Store'; const theme = createMuiTheme(); // Wait For Auth To Load // function AuthIsLoaded({ children }) { // const auth = useSelector(state => state.firebase.auth); // if (!isLoaded(auth)) // return ( // <div // style={{ // left: "50%", // right: "50%", // top: "40%", // position: "absolute" // }}> // Loading...... // </div> // ); // return children; // } const store = Appstore(); ReactDOM.render( <React.StrictMode> <Provider store={store}> {/* <ReactReduxFirebaseProvider {...rrfProps}> */} <MuiThemeProvider theme={theme}> <Router> {/* <AuthIsLoaded> */} <App /> {/* </AuthIsLoaded> */} </Router> </MuiThemeProvider> {/* </ReactReduxFirebaseProvider> */} </Provider> </React.StrictMode>, document.getElementById('root') ); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
import axios from 'axios' import config from "@/config"; const $http = axios.create({ baseURL: config.apiURL, timeout: 10000 }); export default { getRegions() { return $http.get('/Regiones') }, getCities(identifier) { return $http.get(`/Ciudades/Region/${identifier}`); }, saveLead(data) { return $http.post("/saveLeads", data) }, sendLead(data) { return $http.post("/EnvioCorreoGlobal", data) }, createLead(lead){ return axios.all([this.saveLead(lead.metadata), this.sendLead(lead)]) } }
export default { build: { loaders: { imgUrl: { limit: 1000000000 } } } }
// pages/android/andview.js Page({ data:{ }, onLoad:function(options){ // 页面初始化 options为页面跳转所带来的参数 this.setData({ title: options.title, secondtitle: options.secondtitle, tool: options.tool, skillDetail: options.skillDetail, detailFunction: options.detailFunction, detailWork: options.detailWork, downAddress: options.downAddress, imageUrlOne: options.imageUrlOne, add: options.downAddress, }), wx.setNavigationBarTitle({ title: options.title, success: function(res) { // success } }) }, priviewImage: function(options){ var add = options.downAddress; wx.previewImage({ current: add, // 当前显示图片的链接,不填则默认为 urls 的第一张 urls: [add], success: function(res){ // success }, fail: function(res) { // fail }, complete: function(res) { // complete } }) }, // 分享 onShareAppMessage: function () { return { title: '商品详情', path: '/pages/home/home', success: function (res) { // 分享成功 // wx.showToast({ // title: '转发成功!', // icon: 'success', // duration: 2000 // }); }, fail: function (res) { // 分享失败 // wx.showToast({ // title: '转发失败!', // icon: 'fail', // duration: 2000 // }); } } }, onReady:function(){ // 页面渲染完成 }, onShow:function(){ // 页面显示 }, onHide:function(){ // 页面隐藏 }, onUnload:function(){ // 页面关闭 } })
import { connect } from "react-redux"; import MusicPlayer from "./presenter"; import ActionCreator from "./../../redux/actions"; const mapStateToProps = (state, ownProps) => { const {musicPlayer} = state; return { music: musicPlayer.music, isPlay: musicPlayer.isPlay, }; }; const mapDispatchToProps = (dispatch, ownProps) => { return { AddMusic: (music) => { dispatch(ActionCreator.AddMusic(music)); }, DeleteMusic: (music) => { dispatch(ActionCreator.DeleteMusic(music)); }, TogglePlayMusic: (music) => { dispatch(ActionCreator.TogglePlayMusic(music)); }, } } export default connect(mapStateToProps, mapDispatchToProps)(MusicPlayer);
import React from "react"; import { useState } from "react"; import styled from "styled-components"; const Form = styled.form` width: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center; padding-bottom: 60px; input { width: 400px; height: 40px; margin-top: 20px; border: 1px solid black; padding: 5px; font-size: 15px; @media (max-width: 1024px) { width: 300px; } } button { height: 40px; width: 80px; margin-top: 20px; border: none; background-color: black; color: white; } `; function ContactForm({ project }) { const [whatsAppMsgName, setWhatsAppMsgName] = useState(); const [whatsAppMsgEmail, setWhatsAppMsgEmail] = useState(); const [whatsAppMsgText, setWhatsAppMsgText] = useState(project.nombre); function openInNewTab(url) { var win = window.open(url, "_blank"); win.focus(); } const initiateWhatsAppSMS = () => { let url = "https://wa.me/543794275060?text=" + "Hola, mi nombre es " + whatsAppMsgName + ". Me gustaria agendar una visita a la propiedad " + whatsAppMsgText + ". Mi email es " + whatsAppMsgEmail + ". Muchas gracias, espero su respuesta."; openInNewTab(url); }; return ( <Form> <h2>AGENDAR UNA VISITA</h2> <input value={whatsAppMsgName} onChange={e => setWhatsAppMsgName(e.target.value)} placeholder={"Nombre"} type='text' /> <input value={whatsAppMsgEmail} onChange={e => setWhatsAppMsgEmail(e.target.value)} placeholder={"Email"} type='email' /> <button type='submit' id='BotonEnviar' onClick={initiateWhatsAppSMS}> ENVIAR </button> </Form> ); } export default ContactForm;
import * as actionTypes from '../actionTypes'; const initialState = { error: null, loading: false, }; const registrationStart = (state, action) => { return { error: null, loading: true, }; }; const registrationSuccess = (state, action) => { return { error: null, loading: false, }; }; const registrationFail = (state, action) => { return { error: action.error, loading: false, }; }; const reducer = (state = initialState, action) => { switch (action.type) { case actionTypes.REGISTRATION_START: return registrationStart(state, action); case actionTypes.REGISTRATION_SUCCESS: return registrationSuccess(state, action); case actionTypes.REGISTRATION_FAILED: return registrationFail(state, action); default: return state; } }; export default reducer;
/** * 4pl Grid thead配置 * check:true //使用checkbox 注(选中后对象中增加pl4GridCheckbox.checked:true) * checkAll:true //使用全选功能 * field:’id’ //字段名(用于绑定) * name:’序号’ //表头标题名 * link:{ * url:’/aaa/{id}’ //a标签跳转 {id}为参数 (与click只存在一个) * click:’test’ //点击事件方法 参数test(index(当前索引),item(当前对象)) * } * input:true //使用input 注(不设置默认普通文本) * type:text //与input一起使用 注(type:operate为操作项将不绑定field,与按钮配合使用) * buttons:[{ * text:’收货’, //显示文本 * call:’tackGoods’, //点击事件 参数tackGoods(index(当前索引),item(当前对象)) * type:’link button’ //类型 link:a标签 button:按钮 * state:'checkstorage', //跳转路由 注(只有当后台传回按钮数据op.butType=link 才会跳转) * style:’’ //设置样式 * }] //启用按钮 与type:operate配合使用 可多个按钮 * style:’width:10px’ //设置样式 * */ 'use strict'; define(['../../../app'], function(app) { app.factory('carManage', ['$http', '$q', '$filter', 'HOST', function($http, $q, $filter, HOST) { return { getThead: function() { return [{ field: 'pl4GridCount', name: '序号', type: 'pl4GridCount' }, { field: 'carId', name: '车辆编号' }, { field: 'licenseNumber', name: '车牌号' }, { field: 'vehicleName', name: '车辆名称' }, { field: 'vehicleModel', name: '车型' }, { field: 'drivingNum', name: '行驶证号' }, { field: 'vehicleDescription', name: '车辆描述' }, { field: 'vehicleState', name: '车辆状态' }, { field: 'name11', name: '操作', type: 'operate', buttons: [{ text: '修改', btnType: 'btn', call:'editCar', openModal:'#addCar' },{ text: '查看', btnType: 'btn', call:'queryCar', openModal:'#queryCar' }, { text: '冻结', call: 'freezeCar' }, { text: '恢复', call: 'recovery' }] }] }, getSearch: function() { var deferred = $q.defer(); $http.post(HOST + '/wlCar/getDicLists',{}) .success(function(data) { deferred.resolve(data); }) .error(function(e) { deferred.reject('error:' + e); }); return deferred.promise; }, getDataTable: function(data,url) { //将parm转换成json字符串 data.param = $filter('json')(data.param); var deferred = $q.defer(); $http.post(HOST + (!url?'/wlCar/queryWlCar':url), data) .success(function(data) { // console.log(data) deferred.resolve(data); }) .error(function(e) { deferred.reject('error:' + e); }); return deferred.promise; } } }]); });
function select_reg(sel) { if (sel == 'email') { $('#check-email').prop('checked', true); $('#check-domain').prop('checked', false); $('#email_1').prop('disabled', false); $('#domain_2').prop('disabled', true); $('#email_2').prop('disabled', true); } else if (sel == 'domain') { $('#check-email').prop('checked', false); $('#check-domain').prop('checked', true); $('#email_1').prop('disabled', true); $('#domain_2').prop('disabled', false); $('#email_2').prop('disabled', false); } }
import React from "react"; import Helmet from "react-helmet"; import Banner from "../../components/Banner"; import { Link } from "react-router-dom"; import Image from "../../components/Image"; import Turn from "./Turn"; import Join from "./Join"; import large from "../../assets/membership/bannerimg.png"; import medium from "../../assets/membership/bannerimg-800.png"; import small from "../../assets/membership/bannerimg-600.png"; import "./style.scss"; import img1 from "../../assets/membership/img1.png"; import img2 from "../../assets/membership/img2.png"; import img3 from "../../assets/membership/img3.png"; const imgs = { large, medium, small, }; const turn = [ { title: "Have a Relationship With God", image: img1, desc: "Gbagada Estate Baptist Church is a family of individuals who have put their faith in Jesus Christ alone for eternal salvation. If you have never made the decision to accept Jesus Christ as your personal saviour, it is the most important decision you can ever make, and we would be thrilled to talk to you about it and personally explain what the Bible says about how you can know for sure you are on your way to Heaven when this life is over. If we can talk to you about this, please contact us today.", }, { title: "Understanding Our Purpose and Beliefs", image: img2, desc: "Gbagada Estate Baptist Church is a biblical church united in our purpose to love God, grow together in Christ, and reach others. You can find out more about our purpose here. We are also united in our belief about basic truths from the Bible. You can read about the Bible truths we teach and believe here.", }, ]; const About = () => { return ( <main className="min_st"> <Helmet> <title>Ministries</title> <meta name="description" content="" /> </Helmet> <Banner imgs={imgs} head="Membership" sub="Know more about how to become one of us" /> <section className="mn_sec"> {turn.map((pturn, i) => ( <Turn i={i} {...pturn} key={`pturn_${i}`} /> ))} </section> <Join /> <section className="learn-us flex-row card"> <div className="flex-row text-sec"> <div className="text-sec"> <h2 className="hd">Welcome to be body of Christ</h2> <p className="s_hd"> <Link className="links learn" to="/"> <strong className="theme-color">Click here</strong> </Link>{" "} to fill the membership form online </p> </div> </div> <div className="image-sec"> <Image image={img3} imgClass="img cover" alt="img" lazyLoad={true} usePlaceHolder={true} /> </div> </section> </main> ); }; export default About;
import React, { Component } from "react"; import { ImageBackground, StyleSheet, TextInput, View, Dimensions } from 'react-native'; import Icon from 'react-native-vector-icons/Ionicons'; import Background from '../assets/Background.png'; export default class Search extends Component { constructor(props) { super(props); // State for searchvalue this.state = { value: '', }; } render() { return ( <ImageBackground source={Background} style={styles.container} > <View style={styles.searchSection}> <Icon style={styles.searchIcon} name="ios-search" size={20} color="#000"/> {/* Input for searchvalue */} <TextInput style={styles.input} underlineColorAndroid="transparent" placeholderTextColor='#333333' name="SearchValue" placeholder='Search...' autoCapitalize="none" autoCorrect={false} autoFocus={false} keyboardType="default" value={this.state.value} // Call this whenever user inputs something to update value state onChangeText={text => this.setState({ value: text })} /> </View> </ImageBackground> ); } }; const styles = StyleSheet.create({ container: { width: '100%', height: '100%', alignItems: 'center', justifyContent: 'flex-start', }, searchSection: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', backgroundColor: "#fafafa", color: "#333333", height: Dimensions.get("window").height / 19, width: Dimensions.get("window").width - 80, paddingHorizontal: 12, fontSize: 18, fontWeight: "normal", borderRadius: 8, borderColor: '#333333', borderWidth: 1, marginVertical: 30, }, input: { flex: 1, paddingTop: 10, paddingRight: 10, paddingBottom: 10, paddingLeft: 0, color: '#333333', }, searchIcon: { padding: 10, }, });
//通过id获取元素 $("#id") //类选择器 $(".class") //元素选择器 $("element") //全选择器 $("*") /* IE会将注释节点实现为元素,所以在IE中调用getElementsByTagName里面会包含注释节点,这个通常是不应该的 getElementById的参数在IE8及较低的版本不区分大小写 IE7及较低的版本中,表单元素中,如果表单A的name属性名用了另一个元素B的ID名并且A在B之前,那么getElementById会选中A IE8及较低的版本,浏览器不支持getElementsByClassName */ /*层级选择器*/ //子选择器:选择所有指定"parent"元素中指定的"child"的直接子元素 $("parent > child") //后代选择器:选择给定的祖父元素的所有后代元素,一个元素的后代可能是该元素的一个孩子、孙子、曾孙等 $("ancestor descendant") //相邻兄弟选择器:选择所有紧接着"prev"元素后的"next"元素 $("prev + next") //一般兄弟选择器:匹配"prev"元素之后的所有兄弟元素。具有相同的父元素,并匹配过滤"siblings"选择器 $("prev ~ siblings") /*基本筛选选择器 :eq(), :lt(), :gt(), :even, :odd 用来筛选他们前面的匹配表达式的集合元素,根据之前匹配的元素在进一步筛选,注意jQuery合集都是从0开始索引 gt是一个段落筛选,从指定索引的下一个开始,gt(1) 实际从2开始 */ //匹配第一个元素 $(":first") //匹配最后一个元素 $(":last") //一个用来过滤的选择器,选择所有元素去除不匹配给定的选择器元素 $(":not(selector)") //在匹配的集合中选择索引值为index的元素 $(":eq(index)") //选择匹配集合中所有大于给定index(索引值)的元素 $(":gt(index)") //选择索引值为偶数的元素,从0开始计数 $(":even") //选择索引值为奇数的元素,从0开始计数 $(":odd") //选择匹配集合中所有索引值小于给定index参数的元素 $(":lt(index)") //选择所有标题元素,h1,h2,h3 $(":header") //选择指定语言的所有元素 $(":lang(language)") //选择该文档的根元素 $(":root") //选择所有正在执行动画效果的元素 $(":animated") /*内容筛选选择器 :contains与:has都有查找的意思,但是contains查找包含“指定文本”的元素,has查找包含“指定元素”的元素 如果:contains匹配的文本包含在元素的子元素中,同样认为是符合条件的。 :parent与:empty是相反的,两者所涉及的子元素,包括文本节点 */ //选择所有包含指定文本的元素 $(":contains(text") //选择所有含有子元素或者文本的元素 $(":parent") //选择所有没有子元素的元素(包含文本节点) $(":empty") //选择元素中至少包含指定选择器的元素 $(":has(selector)") /*可见性选择器*/ //选择所有显示的元素 $(":visilbe") //选择所有隐藏元素 $(":hidden") /*属性筛选选择器*/ //选择指定属性值等于给定字符串或以该字符串为前缀(该字符串后跟一个连子符"-")的元素 $("[attribute|= 'value']") //选择指定属性具有包含一个给定的字符串的元素(选择给定的属性值是包含某些值的元素) $("[attribute*= 'value']") //选择指定属性用空格分隔的值中包含一个给定值的元素 $("[attribute~= 'value']") //选择指定属性是给定值的元素 $("[attribute= 'value']") //选择不存在指定属性,或者指定的属性不等于给定值的元素 $("[attribute!= 'value']") //选择指定属性是以给定字符串开始的元素 $("[attribute^= 'value']") //选择指定属性是以给定值结尾的元素,这个比较是区分大小写 $("[attribute$= 'value']") //选择所有具有指定属性的元素,改属性可以是任何值 $("[attribute]") //选择匹配所有指定的属性筛选器的元素 $("[attributeFilter1][attributeFilterN]") /*子元素筛选选择器 :first只匹配一个单独的元素,但是:first-child选择器可以匹配多个:即为每个父级元素匹配第一个子元素。这相当于:nth-child(1) :last 只匹配一个单独的元素, :last-child 选择器可以匹配多个元素:即,为每个父级元素匹配最后一个子元素 如果子元素只有一个的话,:first-child与:last-child是同一个 :only-child匹配某个元素是父元素中唯一的子元素,就是说当前子元素是父元素中唯一的元素,则匹配 jQuery实现:nth-child(n)是严格来自CSS规范,所以n值是“索引”,也就是说,从1开始计数,:nth-child(index)从1开始的,而eq(index)是从0开始的 nth-child(n) 与 :nth-last-child(n) 的区别前者是从前往后计算,后者从后往前计算 */ //选择所有父级元素下的第一个子元素 $(":first-child") //选择所有父级元素下的最后一个子元素 $(":last-child") //如果某个元素是其父元素的唯一子元素,那么它就会被选中 $(":only-child") //选择的他们所有父元素的第n个子元素 $(":nth-child") //选择所有他们父元素的第n个子元素。计数从最后一个元素开始到第一个 $(":nth-last-child") /*表单元素选择器 除了input筛选选择器,几乎每个表单类别筛选器都对应一个input元素的type值。大部分表单类别筛选器可以使用属性筛选器替换。比如 $(':password') == $('[type=password]') */ //选择所有input,textarea,select和button元素 $(":input") //匹配所有文本框 $(":text") //匹配所有密码框 $(":password") //匹配所有单选按钮 $(":radio") //匹配所有复选框 $(":checkbox") //匹配所有提交按钮 $(":submit") //匹配所有图像区域 $(":image") //匹配所有重置按钮 $(":reset") //匹配所有按钮 $(":button") //匹配所有文件域 $(":file") /*表单对象属性筛选选择器 选择器适用于复选框和单选框,对于下拉框元素, 使用 :selected 选择器 在某些浏览器中,选择器:checked可能会错误选取到<option>元素,所以保险起见换用选择器input:checked,确保只会选取<input>元素 */ //选取可用的表单元素 $(":enabled") //选取不可用的表单元素 $(":disabled") //选取被选中的<input>元素 $(":checked") //选取被选中的option元素 $(":selected") /*特殊选择器this*/ //eg: $('p').click(function(){ //把p元素转化成jQuery的对象 var $this= $(this) $this.css('color','red') }) /*属性与样式 Attribute就是dom节点自带的属性 Property是这个DOM元素作为对象,其附加的内容 /* .attr()与.removeArre() .attr(属性名):获取属性的值 .attr(属性名,属性值):设置属性的值 .attr(属性名,函数值):设置属性的函数值 .attr(attributes):给指定元素设置多个属性值,{属性名一: “属性值一” , 属性名二: “属性值二” , … …} .reamoveAttr(attributeName):为匹配的元素集合中的每一个元素中移除一个属性(attribute) -------------------------------------------------------------------------------------------------------------------------------------------------- .html()与.text() .html()方法内部使用的是DOM的innerHTML属性来处理的,所以在设置与获取上需要注意的一个最重要的问题,这个操作是针对整个HTML内容(不仅仅只是文本内容) .text()结果返回一个字符串,包含所有匹配元素的合并文本 .html与.text的异同: .html与.text的方法操作是一样,只是在具体针对处理对象不同 .html处理的是元素内容,.text处理的是文本内容 .html只能使用在HTML文档中,.text 在XML 和 HTML 文档中都能使用 如果处理的对象只有一个子文本节点,那么html处理的结果与text是一样的 火狐不支持innerText属性,用了类似的textContent属性,.text()方法综合了2个属性的支持,所以可以兼容所有浏览器 .html() 不传入值,就是获取集合中第一个匹配元素的HTML内容 .html( htmlString ) 设置每一个匹配元素的html内容 .html( function(index, oldhtml) ) 用来返回设置HTML内容的一个函数 .text() 得到匹配元素集合中每个元素的合并文本,包括他们的后代 .text( textString ) 用于设置匹配元素内容的文本 .text( function(index, text) ) 用来返回设置文本内容的一个函数 -------------------------------------------------------------------------------------------------------------------------------------------------- .val() 通过.val()处理select元素, 当没有选择项被选中,它返回null .val()方法多用来设置表单的字段的值 如果select元素有multiple(多选)属性,并且至少一个选择项被选中, .val()方法返回一个数组,这个数组包含每个选中选择项的值 .val()无参数,获取匹配的元素集合中第一个元素的当前值 .val( value ),设置匹配的元素集合中每个元素的值 .val( function ) ,一个用来返回设置值的函数 如果select元素有multiple(多选)属性,并且至少一个选择项被选中, .val()方法返回一个数组,这个数组包含每个选中选择项的值 -------------------------------------------------------------------------------------------------------------------------------------------------- .addClass()与.removeClass() .addClass()方法不会替换一个样式类名。它只是简单的添加一个样式类名到元素上 .removeClass()如果一个样式类名作为一个参数,只有这样式类会被从匹配的元素集合中删除 。 如果没有样式名作为参数,那么所有的样式类将被移除 .addClass( className ) : 为每个匹配元素所要增加的一个或多个样式名 .addClass( function(index, currentClass) ) : 这个函数返回一个或更多用空格隔开的要增加的样式名 .removeClass( [className ] ):每个匹配元素移除的一个或多个用空格隔开的样式名 .removeClass( function(index, class) ) : 一个函数,返回一个或多个将要被移除的样式名 -------------------------------------------------------------------------------------------------------------------------------------------------- .toggleClass() toggleClass是一个互斥的逻辑,也就是通过判断对应的元素上是否存在指定的Class名,如果有就删除,如果没有就增加 toggleClass会保留原有的Class名后新增,通过空格隔开 .toggleClass( className ):在匹配的元素集合中的每个元素上用来切换的一个或多个(用空格隔开)样式类名 .toggleClass( className, switch ):一个布尔值,用于判断样式是否应该被添加或移除 .toggleClass( [switch ] ):一个用来判断样式类添加还是移除的 布尔值 .toggleClass( function(index, class, switch) [, switch ] ):用来返回在匹配的元素集合中的每个元素上用来切换的样式类名的一个函数。接收元素的索引位置和元素旧的样式类作为参数 -------------------------------------------------------------------------------------------------------------------------------------------------- .css() 浏览器属性获取方式不同,在获取某些值的时候都jQuery采用统一的处理,比如颜色采用RBG,尺寸采用px .css()方法支持驼峰写法与大小写混搭的写法,内部做了容错的处理 当一个数只被作为值(value)的时候, jQuery会将其转换为一个字符串,并添在字符串的结尾处添加px,例如 .css("width",50}) 与 .css("width","50px"})一样 .css( propertyName ) :获取匹配元素集合中的第一个元素的样式属性的计算值 .css( propertyNames ):传递一组数组,返回一个对象结果 .css(propertyName, value ):设置CSS .css( propertyName, function ):可以传入一个回调函数,返回取到对应的值进行处理 .css( properties ):可以传一个对象,同时设置多个样式 .addClass与.css方法各有利弊,一般是静态的结构,都确定了布局的规则,可以用addClass的方法,增加统一的类规则 如果是动态的HTML结构,在不确定规则,或者经常变化的情况下,一般多考虑.css()方式 */ /*数据存储 jQuery.removeData( element [, name ] ) .removeData( [name ] ) */
// INSTANTIATION var APP = require("/core"); var args = arguments[0] || {}; var type; var tempFunction; // ADDITIONS // FUNCTIONS function getMyAddresses(_type){ if(APP.getToken({openLogin:false})){ if(_type == 1 || _type == 2){ var dataTemp = { url : L("ws_getmyaddresses"), type : 'POST', format : 'JSON', data : { atoken : APP.getToken({openLogin:false}), pkfamily : Ti.App.Properties.getInt('pkfamily'), //flat : event.coords.latitude, //flon : event.coords.longitude } }; // Ti.API.info('dataTemp:'+JSON.stringify(dataTemp)); APP.http.request(dataTemp,function(_result){ //Ti.API.info("-->"+JSON.stringify(_result)); if(_result._result == 1){ if(_result._data.errorcode == 0){ $.addressContainer.add(Alloy.createController("RightBarView/AddressRow",{_data:{faname:"Current Location"},_type:_type}).getView()); for(var i=0;i<_result._data.data.length;i++){ // Ti.API.info('loadLocations'+JSON.stringify(_result._data.data[i])); $.addressContainer.add(Alloy.createController("RightBarView/AddressRow",{_data:_result._data.data[i],_type:_type}).getView()); } }else{ //alert(_result._data.message); // alert("No messages were found."); } }else{ //alert("Internet connection error, please try again."); } }); }else if(_type == 3 || _type == 4){ var dataTemp = { url : L("ws_mygroups"), type : 'GET', format : 'JSON', data : { atoken : APP.getToken({openLogin:false}) } }; // Ti.API.info('dataTemp:'+JSON.stringify(dataTemp)); APP.http.request(dataTemp,function(_result){ //Ti.API.info("-->"+JSON.stringify(_result)); if(_result._result == 1){ if(_result._data.errorcode == 0){ for(var i=0;i<_result._data.data.length;i++){ $.addressContainer.add(Alloy.createController("RightBarView/GroupsRow",{_data:_result._data.data[i],_type:_type}).getView()); } }else{ if(_result._data.errorcode == 4){ var dialog = Ti.UI.createAlertDialog({ buttonNames: ['OK'], message: 'You do not have any groups yet. Please select a group on the next screen', title: 'My Groups' }); dialog.addEventListener('click', function(e){ APP.openWindow({ controller : 'MyNeighborhoods/SearchGroups', controllerParams : { callback : function(){ //send update } } }); }); dialog.show(); } //alert(_result._data.message); // alert("No messages were found."); } }else{ //alert("Internet connection error, please try again."); } APP.hideActivityindicator(); }); } }else{ if(_type == 3 || _type == 4){ APP.hideActivityindicator(); } } } function searchAddress(){ if( $.searchTxtFld.value !== '' ){ $.rencentlyContainer.add(Alloy.createController("RightBarView/RecentlyAddressRow",{address:$.searchTxtFld.value}).getView()); $.searchTxtFld.blur(); APP.currentController.searchAddress($.searchTxtFld.value); } else{ alert('Please enter an address'); $.searchTxtFld.focus(); } } function addAddress(){ tempFunction(); } function changeView(_type,_addFunction){ switch(_type){ case 1: for(var i = $.addressContainer.children.length-1; i >= 0; i--){ $.addressContainer.remove($.addressContainer.children[i]); } $.searchContainer.height = 40; $.groupListContainer.height = Ti.UI.SIZE; $.groupListTitle.text = "My Neighborhoods"; $.recentlyFoundContainer.height = Ti.UI.SIZE; type = _type; tempFunction = _addFunction; getMyAddresses(type); $.titleLbl.text = "Neighborhoods"; break; case 2: for(var i = $.addressContainer.children.length-1; i >= 0; i--){ $.addressContainer.remove($.addressContainer.children[i]); } $.searchContainer.height = 0; $.groupListContainer.height = Ti.UI.SIZE; $.groupListTitle.text = "My Neighborhoods"; $.recentlyFoundContainer.height = 0; type = _type; tempFunction = _addFunction; getMyAddresses(type); $.titleLbl.text = "Neighborhoods"; break; case 3: for(var i = $.addressContainer.children.length-1; i >= 0; i--){ $.addressContainer.remove($.addressContainer.children[i]); } $.searchContainer.height = 0; $.groupListContainer.height = Ti.UI.SIZE; $.groupListTitle.text = "My Groups"; $.recentlyFoundContainer.height = 0; type = _type; tempFunction = _addFunction; getMyAddresses(type); $.titleLbl.text = "Groups"; break; case 4: for(var i = $.addressContainer.children.length-1; i >= 0; i--){ $.addressContainer.remove($.addressContainer.children[i]); } $.searchContainer.height = 0; $.groupListContainer.height = Ti.UI.SIZE; $.groupListTitle.text = "My Friens and Family"; $.recentlyFoundContainer.height = 0; type = _type; tempFunction = _addFunction; getMyAddresses(type); $.titleLbl.text = "Friens and Family"; break; case 5: for(var i = $.addressContainer.children.length-1; i >= 0; i--){ $.addressContainer.remove($.addressContainer.children[i]); } getMyAddresses(type); break; } } function clearSearch(){ $.searchTxtFld.value = ""; } function updateMyAddresses(){ for(var i = $.addressContainer.children.length-1; i >= 0; i--){ $.addressContainer.remove($.addressContainer.children[i]); } getMyAddresses(type) } function addTxtFld(){ Ti.API.info( 'addTxtFld' ) if( !$.searchTxtFld ){ $.searchTxtFld = Ti.UI.createTextField({ backgroundImage: "/images/transparent.png", returnKeyType: Ti.UI.RETURNKEY_DONE, textAlign: 'left', left:0, right:20, height: 36, paddingLeft: 5, color: '#333', font: { fontSize: 14 }, hintText:"Ex: street, city, state" }); $.search_tf_view.add( $.searchTxtFld ); } return true; } function removeTxtFld(){ Ti.API.info( 'removeTxtFld' ); if( $.searchTxtFld ){ $.search_tf_view.remove( $.searchTxtFld ); $.searchTxtFld = null; } return true; } // CODE $.backgroundIosBar.height = APP.fixSizeIos7(); // EXPORTS exports.changeView = changeView; exports.updateMyAddresses = updateMyAddresses; exports.addTxtFld = addTxtFld; exports.removeTxtFld = removeTxtFld;
({ doInit : function(component, event, helper) { helper.GetQuote(component); helper.GetFA(component); helper.GetFR(component) }, StrikeEvent:function(component, event, helper){ var eventValue = event.getParam("data1"); // console.log("123"+eventValue.Product2Id); // if(eventValue.Product2Id!=undefined){ var eventValue1 = eventValue; console.log("evntform"+eventValue1.Id) component.set("v.QLIId",eventValue1.Id); helper.GetQuote(component); helper.GetFA(component); helper.GetFR(component) } })
import React from 'react' import { shallow } from 'enzyme' import Th from '../src/th' test('is not instance of <Th />', () => { const wrapper = shallow(<Th headerData={''} />) const inst = wrapper.instance() expect(inst).not.toBeInstanceOf(Th) }) test('render a table cell <th> HTML element', () => { const wrapper = shallow(<Th headerData={''} />) expect(wrapper.type()).toEqual('th') }) test('contains the property scope set to "col"', () => { const wrapper = shallow(<Th headerData={''} scope={'col'} />) expect(wrapper.props().scope).toEqual('col') }) test('contains the property scope set to "row"', () => { const wrapper = shallow(<Th headerData={''} scope={'row'} />) expect(wrapper.props().scope).toEqual('row') }) test('render the provided data', () => { const wrapper = shallow(<Th headerData={'foo'} />) expect(wrapper.text()).toEqual('foo') })
import React,{Component} from 'react'; import {connect} from 'react-redux'; import PropTypes from 'prop-types'; import {fetchProjectSingleData, projectSingleDataSuccess} from '../../../reducers'; import Html from '../../../_component/html' class ProjectSingle extends Component { static propTypes = { lang: PropTypes.string, } constructor(props){ super(props); this.state = {} } static actions(title){ return [ fetchProjectSingleData(title) ] } static pushData(data){ return projectSingleDataSuccess(data) } componentWillMount() { if(!this.props.projectSingleData) this.props.dispatch(fetchProjectSingleData(this.props.match.params.title)); else if(this.props.projectSingleData.uid !== this.props.match.params.title) this.props.dispatch(fetchProjectSingleData(this.props.match.params.title)); } componentWillReceiveProps(nextProps){ if (nextProps.location.key !== this.props.location.key){ this.props.dispatch(fetchProjectSingleData(nextProps.match.params.title)); } } render(){ if(this.props.projectSingleData){ const data = this.props.projectSingleData.data; return( <Html id="projectSingle" title={data.post_title[0].text} description={`This is ${data.post_title[0].text} page!`}> <div><h1>{data.post_title[0].text}</h1></div> </Html> ) } return <h1>Loading...</h1>; } } const mapStateToProps = (state) => { return { lang: state.lang, projectSingleData: state.projectSingleData } } export default connect(mapStateToProps)(ProjectSingle)
var hljs = require('highlight.js') , fs = require('fs') , path = require('path') , log = require('npmlog') , common = require('./common') , languages = require('./hljs-languages') , support = require('./service/support') , header = '<!DOCTYPE>' + '<head>' + '<link rel="stylesheet" href="./' + common.StylesFolderName + '/magula.css" ' + 'type="text/css" media="screen" charset="utf-8">' + '</head>' + '<body><pre><code>' , footer = '</code></pre></body>' ; module.exports = { // [Path folder, String ext,] Function cb getStyles : getStyles // Path targetDir, Function copiedStylesCb , copyStyles : copyStyles // Path: fullPath, Function highlightedCb , highlightFile : highlightFile , defaultStyle : 'sunburst' }; function getStyles (cb) { support.getStyles(common.paths.hljsStyles, cb); } function copyStyles (tgtDir, cb) { support.copyStyles(common.paths.hljsStyles, tgtDir, cb); } function highlightFile (fullPath, highlightedCb) { fs.readFile(fullPath, 'utf-8', function(err, code) { if (err) { highlightedCb(err); return; } var ext = path.extname(fullPath).slice(1) , language = languages.getLanguage(ext) , highlighted ; try { if (language) { highlighted = hljs.highlight(language.name, code).value; } else { log.silly('hljs', 'auto detecting language'); highlighted = hljs.highlightAuto(code).value; } } catch (err) { highlightedCb(err); return; } var html = wrapInPre(highlighted); highlightedCb(null, html); }); } function wrapInPre(code) { var highlightStart = '<div class="highlight"><pre><code>' , highlightEnd = '</code></pre></div>' ; return highlightStart + code + highlightEnd; }
import React from 'react' import { Tabs, useTabState, Panel } from '@bumaga/tabs' import ContactPanel from './contact-panel'; import NotePanel from './note-panel'; const cn = (...args) => args.filter(Boolean).join(' ') const Tab = ({ children }) => { const { isActive, onClick } = useTabState() return ( <button className={cn('tab', isActive && 'active')} onClick={onClick}> {children} </button> ) } export default () => ( <div className="out-border"> <Tabs> <div className='tabs'> <div className='tab-list'> <Tab>Contract File</Tab> <Tab>P Note File</Tab> <Tab>Pricipal Percentage</Tab> <Tab>Rate Changes</Tab> </div> <div> <ContactPanel/> </div> <div> <NotePanel/> </div> <Panel> <p> Creates a MotionValue that, when set, will use a spring animation to animate to its new state. </p> </Panel> </div> </Tabs> </div> )
const GameOfThronesData = { data: [], init() { this.findAll(); }, elements: { gotCharactersDiv: document.querySelector('.flex-container'), }, setData(gotCharacters) { this.characters = JSON.parse(gotCharacters); this.showAll(); }, showAll() { let figures = ''; for (let i = 0; i < this.characters.length; i += 1) { if (this.characters[i].hasOwnProperty('dead') === false) { figures += this.createFigure(this.characters[i]); } } this.elements.gotCharactersDiv.innerHTML += figures; }, findAll() { const request = new XMLHttpRequest(); request.onload = () => { this.setData(request.responseText); }; request.onerror = () => { console.log('Hiba a betöltéskor'); }; request.open('GET', '/json/got.json'); request.send(); }, createFigure(item) { return `<figure class="item"> <img src="${item.portrait}" alt="${item.name}"> <figcaption>${item.name}</figcaption> </figure>`; }, }; GameOfThronesData.init();
// usage: log('inside coolFunc', this, arguments); // paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/ window.log = function(){ log.history = log.history || []; // store logs to an array for reference log.history.push(arguments); if(this.console) { arguments.callee = arguments.callee.caller; var newarr = [].slice.call(arguments); (typeof console.log === 'object' ? log.apply.call(console.log, console, newarr) : console.log.apply(console, newarr)); } }; // make it safe to use console.log always (function(b){function c(){}for(var d="assert,clear,count,debug,dir,dirxml,error,exception,firebug,group,groupCollapsed,groupEnd,info,log,memoryProfile,memoryProfileEnd,profile,profileEnd,table,time,timeEnd,timeStamp,trace,warn".split(","),a;a=d.pop();){b[a]=b[a]||c}})((function(){try {console.log();return window.console;}catch(err){return window.console={};}})()); // place any jQuery/helper plugins in here, instead of separate, slower script files. // Prototype Extensions if (!Array.prototype.every) { Array.prototype.every = function(fun /*, thisp*/) { var len = this.length; if (typeof fun != "function") throw new TypeError(); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this && !fun.call(thisp, this[i], i, this)) return false; } return true; }; } if (!Array.prototype.filter) { Array.prototype.filter = function(fun /*, thisp*/) { var len = this.length >>> 0; if (typeof fun != "function") { throw new TypeError(); } var res = []; var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) { var val = this[i]; // in case fun mutates this if (fun.call(thisp, val, i, this)) { res.push(val); } } } return res; }; } if (!Date.prototype.toTwelveHourTimeString) { Date.prototype.toTwelveHourTimeString = function() { var hours = this.getHours(); var ext = hours >= 12 ? 'pm' : 'am'; if (hours == 0) hours = 12; if (hours > 12) hours -= 12; var mins = this.getMinutes(); if (mins < 10) mins = '0' + mins; return hours + ':' + mins + ext; }; } /* * object.watch polyfill * * 2012-04-03 * * By Eli Grey, http://eligrey.com * Public Domain. * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. */ // object.watch if (!Object.prototype.watch) { Object.defineProperty(Object.prototype, "watch", { enumerable: false, configurable: true, writable: false, value: function (prop, handler) { var oldval = this[prop], newval = oldval, getter = function () { return newval; }, setter = function (val) { oldval = newval; return newval = handler.call(this, prop, oldval, val); }; if (delete this[prop]) { // can't watch constants Object.defineProperty(this, prop, { get: getter, set: setter, enumerable: true, configurable: true }); } } }); } // object.unwatch if (!Object.prototype.unwatch) { Object.defineProperty(Object.prototype, "unwatch", { enumerable: false, configurable: true, writable: false, value: function (prop) { var val = this[prop]; delete this[prop]; // remove accessors this[prop] = val; } }); };
import React, { useContext } from "react"; import { NavLink } from "react-router-dom"; import { Button, IconButton, Drawer, List, ListItem, Divider, useTheme, } from "@material-ui/core"; import MenuIcon from "@material-ui/icons/Menu"; import ChevronLeftIcon from "@material-ui/icons/ChevronLeft"; import ChevronRightIcon from "@material-ui/icons/ChevronRight"; import { AuthContext } from "../../context/auth-context"; import useStyles from "../../styles/material-ui-syles"; import Backdrop from "../UIElements/Backdrop"; const SideDrawer = (props) => { const auth = useContext(AuthContext); const classes = useStyles(); const theme = useTheme(); const [open, setOpen] = React.useState(false); const handleDrawerOpen = () => { setOpen(true); }; const handleDrawerClose = () => { setOpen(false); }; return ( <React.Fragment> <div className={classes.sectionMobile}> {open && <Backdrop onClick={handleDrawerClose} />} <IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="open drawer" onClick={handleDrawerOpen} > <MenuIcon /> </IconButton> </div> <Drawer className={classes.drawer} variant="persistent" anchor="left" open={open} classes={{ paper: classes.drawerPaper, }} > <div className={classes.drawerHeader}> <IconButton onClick={handleDrawerClose}> {theme.direction === "ltr" ? ( <ChevronLeftIcon /> ) : ( <ChevronRightIcon /> )} </IconButton> </div> <Divider /> <List> <ListItem key="Homepage"> <Button color="inherit" component={NavLink} to={{ pathname: `/`, }} onClick={handleDrawerClose} > Home </Button> </ListItem> {auth.isAdmin && ( <ListItem key="my saber"> <Button color="inherit" component={NavLink} to={{ pathname: `/sabers/new`, }} onClick={handleDrawerClose} > New Saber </Button> </ListItem> )} {auth.isAdmin && ( <ListItem> <Button color="inherit" component={NavLink} to={{ pathname: `/sabers/crystal/new`, }} onClick={handleDrawerClose} > New Crystal </Button> </ListItem> )} {auth.isLoggedIn && ( <ListItem> <Button color="inherit" component={NavLink} to={{ pathname: `/saber/order`, }} onClick={handleDrawerClose} > {auth.isAdmin ? 'All Orders' : 'Your Orders' } </Button> </ListItem> )} </List> <Divider /> </Drawer> </React.Fragment> ); }; export default SideDrawer;
app.get('/getNews',function(req,res){ var news = [ { img:'src//image/main4.png', title:'The priest', brif:'The panda pastor' }, { img:'src/image/main5.png', title:'The druids', brif:'Tauren druid' }, { img:'src/image/main6.png', title:'The thieves', brif:'The troll thieves' }, { img:'src/image/main7.png', title:'The wizard', brif:'The Undead Warlock' }, { img:'src/image/main8.png', title:'The minister', brif:'Human Priest' }, { img:'src/image/main9.png', title:'The Brawler', brif:'By Matt Panepinto' }, { img:'src/image/main10.png', title:'Delaney', brif:'Kalen Delaney' }, { img:'src/image/main11.png', title:'The Paladin', brif:'Phoenix Knight' }, { img:'src/image/main12.png', title:'Short person', brif:'Goblin Sappers' }, { img:'src/image/main13.png', title:'Death Knight', brif:'Orc Death Knight' }, { img:'src/image/main14.png', title:'Lone Druid', brif:'Druid of the Talon' }, { img:'src/image/main15.png', title:'The cow head', brif:'The perfuse strew' } ] var pageIndex = req.query.page; var len = 3; var retNews = news.slice(pageIndex*len,pageIndex*len+len)//获取数据第一次0 3 /第二次 3 6 /.... res.send({ status:0, data:retNews }) })
export default { apiKey: "XXXXXXXXXXXXX", authDomain: "XXXXXXXXXXXXX", databaseURL: "XXXXXXXXXXXXX", projectId: "XXXXXXXXXXXXX", storageBucket: "XXXXXXXXXXXXX", messagingSenderId: "XXXXXXXXXXXXX" };
var fs = require ('fs'); (function(){ fs.readFile(process.argv[2], function (err,data){ if (err){console.log (err.stack);} else { var newlines = data.toString().split('\n'); console.log(newlines.length+1); } }); })();
const express = require('express'); const router = express.Router(); const db = require('../database/config'); router.get('/welcome', (req, res) => { // root page res.send('Testing... Base (Post)\n'); }); router.get('/all', (req, res) => { // retrieve every rows db.query("SELECT `id`, `title`, `author`, `date` FROM Post", (err, rows) => { if (!err) { console.log("All Posts Retrieved!"); return res.json(rows); } else { console.log(`query error : ${err}`); return res.status(400).json({error: "Retrieve Error"}); } }); }) router.get('/latest', (req, res) => { // retrieve every rows db.query("SELECT `id`, `title`, `author`, `date` FROM Post limit 5", (err, rows) => { if (!err) { console.log("Latest Posts Retrieved!"); return res.json(rows); } else { console.log(`query error : ${err}`); return res.status(400).json({error: "Retrieve Error"}); } }); }) router.get('/:id', (req, res) => { console.log(req.params.id); const id = parseInt(req.params.id, 10); db.query("SELECT * FROM Post where id = " + id, (err, rows) => { if (!err) { console.log("Single Post Retrieved!"); return res.json(rows); } else { console.log(`query error : ${err}`); return res.status(400).json({error: "Retrieve Error"}); } }); }) module.exports.base = router;
$(function () { 'use strict'; // jQuery to collapse the navbar on scroll $(window).scroll(function() { if ($(".navbar").offset().top > 50) { $(".navbar-fixed-top").addClass("top-nav-collapse"); } else { $(".navbar-fixed-top").removeClass("top-nav-collapse"); } }); // Testimonial Slider $('a.page-scroll').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top - 40 }, 900); return false; } } }); /*==================================== Show Menu on Book ======================================*/ $(window).bind('scroll', function() { var navHeight = $(window).height() - 100; if ($(window).scrollTop() > navHeight) { $('.navbar-default').addClass('on'); } else { $('.navbar-default').removeClass('on'); } }); $('body').scrollspy({ target: '.navbar-default', offset: 80 }) $(document).ready(function() { $("#testimonial").owlCarousel({ navigation : false, // Show next and prev buttons slideSpeed : 300, paginationSpeed : 400, singleItem:true }); }); /*==================================== Portfolio Isotope Filter ======================================*/ $(window).load(function() { var $container = $('.portfolio-items'); $container.isotope({ filter: '*', animationOptions: { duration: 750, easing: 'linear', queue: false } }); $('.cat a').click(function() { $('.cat .active').removeClass('active'); $(this).addClass('active'); var selector = $(this).attr('data-filter'); $container.isotope({ filter: selector, animationOptions: { duration: 750, easing: 'linear', queue: false } }); return false; }); }); // **************************************************************** // counterUp // **************************************************************** $(document).ready(function( $ ) { if($("span.count").length > 0){ $('span.count').counterUp({ delay: 10, // the delay time in ms time: 1000 // the speed time in ms }); } }); /*==================================== Pretty Photo ======================================*/ $("a[rel^='prettyPhoto']").prettyPhoto({ social_tools: false }); }); $('.btn-default').click(function() { var name = $("#name").val(); var email = $("#email").val(); var message = $("#message").val(); console.log("name="+name+";email="+email+";message="+message); var params = {"name": name, "email": email, "message": message}; $.ajax({ type: 'POST', url: '/leaveMessage', data: params, success: function (result) { if (result.code=== "000") { swal("感谢您的留言,我会尽快回复", { icon: "success" }); $("#message").val(""); } else { swal(result.message, { icon: "error" }); } }, error: function () { swal("留言失败", { icon: "error" }); } }); });
// JS code can be added here.
/* global it expect describe */ import * as Calculations from '../../../src/d3/calculations'; describe('Calculations', () => { describe('#calculateQuota', () => { it('should return Math.PI for full quota 100 and used quota 50', () => { expect(Calculations.calculateQuota(100, 50)).to.be.closeTo(Math.PI, 0.1); }); }); describe('#distirbuteNodes', () => { // it('should assign x, y and r values on depending on size', () => { // const nodes = [ // {master: true, name: 'master'}, // {master: false, name: 'node1'}, // {master: false, name: 'node2'}, // ]; // // const distribution = Calculations.distirbuteNodes(nodes, 500, 500); // // expect(distribution[0].x).to.exist; // expect(distribution[0].y).to.exist; // expect(distribution[1].x).to.exist; // expect(distribution[1].y).to.exist; // expect(distribution[2].x).to.exist; // expect(distribution[2].y).to.exist; // // expect(distribution[0].r).to.be.above(distribution[1].r); // expect(distribution[0].r).to.be.above(distribution[2].r); // }); }); });
const fs = require('fs'); const CSVtoJSON = require('csvtojson'); // const JSONtoCSV = require('json2csv').parse; function createFile(fileName, data){ fs.writeFile(fileName, data, (err)=> { if (err) console.log(err); else console.log('Time table successfully created!'); }); } function readFile(fileName) { CSVtoJSON().fromFile('./' + fileName).then(source => { // console.log(source); return new Promise((resolve, reject) => { if (source !== undefined) resolve(source) else reject('No Content') }); }) } function renameFile(fileName, newName) { fs.rename(fileName, newName, (err)=>{ if (err) console.log(err); else console.log('You have successfully renamed the file to ' + newName); }); } function addLineToFile(fileName, data) { fs.appendFile(fileName, data, (err)=>{ if (err) console.log(err); else console.log('You have succesfully modified the file ' + fileName ); }); } function deleteFile(fileName) { fs.unlink(fileName,(err)=>{ if (err) console.log(err); else console.log('File ' + fileName + 'has been successfully deleted'); }); } module.exports = { createFile : createFile, renameFile : renameFile, addLineToFile : addLineToFile, deleteFile : deleteFile, readFile : readFile, };
import React from 'react'; import './index.css' import split from '../../helpers/split' import objectBuild from '../../helpers/objectBuild' class HowItWorks extends React.Component { constructor(props){ super(props) this.state = { requirements: { map: {}, count: 0 }, resume: [], fileBoxDisabled: true, buttonDisabled: true, result: 0, errors: null } this.onChange = this.onChange.bind(this) this.onFile = this.onFile.bind(this) this.onClick = this.onClick.bind(this) this.compare = this.compare.bind(this) } onChange(e){ const text = e.target.value if(text.length === 0){ return this.setState({ fileBoxDisabled: true, buttonDisabled: true, requirements: { map: {}, count: 0 }, result: 0, errors: 'Please enter some requirements' }) } return this.setState({ fileBoxDisabled: false, requirements: objectBuild(text), buttonDisabled: this.state.resume.length === 0, errors: null }) } onFile(evt){ const file = evt.target.files[0] if(file.size > 200000){ return this.setState({ buttonDisabled: true, errors: 'File must be less then 200KB' }) } const reader = new FileReader() reader.onload = e => { const resume = split(e.target.result) return this.setState({ buttonDisabled: false, resume }) } reader.readAsText(file) } onClick(){ const { requirements, resume} = this.state return this.compare(requirements, resume) } compare({ map, count }, resume){ const len = resume.length let result = 0, i, interval for(i = 0; i < len; i++){ if(map[resume[i]]){ result++ this.setState({result: result * 100 / count}) } } return } render(){ return ( <section> <h1>HOW IT WORKS</h1> <p>We calculate your match rate and let you know how to optimize your resume</p> <form className="matching"> <textarea maxLength="1000" placeholder="please copy and paste your job requirements here. 1000 characters limit" onChange={this.onChange}> </textarea> <div className="drag_and_drop"> <input type="file" onChange={this.onFile} disabled={this.state.fileBoxDisabled}/> </div> </form> <button onClick={this.onClick} disabled={this.state.buttonDisabled}><h3>Compare</h3></button> <span>{this.state.errors}</span> <span className={`result ${this.state.result > 80 ? "green" : "red"}`}>{this.state.result}%</span> </section> ) } } export default HowItWorks;
import React from 'react' import { connect } from 'react-redux' import { Container, Row, Col } from 'react-bootstrap' import { withRouter, Link } from 'react-router-dom' class SideMenu extends React.Component { state = { categSubMenu: this.props.reducer.data[this.props.reducer.currentCateg] } sideMenuCategory = () => { if(this.state.categSubMenu.find(el => el.type === 'category')) { return( <Col sm={ 12 } className='menu__list menu__list--category'> <div className='menu__title'>category</div> <ul> { this.state.categSubMenu.map((el, index) => { if(el.type === 'category') { return <Link to={`./${this.props.reducer.currentCateg}/${el.slug}`} className='menu__items' key={index}><li>{ el.title }</li></Link> } })} </ul> </Col> ) } } sideMenuOthers = () => { const subCateg = this.state.categSubMenu.reduce((a, b) => { const match = a.find(el => el === b.type); if (match) return a; if (b.type === 'category') return a a.push(b.type); return a; }, []); return subCateg.map((type, index) => { return( <React.Fragment key={ index }> <div className='menu__title'>{ type }</div> <ul> { this.sideMenuItems(type) } </ul> </React.Fragment> ) }) } sideMenuItems = (type) => { let categTrim = this.props.reducer.currentCateg.replace(/\s+/g, ''); return this.state.categSubMenu.map((el, index) => { if(type === el.type) return <Link className='menu__items' to={`./${categTrim}/${el.slug}`} key={index}><li key={ index }>{ el.title }</li></Link> }) } render () { return ( <Container className='menu'> <Row> { this.sideMenuCategory() } <Col sm={12} className='menu__list menu__list--others'> { this.sideMenuOthers() } </Col> </Row> </Container> ) } } const mapStateToProps = ({ AppReducer }) => ({ reducer: AppReducer }) export default withRouter(connect( mapStateToProps )(SideMenu));
/*2. Para el departamento de Construcción: A. mostrar la cantidad de alambre a comprar si se ingresara el largo y el ancho de un terreno rectangular y se debe alambra con tres hilos de alambre. B. mostrar la cantidad de alambre a comprar si se ingresara el radio de un terreno circular y se debe alambra con tres hilos de alambre. C. Para hacer un contrapiso de 1m x 1m se necesitan 2 bolsas de cemento y 3 de cal, debemos mostrar cuantas bolsas se necesitan de cada uno para las medidas que nos ingresen. */ var largo; var ancho; var perimetro; var longitudAlambre; function Rectangulo () { largo=document.getElementById('Largo').value; ancho=document.getElementById('Ancho').value; largo=parseInt(largo); ancho=parseInt(ancho); perimetro=(largo*2)+(ancho*2); longitudAlambre=perimetro*3; alert(longitudAlambre); } function Circulo () { var radio; radio=document.getElementById('Radio').value; radio=parseFloat(radio); perimetro=2*radio*(Math.PI); longitudAlambre=perimetro*3; alert(longitudAlambre); } function Materiales () { var metrosCuadrados; var bolsaCemento; var bolsaCal; largo=document.getElementById('Largo').value; ancho=document.getElementById('Ancho').value; largo=parseInt(largo); ancho=parseInt(ancho); metrosCuadrados=largo*ancho; bolsaCemento=metrosCuadrados*2; bolsaCal=metrosCuadrados*3; alert(bolsaCemento+" bolsas de Cemento y "+bolsaCal+" bolsas de Cal."); }
import { BASE_PATH, apiVersion } from "../config"; export function agregarEquiposApi(data) { const url = `${BASE_PATH}/${apiVersion}/agregar-EquipoUtencilios`; const params = { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json" } }; console.log(data); return fetch(url, params).then(response => { return response.json() }).then(result => { return result; }).catch(err => { return err; }) } export function getEquiposApi() { const url = `${BASE_PATH}/${apiVersion}/equipos`; const params = { method: "GET", headers: { "Content-Type": "application/json" }, mode: "cors" }; return fetch(url, params).then(response => { return response.json() }).then(result => { return result; }).catch(err => { return err; }) } export function updateEquipoApi(user, userId) { const url = `${BASE_PATH}/${apiVersion}/updateEquipo/${userId}`; const params = { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(user) } return fetch(url, params).then(response => { return response.json(); }).then(result => { return result; }).catch(err => { return err; }) } export function deleteEquipoaApi(id) { const url = `${BASE_PATH}/${apiVersion}/deleteEquipo/${id}`; const params = { method: "DELETE", headers: { "Content-Type": "application/json", }, }; return fetch(url, params).then(response => { return response.json(); }).then(result => { return result; }).catch(err => { return err; }) }
({ getAttributeMethod : function(component,event,helper){ var params = event.getParam('arguments'); // params.data= component.get('v.data'); params.ClsId= component.get('v.ClsId'); params.selectedlst= component.get('v.selectedlst'); params.QRCP= component.get('v.QRCP'); params.data1= component.get('v.data1'); params.selectedId= component.get('v.selectedId'); params.ClsIndx= component.get('v.ClsIndx'); params.Indx= component.get('v.Indx'); params.ClassId= component.get('v.ClassId'); params.lngth= component.get('v.lngth'); params.Classpackagelist=component.get("v.Classpackagelist"); alert('Parameters'+JSON.stringify(params.Classpackagelist)); params.navigate=true; // alert('Navigation'+params.navigate); return params; }, init : function(component, event, helper){ var enlst = component.get('v.enrollselectedlst'); for(var i=0;enlst[i]!=undefined;i++){ component.set('v.ClsId['+i+']',enlst[i].Id) } component.set("v.showSpinner",true); var action = component.get("c.getClasses"); action.setParams({"ClsId":component.get("v.ClsId")}) action.setCallback(this, function(response){ var state = response.getState(); console.log('State'+state); if(state == "SUCCESS"){ component.set("v.showSpinner",false); component.set("v.data",JSON.parse(response.getReturnValue())); console.log("gotit"+JSON.stringify(JSON.parse(response.getReturnValue()))); $A.createComponent("c:strike_dataGrid", {"data":component.get("v.data"),"parent":"parent" }, function(newCmp) { if (component.isValid()) { component.set("v.body", newCmp); } }); console.log("done12"); } }); $A.enqueueAction(action); console.log("done"); console.log("got"+component.get("v.data")); //var d = '{"columns":[{"sortable":true,"label":"Account Name",dataType":"STRING","name":"Name"},{"sortable":true,"label":"Account Phone","dataType":"PHONE","name":"Phone" },{"sortable":true,"label":"Website","dataType":"URL","name":"Website"],"rows":[{"Name":"Edge Communications","Phone":"(512) 757-6000","Website":"http://edgecomm.com"},{"Name":"Burlington Textiles Corp of America","Phone":"(336) 222-7000","Website":"www.burlington.com"},{"Name":"Grand Hotels & Resorts Ltd","Phone":"(312) 596-1000","Website":"www.grandhotels.com"},{"Name":"United Oil & Gas, UK","Phone":"+44 191 4956203","Website":"http://www.uos.com"}]}'; //component.set("v.data",d); /* var action1 = component.get('c.SrchGroup'); action1.setCallback(this, function(b) { if (b.getState() === "SUCCESS") { var test1 = b.getReturnValue(); var data1 = JSON.parse(test1); component.set("v.data", data1); console.log(b.getReturnValue()); } }); $A.enqueueAction(action1)*/ } /*getAttributeMethod : function(component,event,helper){ var params = event.getParam('arguments'); params.navigate=true; // alert('Navigation'+params.navigate); return params; }*/ })
define(['terminal'], function($terminal) { 'use strict'; $terminal.bind(); });
var tokenModule = angular.module('tokenProvider', []); tokenModule.provider('Token', function () { var token = localStorage.getItem("appToken"); var expires = localStorage.getItem("expires"); var tokenProvider = { isTokenValid: function() { var valid = false; if (expires != '' ) { // This should be returned in a format the client can parse. var date = new Date(expires); if (date > new Date()) valid = true; } return valid; }, getToken: function() { return token; }, getExpires: function() { return expires; }, update: function(newToken, newExpires) { token = newToken; expires = newExpires; localStorage.setItem('appToken', token); localStorage.setItem('expires', expires); }, clear: function() { token = ''; expires = ''; localStorage.removeItem('appToken'); localStorage.removeItem('expires'); } }; return { // Duplicated here so that we can access it in config isTokenValid: function() { return tokenProvider.isTokenValid() }, $get: function () { return tokenProvider; } } });
const QUEUE_NAME = 'tasks' const MESSAGE_TYPES = { REGULAR: 'regular', CRONTAB: 'crontab' } class QueueService { constructor(queueConnectionString) { this.connection = require('amqplib').connect(queueConnectionString) } addOneTimeTask(asin) { // Publisher this.connection .then(function (conn) { return conn.createChannel() }) .then( (channel)=> { return channel.assertQueue(QUEUE_NAME).then( (ok)=> { return channel.sendToQueue(QUEUE_NAME, Buffer.from(JSON.stringify(this.createPayload(MESSAGE_TYPES.REGULAR, {asin})))) }) }) .catch(console.warn) } addCronTask(asin,crontab, action ) { // Publisher this.connection .then(function (conn) { return conn.createChannel() }) .then( (channel)=> { return channel.assertQueue(QUEUE_NAME).then( (ok)=> { return channel.sendToQueue(QUEUE_NAME, Buffer.from(JSON.stringify(this.createPayload(MESSAGE_TYPES.CRONTAB, {asin, crontab, action})))) }) }) .catch(console.warn) } createPayload(type, payload) { return { type, payload: { ...payload } } } } module.exports = { QueueService }
// IIFI var counter = (function(){ var count = 0; count++; return function(){ return ++count; } })()