text
stringlengths
7
3.69M
var searchData= [ ['bandwidth_5fweight_5frule_5ft',['bandwidth_weight_rule_t',['../or_8h.html#a391c33d526d1e1210b4e9a6e85b21268',1,'or.h']]], ['bidi_5fmap_5fentry_5ft',['bidi_map_entry_t',['../rephist_8c.html#afe776d732ebba6b2d589fd3ecc9e4544',1,'rephist.c']]], ['bridge_5fline_5ft',['bridge_line_t',['../config_8h.html#adfd95e03f79ce72d94fc3004e4f256fa',1,'config.h']]], ['broken_5fstate_5fcount_5ft',['broken_state_count_t',['../connection__or_8c.html#a7c4fee93ea184453cf4ea4f4e44add5d',1,'connection_or.c']]], ['buf_5fpos_5ft',['buf_pos_t',['../buffers_8c.html#a26f1838aaee9885f1a135d1a2583579d',1,'buffers.c']]], ['build_5ftime_5ft',['build_time_t',['../or_8h.html#a45411da7d117ffaaf83b8fe4d4274bb8',1,'or.h']]], ['buildtimeout_5fset_5fevent_5ft',['buildtimeout_set_event_t',['../or_8h.html#ab2b66a0502f748bff1e9919aedae30d8',1,'or.h']]], ['bw_5farray_5ft',['bw_array_t',['../rephist_8c.html#aef0bf985394dc6f5fb62b6c65c440ed3',1,'rephist.c']]] ];
import React from 'react'; import FeIcons from 'components/FeIcons'; import SlideCaption from '../SlideCaption/SlideCaption'; export const Slide = (props) => { let style = ' item carousel-img '; if (props.index === props.initialSlideIndex) { style = 'active ' + style; } return ( <div className={style} style={{'backgroundImage': 'url(' + props.image + ')'}}> <div className="slide-top"> <FeIcons opacity={0.6} fade /> </div> <div className="container"> <SlideCaption {...props} /> </div> </div> ); }; Slide.propTypes = { index: React.PropTypes.number, initialSlideIndex: React.PropTypes.number, activeSlideIndex: React.PropTypes.number, prevSlideIndex: React.PropTypes.number, image: React.PropTypes.string, marginTop: React.PropTypes.number, animationType: React.PropTypes.string, animationDelay: React.PropTypes.number, title: React.PropTypes.string, subtitle: React.PropTypes.string, textColor: React.PropTypes.string, textAlign: React.PropTypes.string }; Slide.defaultProps = { image: 'carousel-img9', initialSlideIndex: 0 }; export default Slide;
import { Grid } from '@material-ui/core'; import React, {useState, useEffect} from 'react' import { makeStyles } from '@material-ui/core' import useCIForms, {Form} from '../components/useCIForms'; import Control from '../components/controls/Control'; import * as ciServices from '../service/ciServices' const initialFValues ={ id :0, fullName: '', address: '' } export default function CIForms(props) { const {addOrEdit, recordForEdit} =props const{ values, setvalues, handleInputChange, errors, setErrors, restForm } = useCIForms(initialFValues,true, validate) const validate =(fieldValues= values)=>{ let temp ={...errors} if('fullName' in fieldValues ) temp.fullName=fieldValues.fullName ? "" : "Your Name Is Required" if('address' in fieldValues ) temp.address=fieldValues.address ? "" : "Your Address Is Required" setErrors({ ...temp }) if(fieldValues== values) return Object.values(temp).every(x => x == "") } const handleSubmit = e => { e.preventDefault() if(validate()){ addOrEdit(values,restForm); //ciServices.insertInformation(values) } } useEffect(()=>{ if(recordForEdit!=null) setvalues({ ...recordForEdit }) },[recordForEdit]) return ( <Form onSubmit={handleSubmit}> <Grid container> <Control.Input label="Full Name" name="fullName" value={values.fullName} onChange={handleInputChange} error={errors.fullName} /> <Control.Input label="Address" name="address" value={values.address} onChange={handleInputChange} error={errors.address} /> <div> <Control.Button type="submit" text="Submit" /> <Control.Button type="reset" text="Reset" color="default" onClick={restForm} /> </div> </Grid> </Form> ) }
import './index.less' import {Modal, Form, Input, Button} from "antd"; import React from 'react' import FormItem from "antd/es/form/FormItem"; export default class modal extends React.Component { constructor(props) { super(props) this.state = { form: props.form } } componentWillReceiveProps(nextProps, nextContext) { this.setState({ form: nextProps.form }) } handleSubmit() { } handleInput(name, event) { this.setState({ form: Object.assign(this.state.form, {[name]: event.target.value}) }) } render() { const {form} = this.state; let {visible} = this.props; return ( <Modal visible={visible} title={'用户信息修改'} onCancel={this.props.modalVisibleChange} footer={null} > <Form onSubmit={this.handleSubmit}> <Form.Item> <span className={'name'}>用户昵称</span> <Input value={form.name} onInput={this.handleInput.bind(this, 'name')}/> </Form.Item> <Form.Item> <span className={'name'}>账号</span> <Input value={form.z_h} onInput={this.handleInput.bind(this, 'z_h')}/> </Form.Item> <Form.Item> <span className={'name'}>手机号</span> <Input value={form.phone} onInput={this.handleInput.bind(this, 'phone')}/> </Form.Item> <Form.Item> <span className={'name'}>邮箱</span> <Input value={form.Email} onInput={this.handleInput.bind(this, 'Email')}/> </Form.Item> <FormItem style={{textAlign: 'center'}}> <Button type={'primary'} htmlType={'submit'}>提交</Button> <Button style={{marginLeft: '20px'}} onClick={this.props.modalVisibleChange}>取消</Button> </FormItem> </Form> </Modal> ) } }
const e = require("express"); let express = require("express"); let router = express.Router(); let mongoService = require('./mongo/service'); router.get( "/testQuery", (req, res) => { if (req.query.date && req.query.product) { const dateQuery = req.query.date.split(','); console.log(dateQuery); let endDate = new Date(); let startDate = new Date(); let range = { "daily": 1, "weekly": 7, "monthly": 30 } let query = { ProductId: req.query.product, details: req.query.details || false } if (dateQuery.length === 2) { query.ViewDate = { $gte: new Date(dateQuery[0]), $lt: new Date(dateQuery[1]) } } else if (dateQuery.length === 1) { if (range.hasOwnProperty(dateQuery)) { console.log(startDate, endDate); startDate.setDate(endDate.getDate() - range[dateQuery]); console.log(startDate, endDate); query.ViewDate = { $gte: startDate, $lt: endDate } } else { res.status(400).send('Invalid Query'); } } else { res.status(400).send('Invalid Query'); } if (query.ViewDate) { mongoService.run(query).then((data) => { console.log('data', data); let totalCount = 0 if (data.result.length) { totalCount = data.result.map((e) => e.count).reduce((a,b) => a+b); } const uniqueCount = data.count; const uniqueUsers = data.result; let response = { totalUsers: totalCount, uniqueUsers: uniqueCount } if (req.query.details==="true") { response.uniqueUsers = { users: data.result, count: data.count }; } console.log('res', response); res.send(response); }).catch((err) => { console.log('err', err); res.status(400).send(err); }); } } else { res.status(400).send('Invalid Query'); } } ); module.exports = router;
import logo from './pics/jh.png'; // import tests from './pics/tests.png'; import usatoday from './pics/usatoday.png'; import abcnews from './pics/abcnews.png'; import mashable from './pics/mashable.png'; import { checkURL } from './js/urlChecker' import { handleSubmit } from './js/formHandler' import './styles/resets.scss' import './styles/base.scss' import './styles/footer.scss' import './styles/form.scss' import './styles/header.scss' var mylogo = document.getElementById('jhlogo'); mylogo.src = logo; // var testimg= document.getElementById('testimg'); // testimg.src= tests var nlogo1 = document.getElementById('nlogo1'); nlogo1.src = usatoday; var nlogo2 = document.getElementById('nlogo2'); nlogo2.src = abcnews; var nlogo3 = document.getElementById('nlogo3'); nlogo3.src = mashable; export { checkURL, handleSubmit, } //global vars const titles = []; const anchors= []; // const sectionText = ` <section id="section4" data-nav="Section 4"> // <div class="landing__container"> // <h2>Section 4</h2> // <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi fermentum metus faucibus lectus pharetra dapibus. Suspendisse potenti. Aenean aliquam elementum mi, ac euismod augue. Donec eget lacinia ex. Phasellus imperdiet porta orci eget mollis. Sed convallis sollicitudin mauris ac tincidunt. Donec bibendum, nulla eget bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam nunc eu augue. Pellentesque maximus imperdiet elit a pharetra. Duis lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a tincidunt felis. Sed leo nunc, pharetra et elementum non, faucibus vitae elit. Integer nec libero venenatis libero ultricies molestie semper in tellus. Sed congue et odio sed euismod.</p> // <p>Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar gravida, ipsum lacus aliquet velit, vel luctus diam ipsum a diam. Cras eu tincidunt arcu, vitae rhoncus purus. Vestibulum fermentum consectetur porttitor. Suspendisse imperdiet porttitor tortor, eget elementum tortor mollis non.</p> // </div> // </section>`; const navBar = document.querySelector('#navbar__list'); //get empty ul "#navbar__list" // /** // * End Global Variables // * // * Adding Fourth HTML Section // * // */ // //adding last section // const lastSection = document.getElementById('section3'); // lastSection.insertAdjacentHTML("afterend", sectionText); // /** // * Start Helper Functions // * // */ //Helper Funcs function getInfo(){ //given an array of sections on the page, get all their titles for use in navbar const sec_array = document.querySelectorAll('section'); sec_array.forEach(function(s){ titles.push(s.getAttribute('data-nav')); anchors.push(s.getAttribute('id')); }); } //Main Funcs // build the nav function fillNavBar(){ getInfo();//saves to global variables for (let i=0; i <titles.length; i++){ const item = document.createElement('li'); item.textContent = titles[i]; //item.innerHTML = "<a href= #" +anchors[i] + ">" + titles[i] + "</a>"; navBar.appendChild(item); item.classList.add('navbar__menu', 'menu__link') item.setAttribute('id','link_'+anchors[i]); } } // // Add class 'active' to section when near top of viewport // function activateViewed(){//testing hovering and menulinks // //checks all body children to see whats in viewport // mainSection = document.querySelector('main'); //<main> has landing page h1 and all sections // checklist = mainSection.children; //get the <header> and <section>s // navLinks = document.querySelector('#navbar__list');//get the list w/ data-nav titles to activate in loop //0,1,2,3 // len = checklist.length; // //loop through sections to see if active AND HIGHLIGHT ACTIVE SECTION ON NAVBAR! // for (let i = 1; i <len; i++){//start at 1 to ignore header //1,2,3,4 // let vpInfo = checklist[i].getBoundingClientRect(); //vpInfo contains: domrect obj w/ props: l/r/top/bottom/x/y/width/height // if (vpInfo.top <= 190 && vpInfo.bottom >= 190){ // checklist[i].classList.add('your-active-class'); //make the section active // navLinks.children[i-1].classList.add('menu__link__active');//make the navbar link active; // } else { // checklist[i].classList.remove('your-active-class'); //make sure all sections checked but not in view are not active // navLinks.children[i-1].classList.remove('menu__link__active'); // } // } // } // Scroll to anchor ID using scrollTO event navBar.addEventListener('click', function scrollToSection(e){ let sectionName = e.target.getAttribute('id').slice(5); //get rid of list id prefix (link_xxx) let secInfo = document.querySelector('#'+sectionName).getBoundingClientRect(); window.scrollTo({ top: secInfo.top + window.pageYOffset-180, behavior: 'smooth'}); }); /** * End Main Functions * Begin Events * */ // Build menu fillNavBar(); // Scroll to section on link click //edit to make function indep/not inline??? //navBar.addEventListener('click', scrollToSection(e)); ????? // Set sections as active // document.addEventListener('scroll', activateViewed);
import BaseLfo from '../../src/core/BaseLfo'; /** * node that make assertions against expected frames */ class Asserter extends BaseLfo { constructor(asserter) { super(); this.asserter = asserter; this.counter = 0; } setExpectedFrames(frames) { this.expectedFrames = frames; } processSignal(frame) { const assert = this.asserter; const expectedFrame = this.expectedFrames[this.counter]; const { time, data, metadata } = expectedFrame; assert.deepEqual(frame.time, time, 'should have same time'); assert.looseEqual(frame.data, data, 'should have same data'); assert.looseEqual(frame.metadata, metadata, 'should have same metadata'); this.counter += 1; } processVector(frame) { const assert = this.asserter; const expectedFrame = this.expectedFrames[this.counter]; const { time, data, metadata } = expectedFrame; // time must deal floating point errors assert.deepEqual(Math.abs(frame.time - time) < 1e-9, true, 'should have same time'); assert.looseEqual(frame.data, data, 'should have same data'); assert.looseEqual(frame.metadata, metadata, 'should have same metadata'); this.counter += 1; } } export default Asserter;
import React from 'react'; import { Table, Popconfirm, message } from 'antd'; import { $axios } from '@/utils/interceptor'; import 'moment/locale/zh-cn'; import useAntdTable from '@/hooks/useAntdTable'; import useBreadcrumb from '@/hooks/useBreadcrumb'; import useMount from '@/hooks/useMount'; import { useSelector } from 'react-redux'; // 武汉街道 const streetList = [ { value: 0, label: '洪山区关山街' }, { value: 1, label: '武昌区中南路' }, { value: 2, label: '江夏区流芳街' }, { value: 3, label: '青山区武东街' }, { value: 4, label: '江汉区民族街' }, { value: 5, label: '江岸区谌家矶' } ]; // 订单状态 const orderStatusList = [ { value: 0, label: '未付款' }, { value: 1, label: '正在支付' }, { value: 2, label: '支付成功' }, { value: 3, label: '正在派送' }, { value: 4, label: '订单完成' }, { value: 5, label: '支付失败' }, { value: 6, label: '订单取消' } ]; function RiderManage(props) { useBreadcrumb(['订单管理']); const user = useSelector(state => state.user); useMount(() => { if (!user.userId) { message.warn('请点击右上角登录后再查看'); props.history.replace('/'); } }); const { tableProps, updateList } = useAntdTable({ requestUrl: '/api/token/GosOrder/query', queryParams: {}, columns: [ { title: '订单ID', dataIndex: 'id' }, { title: '用户姓名', dataIndex: 'userName' }, { title: '用户电话号码', dataIndex: 'userPhone' }, { title: '骑手姓名', dataIndex: 'riderName' }, { title: '骑手电话号码', dataIndex: 'riderPhone' }, { title: '下单时间', dataIndex: 'orderTime' }, { title: '商品总价', dataIndex: 'goodsPrice' }, { title: '骑手费用', dataIndex: 'riderPrice' }, { title: '订单总价', dataIndex: 'totalPrice' }, { title: '下单地址街道', dataIndex: 'addressStreet', render: (text, record) => { const status = streetList.find(v => text === v.value); return status.label || '未知'; } }, { title: '下单小区楼栋', dataIndex: 'addressDetail' }, { title: '订单状态', dataIndex: 'orderStatus', render: (text, record) => { const status = orderStatusList.find(v => text === v.value); return status.label || '未知'; } }, { title: '备注', dataIndex: 'remark' }, { title: '操作', render: (text, record) => { if (record.orderStatus === 0) { return <a onClick={() => payMethod(record)}>立即支付</a>; } if (record.riderId && record.orderStatus === 3) { return ( <Popconfirm title="是否确认订单?" onConfirm={e => updateList(() => $axios .post(`/api/token/GosOrder/confirm`, { id: record.id, userId: user.userId, riderId: record.riderId }) .then(res => { message.success('确认收货成功'); }) ) } > <a>确认收货</a> </Popconfirm> ); } return <></>; } } ], adminCheck: false, userCheck: true }); function payMethod(order) { let htmlStr = ` <form id="alipaysubmit" name="alipaysubmit" action="http://www.lugas.cn/api/token/GosOrder/pay" method="post" enctype="application/x-www-form-urlencoded" style="display:none;" > 订单号: <input name="id" type="text" value="${order.id}" /> 总金额: <input name="totalPrice" type="number" value="${order.totalPrice}" /> 街道编号: <input name="addressStreet" type="number" value="${order.addressStreet}" /> token: <input name="token" type="text" value="${user.token}" /> <input type="submit" value="提交" /> </form> `; const newWindow = window.open('', '_self'); newWindow.document.write(htmlStr); newWindow.document.forms['alipaysubmit'].submit(); } return ( <> <Table {...tableProps} /> </> ); } export default RiderManage;
import React, {Component} from 'react'; import {Platform, StyleSheet, Text, View, TextInput,LayoutAnimation,Animated,Image, TouchableOpacity} from 'react-native'; const instructions = Platform.select({ ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu', android: 'Double tap R on your keyboard to reload,\n' + 'Shake or press menu button for dev menu', }); export default class App extends Component { constuctor(props) { //super(props); this.state={emailValid:false, rightPosition:-100, inputPassShadow : 0.09,inputTextShadow:0.09,showArrow: false}; } state = { fadeIn: new Animated.Value(0), fadeOut : new Animated.Value(1) }; _startIn = () => { Animated.timing(this.state.fadeIn, { toValue: 1, duration: 1000 }).start(); }; _startOut = () => { Animated.timing(this.state.fadeOut, { toValue: 0, duration: 1000 }).start(); }; _onFocusEmail = (e) => { //console.log(e) this.setState({inputTextShadow:0.90,inputPassShadow:0.09}) }; _onFocusPass = (e) => { //console.log(e) this.setState({inputPassShadow:0.90,inputTextShadow:0.09}) }; _renderArrow = () => { if (this.state.showArrow) { return ( <Image style={{height:25, width:25, position : 'absolute' , right : this.state.rightPosition, top : 8, alignSelf:"flex-end" }} source={require('./src/images/arrow.png')}></Image> ); } else { return null; } }; render() { const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'stretch', backgroundColor: '#003F5C', padding:10 }, welcome: { fontSize: 20, textAlign: 'left', margin: 10, color:'#FFF', alignSelf:'stretch', }, textBorderStyle: { backgroundColor: '#465881', borderRadius: 50, shadowColor: 'black', shadowOpacity: this.state.inputTextShadow, shadowOffset: { width: 0, height: 2}, shadowRadius: 10, }, passBorderStyle: { backgroundColor: '#465881', borderRadius: 50, shadowColor: 'black', shadowOpacity: this.state.inputPassShadow, shadowOffset: { width: 0, height: 2}, shadowRadius: 10, marginTop: 20 }, SubmitButtonStyle: { marginTop:10, paddingTop:15, paddingBottom:15, marginLeft:30, marginTop:30, marginRight:30, backgroundColor:'#FB5B5A', borderRadius:50, }, TextStyle:{ color:'#fff', textAlign:'center', } }); return ( <View style={styles.container}> <View style={styles.textBorderStyle}> <TextInput style={styles.welcome} onBlur={this._onBlur} onFocus={this._onFocusEmail} onChangeText={(text) => { this.emailIsValid(text)}}></TextInput> {this._renderArrow()} </View> <View style={styles.passBorderStyle}> <TextInput style={styles.welcome} onBlur={this._onBlur} onFocus={this._onFocusPass} textContentType="password" onChangeText={(text) => { this.emailIsValid(text)}}></TextInput> </View> <TouchableOpacity style={styles.SubmitButtonStyle} activeOpacity = { .5 } onPress={ this.ButtonClickCheckFunction } > <Text style={styles.TextStyle}> SUBMIT </Text> </TouchableOpacity> </View> ); } emailIsValid = (email) => { if(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { console.log(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)); LayoutAnimation.spring(); this.setState({rightPosition:10}) } else { console.log("hi"); LayoutAnimation.spring(); this.setState({showArrow:true}) this.setState({rightPosition:-100}) } /*return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)*/ } }
import React from 'react'; import './Comment.css'; function Comment(props) { const date = new Date(props.date); return ( <div className="comment" data-id={props.id}> <time className="date" dateTime={date.toDateString()}>{date.toDateString()}</time> <div className="content">{props.text}</div> </div> ); } export default Comment;
import template from './navigation.jade' var navigation = [ () => { return { restrict:'E', template:template } } ] export default angular.module('navigation',[]) .directive('zfNavigation',navigation) .name
import React, {Component} from 'react' import Create from './Create.jsx' import Detail from './Detail.jsx' class Form extends Component { static propTypes = { open: React.PropTypes.bool, edit: React.PropTypes.bool, schema: React.PropTypes.array, hide: React.PropTypes.func, selectedItem: React.PropTypes.object, selectedRow: React.PropTypes.number, create: React.PropTypes.func, update: React.PropTypes.func, delete: React.PropTypes.func, } render() { return this.props.selectedItem ? <Detail title="订单详情" open={this.props.open} schema={this.props.schema} hide={this.props.hide} item={this.props.selectedItem} update={this.props.update} delete={this.props.delete} /> : <Create title="新建订单" open={this.props.open} schema={this.props.schema} hide={this.props.hide} create={this.props.create} /> } } export default Form
const products = [ { id: 1, name: 'Pencil', price: 8, description: 'A pencil is an implement for writing or drawing, constructed of a narrow, solid pigment core in a protective casing that prevents the core from being broken and/or marking the user hand.' }, { id: 2, name: 'Envelope', price: 6, description: 'An envelope is a common packaging item, usually made of thin, flat material.' }, { id: 3, name: 'Eraser', price: 5, description: ' Erasers have a rubbery consistency and come in a variety of shapes, sizes and colours. Some pencils have an eraser on one end.' }, { id: 4, name: 'Sharpener', price: 10, description: 'A pencil sharpener (also referred to as pencil pointer or in Ireland as a parer or topper) is a tool for sharpening a pencil writing point by shaving away its worn surface. Pencil sharpeners may be operated manually or by an electric motor.' }, { id: 5, name: 'Notebook', price: 12, description: 'A notebook computer is a battery - or AC-powered personal computer generally smaller than a briefcase that can easily be transported and conveniently used in temporary spaces such as on airplanes, in libraries, temporary offices, and at meetings.' }, { id: 6, name: 'Yellow Paper', price: 7, description: 'a pen that has a small metal ball as the point of transfer of ink to paper ballpoint, ballpoint pen, Biro pen - a writing implement with a point from which ink flows Based on WordNet 3.0, Farlex clipart collection. © 2003-2012 Princeton University, Farlex Inc.' }, ] export default products
Session.setDefault('choosenRecipes', []); Template.SearchRecipe.onRendered(function() { this.subscribe('allRecipes'); }); Template.SearchRecipe.onCreated( () => { let template = Template.instance(); template.searchQuery = new ReactiveVar(); }); Template.SearchRecipe.helpers({ query() { return Template.instance().searchQuery.get(); }, lookingProducts() { if(Template.instance().searchQuery.get()) { let regex = new RegExp( Template.instance().searchQuery.get(), 'i' ); let query = { name: regex }; let queryProduct = { name: regex, canBeMeal: true }; return Recipes.find(query).fetch().concat(Products.find(queryProduct).fetch()); } else { return null; } } }); Template.SearchRecipe.events({ 'keyup [name="search"]': function ( event, template ) { let value = event.target.value.trim(); let regex = new RegExp( value, 'i' ); let query = { recipeName: regex }; Template.instance().searchQuery.set(value); }, 'click .recipe': function (event, template) { event.preventDefault(); var holdingName = template.data.toSave; if(holdingName == undefined) holdingName = "choosenRecipes"; var id = this._id; var currentRecipes = []; if(Session.get(holdingName) !== undefined) { currentRecipes = Session.get(holdingName);; } var position = currentRecipes.length; var prod = this.canBeMeal !== undefined; currentRecipes.push({ recipeName: this.name, id: this._id, amount: 0, position: position, itProduct: prod }); Session.set(holdingName, currentRecipes); Template.instance().searchQuery.set(""); } });
const requestURL = 'http://localhost/PoliAPI//Official/GetOfficials/1'; fetch(requestURL) .then(function (response) { return response.json(); }) .then(function (jsonObject) { console.table(jsonObject); const officials = jsonObject; for (let i = 0; i < officials.length; i++) { let card = document.createElement('section'); let h2 = document.createElement('h2'); let pOfficeName = document.createElement('p'); let image = document.createElement('img'); h2.textContent = "Name: " + officials[i].Name; pOfficeName.textContent = "Office Name: " + officials[i].OfficeName; if(officials[i].PhotoUrl != ""){ image.setAttribute('src', officials[i].PhotoUrl); } else { image.setAttribute('src', 'img/placeholder.png'); } image.setAttribute('alt', officials[i].name); card.appendChild(h2); card.appendChild(pOfficeName); card.appendChild(image); document.querySelector('div.cards').appendChild(card); } });
import React, { Component, Fragment } from 'react'; import ReactMapGL, { Marker } from 'react-map-gl'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { Creators as DeveloperActions } from '../../store/ducks/developer'; import Modal from '../../components/modal'; class Main extends Component { state = { viewport: { width: 'auto', height: window.innerHeight, latitude: -20.473885, longitude: -54.613905, zoom: 11, }, }; componentDidMount() { window.addEventListener('resize', this.resizeViewport); this.resizeViewport(); } componentWillUnmount() { window.removeEventListener('resize', this.resizeViewport); } resizeViewport = () => { const { viewport } = this.state; this.setState({ viewport: { ...viewport, width: 'auto', height: window.innerHeight, }, }); }; handleMapClick = (e) => { const { showModalDeveloper } = this.props; const [longitude, latitude] = e.lngLat; showModalDeveloper({ latitude, longitude }); }; render() { const { viewport: vPort } = this.state; const { developers } = this.props; return ( <Fragment> <ReactMapGL {...vPort} onClick={this.handleMapClick} mapStyle="mapbox://styles/mapbox/basic-v9" mapboxApiAccessToken={process.env.REACT_APP_MAPBOXACCESSTOKEN} onViewportChange={viewport => this.setState({ viewport })} > {developers.data.map(developer => ( <Marker latitude={developer.latitude} longitude={developer.longitude} key={developer.id} > <img style={{ borderRadius: 100, width: 48, height: 48, }} src={developer.img} alt="avatar" /> </Marker> ))} </ReactMapGL> {developers.modalDeveloper && <Modal />} </Fragment> ); } } Main.propTypes = { showModalDeveloper: PropTypes.func.isRequired, developers: PropTypes.shape({ modalDeveloper: PropTypes.bool, msg: PropTypes.string, error: PropTypes.string, data: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.number, img: PropTypes.string, latitude: PropTypes.number, longitude: PropTypes.number, }).isRequired, ).isRequired, }).isRequired, }; const mapStateToProps = state => ({ developers: state.developers, }); const mapDispatchToProps = dispatch => bindActionCreators(DeveloperActions, dispatch); export default connect( mapStateToProps, mapDispatchToProps, )(Main);
import React from 'react'; import './styles/Eventos.css'; import AgileInnova from '../img/logo-agile.png' class Eventos extends React.Component{ render(){ return( <section className="eventos"> <div className="container"> <h2 className="h4 mb-3">MÁS SOBRE MI EXPERIENCIA</h2> <article> <div className="row offset-1 col-10"> <div className="col-md-6"> <div className="card tarjeta" > <img src={AgileInnova} className="card-img-top" alt="..."/> <div className="card-body"> <h5 className="card-title">Mentor en Agile Innova</h5> <p className="card-text">Asesoramos colaborativamente a startups o empresas para que puedan definir nuevos modelos de negocio o nuevos procesos que sean innovadores, escalables, sostenibles y repetibles.</p> <a href="#" className="btn btn-outline-primary ">Ver más</a> </div> </div> </div> <div className="col-md-6"> <div className="card tarjeta" > <img src={AgileInnova} className="card-img-top" alt="..."/> <div className="card-body"> <h5 className="card-title">Mentor en Agile Innova</h5> <p className="card-text">Asesoramos colaborativamente a startups o empresas para que puedan definir nuevos modelos de negocio o nuevos procesos que sean innovadores, escalables, sostenibles y repetibles.</p> <a href="#" className="btn btn-outline-primary">Ver más</a> </div> </div> </div> <div className="col-md-6"> <div className="card tarjeta" > <img src={AgileInnova} className="card-img-top" alt="..."/> <div className="card-body"> <h5 className="card-title">Mentor en Agile Innova</h5> <p className="card-text">Asesoramos colaborativamente a startups o empresas para que puedan definir nuevos modelos de negocio o nuevos procesos que sean innovadores, escalables, sostenibles y repetibles.</p> <a href="#" className="btn btn-outline-primary ">Ver más</a> </div> </div> </div> <div className="col-md-6"> <div className="card tarjeta" > <img src={AgileInnova} className="card-img-top" alt="..."/> <div className="card-body"> <h5 className="card-title">Mentor en Agile Innova</h5> <p className="card-text">Asesoramos colaborativamente a startups o empresas para que puedan definir nuevos modelos de negocio o nuevos procesos que sean innovadores, escalables, sostenibles y repetibles.</p> <a href="#" className="btn btn-outline-primary">Ver más</a> </div> </div> </div> </div> </article> </div> </section> ); } } export default Eventos;
$(document).ready(function () { $("a#buttonUp").click(function () { $("html, body").animate({ scrollTop: 0 }, "slow"); return false; }); var btnUp = $('a#buttonUp'); var elemBtnW = $('header h1'); var zapuskBtnUp = false; if ($('a').is('#buttonUp')) { zapuskBtnUp = true; } else { zapuskBtnUp = false; } if (zapuskBtnUp) { var waypointBtnUp = new Waypoint({ element: elemBtnW, handler: function (direction) { if (direction == "down") { btnUp.fadeIn(); } else { btnUp.fadeOut(); }; }, offset: 0 }); }; $("#portfolio_grid").mixItUp(); $("#portfolio_grid2").mixItUp(); $(".s_portfolio li").click(function () { $(".s_portfolio li").removeClass("active"); $(this).addClass("active"); }); $(".popup").magnificPopup({type:"image"}); $(".popup_content").magnificPopup({ type:"inline", midClick: true }); $(".section_header").animated("fadeInUp", "fadeOutDown"); //$(".dopInformation").animated("fadeInUp", "fadeOutDown"); $(".animation_1").animated("flipInY", "fadeOutDown"); $(".animation_2").animated("fadeInLeft", "fadeOutDown"); $(".animation_3").animated("fadeInRight", "fadeOutDown"); $(".left .resume_item").animated("fadeInLeft", "fadeOutDown"); $(".right .resume_item").animated("fadeInRight", "fadeOutDown"); function heightDetect() { $(".main_head").css("height", $(window).height()); }; heightDetect(); $(window).resize(function () { heightDetect(); }); $(".portfolio_item").each(function (i) { $(this).find("a.seework").attr("href", "#work_" + i); $(this).find(".podrt_descr").attr("id", "work_" + i); }); $("input, select, textarea").jqBootstrapValidation(); $(".top_mnu ul a").mPageScroll2id(); });
//Mostra o dobro de um valor qualquer var assert = require('assert') function showDouble(valor){ return valor * 2; } // // Testes // try { assert.equal(10, showDouble(5)); } catch(e) { console.log(e); } console.log(showDouble(9))
//Entity: EntidadClienteBusquedaGrupoA //EntidadClienteBusquedaGrupoA. (Button) View: FormularioFacturacionClientesGrupoA //Evento ExecuteCommand: Permite personalizar la acción a ejecutar de un command o de un ActionControl. task.executeCommand.VA_VABUTTONWLKKQSA_336924 = function( entities, executeCommandEventArgs ) { executeCommandEventArgs.commons.execServer = true; //executeCommandEventArgs.commons.serverParameters.EntidadClienteBusquedaGrupoA = true; executeCommandEventArgs.parameters.nombre = executeCommandEventArgs.commons.api.vc.model.EntidadClienteBusquedaGrupoA.nombre; };
import './style.css'; import React, { useEffect, useState, useContext } from 'react'; import { Link, Redirect } from 'react-router-dom'; import API from '../../Utilities/API'; export default function Registration() { const [redirect, setRedirect] = useState(false); const [user, setUser] = useState({ firstName: null, lastName: null, email: null, password: null, passwordConfirmation: null }); const formUpdate = (fieldName, value) => { let tempUser = { ...user }; tempUser[fieldName] = value; setUser(tempUser); }; const submitNewUser = user => { API.createUser(user).then(res => { if (res.status === 200) { console.log(res.data); setRedirect(true); } }); }; const renderRedirect = () => { if (redirect) { return <Redirect to='/' />; } }; return ( <div className='container'> {renderRedirect()} <form id='form' className='form' onSubmit={e => e.preventDefault()}> <h2 data-test='header'>Register With Us</h2> <div className='form-control'> <label for='first-name' data-test='registration-label-first-name'> First Name </label> <input type='text' id='first-name' data-test='registration-input-first-name' placeholder='Enter first name' name='firstName' value={user.firstName} onChange={e => formUpdate(e.target.name, e.target.value)} /> <small className='error' data-test='registration-error-first-name'> Error message </small> </div> <div className='form-control'> <label for='last-name' data-test='registration-label-last-name'> Last Name </label> <input type='text' id='last-name' data-test='registration-input-last-name' placeholder='Enter last name' name='lastName' value={user.lastName} onChange={e => formUpdate(e.target.name, e.target.value)} /> <small className='error' data-test='registration-error-last-name'> Error message </small> </div> <div className='form-control'> <label for='email' data-test='registration-label-email'> Email </label> <input type='text' id='email' data-test='registration-input-email' placeholder='Enter email' name='email' value={user.email} onChange={e => formUpdate(e.target.name, e.target.value)} /> <small className='error' data-test='registration-error-email'> Error message </small> </div> <div className='form-control'> <label for='password' data-test='registration-label-password'> Password </label> <input type='password' id='password' data-test='registration-input-password' placeholder='Enter password' name='password' value={user.password} onChange={e => formUpdate(e.target.name, e.target.value)} /> <small className='error' data-test='registration-error-password'> Error message </small> </div> <div className='form-control'> <label for='password-confirmation' data-test='registration-label-password-confirmation' > Confirm Password </label> <input type='password' id='password-confirmation' placeholder='Enter password again' data-test='registration-input-password-confirmation' name='passwordConfirmation' value={user.passwordConfirmation} onChange={e => formUpdate(e.target.name, e.target.value)} /> <small className='error' data-test='registration-error-password-confirmation' > Error message </small> </div> <button type='submit' onClick={() => submitNewUser(user)} data-test='registration-submit-button' > Submit </button> <small> Already have an account? Login{' '} <Link to='/' data-test='registration-to-login'> here </Link> . </small> </form> </div> ); }
var menuRouteEntry = require('./menu') var articleDetailsRouteEntry = require('./articleDetails') var articleListRouteEntry = require('./articleList') // 路由配置 var routes = { '/menu': menuRouteEntry, '/articleDetails': articleDetailsRouteEntry, '/articleList/:key' : articleListRouteEntry, } gRouter = Router(routes); gRouter = gRouter.init(['/menu']); gRouter.on('after', 'articleList/:key', function(){ console.log('leave articleList/:key') gData.articleList.unBind() }) //gRouter.on('after', '/menu', function(){ //console.log('leave menu') //}) //p
const socialMediaFooter =()=>{ const body = document.querySelector('body'); const footer = document.createElement("footer"); footer.innerHTML = `<a href="https://github.com/shalommoise" target='_blank'> <img class="footericon" src="./pictures/socials/git hub logo.png" alt="GitHub" /></a> <a href="https://www.linkedin.com/in/shalom-moise-20a294128/" target='_blank'> <img class="footericon" src="./pictures/socials/linkedin logo.png" alt="LinkedIn" /></a> <a href="https://www.strava.com/athletes/51107146" id="strava" target='_blank'><img class="footericon" src="./pictures/socials/strava logo.svg" alt="Strava" /></a> <a href="mailto:mshalom689@gmail.com?subject=Hi Shalom" target='_blank'><img class="footericon" src="./pictures/socials/email logo.png" alt="email" /></a> <a href="https://www.facebook.com/shalom.moise" target='_blank'><img class="footericon" src="./pictures/socials/facbook logo.png" alt="facebook" /></a> <a href="https://www.instagram.com/shalommoise/" target='_blank'><img class="footericon" src="./pictures/socials/instagram logo.png" alt="instagram" /></a> <a href="https://twitter.com/MoiseShalom" target='_blank'><img class="footericon" src="./pictures/socials/twitter logo.png" alt="twitter" /></a>`; body.append(footer); } socialMediaFooter();
// la fonction showArticlesByDate affiche les genres possible const showArticlesByDuration = () => { let html = ''; html += ` <div class="form-check"> <form id="formSearchedByDuration"> <div class="form-check"> <input class="form-check-input" type="radio" name="durationMax" value="30"> <label class="form-check-label" for="durationMax"> 1min to 30min </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="durationMax" value="60"> <label class="form-check-label" for="durationMax"> 30min to 1h </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="durationMax" value="90"> <label class="form-check-label" for="durationMax"> 1h to 1h30 </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="durationMax" value="120"> <label class="form-check-label" for="durationMax"> 1h30 to 2h </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="durationMax" value="150"> <label class="form-check-label" for="durationMax"> 2h to 2h30 </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="durationMax" value="180"> <label class="form-check-label" for="durationMax"> 2h30 to 3h </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="durationMax" value="210"> <label class="form-check-label" for="durationMax"> 3h to 3h30 </label> </div> <br> <input class="btn btn-secondary" type="submit" value="OK"> </form> </div> <hr class="col-xs-12"> `; return html; }; export default showArticlesByDuration;
/** * @fileOverview Carousel View Module File * * @author Zach Walders */ STATUS.Carousel = function($) { 'use strict'; var $window = $(window); /** * Determines current wrapper and creates carousels for each related wrapper found */ var CarouselFactory = function(options) { this.options = options; if (!this.checkOptions()) { return; } this.buildCarousels(); }; /** * checks to see if options and dom elements exist * if options are missing, throws error * if dom elements exist, return true, if not return false */ CarouselFactory.prototype.checkOptions = function() { var requiredOptions = [ 'carouselWrapperSelector', 'slideWrapperSelector', 'slideListSelector', 'buttonClass', 'buttonPrevClass', 'buttonPrevActiveClass', 'buttonNextClass', 'buttonNextActiveClass', 'animationDuration', 'swipeXThresholdModifier' ]; var requiredDomElements = [ 'carouselWrapperSelector', 'slideWrapperSelector', 'slideListSelector' ]; var length = requiredOptions.length; var i = 0; for (; i < length; i++) { if (!this.options[requiredOptions[i]]) { throw new Error(requiredOptions[i] + ' not found in options'); } } length = requiredDomElements.length; i = 0; for (; i < length; i++) { if (!$(this.options[requiredDomElements[i]]).length) { console.log(this.options[requiredDomElements[i]] + ' not found in the dom'); return false; } } return true; }; /** * Builds new carousels for each wrapper found */ CarouselFactory.prototype.buildCarousels= function() { var $wrappers = $(this.options.carouselWrapperSelector); var length = $wrappers.length; var i = 0; this.carousels = []; for (; i < length; i++) { this.options.$wrapper = $wrappers.eq(i); this.carousels.push(new Carousel(this.options)); } }; /** * Initializes a single carousel */ var Carousel = function(options) { this.options = options; this.init(); }; /** * Initializes the UI Component View * Runs a single setupHandlers call, followed by createChildren and layout */ Carousel.prototype.init = function() { this.isUiEnabled = false; this.isResizable = false; this.hasWebkitTransforms = 'WebKitCSSMatrix' in window && 'm11' in new WebKitCSSMatrix(); return this .setupHandlers() .createChildren() .renderNav() .enableUi() .enableResize(); }; /** * Binds the scope of any handler functions * Should only be run on initialization of the view */ Carousel.prototype.setupHandlers = function() { this.onPrevHandler = $.proxy(this.onPrev, this); this.onNextHandler = $.proxy(this.onNext, this); this.onResizeHandler = $.proxy(this.onResize, this); this.onTouchWrapperStartHandler = $.proxy(this.onTouchWrapperStart, this); this.onTouchWrapperMoveHandler = $.proxy(this.onTouchWrapperMove, this); this.onTouchWrapperEndHandler = $.proxy(this.onTouchWrapperEnd, this); return this; }; /** * Create any child objects or references to DOM elements * Should only be run on initialization of the view */ Carousel.prototype.createChildren = function() { this.$wrapper = this.options.$wrapper; this.wrapperWidth = this.$wrapper.outerWidth(); this.$slideWrapper = this.$wrapper.find(this.options.slideWrapperSelector); this.$slideList = this.$wrapper.find(this.options.slideListSelector); this.$slides = this.$slideList.children(); this.$prevButton = null; this.$nextButton = null; this.totalSlides = 0; this.activeIndex = 0; this.animationDuration = this.options.animationDuration; this.isResizing = false; this.swipeXThreshold = Math.round(this.wrapperWidth * this.options.swipeXThresholdModifier); this.isDragging = false; this.dragDirection = null; this.isSwipeReady = false; this.isScrolling = false; this.touchStartX = 0; this.touchStartY = 0; return this; }; /** * Enables the view * Performs any event binding to handlers * Exits early if it is already enabled */ Carousel.prototype.enableUi = function() { if (this.isUiEnabled) { return this; } this.isUiEnabled = true; this.$slideList.on('touchstart', this.onTouchWrapperStartHandler); this.$slideList.on('touchmove', this.onTouchWrapperMoveHandler); this.$slideList.on('touchend', this.onTouchWrapperEndHandler); this.$prevButton.on('tap', this.onPrevHandler); this.$nextButton.on('tap', this.onNextHandler); return this; }; /** * Disables the view * Tears down any event binding to handlers * Exits early if it is already disabled */ Carousel.prototype.disableUi = function() { if (!this.isUiEnabled) { return this; } this.isUiEnabled = false; this.$slideList.off('touchstart', this.onTouchWrapperStartHandler); this.$slideList.off('touchmove', this.onTouchWrapperMoveHandler); this.$slideList.off('touchend', this.onTouchWrapperEndHandler); this.$prevButton.off('tap', this.onPrevHandler); this.$nextButton.off('tap', this.onNextHandler); return this; }; /** * Enables the windwow resize event */ Carousel.prototype.enableResize = function() { if (this.isResizable) { return this; } this.isResizable = true; $window.on('resize', this.onResizeHandler); return this; }; /** * Disable the windwow resize event */ Carousel.prototype.disableResize = function() { if (!this.isResizable) { return this; } this.isResizable = false; $window.off('resize', this.onResizeHandler); return this; }; /** * onPrev Handler * handles using the previous button to jump to the previous slide */ Carousel.prototype.onPrev = function(e) { e.preventDefault() this.prev(); }; /** * prev * jumps to the previous slide */ Carousel.prototype.prev = function() { var isAtStart = this.activeIndex === 0; if (isAtStart) { return false; } this.activeIndex -= 1; this.slide(); }; /** * onNext Handler * handles using the next button to jump to the next slide */ Carousel.prototype.onNext = function(e) { e.preventDefault(); this.next(); }; /** * next * jumps to the mext slide */ Carousel.prototype.next = function(e) { var isAtEnd = this.activeIndex === (this.totalSlides - 1); if (isAtEnd) { return false; } this.activeIndex += 1; this.slide(); }; /** * onTouchWrapperStart Handler * Performs this action on touchstart of the slide wrapper */ Carousel.prototype.onTouchWrapperStart = function(e) { this.touchStartX = e.originalEvent.touches[0].screenX; this.touchStartY = e.originalEvent.touches[0].screenY; this.dragDirection = null; this.isSwipeReady = false; this.isDragging = false; this.isScrolling = false; }; /** * onTouchWrapperMove Handler * Performs this action on touchmove of the slide wrapper */ Carousel.prototype.onTouchWrapperMove = function(e) { var touchCurrentX = e.originalEvent.touches[0].screenX; var touchCurrentY = e.originalEvent.touches[0].screenY; var touchXDistance = this.touchStartX - touchCurrentX; var touchYDistance = this.touchStartY - touchCurrentY; var isSwipeXThresholdMet = Math.abs(touchXDistance) > this.swipeXThreshold; var isHorizontalDrag = Math.abs(touchXDistance) > Math.abs(touchYDistance); this.dragDirection = touchXDistance > 0 ? 'left' : 'right'; if (isHorizontalDrag) { e.preventDefault(); } else { this.isScrolling = true; } if (this.isScrolling) { return; } this.drag(-touchXDistance); if (isSwipeXThresholdMet) { this.isSwipeReady = true; return; } this.isSwipeReady = false; }; /** * onTouchWrapperEnd Handler * Performs this action on touchend of the slide wrapper */ Carousel.prototype.onTouchWrapperEnd = function(e) { if (!this.isSwipeReady) { this.bounce(); return; } if (this.dragDirection === 'left') { this.next(); return false; } if (this.dragDirection === 'right') { this.prev(); return false; } return false; }; /** * onResize Handler * Performs this action on window resize */ Carousel.prototype.onResize = function(e) { var progressPercentage = (this.activeIndex / (this.totalSlides - 1)); this.isResizing = true; this.animationDuration = 0; this.$slideList.css('-webkit-transition-duration', (0 + 'ms')); this .updateLayout(progressPercentage) .slide(); }; /** * Appends new nav elements to the dom and updates their references */ Carousel.prototype.renderNav = function() { var visibleSlides = Math.round(this.$slideList.outerWidth() / this.$slides.eq(0).outerWidth()); var i = 0; this.totalSlides = Math.round(this.$slides.length / visibleSlides); this.$prevButton = this.$wrapper.find('.' + this.options.buttonPrevClass); this.$nextButton = this.$wrapper.find('.' + this.options.buttonNextClass); return this.updateButtons(); }; /** * updateButtons * Hides or show prev and next buttons if you're at the beginning or end of the carousel */ Carousel.prototype.updateButtons = function() { if (this.activeIndex === 0) { this.$prevButton.removeClass(this.options.buttonPrevActiveClass); this.$nextButton.addClass(this.options.buttonNextActiveClass); return this; } if (this.activeIndex === (this.totalSlides - 1)) { this.$prevButton.addClass(this.options.buttonPrevActiveClass); this.$nextButton.removeClass(this.options.buttonNextActiveClass); return this; } this.$prevButton.addClass(this.options.buttonPrevActiveClass); this.$nextButton.addClass(this.options.buttonNextActiveClass); return this; }; /** * updateLayout * Carries out updates necessary after resize */ Carousel.prototype.updateLayout = function(progressPercentage) { this.wrapperWidth = this.$wrapper.outerWidth(); this.activeIndex = Math.round((this.totalSlides - 1) * progressPercentage); this.swipeXThreshold = Math.round(this.wrapperWidth * this.options.swipeXThresholdModifier); return this; }; /** * drag * Sets up values for animating on drag and calls animate */ Carousel.prototype.drag = function(dragDistance) { var animateValue; var isAtStartAndDragRight = this.activeIndex === 0 && this.dragDirection === 'right'; var isAtEndAndDragLeft = this.activeIndex === (this.totalSlides - 1) && this.dragDirection === 'left'; if (isAtStartAndDragRight || isAtEndAndDragLeft) { return; } this.isDragging = true; animateValue = (-(this.activeIndex * this.wrapperWidth) + dragDistance); this.animationDuration = 0; this.$slideList.css('-webkit-transition-duration', (0 + 'ms')); this.animate(animateValue); }; /** * slide * Sets up values for animating when a slide changes and calls animate */ Carousel.prototype.slide = function() { var animateValue = -(this.activeIndex * this.wrapperWidth); if (this.isResizing) { this.isResizing = false; } else { this.animationDuration = this.options.animationDuration; this.$slideList.css('-webkit-transition-duration', (this.animationDuration + 'ms')); } return this .animate(animateValue) .updateButtons(); }; /** * bounce * Animates the slides back to original position after drag if conditions for swipe aren't met */ Carousel.prototype.bounce = function() { if (!this.isDragging) { return; } this.slide(); }; /** * animate * Animates the slides to the passed in animateValue */ Carousel.prototype.animate = function(animateValue) { if (this.hasWebkitTransforms) { this.$slideList.css('-webkit-transform', 'translate3d(' + animateValue + 'px, 0, 0)'); return this; } this.$slides.eq(0).stop().animate({ 'margin-left': (animateValue + 'px') }, this.animationDuration); return this; }; /** * Destroys the view * Tears down any events, handlers, elements * Should be called when the object should be left unused */ Carousel.prototype.destroy = function() { this .disableUi() .disableResize(); return this; }; return CarouselFactory; }(jQuery);
module.exports = { before: { all: [], find: [], get: [], create: [ context => { const { app, data, params } = context; return app.service('push-notification-subs') .find({ query: { token: data.token } }).then(subs => { const sub = subs.data[0]; if (sub) { return app.service('push-notification-subs') .update(sub._id, data, params) .then(() => { context.statusCode = 204; context.result = {}; }); } }); } ], update: [], patch: [], remove: [] }, after: { all: [], find: [], get: [], create: [], update: [], patch: [], remove: [] }, error: { all: [], find: [], get: [], create: [], update: [], patch: [], remove: [] } };
/** * @author v.lugovsky * created on 16.12.2015 */ (function () { 'use strict'; angular.module('BlurAdmin.pages.app.warehouse', [ 'BlurAdmin.pages.app.warehouse.polocation', 'BlurAdmin.pages.app.warehouse.poimport', 'BlurAdmin.pages.app.warehouse.import', 'BlurAdmin.pages.app.warehouse.stockcounting', 'BlurAdmin.pages.app.warehouse.stockbalance', 'BlurAdmin.pages.app.warehouse.stockadjust', ]) .config(routeConfig); /** @ngInject */ function routeConfig($stateProvider) { $stateProvider .state('app.warehouse', { url: '/warehouse', template : '<ui-view></ui-view>', abstract: true, title: 'warehouse.main', sidebarMeta: { icon: 'ion-cube', order: 700, }, }); } })();
import React, {useEffect, useState} from 'react' import axios from 'axios' import { v4 as uuidv4 } from 'uuid'; import NewsItem from './NewsItem' const fetchData = async (setData, setError, keyword ='') => { try { const response = await axios(`http://localhost:8081/api/news?keyword=${keyword}`) setData( response.data.articles || []) setError('') } catch(e) { setData([]) setError(e.message) } } const NewsList = (props) => { const [data, setData] = useState([]) const [keyword, setKeyword] = useState() const [error, setError] = useState('') useEffect(()=>{ fetchData(setData,setError); },[]) const renderContent = () => { if(data && data.length) { return ( data.map(item => <NewsItem key={uuidv4()} {...item}/>) ) } if(error) return <div>{error}</div> return <div>No data found</div> } const handleSearch = () => { fetchData(setData, setError, keyword) } return ( <div> <h2>News Board</h2> <input placeholder='Enter a keyword' onChange={(e) => setKeyword(e.target.value)} /> <button onClick={handleSearch}>Search</button> {renderContent()} </div> ) } export default NewsList;
(function(){ $(document).ready(function(){ var video = document.querySelector("#videoElement"); navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia; if (navigator.getUserMedia) { navigator.getUserMedia({video: true}, handleVideo, videoError); } function handleVideo(stream) { video.src = window.URL.createObjectURL(stream); } function videoError(e) { // do something } var v,canvas,context,w,h; var imgtag = document.getElementById('imgtag'); // get reference to img tag var sel = document.getElementById('fileselect'); // get reference to file select input element console.log("dom loaded"); v = document.getElementById('videoElement'); canvas = document.getElementById('canvas'); context = canvas.getContext('2d'); w = canvas.width; h = canvas.height; var currentURI; var alreadySaved = false; function draw(v,c,w,h) { if(v.paused || v.ended) return false; // if no video, exit here //175,87.5 context.drawImage(v,230,120,180,240, 0,0,150,200); // draw video feed to canvas //context.drawImage(v,0,0,w,h); var uri = canvas.toDataURL("image/png"); // convert canvas to data URI currentURI = uri; //console.log(uri); // uncomment line to log URI for testing var token = $('#token').val(); /*Image equation manier*/ /* $.post( "/store", {dataURI: uri, '_token': token}, function(data){ console.log(data); $("#resultName").html("Is this " + data[0] +"?"); $(".result").css("visibility", "visible"); } );*/ /*Opencv manier*/ $.post( "/comparePictureOpenCv", {dataURI: uri, '_token': token}, function(data){ console.log(data[1]); $("#resultName").html("Is this " + data[0] +"?"); $(".result").css("visibility", "visible"); } ); alreadySaved = false; //imgtag.src = uri; // add URI to IMG tag src } document.getElementById('save').addEventListener('click',function(e){ draw(v,context,w,h); // when save button is clicked, draw video feed to canvas }); var token = $('#token').val(); $("#sendName").on("click",function(){ if(!alreadySaved){ var newName = $("#newName").val(); if(newName != ""){ console.log("send"); /*Image equation manier*/ $.post( "/newName", { name: newName, dataURI: currentURI, '_token': token}, function(data){ console.log(data); } ); $(".result").css("visibility", "hidden"); alreadySaved = true; } } }); // for iOS // create file reader var fr; sel.addEventListener('change',function(e){ var f = sel.files[0]; // get selected file (camera capture) fr = new FileReader(); fr.onload = receivedData; // add onload event fr.readAsDataURL(f); // get captured image as data URI }) function receivedData() { // readAsDataURL is finished - add URI to IMG tag src imgtag.src = fr.result; } }); })();
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var default_rules_1 = require("./default-rules"); var rule_1 = require("./rule"); var RulesManager = (function () { function RulesManager(htmlInputElement) { this.htmlInputElement = htmlInputElement; } RulesManager.appendRules = function (customRules) { for (var ruleName in customRules) { RulesManager.rules[ruleName] = customRules[ruleName]; } }; RulesManager.prototype.extractCallbackChain = function () { var callbackChain = []; var ruleKeys = Object.keys(RulesManager.rules); for (var i = 0; i < ruleKeys.length; i++) { var attributeName = 'validation-' + ruleKeys[i]; if (this.htmlInputElement.hasAttribute(attributeName)) { callbackChain.push(new rule_1.ValidationRule(RulesManager.rules[ruleKeys[i]], this.htmlInputElement)); } } return callbackChain; }; RulesManager.prototype.get = function (key) { }; return RulesManager; }()); RulesManager.rules = default_rules_1.rules; exports.RulesManager = RulesManager;
(function () { 'use strict'; //Localstorage and Sessionstorage ids const LOCALSTORAGE_ID = "deez-web-app-dylan"; const SESSIONSTORAGE_ID = "last-search-deez-web-dylan" //Button to launch the search const startSearch = $('#submitInput'); //Array with all your fav songs let favorites = []; //Last request data to keep on choosing songs let lastRequestData = {}; function init() { //Check sessionstorage for last request if (sessionStorage.getItem(SESSIONSTORAGE_ID)) { lastRequestData = JSON.parse(sessionStorage.getItem(SESSIONSTORAGE_ID)); if (lastRequestData.title.trim().length > 0) { $('.current-search-title').html(`de "${lastRequestData.title.trim()}"`); $('#search').val(lastRequestData.title.trim()); $('#sort').val(lastRequestData.sort); search(lastRequestData.url); } else { $("#show-more").empty(); $('.search-results').html(` <h1 class="ooups">Veuillez saisir au moins un caractère ...</h1> `); } } else { //Message if there is no current search if ($('.search-results').text().length === 0) { $('.search-results').append(`<h1 class="no-search">Aucune recherche actuellement ...</h1>`); } } //Check localstorage to fill the fav array if (localStorage.getItem(LOCALSTORAGE_ID)) { favorites = JSON.parse(localStorage.getItem(LOCALSTORAGE_ID)); //Empty the ctn of your fav songs $('.favorites-ctn').empty(); //Diplay all your fav songs for (let i = 0; i < favorites.length; i++) { const song = favorites[i]; $('.favorites-ctn').append( ` <div class="result-ctn"> <div class="img-add delete"> <img src="${song.album.cover}" alt=""> <input type="submit" value="Retirer des favoris" id="${song.id}" class="btn-remove"> </div> <div class="song-infos"> <h1>${song.title}</h1> <h2>${song.artist.name} / ${song.album.title}</h2> <audio controls src="${song.preview}"></audio> </div> </div> `); //Event when you want to delete a fav song $(`.delete #${song.id}`).click(function (event) { event.preventDefault(); deletefavorite(i, song); init(); }); } } //Event when you click to search a song startSearch.click(function (event) { event.preventDefault(); //Values of the current search const searchValue = $('#search').val(); const sortValue = $('#sort').val(); const url = `https://api.deezer.com/search?q=${searchValue}&order=${sortValue}&output=jsonp`; //Check whitespaces if (searchValue.trim().length > 0) { lastRequestData = { url: url, title: searchValue, sort: sortValue }; sessionStorage.setItem(SESSIONSTORAGE_ID, JSON.stringify(lastRequestData)); $('#search').val(searchValue.trim()); $('.search-results').empty(); $('.more-results').empty(); $('.current-search-title').html(`de "${lastRequestData.title.trim()}"`); search(url); } else { sessionStorage.clear(); $('.more-results').empty(); $('.current-search-title').empty(); $('.search-results').html(` <h1 class="ooups">Veuillez saisir au moins un caractère ...</h1> `); } }); //Choose a random fav song randomFavoriteSong(favorites); //Message if you have no fav songs if (favorites.length <= 0) { $('.favorites-ctn').append(`<h1 class="no-fav">Aucuns coups de coeur dans votre playlist actuellement...</h1>`); } } //Function to launch the search function search(requestUrl) { $.ajax({ url: requestUrl, dataType: 'jsonp', }) .then(obj => { //Get data const songs = obj.data; //Next url const next = obj.next; //If there is no results if (songs === undefined || songs.length <= 0) { $('.search-results').append(` <h1 class="ooups">Ooups, on dirait qu'il n'y a pas de résultat pour "${lastRequestData.title.trim()}"</h1> `); } else { $('.search-results').empty(); displayResults(songs); $('.more-results').append(`<input type="submit" value="Voir plus" id="show-more">`); $("#show-more").click(function (event) { event.preventDefault(); $(this).remove(); //Display next reults getMoreResults(next); }); } }) //Errors .catch(error => { if (error.status) { $('.search-results').append(` <h1 class="ooups">Erreur ${error.status}</h1> `); } }) } //Function to display all the results function displayResults(songs) { $.each(songs, function (index, song) { //If not already added to your fav if (!isAlreadyAdded(song, favorites)) { $('.search-results').append( ` <div class="result-ctn"> <div class="img-add add-song-${song.id}"> <img src="${song.album.cover}" alt=""> <input type="submit" value="Ajouter aux Favoris" id="add-${song.id}" class="input-add"> </div> <div class="song-infos"> <h1>${song.title}</h1> <h2>${song.artist.name} / ${song.album.title}</h2> <audio controls src="${song.preview}"></audio> </div> </div> `); //Add fav song selected $(`.add-song-${song.id} #add-${song.id}`).click(function (event) { event.preventDefault(); if (!isAlreadyAdded(song, favorites)) { addFavorite(song); } }); } else { //If already added $('.search-results').append( ` <div class="result-ctn"> <div class="img-add add-song-${song.id}"> <img src="${song.album.cover}" alt=""> <input type="submit" value="Retirer de mes Favoris" id="add-${song.id}" class="input-add btn-remove"> </div> <div class="song-infos"> <h1>${song.title}</h1> <h2>${song.artist.name} / ${song.album.title}</h2> <audio controls src="${song.preview}"></audio> </div> </div> `); //Deletion of the fav song $(`.add-song-${song.id} #add-${song.id}`).click(function (event) { event.preventDefault(); //Index of the song to delete let favIndex = getIndex(song, favorites); //Deletion deletefavorite(favIndex, song); }); } }); } //Function to get more results function getMoreResults(next) { $.ajax({ url: next, dataType: 'jsonp', }) .then(obj => { //Get data const songs = obj.data; const nextSongs = obj.next; //If there is no more results if (songs === undefined || songs.length <= 0) { $('.search-results').append(` <h1 class="ooups">Ooups, on dirait qu'il n'y a pas plus de résultats pour "${lastRequestData.title.trim()}" ...</h1> `); } else { displayResults(songs); $('.more-results').append(`<input type="submit" value="Voir plus" id="show-more">`); $("#show-more").click(function (event) { event.preventDefault(); $(this).remove(); getMoreResults(nextSongs); }) } }) //Errors .catch(error => { if (error.status) { //Hack for the api errors management if (error.status === 200) { $('.search-results').append(` <h1 class="ooups">Ooups, on dirait qu'il n'y a pas plus de résultats pour "${lastRequestData.title.trim()}" ...</h1> `); } else { $('.search-results').append(` <h1 class="ooups">Erreur ${error.status}</h1> `); } } }) } //Put the song in your favorites function addFavorite(song) { favorites.push(song); localStorage.setItem(LOCALSTORAGE_ID, JSON.stringify(favorites)); $(`.add-song-${song.id} input`).remove(); $(`.add-song-${song.id}`).append(` <input type="submit" value="Retirer des Favoris" id="add-${song.id}" class="input-add btn-remove"> `); $(`.add-song-${song.id} #add-${song.id}`).click(function (event) { event.preventDefault(); let favIndex = getIndex(song) deletefavorite(favIndex, song); }); } //Delete the specific fav song function deletefavorite(index, song) { favorites.splice(index, 1); localStorage.setItem(LOCALSTORAGE_ID, JSON.stringify(favorites)); onChangeDelete(song, index); } //Changing of the button when you need to delete one of your fav songs function onChangeDelete(song, index) { $(`.add-song-${song.id} input`).remove(); $(`.add-song-${song.id}`).append(` <input type="submit" value="Ajouter aux Favoris" id="new-${song.id}" class="input-add btn-add"> `); $(`#new-${song.id}`).click(function (event) { event.preventDefault(); addFavorite(song); }); } //Diplay a random of your fav songs function randomFavoriteSong(favorites) { $('.random-favorite').empty(); //Check your fav array to display a random song if (favorites.length > 0) { //Random song to display let randomSong = favorites[Math.floor(Math.random() * favorites.length)]; $('.random-favorite').append( ` <div class="result-ctn"> <div class="img-add random"> <img src="${randomSong.album.cover}" alt=""> <input type="submit" value="Autre titre aléatoire" id="random-${randomSong.id}"> </div> <div class="song-infos"> <h1>${randomSong.title}</h1> <h2>${randomSong.artist.name} / ${randomSong.album.title}</h2> <audio controls src="${randomSong.preview}"></audio> </div> </div> `); //Display another random song $(`#random-${randomSong.id}`).click(function (event) { event.preventDefault(); randomFavoriteSong(favorites); }); } else { //If there is no fav song $('.random-favorite').html( `<h1 class="add-one">Enregistrez votre premier coup de coeur pour écouter un titre aléatoire !</h1> `); $('.background').html(` <img src="img/background-music.png" alt=""> `); } } //Return if the song is already added function isAlreadyAdded(song, favorites) { for (let i = 0; i < favorites.length; i++) { if (favorites[i].id === song.id) { return true; } } return false } //Get index of the fav array to delete it function getIndex(song) { for (let i = 0; i < favorites.length; i++) { if (favorites[i].id === song.id) { return i; } } } //App init init(); })();
import React,{useState} from 'react'; import {Card,Form, Button, Container, Row, Col, InputGroup, FormControl, Badge, FormGroup} from 'react-bootstrap'; import {Input} from 'reactstrap'; import axios from 'axios'; import { Redirect } from "react-router-dom"; import "../Postaproject.css"; import button1 from './images/button1.png'; import button2 from './images/button2.png'; import button3 from './images/button3.png'; import button4 from './images/button4.png'; import button5 from './images/button5.png'; import button6 from './images/button6.png'; import button7 from './images/button7.png'; import button8 from './images/button8.png'; import 'react-bootstrap-range-slider/dist/react-bootstrap-range-slider.css'; import RangeSlider from 'react-bootstrap-range-slider'; function PostaProject(props){ const[state, setState] = useState({ counter:0, name:"", description:"", skills:"", projecttype:"", payment:"", budget:"", counter1:false, help:"" ,contestvalue:0, currency:"", urgent:"", contest:0}); console.log(props.login); return( <> {!props.login ? <Redirect to="/login"/> : ( <Card className="postcard"> <Card.Body> <Form className="form" onSubmit={(e)=>{ e.preventDefault(); axios.post('http://FreelancerLaravel.test/api/postaproject',{ name: state.name, description: state.description, skills: state.skills, projecttype: state.projecttype, payment: state.payment, budget: state.budget, contestvalue: state.contestvalue, contest: state.contest, help: state.help, }, { headers: { Authorization: "Bearer " + localStorage.getItem("token") } } ).then((response)=>{ alert("Your project has been posted"); setState({counter:0, name:"", description:""}); }).catch(()=>{ alert("Something went wrong"); }) }}> <Form.Group controlId="choosename"> <Form.Label> <h3> Choose a name for your project </h3> </Form.Label> <Form.Control type="text" placeholder="e.g. Build me a website" value={state.name} onChange={(e)=>{ setState({...state,name:e.target.value}) }}/> </Form.Group> <br/> <Form.Group controlId="Textarea"> <Form.Label> <h3> Tell us more about your project </h3> <br/> Start with a bit about yourself or your business, and include an overview of what you need done. </Form.Label> <Form.Control as="textarea" rows="5" placeholder="Describe your project here..." value={state.description} onChange={(e)=>{ setState({...state,description:e.target.value}) }}/> </Form.Group> <div className="dropzone"> <button type="button" className="btnnn" name="uploadbutton"> Upload Files</button> <p className="uploadbtn"> Drag and drop any images or documents that might be helpful in explaining your project brief here. </p> <input type="file" className="upload-input" /> </div> {state.counter===0 ? <Button variant="dark" disabled={!state.name || !state.description} onClick={()=>{ setState({...state, counter: state.counter + 1}) console.log(state.counter); }}> Next </Button> : null} {state.counter===1 ? ( <> <br/> <Form.Group controlId="Input1"> <Form.Label> <h3> What skills are required? </h3> <br/> Enter up to 5 skills that best describe your project. Freelancers will use these skills to find projects they are most interested and experienced in. </Form.Label> <Form.Control type="text" placeholder="What skills are required?" value={state.skills} onChange={(e)=>{ setState({...state,skills:e.target.value}) }}/> </Form.Group> <Button variant="dark" disabled={!state.skills} onClick={()=>{ setState({...state, counter: state.counter + 1}) console.log(state.counter); }}> Next </Button> </> ) : null} {state.counter===2 ? ( <> <br/> <Form.Group controlId="Input1"> <Form.Label> <h3> What skills are required? </h3> <br/> Enter up to 5 skills that best describe your project. Freelancers will use these skills to find projects they are most interested and experienced in. </Form.Label> <Form.Control type="text" placeholder="What skills are required?" value={state.skills} onChange={(e)=>{ setState({...state,skills:e.target.value}) }}/> </Form.Group> <br/> <Container> <Row> <h2> How would you like to get it done? </h2></Row> <Row> <Col sm={6}><a href="#" onClick={(e)=>{ e.preventDefault(); setState({...state, projecttype:"project"}) }}> <img className="image" className="image" src={button1}/> </a></Col> <Col sm={6}><a href="#" onClick={(e)=>{ e.preventDefault(); setState({...state, projecttype:"contest", counter1:false, payment:"", help:""}) }}> <img className="image" src={button2}/> </a></Col> </Row> </Container> </> ) : null} {state.projecttype==="project" ? <> <br/> <Container> <Row> <h2> How do you want to pay? </h2></Row> <Row> <Col sm={6}><a href="#" onClick={(e)=>{ e.preventDefault(); setState({...state, payment:"fixed"}) }}> <img className="image" src={button3}/> </a></Col> <Col sm={6}><a href="#" onClick={(e)=>{ e.preventDefault(); setState({...state, payment:"hourly"}) }}> <img className="image" src={button4}/> </a></Col> </Row> </Container> </>: null} <br/> {state.projecttype==="contest" ? <> <h2> What is your budget? </h2> <br/> <Card className="contest"> <Container> <Row sm={12}> {state.contestvalue <= 30 ? <Badge className="badge1"> <span>EXCELLENT RESULTS</span><br/> <span> Expect around 150 entries</span> </Badge> : <Badge className="badge2"> <span> BEST RESULTS </span> <br/> <span> Expect around 250 entries </span> </Badge> } </Row> <RangeSlider value={state.contestvalue} onChange={(e)=>{ setState({...state,contestvalue:e.target.value}) }} /> <Row className="hund"> <Col> 0 </Col> <Col className="hundred"> 100+ </Col> </Row> <Row> <Col sm={6}> <InputGroup className="mb-3"> <InputGroup.Prepend> <InputGroup.Text id="basic-addon1"> &euro; </InputGroup.Text> </InputGroup.Prepend> <FormControl value={state.contestvalue}/> </InputGroup> </Col> <Col sm={6}> <FormGroup> <Input type="select" name="select" id="currency" onChange={(e)=>{ setState({...state, currency: e.target.value}) }}> <option> Euro </option> <option> Dollar </option> <option> Pounds </option> <option> Australian Dollar </option> </Input> </FormGroup> </Col> </Row> </Container> </Card> <br/> <Container> <Row> <h2> Is your contest urgent? </h2></Row> <Row> <Col sm={6}><a href="#" onClick={(e)=>{ e.preventDefault(); setState({...state, urgent:1}) }}> <img className="image" src={button7}/> </a></Col> <Col sm={6}><a href="#" onClick={(e)=>{ e.preventDefault(); setState({...state, urgent:2}) }}> <img className="image" src={button8}/> </a></Col> </Row> </Container> <br/> <Container> <Row> <h2> How long would you like to run your contest? </h2> </Row> <Row> <InputGroup size="sm" className="mb-3"> <InputGroup.Prepend> <InputGroup.Text id="inputGroup-sizing-sm"> Days </InputGroup.Text> </InputGroup.Prepend> <FormControl type="number" aria-label="Small" aria-describedby="inputGroup-sizing-sm" value={state.contest} onChange={(e)=>{ setState({...state,contest:e.target.value}) }}/> </InputGroup> </Row> </Container> <Button variant="primary" type ="submit" onClick={()=>{ console.log(state); }}> Post my project </Button> </> : null} {state.payment==="fixed" || state.payment==="hourly" ? <> <br/> <h2> What is your estimated budget? </h2> <InputGroup size="sm" className="mb-3"> <InputGroup.Prepend> <InputGroup.Text id="inputGroup-sizing-sm"> CAD </InputGroup.Text> </InputGroup.Prepend> <FormControl type="number" aria-label="Small" aria-describedby="inputGroup-sizing-sm" value={state.budget} onChange={(e)=>{ setState({...state,budget:e.target.value, counter1:true}) }}/> </InputGroup> </> : null} {state.counter1 ? <> <br/> <Container> <Row> <h2> Do you need a helping hand? </h2></Row> <Row> <Col sm={6}><a href="#" onClick={(e)=>{ e.preventDefault(); setState({...state, help:"self"}) }}> <img className="image" src={button5}/> </a></Col> <Col sm={6}><a href="#" onClick={(e)=>{ e.preventDefault(); setState({...state, help:"recruiter"}) }}> <img className="image" src={button6}/> </a></Col> </Row> </Container> </> : null } {state.help ? <> <br/> <Button variant="primary" type ="submit" onClick={()=>{ console.log(state); }}> Post my project </Button> </> : null} </Form> </Card.Body> </Card> )} </> ); } export default PostaProject;
import React, {useEffect, useState} from 'react'; import {CircularProgress, makeStyles} from "@material-ui/core"; import Paper from "@material-ui/core/Paper"; import useInput from "../../hooks/useInput"; import Input from "../Common/Form/Input"; import FileInput from "../Common/Form/FileInput"; import useFileInput from "../../hooks/useFileInput"; import Button from "@material-ui/core/Button"; import FilesUpload from "./FilesUpload"; import useFileList from "./hooks/useFileList"; import FileList from "./FileList"; import Preloader from "../Common/Preloader"; import Icon from "@material-ui/core/Icon"; const useStyles = makeStyles({ root: { width: '80%', margin: '0 auto', padding: 20 }, loading: { display: 'flex', justifyContent: 'center', alignItems: 'center', height: '80vh' }, nothing: { display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', height: '80vh', '& h4, & span': { color: "#707070", margin: 10 }, '& p': { color: "#9a9a9a" } } }) const Files = () => { const classes = useStyles(); const data = useFileList(); return ( <Paper className={classes.root}> <FilesUpload/> {data.data.length > 0 && <FileList {...data}/>} {data.loading && <div className={classes.loading}> <CircularProgress/> </div>} {data.data.length === 0 && !data.loading && ( <div className={classes.nothing}> <Icon fontSize="large">insert_drive_file</Icon> <h4>No data to display</h4> <p>You can upload your files in the bottom input</p> </div> )} </Paper> ) }; export default Files;
'use strict'; import { UnknownValueError } from 'Error.js'; import { formatNumber, CALC_DISPLAY_ERROR, CalcDisplay, } from './display/CalcDisplay.js'; /** * @readonly * @enum {number} */ const CalcState = { NUM1: 0, // 123 OPER: 1, // 123 + NUM2: 2, // 123 + 456 EQ: 3, // 123 + 456 = ERR: 4 // error }; /** * @readonly * @enum {number} */ const CalcOpCode = { NOP: -1, ADD: 0, SUB: 1, MUL: 2, DIV: 3 }; /** * @typedef {function(string): void} CalcExprDisplayChangedCallback */ export class CalcModel { constructor() { /** * @private * @type {CalcDisplay} */ this.display_ = new CalcDisplay(); /** * @private * @type {CalcExprDisplayChangedCallback} */ this.onExprDisplayChanged_ = undefined; this.allClear(true); } /** * @param {boolean} ctor */ allClear(ctor = false) { /** * @private * @type {CalcState} */ this.state_ = CalcState.NUM1; /** * @private * @type {number} */ this.op1_ = NaN; /** * @private * @type {number} */ this.op2_ = NaN; /** * @private * @type {number} */ this.res_ = NaN; /** * @private * @type {CalcOpCode} */ this.opCode_ = CalcOpCode.NOP; if (!ctor) { this.display_.clear(); this.exprDisplayHasChanged(); } } /** * @param {CalcModel} obj */ copyFrom(obj) { this.display_.copyFrom(obj.display_); this.onExprDisplayChanged_ = obj.onExprDisplayChanged_; this.state_ = obj.state_; this.op1_ = obj.op1_; this.op2_ = obj.op2_; this.res_ = obj.res_; this.opCode_ = obj.opCode_; this.exprDisplayHasChanged(); } /** * @param {number} digit * @returns {CalcModel} * @throws {UnknownValueError} */ dig(digit) { switch (this.state_) { case CalcState.NUM1: case CalcState.NUM2: this.display_.dig(digit); break; case CalcState.OPER: this.display_.clear(); this.display_.dig(digit); this.setState(CalcState.NUM2); break; case CalcState.EQ: this.display_.clear(); this.display_.dig(digit); this.setState(CalcState.NUM1); break; case CalcState.ERR: break; // do nothing default: throw new UnknownValueError('state_', this.state_); } return this; } /** * @returns {CalcModel} * @throws {UnknownValueError} */ sign() { switch (this.state_) { case CalcState.NUM1: case CalcState.NUM2: this.display_.sign(); break; case CalcState.OPER: this.display_.value = -this.op1_; this.setState(CalcState.NUM2); break; case CalcState.EQ: this.display_.sign(); this.setState(CalcState.NUM1); break; case CalcState.ERR: break; // do nothing default: throw new UnknownValueError('state_', this.state_); } return this; } /** * @returns {CalcModel} */ add() { return this.oper(CalcOpCode.ADD); } /** * @returns {CalcModel} */ sub() { return this.oper(CalcOpCode.SUB); } /** * @returns {CalcModel} */ mul() { return this.oper(CalcOpCode.MUL); } /** * @returns {CalcModel} */ div() { return this.oper(CalcOpCode.DIV); } /** * @private * @param {CalcOpCode} opCode * @returns {CalcModel} * @throws {UnknownValueError} */ oper(opCode) { switch (this.state_) { case CalcState.NUM1: this.op1_ = this.display_.value; this.opCode_ = opCode; this.setState(CalcState.OPER); break; case CalcState.OPER: this.opCode_ = opCode; this.exprDisplayHasChanged(); break; case CalcState.NUM2: this.op2_ = this.display_.value; this.calculateResult(CalcState.OPER); this.op1_ = this.res_; this.opCode_ = opCode; this.exprDisplayHasChanged(); break; case CalcState.EQ: this.op1_ = this.res_; this.opCode_ = opCode; this.setState(CalcState.OPER); break; case CalcState.ERR: break; // do nothing default: throw new UnknownValueError('state_', this.state_); } return this; } /** * @returns {CalcModel} * @throws {UnknownValueError} */ eq() { switch (this.state_) { case CalcState.NUM2: this.op2_ = this.display_.value; this.calculateResult(CalcState.EQ); break; case CalcState.EQ: this.op1_ = this.res_; this.calculateResult(CalcState.EQ); break; case CalcState.OPER: this.op2_ = this.op1_; this.calculateResult(CalcState.EQ); case CalcState.NUM1: case CalcState.ERR: break; // do nothing default: throw new UnknownValueError('state_', this.state_); } return this; } /** * @returns {CalcModel} * @throws {UnknownValueError} */ dot() { switch (this.state_) { case CalcState.NUM1: case CalcState.NUM2: this.display_.dot(); break; case CalcState.OPER: this.display_.clear(); this.display_.dot(); this.setState(CalcState.NUM2); break; case CalcState.EQ: this.display_.clear(); this.display_.dot(); this.setState(CalcState.NUM1); case CalcState.ERR: break; // do nothing default: throw new UnknownValueError('state_', this.state_); } return this; } /** * @returns {CalcModel} * @throws {UnknownValueError} */ percent() { switch (this.state_) { case CalcState.NUM2: switch (this.opCode_) { case CalcOpCode.ADD: case CalcOpCode.SUB: this.display_.value = this.op1_ * this.display_.value / 100; break; case CalcOpCode.MUL: case CalcOpCode.DIV: this.display_.value /= 100; break; default: throw new UnknownValueError('opCode_', this.opCode_); } break; case CalcState.NUM1: case CalcState.OPER: case CalcState.EQ: case CalcState.ERR: break; // do nothing default: throw new UnknownValueError('state_', this.state_); } return this; } /** * @private * @param {CalcState} newState * @throws {UnknownValueError} */ calculateResult(newState) { switch (this.opCode_) { case CalcOpCode.ADD: this.res_ = this.op1_ + this.op2_; break; case CalcOpCode.SUB: this.res_ = this.op1_ - this.op2_; break; case CalcOpCode.MUL: this.res_ = this.op1_ * this.op2_; break; case CalcOpCode.DIV: this.res_ = this.op1_ / this.op2_; break; default: throw new UnknownValueError('opCode_', this.opCode_); } this.display_.value = this.res_; this.setState(Number.isFinite(this.res_) ? newState : CalcState.ERR); } /** * @private * @param {CalcState} value */ setState(value) { this.state_ = value; this.exprDisplayHasChanged(); } /** * @returns {import('./display/CalcDisplay.js').CalcDisplayChangedCallback} */ get onDisplayChanged() { return this.display_.onDisplayChanged; } /** * @param {import('./display/CalcDisplay.js').CalcDisplayChangedCallback} value */ set onDisplayChanged(value) { this.display_.onDisplayChanged = value; } /** * @returns {CalcExprDisplayChangedCallback} */ get onExprDisplayChanged() { return this.onExprDisplayChanged_; } /** * @param {CalcExprDisplayChangedCallback} value */ set onExprDisplayChanged(value) { this.onExprDisplayChanged_ = value; } /** * @private */ exprDisplayHasChanged() { /** * @param {CalcOpCode} opCode */ function opCode2str(opCode) { switch (opCode) { case CalcOpCode.ADD: return '+'; case CalcOpCode.SUB: return '-'; case CalcOpCode.MUL: return '×'; case CalcOpCode.DIV: return '÷'; default: throw new UnknownValueError('opCode', opCode); } }; if (this.onExprDisplayChanged_) { /** @type {string[]} */ let expr = []; switch (this.state_) { case CalcState.NUM1: break; // do nothing case CalcState.OPER: case CalcState.NUM2: expr = [formatNumber(this.op1_), opCode2str(this.opCode_)]; break; case CalcState.EQ: expr = [formatNumber(this.op1_), opCode2str(this.opCode_), formatNumber(this.op2_), '=']; break; case CalcState.ERR: expr = [CALC_DISPLAY_ERROR]; break; default: throw new UnknownValueError('state_', this.state_); } this.onExprDisplayChanged_(expr.join(' ')); } } }
import React, { Fragment } from "react"; import styled from "styled-components"; const ViewTag = props => { const { url, name } = props[0]; return ( <Fragment> <StyledViewTag> <img src={url} alt={name} /> <div>{name}</div> </StyledViewTag> </Fragment> ); }; const StyledViewTag = styled.div` display: flex; align-items: center; justify-content: center; img { width: 20px; height: 20px; margin-right: 10px; } div { font-size: 18px; vertical-align: super; font-family: "book"; margin-top: 3px; } `; export default ViewTag;
var CONSTANTS = require('../constants/constants'); var Session = function ( PostGre ) { this.register = function ( req, res, options) { if(req.session && options && req.session.userId === options.userId){ return res.status( 200 ).send( { success: CONSTANTS.LOG_IN, cid: options.id } ); } req.session.loggedIn = true; req.session.userId = options.userId; req.session.login = options.email; res.status( 200 ).send( { success: CONSTANTS.LOG_IN, cid: options.id } ); }; this.kill = function ( req, res, next ) { if(req.session) { req.session.destroy(); } res.status(200).send({ success: CONSTANTS.LOG_OUT }); }; this.authenticatedUser = function ( req, res, next ) { if( req.session && req.session.userId && req.session.loggedIn ) { next(); } else { var err = new Error(CONSTANTS.UNATHORIZED); err.status = 401; next(err); } }; this.authenticatedSuperAdmin = function ( req, res, next ) { if( req.session && req.session.userId && req.session.loggedIn && (req.session.role === 'superAdmin') ) { next(); } else { var err = new Error(CONSTANTS.UNATHORIZED); err.status = 401; next(err); } }; }; module.exports = Session;
//returns the test score function scoreTest(str, right, omit, wrong){ for(var i = 0, sum = 0; i < str.length; i++) { switch(str[i]) { case 0: sum += right; break; case 1: sum += omit; break; case 2: sum -= wrong; break; } } return sum; }
const { exec } = require('child_process'); exec('openssl genrsa -out ./certs/privatekey.pem 2048 && openssl req -new -key ./certs/privatekey.pem -out ./certs/certrequest.csr -subj "/C=NL/ST=All/L=Amsterdam/O=openstad/CN=www.openstad.org" && openssl x509 -req -in ./certs/certrequest.csr -signkey ./certs/privatekey.pem -days 3650 -out ./certs/certificate.pem;', (err, stdout, stderr) => { if (err) { //some err occurred console.error(err) } else { // the *entire* stdout and stderr (buffered) console.log(`stdout: ${stdout}`); console.log(`stderr: ${stderr}`); } });
import React, { useState, useRef, useEffect } from "react"; import { Form, Button, Container, Row, Col, Toast, Spinner, ProgressBar, } from "react-bootstrap"; import { BsBoxArrowInUp, BsArrowLeftShort } from "react-icons/bs"; import { FaTimes, FaCheck } from "react-icons/fa"; import { Link, useHistory } from "react-router-dom"; import { useAuth } from "../contexts/AuthContext"; import { useFirestoreBeforeLogin } from "../contexts/FirestoreBeforeLoginContext"; import firebase from "firebase/app"; import "firebase/storage"; export default function EditProfile() { const { updateEmail, updatePassword, updateProfile, sendEmailVerification, currentUser, } = useAuth(); const { updateUser } = useFirestoreBeforeLogin(); const [loading, setLoading] = useState(false); const [success, setSuccess] = useState(false); const [error, setError] = useState(false); const [lengthError, setLengthError] = useState(false); const [matchingError, setMatchingError] = useState(false); const [errorText, setErrorText] = useState(""); const [uploadLoading, setUploadLoading] = useState(false); const [progress, setProgress] = useState(0); const prevEmail = currentUser.email; const history = useHistory(); const fileRef = useRef(); const nameRef = useRef(); const emailRef = useRef(); const passRef = useRef(); const confPassRef = useRef(); function handleSubmit(e) { e.preventDefault(); setError(false); setLengthError(false); setMatchingError(false); setSuccess(false); setUploadLoading(false); //initial checks for password requirements if (passRef.current.value !== "" && passRef.current.value.length < 6) { setLengthError(true); passRef.current.focus(); return; } if (passRef.current.value !== confPassRef.current.value) { setMatchingError(true); passRef.current.focus(); return; } let promises = []; //first uploadImage as a promise if a file is selected. if (fileRef.current.files.length > 0) { setLoading(true); promises.push( new Promise((resolve, reject) => uploadImage( fileRef.current.files[0], currentUser.uid, resolve, reject ) ) ); } //if promise has items (in our case if uploadImage called) if (promises.length > 0) //wait uploadImage to execute Promise.all(promises).then((values) => { promises = []; //store imageurl const resolveURL = values[0]; //check for changes in displayName, if so update if ( nameRef.current.value !== currentUser.displayName || fileRef.current.files.length > 0 ) { promises.push( updateProfile(currentUser, { name: nameRef.current.value, url: resolveURL, }) ); promises.push( updateUser({ uid: currentUser.uid, displayName: nameRef.current.value, photoURL: resolveURL, }) ); } //check for changes in email, is so update if (emailRef.current.value !== currentUser.email) { promises.push(updateEmail(emailRef.current.value)); } //check for changes in password, if so update if (passRef.current.value !== "") promises.push(updatePassword(passRef.current.value)); //wait all these functions to execute Promise.all(promises) .then(() => { //if email changed send verification mail to new mail address if (prevEmail !== currentUser.email) { sendEmailVerification(currentUser); } setSuccess(true); setTimeout(() => { setLoading(false); }, 3000); }) .catch((error) => { setError(true); setErrorText(error.message); }); }); //if uploadImage didnt called do the same checks for the other account info,and execute functions else { if (nameRef.current.value !== currentUser.displayName) { promises.push( updateProfile(currentUser, { name: nameRef.current.value, }) ); promises.push( updateUser({ uid: currentUser.uid, displayName: nameRef.current.value, photoURL: currentUser.photoURL, }) ); } if (emailRef.current.value !== currentUser.email) { promises.push(updateEmail(emailRef.current.value)); } if (passRef.current.value !== "") promises.push(updatePassword(passRef.current.value)); if (promises.length > 0) { setLoading(true); Promise.all(promises) .then(() => { if (prevEmail !== currentUser.email) sendEmailVerification(currentUser); setSuccess(true); setTimeout(() => { setLoading(false); }, 3000); }) .catch((error) => { setError(true); setErrorText(error.message); }); } } } function handleChange() { const fr = new FileReader(); fr.onload = function () { document.querySelector(".profImage").src = fr.result; }; fr.readAsDataURL(fileRef.current.files[0]); } function uploadImage(file, uid, resolve, reject) { var storageRef = firebase.storage().ref(); const metadata = { contentType: file.type, }; const uploadTask = storageRef .child(`flashsend/${uid}/profilePic/${file.name}`) .put(file, metadata); setUploadLoading(true); uploadTask.on( "state_changed", function (snapshot) { // Observe state change events such as progress, pause, and resume // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; setProgress(progress); console.log("Upload is " + progress + "% done"); }, function (error) { reject(); // Handle unsuccessful uploads }, function () { // Handle successful uploads on complete // For instance, get the download URL: https://firebasestorage.googleapis.com/... uploadTask.snapshot.ref.getDownloadURL().then(function (downloadURL) { console.log("File available at", downloadURL); setUploadLoading(false); resolve(downloadURL); }); } ); } return ( <div className="editProfileContainer min-vh-100 d-flex align-items-center justify-content-center flex-column"> <Link to="/"> <BsArrowLeftShort style={{ position: "absolute", fontSize: "3em", top: "5%", left: "5%", color: "white", }} /> </Link> <header style={{ fontSize: "3rem", color: "white", textShadow: "2px 2px 2px red", }} > Profile </header> <Container className="d-flex justify-content-center p-4"> <Form onSubmit={handleSubmit}> <Row className="w-100 mx-0"> <Col md={12} className="d-flex justify-content-center mb-4"> <Form.Group className="col-5 d-flex justify-content-center" style={{ position: "relative", overflow: "initial" }} > <Form.Label style={{ cursor: "pointer", position: "relative", overflow: "initial", }} > <img className="profImage" style={{ width: "150px", height: "150px", borderRadius: "50%", }} src={ currentUser.photoURL ? currentUser.photoURL : "https://firebasestorage.googleapis.com/v0/b/flashsend-ece71.appspot.com/o/blank-profile-picture-973460_640.png?alt=media&token=aaa87789-49e5-477d-897a-ab83ce57ccc7" } /> <div className="profilePhotoOverlay" style={{ display: "none" }} > <BsBoxArrowInUp style={{ fontSize: "3em", position: "absolute", left: "0", right: "0", top: "0", bottom: "0", margin: "auto", }} /> </div> <Form.Control onChange={handleChange} ref={fileRef} type="file" style={{ opacity: "0", position: "absolute", zIndex: "-1" }} ></Form.Control> </Form.Label> </Form.Group> </Col> <Col md={6}> <Form.Group> <Form.Label>Full Name</Form.Label> <Form.Control ref={nameRef} type="text" defaultValue={currentUser.displayName} ></Form.Control> </Form.Group> </Col> <Col md={6}> <Form.Group> <Form.Label>Email</Form.Label> <Form.Control ref={emailRef} type="text" defaultValue={currentUser.email} ></Form.Control> </Form.Group> </Col> <Col md={6}> <Form.Group> <Form.Label>Password</Form.Label> <Form.Control ref={passRef} type="password"></Form.Control> </Form.Group> </Col> <Col md={6}> <Form.Group> <Form.Label>Confirm Password</Form.Label> <Form.Control ref={confPassRef} type="password"></Form.Control> </Form.Group> </Col> <Col md={12}> <Form.Text className="text-light"> <em> Fill password field, only if you want to change your password. Else leave it blank. </em> </Form.Text> </Col> <Col md={12} className="mt-3"> <Button type="submit" className="bg-light text-dark font-weight-bold mt-4 mb-2" style={{ borderRadius: "0", boxShadow: "4px 4px 2px red", fontSize: "1.2rem", }} > Update </Button> {/* display toast if password contains less than 6 characters */} {lengthError && ( <Toast className="mx-auto mt-4"> <Toast.Body className="bg-danger text-light"> <strong>Password should be at least 6 characters</strong> </Toast.Body> </Toast> )} {/* display toast if passwords doesnt match */} {matchingError && ( <Toast className="mx-auto mt-4"> <Toast.Body className="bg-danger text-light"> <strong>Passwords do not match</strong> </Toast.Body> </Toast> )} </Col> </Row> </Form> </Container> {/* display overlay with toasts when user creating account */} {loading && ( <div className="min-vh-100 w-100 d-flex align-items-center justify-content-center position-absolute" style={{ backgroundColor: "rgba(0,0,0,0.8)", zIndex: "999" }} > {/* display spinner as long as waiting for firebase response */} {!success && !error && !uploadLoading && ( <Spinner animation="border" role="status" variant="danger"> <span className="sr-only">Loading...</span> </Spinner> )} {/* display this toast if image is uploading \\*/} {uploadLoading && ( <Toast style={{ maxWidth: "800px", minWidth: "350px" }} onClose={() => { setLoading(false); }} > <Toast.Header className="d-flex justify-content-end"></Toast.Header> <Toast.Body className="d-flex flex-column"> <strong className="my-3">Uploading Profile Image...</strong> <ProgressBar animated variant="danger" now={progress} /> </Toast.Body> </Toast> )} {/* display this toast if response is success */} {success && ( <Toast style={{ maxWidth: "800px", minWidth: "350px" }} onClose={() => { setLoading(false); }} > <Toast.Header className="d-flex justify-content-end"></Toast.Header> <Toast.Body className="d-flex flex-column justify-content-center align-items-center"> <FaCheck style={{ color: "green", fontSize: "2rem", marginBottom: "20px", }} /> <strong>You profile information updated successfully</strong> </Toast.Body> </Toast> )} {/* display this toast if request fails */} {error && ( <Toast style={{ maxWidth: "800px", minWidth: "350px" }} onClose={() => setLoading(false)} > <Toast.Header className="d-flex justify-content-end"></Toast.Header> <Toast.Body className="d-flex flex-column justify-content-center align-items-center"> <FaTimes style={{ color: "red", fontSize: "2rem", marginBottom: "20px", }} /> <strong>{errorText}</strong> </Toast.Body> </Toast> )} </div> )} </div> ); }
let Models = require("../models"); var http_status = require('http-status-codes'); let sequelizeErrorHandler=require("../helpers/sequelizeErrorHandler").handleErrors; module.exports.controllers = { getAll: async (request, response) => { try { let all_amenities = await Models.Amenity.findAll({ attributes: ['id', 'type'] }); if (all_amenities.length > 0) { return response.status(http_status.OK).send(all_amenities); } else { return response.status(http_status.NOT_FOUND).send(); } } catch (error) { console.log(error); let sql_error = sequelizeErrorHandler(error) if (sql_error) { return res.status(sql_error.status).send({ error: sql_error.message }) } return response.status(http_status.INTERNAL_SERVER_ERROR).send({ error: http_status.getStatusText(http_status.INTERNAL_SERVER_ERROR) }) } } }
'use strict'; define(['app'], function (app) { var branchController = function ($rootScope, $scope, $log, $timeout, $route,$routeParams, _, messageService, dashboardService, constantService, navigationService, localStorageService, configurationService,branchService) { var userInfo, promis; $scope.saveBranch=function(branch){ userInfo = localStorageService.getValue(constantService.userInfoCookieStoreKey); $scope.branchObj = branch; $scope.branchObj.loginBean = userInfo; $scope.branchObj.operation = constantService.Save; promis = branchService.postObject($scope.branchObj); promis.then(function(data) { if (!data.success) { messageService.showMessage(constantService.Danger,data.message); return; } messageService.showMessage(constantService.Success,data.message); $scope.branch= {}; }); }; var getBranchByID = function() { userInfo = localStorageService.getValue(constantService.userInfoCookieStoreKey); var Obj = { operation : constantService.GetByOId, loginBean : userInfo }; Obj.oid = $routeParams.oid; promis =branchService.postObject(Obj); debugger; promis.then(function(data) { if (!data.success) { messageService.showMessage(constantService.Danger, 'Unable to load branch'); return; } $scope.branch = data.data; }); }; var init = function () { if ($routeParams.oid == undefined || $routeParams.oid == null || $routeParams.oid.length == 0) { return; } getBranchByID(); }; init(); }; app.register.controller('branchController', ['$rootScope', '$scope', '$log', '$timeout', '$route','$routeParams', '_', 'messageService', 'dashboardService', 'constantService', 'navigationService', 'localStorageService','configurationService','branchService', branchController]); });
// share buttons link properly function shareLink(sPermaUrl) { var addthis_share = { url: sPermaUrl }; } // overlay/modals function popupModal(divId) { $("#" + divId).show(); $(".page-overlay").show(); } function hideModal() { $(".popup-container").hide(); $(".page-overlay").hide(); $(".watermark").hide(); } function verifiedExampleModal() { popupModal("divVerifiedExample"); drawGraph("divTimelineEx", "timelineTooltipEx", "lblDurationEx", false, true); $(".watermark").show(); } function noUrlModal() { popupModal("divNoUrl"); } function decodedSignatureModal() { popupModal("divDecodedSignature"); var dateContainer = $("#spDateSignatureContainer"); if (dateContainer.hasClass("hidden")) { var txtSignature = $(".decoded-signature"); var spinner = drawSpinner("divDecodeSpinner"); $.ajax({ type: "POST", url: "Status.aspx/DecompressString", data: '{compressedText:"' + txtSignature.text() + '"}', contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { var txtDecompressed = data.d; var date = new Date(txtDecompressed.substr(txtDecompressed.indexOf("Date") + 6, 29)); $("#spDateSignature").text(isNaN(date.getTime()) ? "Unavailable" : formatDate(date)); setTimeout(function () { txtSignature.text(txtDecompressed); dateContainer.removeClass("hidden"); spinner.stop(); $("#divDecodeSpinnerContainer").hide(); }, 2000); }, error: function (e) { console.log(e); spinner.stop(); $("#divDecodeSpinnerContainer").hide(); } }); } function formatDate(date) { return padNum(date.getMonth() + 1) + "/" + padNum(date.getDate()) + "/" + padNum(date.getFullYear()) + " " + padNum(date.getHours()) + ":" + padNum(date.getMinutes()) + ":" + padNum(date.getSeconds()); function padNum(n) { return (n < 10) ? ("0" + n) : n; } } } // language select box flag image support function languageSelectBox() { var options = $(".language-selector option"); for (var i = 0; i < options.length; i++) { $(options[i]).attr("data-image", "https://az25533.vo.msecnd.net/assets/flags/" + options[i].value + ".gif"); } $(".language-selector").msDropDown(); } // help tooltip function setupHelpTooltip() { var certTt = $(".certificate-tooltip"); for (var i = 0; i < certTt.length; i++) { var certHelp = $(certTt[i]); if (certHelp.hasClass("help")) { // help icons if (certHelp.hasClass("help")) { var certTooltip = certHelp.children("span"); certTooltip.css("left", (certHelp.position().left - (certTooltip.width() / 2)) + "px"); } } else { // certificate buttons var certBtn = $(certTt[i]).find(".certificate-button"); if (certBtn.length > 0) { var certTooltip = certBtn.next("span"); certTooltip.css("left", (certBtn.position().left - (certTooltip.width() / 2) + certBtn.width()) + "px"); } } } } // draw spinner function drawSpinner(spinnerId) { var opts = { lines: 6, length: 0, width: 10, radius: 8, scale: 0.6, corners: 1, color: "#000", opacity: 0.3, rotate: 30, trail: 54, fps: 20, className: "spinner", top: "auto", left: "auto" }; var spinner = new Spinner(opts).spin($("#" + spinnerId)[0]); return spinner; } // zoom hover over certificate signature function signatureZoom() { $(".magnify").mousemove(function (e) { var magnify_offset = $(this).offset(), mx = e.pageX - magnify_offset.left, my = e.pageY - magnify_offset.top; // fade out the magnifying glass if the mouse is outside the container if (mx < $(this).width() && my < $(this).height() && mx > 0 && my > 0) { $(".mag-glass").fadeIn(100); $(".sig-large").fadeIn(100); } else { $(".mag-glass").fadeOut(100); $(".sig-large").fadeOut(100); } if ($(".mag-glass").is(":visible")) { // background position of .large changes based on mouse position var rx = Math.round(mx - $(".mag-glass").width() / 2) * -1, ry = Math.round(my - $(".mag-glass").height() / 2) * -1; var bgpx = (rx * 3 - 70) + "px", bgpy = (ry - 5) + "px"; // move magnifying glass and larger background zoom div with the mouse var px = mx - $(".mag-glass").width() / 2, py = my - $(".mag-glass").height() / 2; $(".mag-glass").css({ left: px, top: py }); $(".sig-large").css({ left: bgpx, top: bgpy }); } }); } // tiny url api call function getTinyUrl(sPermaUrl) { var url = encodeURI(sPermaUrl); $.getJSON('https://api-ssl.bitly.com/v3/shorten?callback=?', { format: "json", apiKey: "R_284bfd72f13149d7a18cd10c37b7eb46", login: "netromedia", longUrl: url }, function (response) { var tinyUrl = response.data.url; if (tinyUrl != undefined) { $("#lnkTinyUrl").attr("href", tinyUrl); $("#txtTinyUrl").val(tinyUrl); } } ); } // get registered badges function getBadgesList(gAccountId) { var spinnerContainer = $("#divBadgesSpinnerContainer"); var spinner = null; if (!spinnerContainer.hasClass("hidden")) { spinner = drawSpinner("divBadgesSpinner"); // ajax call get registered badges if ($("#dlstBadges").is(":empty")) { $.ajax({ type: "GET", url: "../rest/GetRegisteredBadges", data: "AccountID=" + gAccountId, dataType: "xml", success: function (data) { var xml = $(data).children()[0]; populateBadgesList($(xml).html()); }, error: function (e) { console.log(e); spinner.stop(); } }); } } // badges callback function function populateBadgesList(allBadges) { var containerHtml = ""; var lastLoop = false; allBadges = allBadges.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); // each badge entry starts with <a> tag while (!lastLoop) { var ind = allBadges.indexOf('<a '); var nextInd = allBadges.indexOf('<a ', ind + 1); if (nextInd == -1) { nextInd = allBadges.length; lastLoop = true; } var badge = allBadges.substring(ind, nextInd); allBadges = allBadges.substring(nextInd); var imgUrl = badge.substring(badge.indexOf('//images')); imgUrl = imgUrl.substring(0, imgUrl.indexOf('"')); containerHtml += '<div class="modal-badges">' + badge + '<br/><br/>' + '<strong>Copy this embed code:</strong>' + '<p>' + '<textarea class="embedTextbox" id="txtEmbed" rows="3" cols="50" onclick="this.focus();this.select()">' + badge + '</textarea>' + '<strong><a href="' + imgUrl + '" rel="<%=sStatusLink %>" class="addToBlogger">Add this Badge to Blogger</a></strong><br />' + '<span style="padding-left:5px;"><img src="https://az25533.vo.msecnd.net/assets/images/facebook.gif" /> <a href="#" class="shareFBLink">Share on Facebook</a></span>' + '</p>' + '</div>'; } spinnerContainer.addClass("hidden"); spinner.stop(); $("#dlstBadges").html(containerHtml); } } // protection date timeline function dateTimeline(isVerified) { // cancel graph render on rescan reload if ($("#ctl00_cntBody_btnRescan").hasClass("grey")) return; var spinner = drawSpinner("divSpinner"); setTimeout(function () { // show protection info if ($("#ctl00_cntBody_spProtectionPendingDays").text() == "") { $("#spDuration").show(); } if (!$(".protection-info").hasClass("unavail")) { $(".timeline-lock").show(); $(".button-recheck").show(); } $("#spProtectionStatus").removeClass("hidden"); $("#spProtectionStatusHelp").css("visibility", "visible"); $("#spProtectionStatusTmp").addClass("hidden"); // remove loading spinner spinner.stop(); $("#divSpinnerContainer").hide(); // draw graph $("#divTimeline").show(); drawGraph("divTimeline", "timelineTooltip", "lblDuration", isVerified, false); }, 2000); } function drawGraph(divId, tooltipId, durationId, isVerified, isUpgradeExample) { var canvas = $("#" + divId), w = canvas.width(), h = canvas.height(); //red, red-orange, orange, yellow, green var colors = ["#dd340d", "#da6f22", "#daa42d", "#c5b138", "#7eca26"]; // if canvas is visible if (!canvas.hasClass("hidden")) { canvas.empty(); var svg = d3.select("#" + divId).append("svg") .attr("width", w) .attr("height", h); var recentDate = new Date($("#ctl00_cntBody_lblLastChecked").text()), startDate = new Date($("#ctl00_cntBody_lblStarted").text()); // unavailable/unauthorized (no dates) if (!recentDate.getTime() || !startDate.getTime()) { $("#" + divId).addClass("hidden"); return; } var protectionDate = new Date(startDate), today = new Date(Date.now()); if (isVerified || isUpgradeExample) { protectionDate.setDate(protectionDate.getDate() + 1); // 24 hr pending period } else { protectionDate.setDate(protectionDate.getDate() + 30); // 30 day pending period } today.setHours(0, 0, 0, 0); // setup d3 variables var isPending = (today < protectionDate), pendingDays = (isPending) ? Math.floor((protectionDate - today) / (1000 * 60 * 60 * 24)) : 0; var futureHatchPx = 30; var data = [recentDate, startDate, protectionDate, today]; var x = d3.time.scale().range([1, w - (isPending ? futureHatchPx + 1 : 1)]); x.domain(d3.extent(data)); var xStart = x(startDate), xProtection = x(protectionDate), xToday = x(today); var xProtectedBorder = (xToday - xStart) * 0.7; var tooltipText = [$("#spnLastChecked").text(), "Date of First Scan:", $("#spnStarted").text(), "Current Date:"], tooltip = $("#" + tooltipId), ttWidthHalf = 112; var fmt = d3.time.format("%x"); // duration days count loop var duration = 2500; var lblTimer = $("#" + durationId), totalDays = Math.floor((today - protectionDate) / (1000 * 60 * 60 * 24)), day = 0; lblTimer.text(0); // diagonal hatch defs svg.append("defs").append("pattern") .attr("id", "diagonalHatchPending" + (isUpgradeExample ? "Ex" : "")) .attr("patternUnits", "userSpaceOnUse") .attr("width", 4) .attr("height", 4) .append("path") .attr("d", "M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2"); svg.append("defs").append("pattern") .attr("id", "diagonalHatchProtected" + (isUpgradeExample ? "Ex" : "")) .attr("patternUnits", "userSpaceOnUse") .attr("width", 4) .attr("height", 4) .append("path") .attr("d", "M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2"); // hatch rects svg.append("rect") .attr("x", xStart) .attr("y", 10) .attr("width", isPending ? xProtection - xStart : xProtectedBorder - xStart) .attr("height", 20) .attr("fill", "url(#diagonalHatchPending" + (isUpgradeExample ? "Ex" : "") + ")") .on("mouseover", onMouseoverPending) .on("mouseout", hideTooltip); svg.append("rect") .attr("x", isPending ? xProtection : xProtectedBorder) .attr("y", 10) .attr("width", isPending ? futureHatchPx : xToday - xProtectedBorder) .attr("height", 20) .attr("fill", "url(#diagonalHatchProtected" + (isUpgradeExample ? "Ex" : "") + ")") .on("mouseover", onMouseoverProtected) .on("mouseout", hideTooltip); $(".timeline-lock").on("mouseover", onMouseoverProtected).on("mouseout", hideTooltip); if (isPending) { // still in protection pending zone var percentToProtected = (xToday - xStart) / (xProtection - xStart), shortDuration = percentToProtected * duration; var rect = svg.append("rect") .attr("class", "rect") .attr("x", xStart) .attr("y", 10) .attr("width", 0) .attr("height", 20) .style("fill", colors[0]) .on("mouseover", function () { if (!isVerified && !isUpgradeExample) { onMouseoverElapsed(); } }) .on("mouseout", hideTooltip); // status pending transitions if (percentToProtected < .5) { var endColor = (percentToProtected < .25) ? colors[0] : colors[1]; rect.transition() .duration(shortDuration) .ease("linear") .style("fill", endColor) .attr("width", xToday - xStart); } else { var endColor = (percentToProtected < .75) ? colors[2] : colors[3]; rect.transition() .duration(shortDuration * (3 / 4)) .ease("linear") .style("fill", colors[2]) .attr("width", (xToday * (3 / 4)) - xStart) .transition() .duration(shortDuration * (1 / 4)) .ease("linear") .style("fill", endColor) .attr("width", xToday - xStart); } // text days for pending if (!isVerified && !isUpgradeExample) { svg.append("text") .attr("class", "timelinetext") .attr("x", xStart - 4 + (xToday - xStart) / 2) .attr("y", 24) .text(0) .on("mouseover", onMouseoverElapsed) .on("mouseout", hideTooltip) .transition() .duration(shortDuration) .ease("linear") .tween("text", function () { var i = d3.interpolateRound(0, (30 - pendingDays)); return function (t) { this.textContent = i(t); }; }); svg.append("text") .attr("class", "timelinetext") .attr("x", xToday - 4 + (xProtection - xToday) / 2) .attr("y", 24) .text(30) .on("mouseover", onMouseoverPending) .on("mouseout", hideTooltip) .transition() .duration(shortDuration) .ease("linear") .tween("text", function () { var i = d3.interpolateRound(30, pendingDays); return function (t) { this.textContent = i(t); }; }); } else { svg.append("text") .attr("class", "timelinetext") .attr("x", xToday - 4 + (xProtection - xToday) / 2) .attr("y", 24) .text(1) .on("mouseover", onMouseoverPending) .on("mouseout", hideTooltip); } } else { // protection pending date has been passed var redDuration = ((xProtectedBorder - xStart) / (xToday - xStart)) * duration; var interval = (duration - redDuration) / totalDays, timer = null, incr = 1; // if interval < 5 milliseconds, skip numbers so script can keep up if (interval < 5) { incr = Math.ceil(5 / interval); interval = 5; } setTimeout(function () { timer = setInterval(updateDays, interval) }, redDuration); // status protected transitions svg.append("rect") .attr("class", "rect") .attr("x", xStart) .attr("y", 10) .attr("width", 0) .attr("height", 20) .style("fill", colors[0]) .transition() .ease("linear") .duration(redDuration * (3 / 4)) .style("fill", colors[2]) .attr("width", (xProtectedBorder * (3 / 4)) - xStart) .transition() .ease("linear") .duration(redDuration * (1 / 4)) .style("fill", colors[4]) .attr("width", xProtectedBorder - xStart) .each("end", function () { // reached green protected zone d3.select(this) .transition() .ease("linear") .duration(30) .style("fill", "#9bf92f") .transition() .ease("linear") .duration((duration - redDuration) / 3) .attr("width", (xProtectedBorder - xStart) + ((xToday - xStart) - (xProtectedBorder - xStart)) / 3) .style("fill", colors[4]) .transition() .ease("linear") .duration((duration - redDuration) / 2) .attr("width", xToday - xStart); svg.append("text") .attr("class", "timelinetext") .attr("x", 90) .attr("y", 24) .style("font-weight", "bold") .text("Page is Protected"); }); } // date ticks var node = svg.selectAll("g") .data(data) .enter() .append("g"); node.append("svg:line") .attr("class", function (d, i) { return "tick" + (i == 0 ? " grey-dashed" : ""); }) .attr("x1", function (d) { return x(d); }) .attr("x2", function (d) { return x(d); }) .attr("y1", function (d, i) { return i == 0 ? 7 : 8; }) .attr("y2", function (d, i) { return i == 0 ? 33 : 32; }) .on("mouseover", function (d, i) { if (!isUpgradeExample) { tooltip.find("span").show() .css("top", "31px").css("left", (x(d) - ttWidthHalf) + "px") .text(tooltipText[i] + " " + fmt(d)); } }) .on("mouseout", hideTooltip); tooltip.mouseover(function () { if (!isUpgradeExample) { tooltip.find("span").show(); } }).mouseout(hideTooltip); } // count up days with rect transitions function updateDays() { day += incr; if (day >= totalDays) { clearInterval(timer); day = totalDays; } lblTimer.text(day); } // hide rectangle zone tooltip function hideTooltip() { if (!isUpgradeExample) { tooltip.find("span").hide(); } } function onMouseoverProtected() { if (!isUpgradeExample) { var leftPx = (isPending) ? xProtection - ttWidthHalf + futureHatchPx / 2 : xToday - ttWidthHalf - 14; var txt = (isPending) ? (isVerified ? "Page protection begins 24 hours after first successful scan of page." : "Page protection begins 30 days after first successful scan of page. To speed up this process, click to <a href='../ProtectionPro.aspx?r=pstu'>upgrade</a>") : "Page is Protected"; tooltip.find("span").show() .css("top", "31px").css("left", leftPx + "px") .html(txt); } } function onMouseoverPending() { if (!isUpgradeExample) { tooltip.find("span").show() .css("top", "31px").css("left", (xToday - ttWidthHalf + (xProtection - xToday) / 2) + "px") .text(pendingDays + " days left until page is protected by dmca.com"); } } function onMouseoverElapsed() { if (!isUpgradeExample) { tooltip.find("span").show() .css("top", "31px").css("left", (xStart - ttWidthHalf + (xToday - xStart) / 2) + "px") .text((30 - pendingDays) + " days since badge was succesfully scanned"); } } }
// STEP 3: Create Article cards. // ----------------------- // Send an HTTP GET request to the following address: https://lambda-times-backend.herokuapp.com/articles // Stduy the response data you get back, closely. // You will be creating a component for each 'article' in the list. // This won't be as easy as just iterating over an array though. // Create a function that will programmatically create the following DOM component: // // <div class="card"> // <div class="headline">{Headline of article}</div> // <div class="author"> // <div class="img-container"> // <img src={url of authors image} /> // </div> // <span>By {authors name}</span> // </div> // </div> // // Create a card for each of the articles and add the card to the DOM. const cardContainer = document.querySelector('.cards-container') axios.get('https://lambda-times-backend.herokuapp.com/articles') .then(response => { console.log(response.data.articles) Object.values(response.data.articles).forEach(elements => { elements.forEach(element =>{ cardContainer.appendChild(createCards(element)) }) }); }) .catch(error => { }) function createCards(obj){ const newCard = document.createElement('div'), newHeadLine = document.createElement('div'), newAuthor = document.createElement('div'), newImgContainer = document.createElement('div'), newImg= document.createElement('img'), newSpan = document.createElement('span') //add classes newCard.classList.add("card"); newHeadLine.classList.add("headline"); newAuthor.classList.add("author"); newImgContainer.classList.add("img-container"); //add content newHeadLine.textContent = obj.headline; newImg.setAttribute("src", obj.authorPhoto); newSpan.textContent = obj.authorName; // append newCard.appendChild(newHeadLine); newCard.appendChild(newAuthor); newAuthor.appendChild(newImgContainer); newAuthor.appendChild(newSpan); newImgContainer.appendChild(newImg); return newCard }
const path = require('path'); const winston = require('winston'); const onFinished = require('on-finished'); const uaParser = require('ua-parser-js'); require('winston-loggly-bulk'); const {exec} = require('child_process'); let gitHead; let appVersion; const cmd = 'git describe --tags || git log --pretty="%h" -n1 HEAD'; exec(cmd, (err, stdout) => { if (!err) { gitHead = stdout; } }); const packageJson = require(path.join(process.cwd(), 'package.json')); appVersion = packageJson.version; exports.default = (config) => { let logglyParams = { token: config.token, subdomain: config.subdomain, tags: config.tags, json: true, }; winston.add(winston.transports.Loggly, logglyParams); if (!config.ignoreUserAgent) { config.ignoreUserAgent = /^curl/; } return function(req, res, next) { req.expressLoggly = { startTime: (new Date()).getTime(), params: {}, }; onFinished(res, function(err, res) { let userAgent = req.headers['user-agent']; if (!userAgent || userAgent.match(config.ignoreUserAgent)) { return; } let logObject = { remoteAddr: req.realip, url: req.originalUrl || req.url, referrer: req.headers['referer'] || req.headers['referrer'], userAgent: uaParser(req.headers['user-agent']), appParams: req.expressLoggly.params, method: req.method, time: (new Date()).toISOString(), status: res.statusCode, length: res.getHeader('content-length'), responseTime: (new Date()).getTime() - req.expressLoggly.startTime, gitHead, appVersion, }; winston.log('info', logObject); }); next(); }; };
var google; function initRewardsMap() { if ("geolocation" in navigator) { /* geolocation is available */ //Get user location navigator.geolocation.getCurrentPosition(function(position) { locateUser(position.coords.latitude, position.coords.longitude); }); function locateUser(lat,lng) { //Create Map var styles = [ { stylers: [ { hue: "#00ffe6" }, { saturation: -20 } ] },{ featureType: "road", elementType: "geometry", stylers: [ { lightness: 100 }, { visibility: "simplified" } ] },{ featureType: "road", elementType: "labels", stylers: [ { visibility: "off" } ] } ]; var rewardsMap = new google.maps.Map(document.getElementById('rewards_map2'), { zoom: 13, scrollwheel: false, center: {lat: lat, lng: lng} }); rewardsMap.setOptions({styles: styles}); //Create user marker var myLatlng = new google.maps.LatLng(lat, lng); var pinColor = "ffff19"; var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor, new google.maps.Size(21, 34), new google.maps.Point(0, 0), new google.maps.Point(10, 34)); var pinShadow = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_shadow", new google.maps.Size(40, 37), new google.maps.Point(0, 0), new google.maps.Point(12, 35)); var userMarker = new google.maps.Marker({ position: myLatlng, map: rewardsMap, icon: pinImage, shadow: pinShadow, animation: google.maps.Animation.DROP, title: $('.js-user-name').data('user-name') }); //Info window appear when click User marker var contentStringUser = '<div id="content">' + '<h5 id="firstHeading" class="firstHeading">'+$('.js-user-name').data('user-name')+'</h5>' + '</div>'; var infowindowUser = new google.maps.InfoWindow({ content: contentStringUser }); userMarker.addListener('click', function () { infowindowUser.open(rewardsMap, userMarker); }); locateRewards(); function locateRewards() { var labels = "ABCDEFGHIJKLMNÑOPQRSTUVWXYZ"; var latitude = []; var longitude = []; var companyName = []; var rewards = []; var locations = []; $('.js-rewards-name').each(function(){ var rewardsName = $(this).data('rewards-name'); rewards.push(rewardsName); }); $('.js-rewards-lat').each(function(){ var lat = $(this).data('rewards-lat'); latitude.push(lat); }); $('.js-rewards-long').each(function(){ var long = $(this).data('rewards-long'); longitude.push(long); }); $('.js-company-name').each(function(){ var name = $(this).data('company-name'); companyName.push(name); }); var position = { lat: latitude, lng: longitude }; for(i = 0; i < latitude.length; i++){ locations.push( { lat: latitude[i], lng: longitude[i] } ) } // Add Accountants markers to the rewardsMap. // Note: The code uses the JavaScript Array.prototype.map() method to // create an array of markers based on a given "locations" array. // The map() method here has nothing to do with the Google Maps API. var rewardsMarkers = locations.map(function (location, i) { return new google.maps.Marker({ position: location, label: labels[i % labels.length], title: companyName[i] }); }); //Add info window to each marker for (i=0; i < rewardsMarkers.length; i++){ var marker = rewardsMarkers[i]; var content = '<h5 id="firstHeading">'+companyName[i]+'</h5>'+'<div id="bodyContent">'+rewards[i]+'</div>'; var infowindow = new google.maps.InfoWindow(); google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){ return function() { infowindow.setContent(content); infowindow.open(rewardsMap,marker); }; })(marker,content,infowindow)); } // Add a marker clusterer to manage the markers. var markerCluster = new MarkerClusterer(rewardsMap, rewardsMarkers, {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'}); } } } else { /* geolocation IS NOT available */ console.log('geolocation IS NOT available') } } google.maps.event.addDomListener(window, 'load', initRewardsMap);
import { createSelector } from 'reselect' import moment from 'moment' export const TRIAL_DURATION = 14 export const getSettings = state => state.settings.data export const hasTrial = createSelector( getSettings, (settings = {}) => { const trialExpiration = moment(settings.installed).add(TRIAL_DURATION, 'days') const whithinTrial = trialExpiration.isAfter(moment()) return !settings.apiKey && whithinTrial } ) export const trialDaysLeft = createSelector( getSettings, (settings = {}) => { const trialExpiration = moment(settings.installed).add(TRIAL_DURATION, 'days') return trialExpiration.diff(moment(), 'days') } )
$(document).ready(function(){ $('[data-toggle="tooltip"]').tooltip() auto_suggest_class() auto_suggest_predicate() $(".attr").each(function() { var ths = $(this) var attr = ths.attr("id") $.ajax({ method: "GET", url: "https://lov.linkeddata.es/dataset/lov/api/v2/term/search", data: { q: attr }, dataType: "json", }).done(function(data) { var pn = data.results[0].prefixedName.toString() var uri = data.results[0].uri.toString() var ns = pn.split(":")[0] var pred = pn.split(":")[1] ths.val(uri) $("#ns-" + attr).html("<strong>" + ns + "</strong>: " + uri.replace(pred, "")) $("#shortns-" + attr).val(ns) }) }) /* auto-suggest: predicates */ function auto_suggest_predicate() { var getPredicates = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), queryTokenizer: Bloodhound.tokenizers.whitespace, remote: { url: 'https://lov.linkeddata.es/dataset/lov/api/v2/term/search?q=%q&type=property', wildcard: '%q', transform: function (results) { // Map the remote source JSON array to a JavaScript object array return $.map(results.results, function (res) { return { value: res.prefixedName, uri: res.uri }; }); } } }); $('.attr').typeahead(null, { name: 'predicates', display: 'uri', source: getPredicates, templates: { header: '<h4 class="results from LOV">Suggestions from LOV</h4>', empty: [ '<div class="empty-message">', 'unable to find any matching predicates', '</div>' ].join('\n'), suggestion: function(data) { return '<p><strong>' + data.value + '</strong> (' + data.uri + ')</p>'; } } }); /* auto-suggest predicate suggestion selected */ $('.attr').bind('typeahead:select', function(ev, suggestion) { var ths = $(this) var attr = ths.attr("id") var pred = (suggestion.value).toString() // eg: foaf:firstName var prefix = pred.split(":")[0] // eg: foaf var url = suggestion.uri.toString() // eg: http://xmlns.com/foaf/0.1/firstName var ns = url.replace(pred.split(":")[1],"") $("#ns-" + attr).html("<strong>" + prefix + "</strong>: " + ':' + ns) $("#shortns-" + attr).val(prefix) console.log('Selection: ' + suggestion.uri); }); } /* auto-suggest: class */ function auto_suggest_class() { var getClass = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), queryTokenizer: Bloodhound.tokenizers.whitespace, remote: { url: 'https://lov.linkeddata.es/dataset/lov/api/v2/term/search?q=%q&type=class', wildcard: '%q', transform: function (results) { // Map the remote source JSON array to a JavaScript object array return $.map(results.results, function (res) { return { value: res.prefixedName, uri: res.uri }; }); } } }); $('#clss').typeahead(null, { name: 'class', display: 'uri', source: getClass, templates: { header: '<h4 class="results from LOV">Suggestions from LOV</h4>', empty: [ '<div class="empty-message">', 'unable to find any matching class', '</div>' ].join('\n'), suggestion: function(data) { return '<p><strong>' + data.value + '</strong> (' + data.uri + ')</p>'; } } }); $('#clss').bind('typeahead:select', function(ev, suggestion) { var ths = $(this) var attr = ths.attr("id") var clss = (suggestion.value).toString() // eg: schema:author var prefix = clss.split(":")[0] // eg: schema var url = suggestion.uri.toString() // eg: http://schema.org/author var ns = url.replace(clss.split(":")[1],"") $("#ns-" + attr).html("<strong>" + prefix + "</strong>: " + ':' + ns) $("#shortns_clss").val(prefix) $("#ns_clss").val(ns) console.log('Selection: ' + suggestion.uri); }); } $('input[name=pk]').change(function() { var radio = $(this).val() $("#" + radio).val("") $("#ns-" + radio).html("") $("#shortns-" + radio).html("") }) /* save mappings to disk */ $("#addMappings").click(function() { var map = new Map(); var short_nsEmpty = false $(".attr[id]").each(function() { var pred = $(this).attr("id") var short_ns = "" var mapping = $(this).val() if (mapping.includes(">")) { // abc>http://example.com/ns/publishdata => personalized URI var bits = mapping.split(">") short_ns = bits[0] mapping = bits[1] } else { short_ns = $("#shortns-" + pred).val() if (short_ns == "") { short_nsEmpty = true alert("Please enter the namespace of the manually entered class/property for the attribute [" + pred + "]. For example: [npg>http://ns.nature.com/terms/date]") $(this).css("background-color","f2dede") $(this).focus() } } map.set(pred, short_ns + "___" + mapping) }) var pk = $('input[name=pk]:checked').val() var dtype = $("#dtype").val() var clss = $("#clss").val() var shortns_clss = "" var ns_clss = "" if (clss.includes(">")) { // abc>http://example.com/ns/Product => personalized URI var bits = clss.split(">") shortns_clss = bits[0] clss = bits[1] var tmp = clss.includes("#") ? clss.lastIndexOf('#') : clss.lastIndexOf('/') ns_clss = clss.substring(0, tmp + 1) // +1 to include the last '/' } else { shortns_clss = $("#shortns_clss").val() ns_clss = $("#ns_clss").val() } var src = $("#src").val() var entity = $("#entity").val() if (!short_nsEmpty) { $(".attr").css("background-color","#fff") $.ajax({ method: "POST", url: "/newMappings", data: { mappings: mapToJson(map), pk: pk, dtype: dtype, clss: clss, ns_clss: ns_clss, shortns_clss: shortns_clss, src: src, entity: entity}, dataType: "json", success: function(data) { $("#map-success").show().html(data) }, error: function(jqXHR, textStatus, errorThrown) { alert('An error occurred... open console for more information!'); $('#result').html('<p>status code: '+jqXHR.status+'</p><p>errorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>'); console.log('jqXHR:'); console.log(jqXHR); console.log('textStatus:'); console.log(textStatus); console.log('errorThrown:'); console.log(errorThrown); } }) } }) $("#addField").click(function() { $("#newFieldModal").modal('toggle') }) $("#saveField").click(function() { var newField = $("#newField") var newFieldVal = newField.val() if (newFieldVal != "") { $("#fieldsTable tr:last").after("<tr><td>" + newFieldVal + "<td><input type='radio' name='pk' id='" + newFieldVal + "'></td><td><input type='text' class='form-control attr' id='" + newFieldVal + "'></td></tr>") newField.val("") $("#fieldAdded").css("color","blue").html("Field: " + newFieldVal + " added! you can add more") auto_suggest_predicate() } else $("#fieldAdded").css("color","red").html("Field name empty!") }) }) function mapToJson(map) { return JSON.stringify([...map]); }
// Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. // Input: nums = [3,0,1] // Output: 2 // Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums. // Input: nums = [0,1] // Output: 2 // Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums. // Input: nums = [9,6,4,2,3,5,7,0,1] // Output: 8 // Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums. // Input: nums = [0] // Output: 1 // Explanation: n = 1 since there is 1 number, so all numbers are in the range [0,1]. 1 is the missing number in the range since it does not appear in nums. var missingNumber = function(nums) { let result = 0; let numPresent = false; for (let i = 1; i <= nums.length; i++) { numPresent = false; for (let j = 0; j < nums.length; j++) { if (nums[j] == i) { numPresent = true; } } if (!numPresent) { result = i; } } return result; };
/** * Allows you to remove the QUOTA_BYTES_PER_ITEM restriction, leaving only BYTES_PER_ITEM */ export default class Storage { _data = {}; /** * The maximum total amount (in bytes) of data that can be stored in sync storage * https://developer.chrome.com/extensions/storage#properties * @type {number} */ static QUOTA_BYTES = 102400; /** * The maximum size (in bytes) of each individual item in sync storage * https://developer.chrome.com/extensions/storage#properties * @type {number} */ static QUOTA_BYTES_PER_ITEM = 8192; /** * Unique prefix for keys * @type {string} */ static ITEM_KEY_PREFIX = 'p'; static getRegexKey() { return new RegExp(`^${Storage.ITEM_KEY_PREFIX}\\d+$`); } constructor() { chrome.storage.sync.onChanged.addListener(this._applyChanges.bind(this)); } /** * Splits a string into pieces no more than QUOTA_BYTES_PER_ITEM bytes * @param string * @returns {Array<string>} * @private */ _split(string) { // The maximum number of pieces into which a string can be divided const maximumNumberOfParts = Math.ceil(Storage.QUOTA_BYTES / Storage.QUOTA_BYTES_PER_ITEM); // The size of the split string in bytes. We use the JSON.stringify method, // since it is in this form that Chrome will later store data. const stringSize = Storage._getSizeInBytes(JSON.stringify(string)); // Get the maximum key size in bytes const reservedSize = Storage._getSizeInBytes( `${Storage.ITEM_KEY_PREFIX}${maximumNumberOfParts}`, ); // If the saved data does not fit into the storage if ((stringSize + (reservedSize * maximumNumberOfParts)) > Storage.QUOTA_BYTES) { // TODO: error } // If the total size of the entire row and its key size is less // than the maximum available size of a single storage item if ((stringSize + reservedSize) < Storage.QUOTA_BYTES_PER_ITEM) { // Insert the whole string, no need to split it return [string]; } // Maximum available size for one chunk const chunkSize = Storage.QUOTA_BYTES_PER_ITEM - reservedSize; // Offset from the beginning of the line let offset = 0; const chunks = []; for (let step = 0; step < maximumNumberOfParts; step++) { let currentChunkSize = chunkSize; const position = offset + currentChunkSize; let newChunk = string.slice(offset, position); let newChunkSize = Storage._getSizeInBytes(JSON.stringify(newChunk)); // Reduce the chunk until it fits the maximum available value while (newChunkSize > chunkSize) { currentChunkSize--; newChunk = string.slice(offset, offset + currentChunkSize); newChunkSize = Storage._getSizeInBytes(JSON.stringify(newChunk)); } chunks.push(newChunk); offset += currentChunkSize; if (offset >= stringSize) { break; } } return chunks; } /** * Returns the string size in bytes * @param {string} string * @returns {number} * @private */ static _getSizeInBytes(string) { return new TextEncoder('utf-8').encode(string).length; } _getIds() { return new Promise((resolve, reject) => { chrome.storage.sync.get(null, (items) => { if (chrome.runtime.lastError) { return reject(chrome.runtime.lastError); } const Ids = []; Object.keys(items).forEach((index) => { if (index.match(Storage.getRegexKey()) !== null) { Ids.push(index); } }); resolve(Ids); }); }); } _updateDate(addedItems, removeItems) { return new Promise((resolve, reject) => { chrome.storage.sync.set(addedItems, () => { if (chrome.runtime.lastError) { return reject(chrome.runtime.lastError); } if (removeItems.length > 0) { chrome.storage.sync.remove(removeItems, () => { if (chrome.runtime.lastError) { return reject(chrome.runtime.lastError); } resolve(); }); } else { resolve(); } }); }); } async _applyChanges() { this._data = await this.fetch(); } /** * @param {Object} options * @returns {Promise<Object>} */ async set(options) { const Ids = await this._getIds(); const items = {}; let chunks = []; try { chunks = this._split(JSON.stringify(options)); } catch (error) { throw new Error(error); } chunks.forEach((item, index) => { const id = `${Storage.ITEM_KEY_PREFIX}${index}`; items[id] = item; const idPosition = Ids.indexOf(id); if (idPosition !== -1) { Ids.splice(idPosition, 1); } }); await this._updateDate(items, Ids); this._data = options; } get() { return this._data; } /** * Retrieves all data from storage * @returns {Promise<Object>} */ fetch() { return new Promise((resolve, reject) => { chrome.storage.sync.get(null, (items) => { if (chrome.runtime.lastError) { return reject(chrome.runtime.lastError); } let string = ''; Object.keys(items).forEach((index) => { if (index.match(Storage.getRegexKey()) !== null) { string += items[index]; } }); if (string === '') { resolve({}); } try { this._data = JSON.parse(string); resolve(this._data); } catch (error) { reject(error); } }); }); } }
/*赛事*/ let NormalGameView = require("../normalgame/NormalGameView"); cc.Class({ extends: NormalGameView, properties: { TAG: { override: true, default: "EventGameView", }, }, init(parameters) { this._super(parameters); this.btn_task.active = false; // this.btn_win_streak.setVisible(false); // this.btn_mult.setVisible(false); // this.pan_mult_msg.setVisible(false); //this.initComponentEvent(); }, //override 创建用户组件 createLordUser(index) { var node = cc.find("pan_user" + index, this.root); let lordUser = node.addComponent("EventLordUser"); lordUser.index = index; lordUser.onLoad(); return lordUser; }, //override initButtonManager(node) { this.BM = node.addComponent("EventButtonManager"); //除托管按钮外,其他的按钮都在ui中,且在pm的下层 }, //override 初始化不同类型牌桌按钮 initBtnOtherDif() { this.panelBottom.setVisible(false); this.panelEventBottom.setVisible(true); this.btnEventRecord = cc.find("panel_event_bottom/btn_event_record", this.root); this.btnEventRecord.interactable = true; this.btnEventRecord.node.on(cc.Node.EventType.TOUCH_END, this.onClickEventRecord.bind(this)); this.btnEventAvtivity.interactable = true; this.btnEventAvtivity.node.on(cc.Node.EventType.TOUCH_END, this.onClickEventAvtivity.bind(this)); }, onClickEventRecord() { qf.event.dispatchEvent(qf.ekey.OPEN_ROUND_DETAIL_DIALOG); }, onClickEventAvtivity() { // function eventGameActivityModule() { // //赛事活动 // qf.event.dispatchEvent(qf.ekey.OPEN_VIEW_DIALOG, {name: "eventgameactivity"}); // } // // ModuleManager.checkPreLoadModule({callback: eventGameActivityModule, loadResName: "eventgameactivity"}); }, setMatchingShow(visible, enterUin) { let user = qf.cache.desk.getOnDeskUserByUin(qf.cache.user.uin); if (visible) { // //打开赛事匹配界面 // qf.rm.checkLoad("event_match",()=>{ // qf.mm.show("event_match", null, true); // }) } else { //qf.mm.remove("event_match"); qf.cache.global.setStatUploadTime(qf.rkey.PYWXDDZ_EVENT_PERFORMANCE_MATCH_WAIT_SUCC_TIME); qf.platform.uploadEventStat({ "module": "performance", "event": qf.rkey.PYWXDDZ_EVENT_PERFORMANCE_MATCH_WAIT_SUCC, "value": 1, "custom": user.match_level, }); } let controller = qf.mm.get("event_match"); let match_view = controller.view; if (match_view) { match_view.refreshUI(enterUin); } }, //override 更新菜单项依据主动托管是否显示 updateMenuIdsByAutoPlayShow(idArr, isBtnAutoPlayVisible) { return idArr; }, //override setCurJu() { this.setTypeInfo(); }, //override 设置底纹信息 setTypeInfo(typeInfo) { let typeStr = qf.cache.desk.getDeskName(); let baseScore = qf.cache.desk.getMaxGrabAction(); if (!baseScore || baseScore <= 0) { baseScore = qf.cache.desk.getBaseScore(); } //底分 let scoreStr = baseScore; let curRound = qf.cache.desk.getCurRound() || 0; curRound = curRound + 1; let curRoundStr = cc.js.formatStr(qf.txt.cur_round_txt, curRound); let serverStr = " "; this.txtPlayWay.getComponent(cc.Label).string = typeStr + " " + curRoundStr; this.txtScore.getComponent(cc.Label).string = scoreStr; this.txtServer.getComponent(cc.Label).string = serverStr; this.txtCapping.getComponent(cc.Label).string = curRoundStr; }, showSpringAnimation() { let resultInfo = qf.cache.desk.getResultInfo(); if (resultInfo.over_flag === qf.const.RESULT_OVER_FLAG.TRUE) { return this._super(); } return 0; }, //添加结算弹窗 addGameOver() { let resultInfo = qf.cache.desk.getResultInfo(); let res; if (resultInfo.is_winner === 0) { qf.music.playMyEffect("fail", false); res = qf.tex.table_you_lose; } else { qf.music.playMyEffect("victory", false); res = qf.tex.table_you_win; } if (resultInfo.over_flag === qf.const.RESULT_OVER_FLAG.TRUE) { qf.rm.checkLoad("eventgameover", () => { if (resultInfo.cur_level >= qf.const.MATCH_LEVEL.WANGZHE) { qf.event.dispatchEvent(qf.ekey.OPEN_VIEW_DIALOG, { name: "event_wangzhe_share" }); } else { qf.event.dispatchEvent(qf.ekey.OPEN_VIEW_DIALOG, { name: "event_game_over" }); } }) } else { this.showOnePairEndAnimation(res); } }, showOnePairEndAnimation(res) { this.img_you_result.runAction(cc.sequence( cc.callFunc((sender) => { sender.position = this.pos_you_result; sender.getComponent(cc.Sprite).spriteFrame = qf.rm.getSpriteFrame(qf.res.table, res), sender.active = true; }), cc.moveBy(0.8, 0, -400), cc.delayTime(1), cc.callFunc((sender) => { sender.active = false; }) )); }, //显示结算动画 showGameOverAnimation() { }, //override exitBtnFun() { qf.event.dispatchEvent(qf.ekey.LORD_NET_EXIT_DESK_REQ); }, //最后一副牌自动打出 setAutoLastCards(rsp) { this.getButtonManager().hideAllBtns(); this.PM.setLastCardsAuto(); }, //override 一副牌结束后清除托管 clearRobot(uin, isAllOver) { if (isAllOver) this._super(uin, isAllOver); }, //初始化加倍文字动画ui initMultiRunTxt() { this.panelMultiRunTxt = cc.find("panel_multi_run_txt", this.root); this.imgMultiDeng = this.panelMultiRunTxt.getChildByName("img_multi_deng"); this.imgMultiDai = this.panelMultiRunTxt.getChildByName("img_multi_dai"); this.imgMultiNong = this.panelMultiRunTxt.getChildByName("img_multi_nong"); this.imgMultiMing = this.panelMultiRunTxt.getChildByName("img_multi_ming"); this.imgMultiJia = this.panelMultiRunTxt.getChildByName("img_multi_jia"); this.imgMultiBei = this.panelMultiRunTxt.getChildByName("img_multi_bei"); this.imgMultiEllipsis1 = this.panelMultiRunTxt.getChildByName("img_multi_shengluehao_1"); this.imgMultiEllipsis2 = this.panelMultiRunTxt.getChildByName("img_multi_shengluehao_2"); this.imgMultiEllipsis3 = this.panelMultiRunTxt.getChildByName("img_multi_shengluehao_3"); this.runMultiTxtAction(); }, //跑等待农民加倍文字动画 runMultiTxtAction() { let txtArr = [ this.imgMultiDeng, this.imgMultiDai, this.imgMultiNong, this.imgMultiMing, this.imgMultiJia, this.imgMultiBei, this.imgMultiEllipsis1, this.imgMultiEllipsis2, this.imgMultiEllipsis3, ]; let i = -1; let runMultiTxtFunc = () => { i++; let v = txtArr[i]; v.runAction( cc.sequence( cc.moveBy(this.RUNMULTITXTTIME, cc.v2(0, this.RUNMULTITXTDISTANCE)), cc.moveBy(this.RUNMULTITXTTIME, cc.v2(0, -this.RUNMULTITXTDISTANCE)) ) ); if (i === txtArr.length - 1) i = -1; } this.schedule(runMultiTxtFunc, this.RUNMULTITXTTIME); }, updateResultValue() { let resultInfo = qf.cache.desk.getResultList(); for (let k in resultInfo) { let v = resultInfo[k]; let u = this.getUser(v.uin); if (u) { u.updateResultValue(v.score); } } }, //设置等待农民加倍显示与否 setWaitMultiShow(visible) { this.panelMultiRunTxt.active = visible; }, enterUser(uin) { if (uin === qf.cache.user.uin) { this.beforeChangDesk(); //qf.music.playBackGround(qf.res.lord_music.fightbgm); } let userList = qf.cache.desk.getUserList(); this.updateMeIndex(userList); for (let uin in userList) { let v = userList[uin]; this.getUser(v.uin).update(v.uin); if (v.status !== qf.const.UserStatus.USER_STATE_INGAME) { let u = qf.cache.desk.getUserByUin(v.uin); this.getUser(v.uin).setDefaultHead(u); } } }, });
const Parser = require('../parser'); const choice = parsers => new Parser(state => { if (state.isError) return state; for (let parser of parsers) { let nextState = parser.parserStateTransformer(state); if (!nextState.isError) return nextState; } return state.updateError(`choice: Unable to match with any parser at index ${state.index}`); }); module.exports = choice;
import React, {Component} from 'react'; import { View, Text, ImageBackground, Image, TouchableOpacity, StyleSheet, Dimensions } from 'react-native'; import mainStyle from '../src/styles/mainStyle'; export default class Home extends Component{ render() { return ( <ImageBackground source = {require('../assets/backgroundImage.png')} style = {mainStyle.container}> <View style = {mainStyle.content_1}> <View style = {mainStyle.content_1a}> <Image source = {require('../assets/logo.png')} style = {mainStyle.logo_home}></Image> </View> <View style = {mainStyle.content_1b}> <Text style = {mainStyle.textContent_1b}>Chào mừng bạn, </Text> <Text style = {mainStyle.textContent_1b}>đã đến với App Trắc Địa</Text> </View> <View style = {mainStyle.content_1c}> <TouchableOpacity style = {mainStyle.button_1__Content_1c}> <Text style = {mainStyle.home_banLaKhachHang}>Bạn là Khách Hàng</Text> </TouchableOpacity> <View style = {mainStyle.empty}></View> <TouchableOpacity style = {mainStyle.button_2__Content_1c}> <Text style ={mainStyle.home_banLaKyThuat}>Bạn là Kỹ thuật</Text> </TouchableOpacity> </View> </View> <View style = {mainStyle.content_2}> <View style = {mainStyle.content_2a}> <TouchableOpacity style = {mainStyle.buttonSignIn}> <Text style = {mainStyle.textButtonSignIn}>ĐĂNG NHẬP NGAY</Text> </TouchableOpacity> </View> <View style = {mainStyle.content_2b}> <TouchableOpacity style = {mainStyle.buttonSignUp}> <Text style = {mainStyle.textButtonSignUp}>TẠO TÀI KHOẢN</Text> </TouchableOpacity> </View> <View style = {mainStyle.content_2c}> <TouchableOpacity> <Text style ={{color:'#ffffff'}}>Quên mật khẩu?</Text> </TouchableOpacity> </View> </View> </ImageBackground> ); } }
import React, { useEffect, useRef } from 'react'; import Skills from '../skills/Skills'; const SkillsPage = () => { const pageRef = useRef(null) useEffect(() => { if(pageRef.current.getBoundingClientRect().top <= 0) { pageRef.current.scrollIntoView({ behavior: "smooth" }); } }, []); return ( <div className="page container-column" ref={pageRef}> <Skills /> </div> ); } export default SkillsPage;
import React from 'react'; import './style.sass'; const Footer = () => ( <div className="ui inverted vertical footer segment footer-style"> <div className="ui container"> <div className="ui stackable inverted divided equal height stackable grid"> <div className="three wide column"> <h4 className="ui inverted header dark">Help</h4> <div className="ui inverted link list"> <a href="#sdf" className="item blued">Getting started</a> <a href="#sf" className="item blued">Contact Us</a> </div> </div> <div className="three wide column"> <h4 className="ui inverted header dark">Careers</h4> <div className="ui inverted link list"> <a href="#sdf" className="item blued">Authors</a> <a href="#sdf" className="item blued">Reviewers</a> </div> </div> <div className="seven wide column"> <h4 className="ui inverted header dark">Blog</h4> <a href="#sdf" className="item blued">More</a> </div> </div> </div> </div> ); export default Footer;
const mongoose = require("mongoose"), UserSchema = require('./schemas/user'), GuildSchema = require('./schemas/guild'), config = require('./config.json'); mongoose.connect(config.url); var User = mongoose.model("users", UserSchema); var Guild = mongoose.model("guilds", GuildSchema); class npc { constructor(name, dialog) { this.name = name; this.dialog = dialog; this.User = User; this.Guild = Guild; } rdialog() { this.tts = this.dialog[Math.floor(Math.random() * this.dialog.length)]; return this.tts; } } module.exports = npc;
const statTable = { 0: [0,0], 1: [1,4], 2: [1,6], 3: [1,8], 4: [1,10], 5: [2,6], 6: [2,8], 7: [2,10], 8: [3,8], 9: [3,10], 10: [4,8] } const rollFromStat = (stat, mods) => { if( stat < 0 || stat > 10 ) return ('invalid stat!') if( !mods ){ mods = 0 } //convert undefined mods to 0 let [numRolls, dieSize] = statTable[stat] let absMod = Math.abs(mods) //convert stat to dice let allRolls = numRolls + absMod let diePool = [] for(let i = 0; i < allRolls; i++){ diePool.push(rollOne(dieSize)) } //rolling all dice if(mods>0){ diePool.sort((a,b)=>b-a) }else if(mods<0){ diePool.sort((a,b)=>a-b) } //sorting values diePool = diePool.slice(0,numRolls) //trimming the rolls //need to check for max rolls and explode the dice, also increasing the numrolls by 1 for each explosion let explodedDiePool = [] const explodeDie = (die, maxRoll) => { if(die===maxRoll){ let newRoll = rollOne(die) if(newRoll === maxRoll){ console.log('exploding roll explodes again!') explodeDie(die, maxRoll) //if the roll explodes again, repeat the function //and do not push the new roll as it will be updated in the next loop }else{ explodedDiePool.push(newRoll) } } explodedDiePool.push(die) } diePool.forEach((die)=>{ explodeDie(die, dieSize) }) let rollTotal = 0 //die sum here for(let i = 0; i < explodedDiePool.length; i++){ rollTotal += explodedDiePool[i] } // const statRolls = diePool.slice(0,numRolls) const d20Roll = rolld20(stat, mods) const statRolls = explodedDiePool.sort((a,b)=>b-a) return { rollTotal:rollTotal+d20Roll, d20Roll, statRolls, dieSize } } const rollOne = (dieSize) => { if(!dieSize) return 0 const rollRes = Math.ceil(Math.random() * dieSize) return rollRes } const explodeD20 = () => { let res = rollOne(20) return res === 20 ? res + explodeD20() : res } const rolld20 = (stat, mods) => { let res = 0 //if no stat apply adv/disadv to d20, else do not apply if (stat) { res = rollOne(20) }else{ console.log('no stats were found, applying adv') if(mods>0){ res = Math.max(rollOne(20), rollOne(20)) }else if(mods<0){ res = Math.min(rollOne(20),rollOne(20)) }else{ res = rollOne(20) } } //now explode the die if necessary if(res===20){ res += explodeD20() } return res } export { rollFromStat, rollOne }
function f(property, object) { for (var key in object) { if ( key === property ) { if ( object.hasOwnProperty(property) ) { return false; } else { return true; } } } } var obj1 = { job: "waiter", salary: 1000 }; var obj2 = Object.create(obj1); obj2.name = "John";
export const Fonts = { "Ogg": "Ogg-Roman", "OggItalic": "Ogg-Italic", "Maison": "MaisonNeue-Book", "MaisonLight": "MaisonNeue-Light" }
import React, { Component } from 'react'; import axios from 'axios'; import Boss from './Boss/Boss'; import Grid from 'material-ui/Grid'; import { CircularProgress } from 'material-ui/Progress'; class Bosses extends Component { state = { data: [] } componentDidMount = () => { axios.get('https://isaac.jamesmcfadden.co.uk/api/v1/boss?limit=83') .then((response) => { const data = response.data.data; this.setState({data}); }) } render() { const bossesList = this.state.data.map(boss => { return ( <Grid item xs={3}> <Boss image={boss.sprite_url} name={boss.name}/> </Grid> ) }) const loader = <Grid item><CircularProgress/></Grid> return ( <Grid container spacing={24} justify="center"> {this.state.data.length == 0 ? loader : bossesList} </Grid> ) } } export default Bosses;
import PropTypes from 'prop-types' import { Button as AntButton } from 'antd-styled' import styled from 'styled-components' import { variant } from 'styled-system' const getPrimaryStyles = (theme) => ({ color: theme.color.white.default, backgroundColor: theme.color.primary.default, borderColor: 'transparent' }) const getSecondaryStyles = (theme) => ({ color: theme.color.primary.default, backgroundColor: theme.color.primary.t.lighten3, borderColor: 'transparent' }) const Button = styled(AntButton)( () => ({ textTransform: 'uppercase' }), ({ theme }) => variant({ prop: 'type', variants: { white: { color: theme.color.primary.default, backgroundColor: theme.color.white.default, '&:hover': getSecondaryStyles(theme) }, success: { color: theme.color.white.default, backgroundColor: theme.color.success.default, '&:hover': { color: theme.color.success.default, backgroundColor: theme.color.success.t.lighten3, borderColor: 'transparent' } }, warning: { color: theme.color.white.default, backgroundColor: theme.color.warning.default, '&:hover': { color: theme.color.warning.default, backgroundColor: theme.color.warning.t.lighten3, borderColor: 'transparent' } }, primary: { ...getPrimaryStyles(theme), '&:hover': getSecondaryStyles(theme) }, secondary: { ...getSecondaryStyles(theme), '&:hover': getPrimaryStyles(theme) } } }), ({ theme }) => variant({ prop: 'hover', variants: { primary: { '&:hover': getPrimaryStyles(theme) }, secondary: { '&:hover': getSecondaryStyles(theme) } } }), ({ theme }) => variant({ prop: 'isActive', variants: { true: getPrimaryStyles(theme) } }), ({ theme }) => variant({ prop: 'size', variants: { middle: { borderRadius: theme.borderRadius.sm }, gigant: { height: 80, '&.ant-btn-icon-only': { width: 80 }, padding: '11px 0', fontSize: theme.typography.fontSize.h2, '&>*': { fontSize: theme.typography.fontSize.h2 } } } }) ) Button.propTypes = { block: PropTypes.bool, isActive: PropTypes.bool, size: PropTypes.oneOf(['small', 'middle', 'large']), type: PropTypes.oneOf([ 'white', 'primary', 'secondary', 'text', 'default', 'ghost', 'dashed' ]), hover: PropTypes.oneOf(['primary', 'secondary']), danger: PropTypes.bool } Button.defaultProps = { size: 'middle' } export default Button
function tracking(map, lineCoords) { var trackingUAV = new Promise((resolve, reject) => { var token = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJsaW5oLm5uMjgwMzk5QGdtYWlsLmNvbSIsInNjb3BlcyI6WyJURU5BTlRfQURNSU4iXSwidXNlcklkIjoiYmJhYTFlNTAtZDY1My0xMWViLTkzODEtYWIyYTFhOGRhYWYwIiwiZmlyc3ROYW1lIjoiTmd1eWVuIiwibGFzdE5hbWUiOiJOaGF0IExpbmgiLCJlbmFibGVkIjp0cnVlLCJwcml2YWN5UG9saWN5QWNjZXB0ZWQiOnRydWUsImlzUHVibGljIjpmYWxzZSwidGVuYW50SWQiOiJiYTgyOGU0MC1kNjUzLTExZWItOTM4MS1hYjJhMWE4ZGFhZjAiLCJjdXN0b21lcklkIjoiMTM4MTQwMDAtMWRkMi0xMWIyLTgwODAtODA4MDgwODA4MDgwIiwiaXNzIjoidGhpbmdzYm9hcmQuaW8iLCJpYXQiOjE2MzQ3MTUyNzQsImV4cCI6MTYzNjUxNTI3NH0.NSfw4O7ZcikO7brENcDc1oOhvmrXI92FyWIANxQWxeTfrrHivfA5746oXb5KWpd2WiAsE6VkqjQIz3ICy-iErA"; var entityId = "e526c210-dd65-11eb-bb75-a1672e109977" var webSocket = new WebSocket("wss://demo.thingsboard.io/api/ws/plugins/telemetry?token=" + token); webSocket.onopen = function () { var object = { tsSubCmds: [ { entityType: "DEVICE", entityId: entityId, scope: "LATEST_TELEMETRY", cmdId: 10 } ], historyCmds: [], attrSubCmds: [] }; var data = JSON.stringify(object); webSocket.send(data); }; webSocket.onmessage = function (event) { var received_msg = event.data; received_msg = JSON.parse(received_msg) received_msg = received_msg.data resolve(received_msg) }; webSocket.onclose = function (event) { console.log("Connection is closed! Please reload..."); }; }) trackingUAV .then((res) => { var gps = { lat: parseFloat(res.Lat_UAV[0][1]), lng: parseFloat(res.Lon_UAV[0][1]) } console.log(gps) setGPS(gps) redraw(gps, map, lineCoords) }) .catch(err => console.log(err)) } // Draw map var redraw = function (payload, map, lineCoords) { if (payload != null) { lat = payload.lat; lng = payload.lng; // map.setCenter({lat:lat, lng:lng, alt:0}); mark.setPosition({ lat: lat, lng: lng, alt: 0 }); lineCoords.push(new google.maps.LatLng(lat, lng)); var lineCoordinatesPath = new google.maps.Polyline({ path: lineCoords, geodesic: true, strokeColor: '#2E10FF' }); lineCoordinatesPath.setMap(map); } }; //set new GPS drone function setGPS(gps) { document.getElementById("lat").innerHTML = gps.lat; document.getElementById("lng").innerHTML = gps.lng; } module.exports = tracking
import React from "react"; import { Payment, ModalCardUpdated, } from "../../../components/dashboard/parent/payment"; import { useSelector } from "react-redux"; import { getCardInfo } from "../../../redux/actions/parent"; function PaymentPage(props) { const [openModalCardUpdated, setOpenModalCardUpdated] = React.useState(false); React.useEffect(() => { getCardInfo(); }, []); const storeCardInfo = useSelector((store) => store.parent.cardInfo); const handleModalCardUpdated = (e) => { if (e) { e.preventDefault(); } setOpenModalCardUpdated(!openModalCardUpdated); }; return ( <> <Payment handleToggleModalCardUpdated={handleModalCardUpdated} storeCardInfo={storeCardInfo} /> <ModalCardUpdated isOpen={openModalCardUpdated} handleToggle={handleModalCardUpdated} /> </> ); } export default PaymentPage;
import React from 'react'; import { View, StatusBar, Image, Text, StyleSheet, TextInput, TouchableOpacity, ScrollView, Alert } from 'react-native'; import { connect } from 'react-redux'; // import { Ionicons } from '@expo/vector-icons'; import { Ionicons } from 'react-native-vector-icons'; // import camera from '../assets/icons/camera.png'; import whatsapp from '../assets/icons/whatsapp-green.png'; import * as Styled from '../assets/styles/styled'; import Header from '../components/Header'; import Footer from '../components/Footer'; import * as ClassesController from "../controllers/classes.controller"; const Cancel = (props) => { const confirmCancellation = async () => new Promise((resolve) => { Alert.alert("Cancelamento", "Deseja cancelar a aula?", [ { text: "NÃO", onPress: () => resolve(false) }, { text: "SIM", onPress: () => resolve(true) }, ]); }) const handleCancel = async (classToCancel) => { if (!classToCancel.id || !classToCancel.id_user_client || !classToCancel.text) { Alert.alert("Oooops!", "Preencha todos os campos antes de cancelar a aula :)"); console.log({ scheduledClass: props.scheduledClass, classToCancel }) return false; } try { let canceledClass = await ClassesController.cancel(classToCancel); console.log({ canceledClass }); if (!canceledClass.error) { props.setScheduledClasses(canceledClass.data.scheduled_lessons); props.setClassesCredits(canceledClass.data.classes_credits); props.setScheduledClass({}); Alert.alert("Aula cancelada!", "A aula que estava agendada anteriormente foi cancelada."); props.navigation.navigate("Home"); } else { Alert.alert("Erro", "Não foi possível cancelar a aula. Verifique os dados e tente novamente mais tarde.\nError code: " + canceledClass.error_code + " - " + canceledClass.error); } return true; } catch (error) { console.log({ error }); Alert.alert("Erro", "Não foi possível cancelar a aula. Verifique os dados e tente novamente mais tarde."); return false; } } React.useEffect(() => { if (!props.scheduledClass) { props.navigation.goBack(); } }, []); return ( <Styled.Container style={{ paddingTop: 0 }}> <Header screenTitle="Home" client psychologist navigation={props.navigation} /> {/* <Styled.Scroll> */} <Styled.ScrollContainer> <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: '#C43A57', width: '100%', paddingVertical: 30, marginBottom: 30 }}> <Styled.TxtQuestion style={{ color: "#FFF", width: '90%', fontWeight: '400' }}>Aulas canceladas ficarão como créditos para você usar quando bem entender.</Styled.TxtQuestion> </View> <Styled.TxtQuestion style={{ fontWeight: '500', fontSize: 14, color: "#D987A3", margin: 0, padding: 0, width: '90%', textAlign: 'left' }}>Conte para nós o motivo do cancelamento*</Styled.TxtQuestion> <Styled.TxtInput defaultValue={props.scheduledClass?.text} onChangeText={(e) => props.setScheduledClass({ ...props.scheduledClass, text: e })} placeholder="Escreva aqui..." /> <Styled.TxtQuestion style={{ fontWeight: '500', fontSize: 14, color: "#D987A3", margin: 0, padding: 0, width: '90%', textAlign: 'left', marginVertical: 10 }}>Ficou doente e tem atestado?</Styled.TxtQuestion> <TouchableOpacity style={{ padding: 5, borderRadius: 5, borderWidth: 1, borderColor: '#D987A3', flexDirection: 'row', flexWrap: 'nowrap', alignItems: 'center', justifyContent: 'center' }}> <Text style={{ fontWeight: '500', fontSize: 14, color: "#D987A3", margin: 0, padding: 0, }}>anexar atestado</Text> <Styled.Illustration source={camera} style={{ width: 25, height: 21.88, marginHorizontal: 3, }} /> </TouchableOpacity> <Styled.BtnCTA2 onPress={async () => await confirmCancellation() ? handleCancel(props.scheduledClass) : ""} style={{ marginTop: 50 }}> <Styled.TxtBtnCTA2>CANCELAR AULA</Styled.TxtBtnCTA2> </Styled.BtnCTA2> <Styled.TxtQuestion style={{ fontWeight: '500', fontSize: 14, color: "#D987A3", margin: 0, padding: 0, width: '90%', textAlign: 'center' }}>Obs: cancelamentos fora do prazo de 24 horas e não resultantes de caso fortuito ou força maior serão taxados em 10% do valor na aula/sessão</Styled.TxtQuestion> <TouchableOpacity style={{ flexDirection: 'row', flexWrap: 'nowrap', alignItems: 'center', justifyContent: 'center', marginVertical: 20 }}> <Text style={{ fontWeight: '800', fontSize: 14, color: "#D987A3", margin: 0, padding: 0, textAlign: 'center' }}>Precisa da nossa ajuda?</Text> <Styled.Illustration source={whatsapp} style={{ width: 22, height: 22, marginHorizontal: 5, }} /> <Text style={{ fontWeight: '400', fontSize: 14, color: "#D987A3", margin: 0, padding: 0, textAlign: 'center' }}>Fale conosco</Text> </TouchableOpacity> {/* </Styled.Scroll> */} </Styled.ScrollContainer> <Footer screenTitle="Home" client navigation={props.navigation} /> </Styled.Container > ); }; const mapStateToProps = (state) => { return { //modal modalInfoVisible: state.modalReducer.modalInfoVisible, //class scheduledClass: state.classReducer.scheduledClass, scheduledClasses: state.classReducer.scheduledClasses, } }; const mapDispatchToProps = (dispatch) => { return { //modal setModalInfoVisible: (modalInfoVisible) => dispatch({ type: 'SET_MODAL_INFO_VISIBLE', payload: { modalInfoVisible } }), //class setClasses: (classes) => dispatch({ type: 'SET_CLASSES', payload: { classes } }), setClassesCredits: (classes_credits) => dispatch({ type: 'SET_CLASSES_CREDITS', payload: { classes_credits } }), setScheduledClass: (scheduledClass) => dispatch({ type: 'SET_SCHEDULED_CLASS', payload: { scheduledClass } }), setScheduledClasses: (scheduledClasses) => dispatch({ type: 'SET_SCHEDULED_CLASSES', payload: { scheduledClasses } }), } }; export default connect(mapStateToProps, mapDispatchToProps)(Cancel);
'use strict'; module.exports = function (grunt, data) { if (grunt.cli.options.debug) { console.log('Loading `karma.js`'); } return { unit: { configFile: data.appConfigPath + '/karma.conf.js', singleRun: false } }; };
import React from "react"; import img3 from "../images/solar.jpg"; export default function Home() { return ( <div> <br /> <div className="row"> <div className="col col-lg-5 col-md-12 col-xs-12"> <div className="card"> <div className="card-body"> <h4 className="card-title">Latest News</h4> <br /> <h6 className="card-subtitle mb-2">Important Dates</h6> <p className="card-text"> <div className="list-group" style={{ fontSize: "13px" }}> <a href="#" className="list-group-item list-group-item-action" > The last date for full length submission 10.10.21{" "} </a> <a href="#" className="list-group-item list-group-item-action" > Notification of acceptance 10.11.21{" "} </a> <a href="#" className="list-group-item list-group-item-action" > Registration of accepted papers without late fees 20.11.21{" "} </a> <a href="#" className="list-group-item list-group-item-action" > Convention dates 27.11.21 and 28.11.21{" "} </a> </div> </p> <h6 className="card-subtitle mb-2 " style={{ display: "inline" }}> Paper Submission{" "} </h6> <a href="https://easychair.org/conferences/?conf=ncefes2021" className="card-link" > Link </a> </div> </div> </div> <div className="col col-lg-7 col-md-12 col-xs-12"> <div class="card"> <div class="card-body"> <h4 class="card-title" style={{textAlign:"center", fontWeight:"bold"}}>ABOUT THE CONVENTION</h4> <p class="card-text" style={{borderTop:"1px solid black", fontSize: "15px",textAlign: "justify"}}> <br /> Electrical power systems have been traditionally designed taking energy from high voltage level and distributing it to lower voltage level networks. There are large generation units connected to transmission networks. But in the past few years a trend has been established wherein many small generators are connected to the distribution networks. However, future electricity systems will require massive deployment of distributed energy resources (DER), especially distributed generation (DG) based on renewable energy sources (RES). Efficient integration of this distributed generation requires network innovations. A development of active distribution network management, from centralized to more distributed system management, is needed. Information, communication, and control infrastructures will be needed with increasing complexity of system management. Therefore, there is a need to have deliberations on many issues specially the challenges and current trends associated with future electricity system. </p> </div> </div> </div> </div> <br /> </div> ); }
class Reservation { //Add if available constructor(reservationId, reservationTicketId, reservationRoomId, reservationTravelPlanId,reservationPrice,ticketDateOfPurchase,departureDate,ticketCustomerId) { this.reservationId = reservationId; this.reservationTicketId = reservationTicketId; this.reservationRoomId = reservationRoomId; this.reservationTravelPlanId = reservationTravelPlanId; this.reservationPrice = reservationPrice; this.ticketDateOfPurchase = ticketDateOfPurchase; this.departureDate = departureDate; this.ticketCustomerId = ticketCustomerId; } } module.exports.Reservation = Reservation;
import styled from 'styled-components'; const Input = styled.input` padding: 15px; border: solid 1px #d3d4d5; border-radius: 4px; ::placeholder { color: #8a8a8a; opacity: 1; } :focus { outline: none; border: 1px solid #009fd9; } `; export default Input;
const React = require("react") exports.onRenderBody = ({ setHeadComponents, setPostBodyComponents }) => { setHeadComponents([ <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.19.0/themes/prism-coy.min.css" rel="stylesheet" />, <script src="https://d3js.org/d3.v5.min.js"></script>, ]) setPostBodyComponents([ <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.19.0/components/prism-core.min.js" data-manual></script>, <script src="/libs/prism-highlight.js"></script>, ]) }
import React, { Component } from 'react'; import PropTypes from 'prop-types' import styled from 'styled-components' import { Route, NavLink, } from 'react-router-dom' import {connect} from 'react-redux' import {ConnectedRouter} from 'react-router-redux' import About from './_About/' import View from './_View/' import Create from './_Create/' import colors from './styles/colors' import {actions} from './App.ducks' import {history} from './store' const AppContainer = styled.div` display: flex; flex: 1 0; flex-direction: column; height: 100vh; background-color: ${colors.container}; ` const RoutesContainer = styled.div` flex: 13 0; display: flex; ` const Header = styled.header` display: flex; flex: 1 0; min-height: 60px; width: 100%; background-color: ${colors.navbar_bg}; justify-content: space-between; ` const Title = styled(NavLink)` display: flex; flex: 1.5 0; font-weight: 600; font-size: 1.6em; color: white; align-items: center; margin-left: 10px; text-decoration: none; ` const NavButtonContainer = styled.div` display: flex; flex: 1 0; ` const NavButton = styled(NavLink)` display: flex; justify-content: center; align-items: center; height: 100%; flex: 1 0; text-decoration: none; color: ${colors.navbar_text}; ` const activeStyle = { color: colors.navbar_selection_text, backgroundColor: colors.navbar_selection_bg, } class App extends Component { static propTypes = { connectToNet: PropTypes.func.isRequired, } constructor(props) { super(props) this.props.connectToNet() } render() { return ( <ConnectedRouter history={history}> <AppContainer> <Header> <Title exact to="/" > Split It </Title> <NavButtonContainer> <NavButton exact to="/create" activeStyle={ activeStyle } > Create </NavButton> <NavButton exact to="/view" activeStyle={ activeStyle } > View </NavButton> </NavButtonContainer> </Header> <RoutesContainer> <Route exact path="/" render={() => <About />} /> <Route path="/create" render={() => <Create />} /> <Route path="/view" render={() => <View />} /> </RoutesContainer> </AppContainer> </ConnectedRouter> ); } } const mapStateToProps = state => ({ }) const mapDispatchToProps = dispatch => ({ connectToNet: () => dispatch(actions.connectToNet()) }) export default connect(mapStateToProps, mapDispatchToProps)(App)
import makeInspectable from 'mobx-devtools-mst'; import RootStore from "./models/RootStore"; const store = RootStore.create({ todos: { 'todo-1': {id: 'todo-1', content: 'Todo content_1'}, 'todo-2': {id: 'todo-2', content: 'Todo content_2'}, 'todo-3': {id: 'todo-3', content: 'Todo content_3'} }, columns: { 'column-1': {id: 'column-1', todoIds: ['todo-1', 'todo-2', 'todo-3']}, 'column-2': {id: 'column-2'}, 'column-3': {id: 'column-3'}, }, columnOrder: ['column-1', 'column-2', 'column-3'] }); export default makeInspectable(store)
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.set('view engine', 'pug') app.set('view options', { pretty: true }); if (app.get('env') === 'development') { app.locals.pretty = true; } //Set public folder app.use(express.static(__dirname + '/public')); //Routes app.use('/', require('./controllers')); //Router for index app.get('/', function (req, res) { res.render('index', { title: 'Главная страница', currentMenuItem: 0, message: 'Главная' }) }) app.listen(3000, function () { console.log('Server started on port 3000!'); });
const fs = require("fs"); describe('Tests to verify the file .txt', ()=>{ test('Verify if exist employes.txt', () => { expect(fs.existsSync('./employes.txt')).toBe(true); }); test('Verify if dont exist employesdata.txt', () => { expect(fs.existsSync('./employesdata.txt')).toBe(false); }); });
function taskOne() { return new Promise((resolve,reject)=>{ setTimeout(function () { console.log("this is task 1"); resolve() }, 500); }) } function taskTwo() { return new Promise((resolve,reject)=>{ setTimeout(function () { console.log("this is task 2"); resolve() }, 2000); }) } function taskThree() { return new Promise((resolve,reject)=>{ setTimeout(function () { console.log("this is task 3"); resolve() }, 1000); }) } async function main(){ //จะ await ตรงไหน function นั้นต้องเป็น promise เท่านั้นไม่งั้นไม่เกิดประโยชน์ await taskOne() await taskTwo() await taskThree() } main()
/* global QUnit */ /** * Before doing the test, import test-removeparam-rules.txt to AdGuard */ const request = async (url, header) => { const headers = header || { Accept: 'text/html' }; // eslint-disable-next-line compat/compat const response = await fetch(url, { headers, }); return response; }; const { log } = console; // eslint-disable-next-line compat/compat const baseUrl = window.location.origin; window.addEventListener('DOMContentLoaded', () => { const adgCheck = getComputedStyle(window.document.getElementById('subscribe-to-test-removeparam-rules-filter')).display === 'none'; QUnit.test('Case 1: $removeparam rule test', async (assert) => { const testUrl = `${baseUrl}/?p1case1=true&p2case1=true`; log('\nCase 1:'); log(`Requesting ${testUrl}`); const result = await request(testUrl); log(`result.url is ${result.url}`); assert.ok( !result.url.includes('p1case1=true') && result.url.includes('p2case1=true'), '$removeparam rule removes passed parameter' ); }); QUnit.test('Case 2: $removeparam with regexp test', async (assert) => { const testUrl = `${baseUrl}/?p1case2=true&p2case2=true`; log('\nCase 2:'); log(`Requesting ${testUrl}`); const result = await request(testUrl); log(`result.url is ${result.url}`); assert.ok( result.url.includes('p1case2=true') && !result.url.includes('p2case2=true'), '$removeparam rule removes passed regexp parameter' ); }); QUnit.test( 'Case 3: Test two $removeparam rules for the same request', async (assert) => { const testUrl = `${baseUrl}/?p1case3=true&p2case3=true`; log('\nCase 3:'); log(`Requesting ${testUrl}`); const result = await request(testUrl); log(`result.url is ${result.url}`); assert.ok( !result.url.includes('p1case3=true') && !result.url.includes('p2case3=true'), 'Both $removeparam rule are applied' ); } ); QUnit.test('Case 4: $removeparam case sensitivity test', async (assert) => { const testUrl = `${baseUrl}/?p1case4=true&P1Case4=true`; log('\nCase 4:'); log(`Requesting ${testUrl}`); const result = await request(testUrl); log(`result.url is ${result.url}`); assert.ok( adgCheck && result.url.includes('p1case4=true') && !result.url.includes('P1Case4=true'), '$removeparam is case sensitive' ); }); QUnit.test('Case 5: $removeparam exception test', async (assert) => { const testUrl = `${baseUrl}/?p1case5=true&p2case5=true`; log('\nCase 5:'); log(`Requesting ${testUrl}`); const result = await request(testUrl); log(`result.url is ${result.url}`); assert.ok( !result.url.includes('p1case5=true') && result.url.includes('p2case5=true'), '$removeparam exception prevents removing parameter' ); }); QUnit.test('Case 6: $removeparam with $important test', async (assert) => { const testUrl = `${baseUrl}/?p1case6=true&p2case6=true`; log('\nCase 6:'); log(`Requesting ${testUrl}`); const result = await request(testUrl); log(`result.url is ${result.url}`); assert.ok( !result.url.includes('p1case6=true') && !result.url.includes('p2case6=true'), '$removeparam rule with $important modifier has priority over $removeparam exception rule' ); }); QUnit.test('Case 7: $removeparam with $domain test', async (assert) => { const testUrl = `${baseUrl}/?p1case7=true&p2case7=true`; log('\nCase 7:'); log(`Requesting ${testUrl}`); const result = await request(testUrl); log(`result.url is ${result.url}`); assert.ok( !result.url.includes('p1case7=true') && !result.url.includes('p2case7=true'), '$removeparam works with $domain modifier' ); }); QUnit.test('Case 8: $removeparam with inversion test', async (assert) => { const testUrl = `${baseUrl}/?p1case8=true&p2case8=true`; log('\nCase 8:'); log(`Requesting ${testUrl}`); const result = await request(testUrl); log(`result.url is ${result.url}`); assert.ok( !result.url.includes('p1case8=true') && result.url.includes('p2case8=true'), '$removeparam works with inversion' ); }); QUnit.test('Case 9: negate $removeparam test', async (assert) => { const testUrl = `${baseUrl}/?p1case9=true&p2case9=true`; log('\nCase 9'); log(`Requesting ${testUrl}`); const result = await request(testUrl); log(`result.url is ${result.url}`); assert.ok( adgCheck && result.url.includes('p1case9=true') && result.url.includes('p2case9=true'), '$removeparam exception rule prevents removing parameter in a request' ); }); QUnit.test('Case 10: match parameter with value by $removeparam rule with regexp', async (assert) => { const testUrl = `${baseUrl}/?p1case10=xxx&p2case10=yyy`; log('\nCase 10:'); log(`Requesting ${testUrl}`); const result = await request(testUrl); log(`result.url is ${result.url}`); assert.ok( !result.url.includes('p1case10=xxx') && result.url.includes('p2case10=yyy'), '$removeparam with regexp matches parameter with value' ); }); QUnit.test('Case 11: $removeparam rule for script request test', async (assert) => { const testUrl = `${baseUrl}/Filters/removeparam-rules/test-removeparam-rules.js?p1case11=true&p2case11=true`; log('\nCase 11:'); log(`Requesting ${testUrl}`); const result = await request(testUrl, { 'Content-Type': 'text/javascript' }); log(`result.url is ${result.url}`); assert.ok( adgCheck && result.url.includes('p1case11=true') && !result.url.includes('p2case11=true'), 'Rule with $removeparams and $script modifier removes parameter for script request, but rule without $script modifier not' ); }); QUnit.test('Case 12: $removeparam rule for image request test', async (assert) => { const testUrl = `${baseUrl}/Filters/removeparam-rules/test-files/adg1.png?p1case12=true&p2case12=true`; log('\nCase 12:'); log(`Requesting ${testUrl}`); const result = await request(testUrl, { 'Content-Type': 'image/png' }); log(`result.url is ${result.url}`); assert.ok( adgCheck && result.url.includes('p1case12=true') && !result.url.includes('p2case12=true'), 'Rule with $removeparams and $image modifier removes parameter for image request, but rule without $image modifier not' ); }); });
var greeting = "Welcome to my intro site. This greeting was saved as a variable in javascript and wrote to the page using \"document.write(greeting)\""; document.write(greeting); alert("Hello!"); console.log("%cIt Worked","color:green;") console.warn("%cThis is a warning. Please check.","background:gold;"); console.error("%cThis is an ERROR!!!","color:red;background:pink;");
import 'react-dates/initialize'; import React from 'react' import {DateRangePicker} from 'react-dates' import '../../../datepicker.css' import {bindActionCreators} from "redux"; import * as actions from "../../../redux/actions"; import {connect} from "react-redux"; import moment from 'moment' moment.locale('tr-TR') class DateSearch extends React.Component { constructor(props){ super(props) this.state = { startDate:moment(), endDate:moment().add(1,'day') } } render(){ return( <DateRangePicker startDate={this.state.startDate} // momentPropTypes.momentObj or null, startDateId="your_unique_start_date_id" // PropTypes.string.isRequired, endDate={this.state.endDate} // momentPropTypes.momentObj or null, endDateId="your_unique_end_date_id" // PropTypes.string.isRequired, onDatesChange={({ startDate, endDate }) => this.setState({ startDate, endDate })} // PropTypes.func.isRequired, focusedInput={this.state.focusedInput} // PropTypes.oneOf([START_DATE, END_DATE]) or null, onFocusChange={focusedInput => this.setState({ focusedInput })} displayFormat="DD-MM-YYYY" keepOpen={true}// PropTypes.func.isRequired, /> ) } } export default DateSearch;
import React from "react"; import "./App.css"; import { applyMiddleware } from "redux"; import thunk from "redux-thunk"; import { Router, Route, Switch } from "react-router-dom"; import { createBrowserHistory } from "history"; import { Provider } from "react-redux"; import { createStore } from "redux"; import { reducer } from "./store/reducers"; import PrivateRoute from "./components/PrivateRoute"; import CatalogContainer from "./components/CatalogContainer"; import News from "./components/News"; import MyProfileContainer from "./components/MyProfileContainer"; import HeaderContainer from "./components/HeaderContainer"; import Footer from "./components/Footer/Footer"; export const store = createStore(reducer, applyMiddleware(thunk)); const auth = () => store.getState().login; function App() { return ( <div> <Provider store={store}> <div className="App"> <div className="wrapper"> <Router history={createBrowserHistory()}> <HeaderContainer /> <Switch> <Route path={["/", "/catalog"]} component={CatalogContainer} exact /> <Route path="/news" component={News} exact /> <PrivateRoute path="/myprofile" component={MyProfileContainer} auth={auth} exact /> </Switch> </Router> <Footer /> </div> </div> </Provider> </div> ); } export default App;
// ------------------------------------------------------------------------------------------------------- // init at local, upgrade me as dispatcher node of n4c cluster // Author: aimingoo@wandoujia.com // Copyright (c) 2015.09 // // assign right of dispatcher node // ------------------------------------------------------------------------------------------------------- var ResourceCenter = require('../infra/ResourceCenter.js') // taskObject as configurations of per-instance // *) @see default_config in ResourceCenter.js var taskObject = { systemName: 'sandpiper', serverAddr: '127.0.0.1:3232', // groupBasePath: '/com.wandoujia.n4c/sandpiper/nodes', promised: function(taskResult) { return { resource_status_center: new ResourceCenter(taskResult) } } } module.exports = taskObject;
import expect, { spyOnRewired } from '../index' /*eslint-disable no-unused-vars, import/named */ import { foo, barCalledByFoo, __RewireAPI__ as rewiredModule } from './spyOnRewired-module' /*eslint-enable no-unused-vars, import/named */ describe('A rewired function that was spied on', () => { let spy beforeEach(() => { spy = spyOnRewired(rewiredModule, 'barCalledByFoo') foo('some', 'args') }) it('tracks the number of calls', () => { expect(spy.calls.length).toEqual(1) }) it('tracks the context that was used', () => { expect(spy.calls[0].context).toBe(undefined) }) it('tracks the arguments that were used', () => { expect(spy.calls[0].arguments).toEqual([ 'some', 'args' ]) }) it('was called', () => { expect(spy).toHaveBeenCalled() }) it('was called with the correct args', () => { expect(spy).toHaveBeenCalledWith('some', 'args') }) it('can be restored', () => { expect(rewiredModule.__get__('barCalledByFoo')).toEqual(spy) spy.restore() expect(rewiredModule.__get__('barCalledByFoo')).toNotEqual(spy) }) after(() => { spy.restore() }) }) describe('A rewired function that was spied on but not called', () => { let spy beforeEach(() => { spy = spyOnRewired(rewiredModule, 'barCalledByFoo') }) it('number of calls to be zero', () => { expect(spy.calls.length).toEqual(0) }) it('was not called', () => { expect(spy).toNotHaveBeenCalled() }) after(() => { spy.restore() }) })
#!/usr/bin/env node "use strict"; const fsp = require('fs-promise'); const path = require('path'); const mkdirp = require('mkdirp-promise'); const rimraf = require('rimraf-promise'); const minimist = require('minimist'); const NODE_MODULES_ROOT = 'node_modules/'; // Given a package.json location, return the value of the style property within. function getPackageStyleSheet(packageJsonLocation) { return fsp.readFile(packageJsonLocation).then(data => { const pkg = JSON.parse(data); if (pkg.style) { return path.join(path.dirname(packageJsonLocation), pkg.style) } else { return false; } }); } function normalizePackageName(packageJsonPath) { return packageJsonPath .replace(/^node_modules\//, '') .replace(/\/package.json$/, ''); } function recurse(basePath, styles) { styles = styles || [] return fsp.readdir(basePath).then(files => { // Loop through each file in the directory const all = files.map(file => { const packageJsonPath = path.join(basePath, file); return fsp.lstat(packageJsonPath).then(stat => { // Traverse further into directories if (stat.isDirectory()) { return recurse(packageJsonPath, styles); // And parse any file named `package.json` } else if (stat.isFile() && path.basename(packageJsonPath) === 'package.json') { return getPackageStyleSheet(packageJsonPath).then(style => { if (style) { styles.push({ // Path to package.json, ie, `node_modules/normalize.css/package.json` name: packageJsonPath, // Path to css, ie, `node_modules/normalize.css/normalize.css`, style, // The name of the css file, ie, `normalize.css` normalized: normalizePackageName(packageJsonPath), }) } }) } }); }); return Promise.all(all).then(() => styles); }); } const argv = minimist(process.argv.slice(2)); const root = argv.root || 'styles/'; const extension = argv.ext || 'css'; if (argv.help || argv.h || argv['?']) { console.log(`Usage: nicss [--root] [--clean] [--ext]`); console.log(); console.log(`Options:`); console.log(); console.log('--root dir ........ path to the directory to symlink styles within, defaults to `styles/`'); console.log('--clean ........... instead of installing dependencies, remove all dependencies.'); console.log('--ext scss ........ extension to give to all linked styles, defaults to `css`'); console.log(); console.log(`Examples:`); console.log(); console.log(`$ nicss`); console.log(`🔗 Symlinking styles to styles/`); console.log(`styles/_normalize.css => ../node_modules/normalize.css/normalize.css`); console.log(`✅ Linked 1 style(s) into styles/`); console.log(`$ nicss --ext scss`); console.log(`🔗 Symlinking styles to styles/`); console.log(`styles/_normalize.scss => ../node_modules/normalize.css/normalize.scss`); console.log(`✅ Linked 1 style(s) into styles/`); console.log(`$ nicss --clean`); console.log(`Cleaned up styles in styles/`); process.exit(1) } if (argv.clean) { return rimraf(root).then(() => { console.log(`Cleaned up styles in ${root}.`); }); } else { // Install styles: // 1. Recursively move through all dependencies to find packages that have a `style` key in the // package.json // 2. Create a folder to link all styles. // 3. Symlink all styles into the styles folder. console.log(`🔗 Symlinking styles to ${root}`); recurse(NODE_MODULES_ROOT).then(styles => { return rimraf(root).then(() => { return mkdirp(root); }).then(() => { const all = styles.map(style => { const target = path.join('..', style.style); // Given a file extension, determine the name for the stylesheet const normalizedStylesheetName = style.normalized.replace(/.css$/, '').replace(/\//g, '-'); let styleSheetName; if (extension === 'scss') { styleSheetName = `_${normalizedStylesheetName}.scss` } else { styleSheetName = `${normalizedStylesheetName}.${extension}` } const source = path.join('styles', styleSheetName); return fsp.lstat(target).then(() => { console.warn(`NOTE: ${source} already exists, not symlinking over it...`); }).catch(() => { console.log(source, "=>", target); return fsp.symlink(target, source).catch(err => { console.log("❌ Error symlinking:", err.toString()); }); }) }); return Promise.all(all); }).then(resp => { console.log(`✅ Linked ${resp.length} style(s) into ${root}`); }); }).catch(e => console.trace(e)) }
import React, { Component } from 'react'; import { View, Text, StyleSheet, TouchableOpacity } from 'react-native'; import { incrementCounter, decrementCounter } from '../actions/counter'; import { connect } from 'react-redux'; class Counter extends Component { incrementCounter = () => { this.props.dispatch(incrementCounter()); }; decrementCounter = () => { this.props.dispatch(decrementCounter()); }; render() { return ( <View style={styles.container}> <TouchableOpacity onPress={() => { this.incrementCounter(); }} style={styles.button} > <Text style={{ color: 'white', fontSize: 18 }}>Increment (+)</Text> </TouchableOpacity> <Text style={{ fontSize: 18 }}>{this.props.count}</Text> <TouchableOpacity onPress={() => { this.decrementCounter(); }} style={styles.button} > <Text style={{ color: 'white', fontSize: 18 }}>Decrement (-)</Text> </TouchableOpacity> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'space-around', flexDirection: 'row', }, button: { backgroundColor: '#DDA0DD', padding: 10, margin: 30, borderRadius: 7, }, }); const mapStateToProps = ({ count }) => { return { count, }; }; export default connect(mapStateToProps)(Counter);
import { getHorseInfo, performHorseUpdate, getHorseStatisticsResultsInfo, getHorseStatisticsResultsDetailsInfo, getHorseStatisticsFutureDetailsInfo, updateHorseData } from 'api/Services' import { UPDATED_HORSE_DATA } from 'texts/successmessages' import { addToastSuccess, addToastError } from 'actions/toast' /** * @module CALL_ACTION_TYPE */ import { AUTHENTICATED_REQUEST } from 'middleware/AuthenticatedRequest' /** * @module formatHorseData */ import { formatHorseStatisticsData, formatHorseStatisticsResultsData } from 'utils/horseutils' /** * FETCH_HORSE_INFO * @type {String} */ export const FETCH_HORSE_INFO = 'FETCH_HORSE_INFO' /** * RECEIVED_HORSE_INFO * @type {String} */ export const RECEIVED_HORSE_INFO = 'RECEIVED_HORSE_INFO' /** * FAILED_TO_FETCH_HORSE_INFO * @type {String} */ export const FAILED_TO_FETCH_HORSE_INFO = 'FAILED_TO_FETCH_HORSE_INFO' export const FETCH_HORSE_STATISTICS_RESULTS_DETAILS_INFO = 'FETCH_HORSE_STATISTICS_RESULTS_DETAILS_INFO' export const RECEIVED_HORSE_STATISTICS_RESULTS_DETAILS_INFO = 'RECEIVED_HORSE_STATISTICS_RESULTS_DETAILS_INFO' export const FAILED_TO_FETCH_HORSE_STATISTICS_RESULTS_DETAILS_INFO = 'FAILED_TO_FETCH_HORSE_STATISTICS_RESULTS_DETAILS_INFO' export const CLEAR_HORSE_STATISTICS_RESULTS_DETAILS_INFO = 'CLEAR_HORSE_STATISTICS_RESULTS_DETAILS_INFO' /** * For statistics future entries detail * @type {String} */ export const FETCH_HORSE_STATISTICS_FUTURE_DETAILS_INFO = 'FETCH_HORSE_STATISTICS_FUTURE_DETAILS_INFO' export const RECEIVED_HORSE_STATISTICS_FUTURE_DETAILS_INFO = 'RECEIVED_HORSE_STATISTICS_FUTURE_DETAILS_INFO' export const FAILED_TO_FETCH_HORSE_STATISTICS_FUTURE_DETAILS_INFO = 'FAILED_TO_FETCH_HORSE_STATISTICS_FUTURE_DETAILS_INFO' export const CLEAR_HORSE_STATISTICS_FUTURE_DETAILS_INFO = 'CLEAR_HORSE_STATISTICS_FUTURE_DETAILS_INFO' /** * POSTING_HORSE_UPDATE * @type {String} */ export const POSTING_HORSE_UPDATE = 'POSTING_HORSE_UPDATE' /** * POSTED_HORSE_UPDATE * @type {String} */ export const POSTED_HORSE_UPDATE = 'POSTED_HORSE_UPDATE' /** * FAILED_TO_POST_HORSE_UPDATE * @type {String} */ export const FAILED_TO_POST_HORSE_UPDATE = 'FAILED_TO_POST_HORSE_UPDATE' /** * CLEAR_HORSE_DATA * @type {String} */ export const CLEAR_HORSE_DATA = 'CLEAR_HORSE_DATA' /** * gettingHorseInfo * @return {Object} */ export const FETCH_HORSE_STATISTICS_RESULTS_INFO = 'FETCH_HORSE_STATISTICS_RESULTS_INFO' export const RECEIVED_HORSE_STATISTICS_RESULTS_INFO = 'RECEIVED_HORSE_STATISTICS_RESULTS_INFO' export const FAILED_TO_FETCH_HORSE_STATISTICS_RESULTS_INFO = 'FAILED_TO_FETCH_HORSE_STATISTICS_RESULTS_INFO' export const gettingHorseInfo = () => ({ type: FETCH_HORSE_INFO }) /** * receivedHorseInfo * @return {Object} */ export const receivedHorseInfo = data => ({ type: RECEIVED_HORSE_INFO, data }) /** * failedToGetHorseInfo * @return {Object} */ export const failedToGetHorseInfo = () => ({ type: FAILED_TO_FETCH_HORSE_INFO }) export const gettingHorseStatisticsResultsInfo = () => ({ type: FETCH_HORSE_STATISTICS_RESULTS_INFO }) export const receivedHorseStatisticsResultsInfo = data => ({ type: RECEIVED_HORSE_STATISTICS_RESULTS_INFO, data }) export const failedToGetHorseStatisticsResultsInfo = () => ({ type: FAILED_TO_FETCH_HORSE_STATISTICS_RESULTS_INFO }) export const gettingHorseStatisticsResultsDetailsInfo = () => ({ type: FETCH_HORSE_STATISTICS_RESULTS_DETAILS_INFO }) export const receivedHorseStatisticsResultsDetailsInfo = data => ({ type: RECEIVED_HORSE_STATISTICS_RESULTS_DETAILS_INFO, data }) export const failedToGetHorseStatisticsResultsDetailsInfo = () => ({ type: FAILED_TO_FETCH_HORSE_STATISTICS_RESULTS_DETAILS_INFO }) /** * For statistics future entries detail * @return {Object} */ export const gettingHorseStatisticsFutureDetailsInfo = () => ({ type: FETCH_HORSE_STATISTICS_FUTURE_DETAILS_INFO }) export const receivedHorseStatisticsFutureDetailsInfo = data => ({ type: RECEIVED_HORSE_STATISTICS_FUTURE_DETAILS_INFO, data }) export const failedToGetHorseStatisticsFutureDetailsInfo = () => ({ type: FAILED_TO_FETCH_HORSE_STATISTICS_FUTURE_DETAILS_INFO }) /** * postingHorseUpdate * @return {Object} */ export const postingHorseUpdate = () => ({ type: POSTING_HORSE_UPDATE }) /** * postedHorseUpdate * @return {Object} */ export const postedHorseUpdate = () => ({ type: POSTED_HORSE_UPDATE }) /** * failedToPostHorseUpdate * @return {Object} */ export const failedToPostHorseUpdate = () => ({ type: FAILED_TO_POST_HORSE_UPDATE }) /** * clearHorseData * @return {Object} */ export const clearHorseData = () => ({ type: CLEAR_HORSE_DATA }) /** * fetchHorseInfo [async] * @param {String} name * @return {Function} */ export const fetchHorseInfo = slug => { return (dispatch, getState) => { return dispatch({ type: AUTHENTICATED_REQUEST, types: [gettingHorseInfo, receivedHorseInfo, failedToGetHorseInfo], endpoint: getHorseInfo, urlParams: {slug} }) } } /** * fetchHorseStatisticsFutureDetailsInfo [async] * @param {String} name * @return {Function} */ export const fetchHorseStatisticsFutureDetailsInfo = (name) => { return (dispatch, getState) => { // Signal to the store a fetch is going to happen dispatch(gettingHorseStatisticsFutureDetailsInfo()) return getHorseStatisticsFutureDetailsInfo(name) .then((result) => { return Promise.resolve(formatHorseStatisticsData(result[0].horses)) }) .then((data) => { dispatch(receivedHorseStatisticsFutureDetailsInfo(data)) return Promise.resolve(data) }) .catch((error) => { dispatch(failedToGetHorseStatisticsFutureDetailsInfo(error)) return Promise.reject(error) }) } } export const fetchHorseStatisticsResultsDetailsInfo = (name) => { return (dispatch, getState) => { // Signal to the store a fetch is going to happen dispatch(gettingHorseStatisticsResultsDetailsInfo()) return getHorseStatisticsResultsDetailsInfo(name) .then((result) => { let form = formatHorseStatisticsData(result.data.form.data) let raceRecord = formatHorseStatisticsData(result.data.raceRecord.data) return Promise.resolve({ form, raceRecord }) }) .then((data) => { dispatch(receivedHorseStatisticsResultsDetailsInfo(data)) return Promise.resolve(data) }) .catch((error) => { dispatch(failedToGetHorseStatisticsResultsDetailsInfo(error)) return Promise.reject(error) }) } } export const clearHorseStatisticsResultsDetailsInfo = () => ({ type: CLEAR_HORSE_STATISTICS_RESULTS_DETAILS_INFO }) export const getHorseStatisticsResults = (token, name) => { return (dispatch, getState) => { // Signal to the store a fetch is going to happen dispatch(gettingHorseStatisticsResultsInfo()) return getHorseStatisticsResultsInfo(token, name) .then(formatHorseStatisticsResultsData) .then((data) => { dispatch(receivedHorseStatisticsResultsInfo(data)) return Promise.resolve(data) }) .catch((error) => { dispatch(failedToGetHorseStatisticsResultsInfo(error)) return Promise.reject(error) }) } } /** * @name submitHorseUpdate * @description This will filter down to the AuthenticatedRequest middleware. * @param {Object} data * @return {Promise} */ export const submitHorseUpdate = (horseId, data) => { return { type: AUTHENTICATED_REQUEST, types: [postingHorseUpdate, postedHorseUpdate, failedToPostHorseUpdate], endpoint: performHorseUpdate, query: { horseId }, payload: data } } export const submitHorseData = (slug, payload) => { return (dispatch, getState) => { return dispatch({ type: AUTHENTICATED_REQUEST, types: [postingHorseUpdate, postedHorseUpdate, failedToPostHorseUpdate], endpoint: updateHorseData, payload, urlParams: {slug} }) .then(() => { dispatch(addToastSuccess(UPDATED_HORSE_DATA)) dispatch(fetchHorseInfo(slug)) return Promise.resolve() }) .catch((error) => { if (error && error.message) { dispatch(addToastError(error.message)) } }) } }
import axios from "axios"; const API_KEY="d5b44a7ead7a29ad2b779d6fefb1b5cf"; const API_KEY_GOOGLE='AIzaSyAaReInr43kcsS2-TM6WffA1F8_3fQhrCU'; const ROOT_URL=`https://api.openweathermap.org/data/2.5/forecast?` //convension //our Actions needs to be same type as Reducers export const FETCH_WEATHER="FEATCH_WEATHER" export function fetchWeather(city){ const url=`${ROOT_URL}q=${city},us&appid=${API_KEY}`; const request = axios.get(url) return { type:FETCH_WEATHER, payload:request } }
/** * Created by Administrator on 2017/6/2. */ Ext.define('Admin.store.brand.Brand', { extend: 'Admin.store.Base', requires: [ 'Admin.model.brand.Brand' ], model: 'Admin.model.brand.Brand', storeId: 'brand.Brand', proxy: { type: 'ajax', api:{ read: Common.Config.requestPath('Brand', 'queryAllBrand') }, reader: { type: 'json', rootProperty: 'data.list', totalProperty: 'data.total' } } });
import sha1 from 'sha1' import superagent from 'superagent' class UploadImageService { uploadFile(file) { const cloudName = process.env.REACT_APP_CLOUDINARY_CLOUD_NAME; const apiKey = process.env.REACT_APP_CLOUDINARY_API_KEY; const apiSecret = process.env.REACT_APP_CLOUDINARY_API_SECRET; const uploadPreset = process.env.REACT_APP_CLOUDINARY_UPLOAD_PRESET; const timeStamp = Date.now() / 1000; const paramStr = 'timestamp=' + timeStamp + '&upload_preset=' + uploadPreset + apiSecret; const url = 'https://api.cloudinary.com/v1_1/' + cloudName + '/image/upload'; const signature = sha1(paramStr); const params = { 'api_key': apiKey, 'timestamp': timeStamp, 'upload_preset': uploadPreset, 'signature': signature } const image = file let uploadRequest = superagent.post(url); uploadRequest.attach('file', image); Object.keys(params).forEach((key) => { uploadRequest.field(key, params[key]); }); return new Promise((resolve, reject) => { uploadRequest.end((err, res) => { if(err) { reject(err); } const uploaded = res.body; resolve(uploaded); }) }) } } export default new UploadImageService()
import React from 'react'; const RegistroPrueba = () => { return ( <React.Fragment> <div>formato de registro </div> </React.Fragment> ) } export default RegistroPrueba;
const log = console.log; var obj = require("readline-sync") var chalkobj = require("chalk") var user = obj.question("what is your name ") log("Welcome "+chalkobj.red(user)); var age = obj.question("How many levels of stars do you want ") function star(age) { //increamenting for(i=0;i<age;i++){ g = "" for(j=0;j<=i;j++) g=g+'* '; log(g) } //decreamenting for(i=age;i>0;i--){ h ="" for(j=i;j>0;j--) h=h+'* ' log(h) } } star(age)
class objectBase { obj; scene; color; constructor(url, scene, scale, color) { this.scene = scene; this.color = color; //Create cube as a place holder const geometry = new THREE.BoxGeometry(); const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 }); this.obj = new THREE.Mesh(geometry, material); // Load from url const loader = new THREE.GLTFLoader(); loader.load( url, res => { var x = this.obj.position.x; var y = this.obj.position.y; var z = this.obj.position.z; scene.remove(this.obj); res.scene.scale.set(scale, scale, scale); this.obj = res.scene; this.obj.position.set(x, y, z); scene.add(this.obj); }, undefined, function(error) { console.error(error); } ); scene.add(this.obj); } moveTo(x, y, z) { this.obj.position.set(x, y, z); } isJitter = 0; frameMove() {} }
const https = require('https') const fs = require('fs') const fsp = fs.promises const colors = require('colors') const LOG = { download: ' Download > '.bgBlue.yellow, saved : ' Saved √ '.bgGreen.white, exists : ' Existed ♪ '.bgWhite.red, failed : ' Failed × '.bgWhite.red, fetching: ' Fetching > '.bgBlue.white, fetched : ' Fetched √ '.bgGreen.white, retry : ' Re-try > '.bgBlue.white, list: ' List Page '.bgBlue.yellow, post: ' Post Page '.bgBlue.yellow, file: ' File '.bgBlue.yellow } function fetch(url, headers) { return new Promise((resolve, reject) => { https.get(url, { headers }, res => { let data = ''; if (res.statusCode === 302) { resolve(res.headers.location) return } res.on('data', chunk => data += chunk ); res.on('end', () => resolve(data)) }).on('error', reject) }) } function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)) } const fileExists = async path => !!(await fsp.stat(path).catch(() => false)); async function download(url, dest, reserveEmpty, options) { // Pre-Processing let path = dest.slice(0, dest.lastIndexOf('/')) let status = "init" if (!(await fileExists(path))) await fsp.mkdir(path, { recursive: true }) if (await fileExists(dest)) { // exist, check size const localFileSize = (await fsp.stat(dest)).size if (localFileSize > 0) { console.log(`${LOG.exists} ${LOG.file} ${url} skipped.`) status = await new Promise(resolve => { const checkFileReq = https.get(url, { ...options, method: 'HEAD' }, res => { resolve(+res.headers['content-length'] === localFileSize ? 'success' : 'init') }) checkFileReq.on('error', () => status = 'failed') }) } else { try { await fsp.unlink(dest) } catch { status = 'failed' } } } let fileStream = null if (status === 'init') { fileStream = fs.createWriteStream(dest); fileStream.on('error', err => { fileStream.close(); console.log(`${LOG.failed} ${LOG.file} ${err}, ${url} to ${dest}`) status = 'failed' }); console.log(`${LOG.download} ${LOG.file} ${url} to ${dest}`) } return new Promise((resolve, reject) => { if (status === 'success') return resolve(status) if (status === 'failed') return reject(`${status}: ${url}`) let rejectTimer = setTimeout(() => { if (fileStream.bytesWritten === 0) { fs.unlink(dest, () => {}) reject(`Time out: ${url}`) } }, 30000) https.get(url, options, function (response) { response.pipe(fileStream); fileStream.on('finish', () => { if (response.statusCode === 404 || response.statusCode === 403) { fileStream.close(); fs.unlink(dest, () => {}); console.log(`failed: ${url}`); reject(`failed: ${response.statusCode}, url: ${url}`) return; } fileStream.close(); if (fileStream.bytesWritten === 0 && !reserveEmpty) { fs.unlink(dest, () => {}) console.log(`got empty file at ${dest}, deleted`) } else { console.log(`${LOG.saved} ${url}`); } clearTimeout(rejectTimer) resolve(`succeed: ${url}`); }); }).on('error', function (err) { console.log(`failed on ${url}: ${err}`); fs.unlink(dest, () => {}); reject(`error occurred: ${err}`) }); }) } function purifyName(filename) { return filename.replaceAll(':', '').replaceAll('/', '').replaceAll('\\', '').replaceAll('>', '').replaceAll('<', '') .replaceAll('*:', '').replaceAll('|', '').replaceAll('?', '').replaceAll('"', '').replaceAll('.', '') } module.exports = { download, fetch, delay, LOG, fileExists, purifyName }
import React from 'react'; import { Link } from "react-router-dom"; export class ViewTodo extends React.Component { render() { const { todo, changeStatus, removeTodo, changeMode } = this.props; const { id , isDone, title } = todo; return ( <React.Fragment> <li className={"ui-state-default" + (isDone ? ' done' : '')} > <div className="checkbox"> <input type="checkbox" value="" checked={isDone} id={"checkFor" + id} onChange={changeStatus} /> <Link to={`${process.env.PUBLIC_URL}/view/${id}`}> {title} </Link> <button className="remove-item btn btn-default btn-xs pull-right" onClick={removeTodo}><span className="glyphicon glyphicon-remove"></span></button> <Link className="remove-item btn btn-default btn-xs pull-right" to={`${process.env.PUBLIC_URL}/edit/${id}`}>Full edit</Link> <button className="remove-item btn btn-default btn-xs pull-right" type="button" onClick={changeMode}>Edit Title</button> </div> </li> </React.Fragment> ) } }
import React, { Component } from 'react'; import './AddNew.css'; import { Button, Modal, Form, Input, TextArea, Dropdown, Label, Icon, Grid } from 'semantic-ui-react' export default class AddNew extends Component{ state = { openFunc: false, activeAddBox: false, activeFileBox: false, ancestors: this.props.ancestors, newData:[], viewCategory: this.props.viewCategory, AnswerType: 'default' }; componentWillReceiveProps = (nextProps) => { if (nextProps.category !== this.state.categoryList) { this.setState({ categoryList: nextProps.category }); } if (nextProps.ancestors !== this.state.ancestors) { this.setState({ ancestors: nextProps.ancestors }); } if (nextProps.viewCategory !== this.state.viewCategory) { if(nextProps.viewCategory === 'all'){ this.setState({ viewCategory: undefined}); }else{ this.setState({ viewCategory: nextProps.viewCategory}); } } } setDefaultData = () => { const category = this.state.viewCategory this.setState({ newData:{ "category": category, "division": "", "question": "", "answer": "", "topics": [], "date": "", "url": [], "images": [], "attachFiles": [], "isScenario": false, "id": "" } }) } handleOpenFileBox = () => { this.setState({activeFileBox: true}); }; answerType = (type) => { const newData = this.state.newData; // const type = e.target.value if (type === 'default'){ return ( <Form.Field control={TextArea} label='Answer Field' name='answer' placeholder='Answer Field' value={newData.answer} onChange={this.changeAddBox} /> ) }else{ const intentList = this.props.intentList; return( <Form.Field name='intentId' label='Intent' control='select' onChange={this.changeAddBox}> {intentList.map(({intentId, intentName}, i)=> <option value={intentId} key={i}>{intentName}</option> )} </Form.Field> ) } } render() { const topics = this.state.newData.topics; var categoryList = this.props.category; const newData = this.state.newData return( <div className="AddNew"> <ul className={this.state.openFunc === true ? 'addFunc active' : 'addFunc'}> <li className='add addOne' onClick={this.handleAddBox}> <i className="material-icons">note_add</i><br/> <span className="iconTitle">새 질문</span> </li> <li className='add addFile'> <label htmlFor='newFile'> <i className="material-icons">library_add</i><br/> <span className="iconTitle">새 파일</span> </label> <input className='newFile' id='newFile' name='newFile' type='file'/> </li> </ul> <Modal open={this.state.activeAddBox} // onClose={this.handleAddBox} dimmer={'blurring'} size='large' > <Modal.Header> <Dropdown text={newData.category !== undefined ? newData.category.toString() : 'Choose Category'} pointing='left'> <Dropdown.Menu> {categoryList !== undefined && categoryList.map(this.mksub)} </Dropdown.Menu> </Dropdown> </Modal.Header> <Modal.Content> <Form> <Grid columns={2} divided> <Grid.Row> <Grid.Column> <Form.Field control={TextArea} label='Question Field' name='question' placeholder='Question Field' value={newData.question} onChange={this.changeAddBox} /> <Form.Group inline> <Form.Radio label='일반답변' value='default' checked={this.state.AnswerType === 'default'} onChange={this.changeAnswerType} /> <Form.Radio label='Intent 연동' value='intent' checked={this.state.AnswerType === 'intent'} onChange={this.changeAnswerType} /> </Form.Group> {this.answerType(this.state.AnswerType)} </Grid.Column> <Grid.Column> <Form.Field control={Input} label='URL Field' name='url' placeholder='URL Field' value={newData.url} onChange={this.changeAddBox} /> <Form.Field control={Input} label='Tag Field' name='topics' placeholder='Tag Field' onKeyPress={(e)=>{ if(e.key === 'Enter'){ this.enterTag(e.target.value) e.target.value = '' } } } /> <div> {topics !== undefined && topics !== null ? topics.map(this.renderChip) : ''} </div> </Grid.Column> </Grid.Row> </Grid> </Form> </Modal.Content> <Modal.Actions> <Button icon labelPosition='left' secondary onClick={this.handleAddBox} > <Icon name='cancel' /> Cancel </Button> <Button icon labelPosition='left' primary onClick={this.saveAddBox} > <Icon name='save' /> Save </Button> </Modal.Actions> </Modal> <div className='addBtn' onClick={this.clickAddBtn}> <i className="material-icons">playlist_add</i> </div> {/* <div className='overlay' style={this.state.openFunc === true ? {display:'block'}:{display:'none'}}></div> */} </div> ) } mksub =({category, node}, i) => { if(node.length > 0) { if(node.length > 20){ return( <Dropdown scrolling item key={i} text={category}> <Dropdown.Menu> {node.map(this.mksub)} </Dropdown.Menu> </Dropdown> ) }else{ return( <Dropdown item key={i} text={category}> <Dropdown.Menu> {node.map(this.mksub)} </Dropdown.Menu> </Dropdown> ) } }else{ return( <Dropdown.Item key={i} name={category} onClick={this.changeAddBox}> {category} </Dropdown.Item> ) } } clickAddBtn = () => { this.setState({ openFunc:!this.state.openFunc }) } handleAddBox = (e) => { this.setState({ activeAddBox:!this.state.activeAddBox, }, ()=> { if(this.state.activeAddBox === false){ this.clickAddBtn() }else{ this.setDefaultData(); } }) } changeAddBox = (e, data) => { var key = e.target.name; var newData = this.state.newData if(data === undefined) //intent select { newData[key] = e.target.value }else{ var value = data.value if (key === undefined){ key = 'category'; value = data.name } newData[key] = value } this.setState({ newData: newData }) } saveAddBox = () => { const target = this.state.newData; if(target.answerType === undefined){ target['answerType'] = this.state.AnswerType }else{ target.answerType = this.state.AnswerType } this.props.addData(target, target.category) this.handleAddBox() } enterTag = (value) => { var changedState = this.state.newData; if(value !== undefined && value.length > 0){ if(changedState['topics'] === null){ changedState['topics'] = [] } changedState['topics'].push(value); this.setState({newData: changedState}); value = ''; } } renderChip = (data, i) => { return ( <Label key={i}> {data} <Icon name='delete' onClick={() => this.handleRequestDelete(i, data)} /> </Label> ); } styles = { chip: { margin: 4, display: 'inline-block', }, chipLabel:{ fontSize: '12px', float:'left' }, deleteIcon:{ width:'20px' }, wrapper: { display: 'flex', flexWrap: 'wrap', }, }; handleRequestDelete = (i) => { var chipData = this.state.newData.topics; chipData.splice(i, 1); var changedState = this.state.newData; changedState['topics'] = chipData; this.setState({newData: changedState}); } changeAnswerType = (e, data) => { const value= data.value; this.setState({ AnswerType: value }) } }
import React, { Component } from 'react'; import GameContainer from './game/GameContainer'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware, combineReducers, compose } from 'redux' import thunkMiddleware from 'redux-thunk' import createLogger from 'redux-logger' import playersReducer from './player/playersReducer'; var reducers = { players: playersReducer }; var rootReducer = combineReducers(reducers); const loggerMiddleware = createLogger(); var configureStore = function configureStore(initialState) { const store = createStore(rootReducer, initialState, compose( applyMiddleware( thunkMiddleware, loggerMiddleware ), window.devToolsExtension ? window.devToolsExtension() : f => f )); return store; }; export default class App extends Component { render() { return ( <Provider store={configureStore()}> <GameContainer/> </Provider> ); } }
const webpack = require('webpack'); const StaticSiteGeneratorPlugin = require('static-site-generator-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const builds = require('../builds'); const lodash = require('lodash'); const flatten = require('lodash/flatten'); const args = require('../args'); const isProductionBuild = process.env.NODE_ENV === 'production'; const thirdPartyModulesRegex = /node_modules\/(?!(seek-style-guide)\/).*/; const jsLoaders = [ { loader: require.resolve('babel-loader'), options: require('../babel/babel.config')({ webpack: true, tenant: args.tenant }) } ]; const makeCssLoaders = (options = {}) => { const { server = false, styleGuide = false } = options; const debugIdent = isProductionBuild ? '' : `${styleGuide ? '__STYLE_GUIDE__' : ''}[name]__[local]___`; return [ { loader: require.resolve(`css-loader${server ? '/locals' : ''}`), options: { modules: true, localIdentName: `${debugIdent}[hash:base64:7]`, minimize: isProductionBuild, importLoaders: 3 } }, { loader: require.resolve('postcss-loader'), options: { plugins: () => [ require('autoprefixer')({ browsers: [ '> 1%', 'Last 2 versions', 'ie >= 10', 'Safari >= 8', 'iOS >= 8' ] }) ] } }, { loader: require.resolve('less-loader') }, { // Hacky fix for https://github.com/webpack-contrib/css-loader/issues/74 loader: require.resolve('string-replace-loader'), options: { search: '(url\\([\'"]?)(\.)', replace: '$1\\$2', flags: 'g' } } ]; }; const makeCssInJsLoaders = (options = {}) => { const { server = false } = options; return [ { loader: require.resolve(`css-loader${server ? '/locals' : ''}`), options: { modules: true, importLoaders: 3 } }, { loader: require.resolve('postcss-loader'), options: { plugins: () => [ require('autoprefixer')({ browsers: [ '> 1%', 'Last 2 versions', 'ie >= 10', 'Safari >= 8', 'iOS >= 8' ] }) ] } }, { loader: require.resolve('css-in-js-loader') }, { loader: require.resolve('babel-loader') } ]; }; const makeImageLoaders = (options = {}) => { const { server = false } = options; return [ { loader: require.resolve('url-loader'), options: { limit: server ? 999999999 : 10000 } } ]; }; const svgLoaders = [ { loader: require.resolve('raw-loader') }, { loader: require.resolve('svgo-loader'), options: { plugins: [ { addAttributesToSVGElement: { attribute: 'focusable="false"' } } ] } } ]; const buildWebpackConfigs = builds.map(({ name, paths, env }) => { const envVars = lodash .chain(env) .mapValues((value, key) => { if (typeof value !== 'object') { return JSON.stringify(value); } const valueForProfile = value[args.profile]; if (typeof valueForProfile === 'undefined') { console.log( `WARNING: Environment variable "${key}" for build "${name}" is missing a value for the "${args.profile}" profile` ); process.exit(1); } return JSON.stringify(valueForProfile); }) .mapKeys((value, key) => `process.env.${key}`) .value(); return [ { entry: paths.clientEntry, output: { path: paths.dist, filename: '[name].js' }, module: { rules: [ { test: /(?!\.css)\.js$/, exclude: thirdPartyModulesRegex, use: jsLoaders }, { test: /(?!\.css)\.js$/, include: thirdPartyModulesRegex, use: [ { loader: require.resolve('babel-loader'), options: { babelrc: false, presets: [require.resolve('babel-preset-es2015')] } } ] }, { test: /\.css\.js$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: makeCssInJsLoaders() }) }, { test: /\.less$/, exclude: /node_modules/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: makeCssLoaders() }) }, { test: /\.less$/, include: paths.seekStyleGuide, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: makeCssLoaders({ styleGuide: true }) }) }, { test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/], use: makeImageLoaders() }, { test: /\.svg$/, use: svgLoaders } ] }, plugins: [ new webpack.DefinePlugin(envVars), new ExtractTextPlugin('style.css') ].concat( !isProductionBuild ? [] : [ new webpack.optimize.UglifyJsPlugin(), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) }) ] ) }, { entry: { render: paths.renderEntry }, output: { path: paths.dist, filename: '[name].js', libraryTarget: 'umd' }, module: { rules: [ { test: /(?!\.css)\.js$/, exclude: thirdPartyModulesRegex, use: jsLoaders }, { test: /\.css\.js$/, use: makeCssInJsLoaders({ server: true }) }, { test: /\.less$/, exclude: /node_modules/, use: makeCssLoaders({ server: true }) }, { test: /\.less$/, include: paths.seekStyleGuide, use: makeCssLoaders({ server: true, styleGuide: true }) }, { test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/], use: makeImageLoaders({ server: true }) }, { test: /\.svg$/, use: svgLoaders } ] }, plugins: [ new webpack.DefinePlugin(envVars), new StaticSiteGeneratorPlugin() ] } ]; }); module.exports = flatten(buildWebpackConfigs);
/* jshint indent: 2 */ module.exports = function(sequelize, DataTypes) { const Categories = sequelize.define('Categories', { id: { type: DataTypes.INTEGER(11), allowNull: false, primaryKey: true, autoIncrement: true }, title: { type: DataTypes.STRING, allowNull: false }, description: { type: DataTypes.TEXT, allowNull: true } }, { classMethods: { associate: (models) => { Categories.hasMany(models.Issues); } } }); return Categories; };
function reverseAndNot(i) { let str = ""; let num = i; while(num >= 1){ let rem = Math.floor(num%10); str += rem; num = Math.floor(num/10); } return (str+`${i}`); } console.log(reverseAndNot(123)); console.log(reverseAndNot(152)); console.log(reverseAndNot(123456789));
P.models.programs.Clone = P.Model.extend({ urlRoot: '/api/program-clone', toJSON: function() { var userID = this.get('user_id') || '', programID = this.get('program_id') || ''; return { 'user_id': String(userID), 'program_id': String(programID) }; } });
angular.module('cnnxtMobile.services', []) .factory('Departments', function($q, Restangular) { return { getByCategoryId: function (categoryId) { //URL is action=get_departments_by_floor_id&floor=1 var queryObj = { action: 'get_departments_by_floor_id', floor: categoryId }; return Restangular.oneUrl('api').getList('', queryObj); }, getByDepartmentId: function (departmentId) { // URL is action=get_hotspots_smh&hotspot_id=123&type=department&hospital_id=9 var queryObj = { action: 'get_hotspots_smh', hotspot_id: departmentId, type: 'department', hospital_id: '9' //For globe demo }; return Restangular.oneUrl('api').getList('', queryObj); } }; }) .factory('Categories', function ($q, Restangular) { return { all: function () { var queryObj = { action: 'get_hotspot_categories_smh', device: 'iphone' }; return Restangular.oneUrl('api').getList('', queryObj); }, allFake: function () { var deferred = $q.defer(); var deps = new Array(); var mapIds = {}; $.getJSON("json/categories.json", function (data) { $.each(data, function (i, row) { deps[i] = { category_id: row.id, name: row.name }; mapIds[deps[i].map_id] = deps[i].name; }); deferred.resolve(deps); }); return deferred.promise; } }; });
//Create variables here var dog,dogImg,happydog,database,food,foodstock; function preload() { //load images here dogImg=loadImage("images/dogImg.png"); happydog=loadImage("images/dogImg1.png"); } function setup() { createCanvas(500, 500); database=firebase.database(); dog=createSprite(250,300,150,150); dog.addImage(dogImg); dog.scale=0.15; foodstock=database.ref('Food'); foodstock.on("value",readstock); } function draw() { background("blue"); drawSprites(); //add styles here fill("black"); text("food remaining "+ food,170,200); } function readstock(data){ food=data.val(); }
import React, { Component } from 'react'; import { Link } from 'react-router'; class Item extends Component { render(){ return ( <div className="item"> <li> <Link to={{ pathname: '/dashboard'+this.props.path }}> <i className={this.props.icon} aria-hidden="true"/> { this.props.text } </Link> </li> </div> ); } } Item.PropTypes = { path: React.PropTypes.string.isRequired, icon: React.PropTypes.string.isRequired, text: React.PropTypes.string.isRequired }; export default Item;
exports.up = function(knex, Promise) { return Promise.all([ knex.schema.createTable('events', (table) => { table.increments('id').primary(); table.string('title').notNullable(); table.date('startDate').notNullable(); table.date('endDate').notNullable(); table.string('link').nullable(); table.string('desc').nullable(); table.string('location').notNullable(); table.boolean('special').defaultTo(false).notNullable(); table.boolean('featured').defaultTo(false).notNullable(); table.string('imageUrl').nullable(); }) ]); }; exports.down = function(knex, Promise) { return Promise.all([ knex.schema.dropTable('events'), ]); };