text
stringlengths 7
3.69M
|
|---|
import Taro, { Component } from '@tarojs/taro'
import { View, Text, Image, Button, Checkbox} from '@tarojs/components';
import './classification.less'
export default class Index extends Component {
render() {
return (
<View className='index'>
分类页面
</View>
)
}
}
|
var local_database =[
{
"id": "guowei",
"banner": "/images/c1.png",
"cate": "果味",
"detail": [
{
"thumb": "/images/c2.png",
"name": "梨花带雨 3个"
},
{
"thumb": "/images/c3.png",
"name": "红枣 500g"
},
{
"thumb": "/images/c4.png",
"name": "奇异果 2个"
},
{
"thumb": "/images/c4.png",
"name": "奇异果 2个"
},
{
"thumb": "/images/c3.png",
"name": "红枣 500g"
},
{
"thumb": "/images/c2.png",
"name": "梨花带雨 3个"
}
]
},
{
"id": "shucai",
"banner": "/images/c1.png",
"cate": "蔬菜",
"detail": [
{
"thumb": "/images/s4.png",
"name": "瓜子 3个"
},
{
"thumb": "/images/s5.png",
"name": "芹菜 500g"
},
{
"thumb": "/images/s6.png",
"name": "小米"
},
{
"thumb": "/images/s6.png",
"name": "小米"
},
{
"thumb": "/images/s5.png",
"name": "芹菜 500g"
},
{
"thumb": "/images/s4.png",
"name": "瓜子 4个"
}
]
},
{
"id": "chaohuo",
"banner": "/images/c1.png",
"cate": "炒货",
"detail": [
{
"thumb": "/images/c2.png",
"name": "梨花带雨 3个"
},
{
"thumb": "/images/c3.png",
"name": "红枣 500g"
},
{
"thumb": "/images/c4.png",
"name": "奇异果 2个"
},
{
"thumb": "/images/c4.png",
"name": "奇异果 2个"
},
{
"thumb": "/images/c3.png",
"name": "红枣 500g"
},
{
"thumb": "/images/c2.png",
"name": "梨花带雨 3个"
}
]
},
{
"id": "dianxin",
"banner": "/images/c1.png",
"cate": "点心",
"detail": [
{
"thumb": "/images/s4.png",
"name": "瓜子 3个"
},
{
"thumb": "/images/s5.png",
"name": "芹菜 500g"
},
{
"thumb": "/images/s6.png",
"name": "小米"
},
{
"thumb": "/images/s6.png",
"name": "小米"
},
{
"thumb": "/images/s5.png",
"name": "芹菜 500g"
},
{
"thumb": "/images/s4.png",
"name": "瓜子 4个"
}
]
},
{
"id": "cucha",
"banner": "/images/c1.png",
"cate": "粗茶",
"detail": [
{
"thumb": "/images/c2.png",
"name": "梨花带雨 3个"
},
{
"thumb": "/images/c3.png",
"name": "红枣 500g"
},
{
"thumb": "/images/c4.png",
"name": "奇异果 2个"
},
{
"thumb": "/images/c4.png",
"name": "奇异果 2个"
},
{
"thumb": "/images/c3.png",
"name": "红枣 500g"
},
{
"thumb": "/images/c2.png",
"name": "梨花带雨 3个"
}
]
},
{
"id": "danfan",
"banner": "/images/c1.png",
"cate": "淡饭",
"detail": [
{
"thumb": "/images/s4.png",
"name": "瓜子 3个"
},
{
"thumb": "/images/s5.png",
"name": "芹菜 500g"
},
{
"thumb": "/images/s6.png",
"name": "小米"
},
{
"thumb": "/images/s6.png",
"name": "小米"
},
{
"thumb": "/images/s5.png",
"name": "芹菜 500g"
},
{
"thumb": "/images/s4.png",
"name": "瓜子 4个"
}
]
}
]
var order=[
{
"number": "A4561245678641685",
"thumb": "/images/c2.png",
"name": "梨花带雨",
"count": 3,
"status": "待付款",
"money": 5.00
}
]
var list=[
{
"id":0,
"image":"/images/s1.png",
"detail": [
{
"thumb": "/images/s4.png",
"name": "瓜子 3个",
"price": "0.02"
},
{
"thumb": "/images/s5.png",
"name": "芹菜 500g",
"price": "0.03"
},
{
"thumb": "/images/s6.png",
"name": "小米",
"price": "0.02"
},
{
"thumb": "/images/s6.png",
"name": "小米",
"price": "0.04"
},
{
"thumb": "/images/s5.png",
"name": "芹菜 500g",
"price": "0.06"
},
{
"thumb": "/images/s4.png",
"name": "瓜子 4个",
"price": "0.06"
}
]
},
{
"id": 1,
"image": "/images/s2.png",
"detail": [
{
"thumb": "/images/c2.png",
"name": "梨花带雨 3个",
"price":"0.01"
},
{
"thumb": "/images/c3.png",
"name": "红枣 500g",
"price": "0.02"
},
{
"thumb": "/images/c4.png",
"name": "奇异果 2个",
"price": "0.01"
},
{
"thumb": "/images/c4.png",
"name": "奇异果 2个",
"price": "0.03"
},
{
"thumb": "/images/c3.png",
"name": "红枣 500g",
"price": "0.01"
},
{
"thumb": "/images/c2.png",
"name": "梨花带雨 3个",
"price": "0.01"
}
]
},
{
"id": 2,
"image": "/images/s3.png",
"detail": [
{
"thumb": "/images/s4.png",
"name": "瓜子 3个",
"price": "0.02"
},
{
"thumb": "/images/s5.png",
"name": "芹菜 500g",
"price": "0.03"
},
{
"thumb": "/images/s6.png",
"name": "小米",
"price": "0.02"
},
{
"thumb": "/images/s6.png",
"name": "小米",
"price": "0.04"
},
{
"thumb": "/images/s5.png",
"name": "芹菜 500g",
"price": "0.06"
},
{
"thumb": "/images/s4.png",
"name": "瓜子 4个",
"price": "0.06"
}
]
},
]
module.exports = {
dataList: local_database,
orderList:order,
List:list
}
|
import React, { Component, Fragment } from 'react'
import {
Collapse,
Navbar,
NavbarToggler,
NavbarBrand,
Nav,
NavItem,
NavLink,
Container,
Alert,
Badge
} from 'reactstrap'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import Logout from './users/Logout'
class NavigationBar extends Component {
state = {
isOpen: false
}
toggle = () => {
this.setState({
isOpen: !this.state.isOpen
})
}
render() {
const { isAuthenticated, user } = this.props.authentication
// let cartItems
// let parsedCartItems
// if (user) {
// cartItems = user.cartItems
// parsedCartItems = JSON.stringify(cartItems)
// console.log(parsedCartItems)
// }
const loggedIn = (
<Fragment>
<NavItem>
<span className="navbar-text mr-3">
<strong>{user ? `Hello, ${user.name}!` : ''}</strong>
</span>
</NavItem>
<NavItem>
<NavLink href="/products">
Start Shopping
</NavLink>
</NavItem>
<NavItem>
<NavLink href="/cart">
Cart
</NavLink>
</NavItem>
<NavItem>
<NavLink href="/orders/history">
Order History
</NavLink>
</NavItem>
<NavItem>
<Logout />
</NavItem>
</Fragment>
)
const adminLoggedIn = (
<Fragment>
<NavItem>
<span className="navbar-text mr-3">
<strong>{user ? `Hello, ${user.name}!` : ''}</strong>
</span>
</NavItem>
<NavItem>
<NavLink href="/products/add">
Add Products
</NavLink>
</NavItem>
<NavItem>
<NavLink href="/products">
View Products
</NavLink>
</NavItem>
<NavItem>
<NavLink href="/users">
View Users
</NavLink>
</NavItem>
<NavItem>
<Logout />
</NavItem>
</Fragment>
)
const notLoggedIn = (
<Fragment>
<NavItem>
<NavLink href="/users/signup">
Sign Up
</NavLink>
</NavItem>
<NavItem>
<NavLink href="/users/login">
Log In
</NavLink>
</NavItem>
</Fragment>
)
return (
<div>
<Navbar dark expand="md" className="mb-5" style={{ backgroundColor: '#783dbf' }}>
<Container>
<NavbarBrand href="/">J-Mart</NavbarBrand>
<NavbarToggler onClick={this.toggle} />
<Collapse isOpen={this.state.isOpen} navbar>
<Nav className="ml-auto" navbar>
{user ? (<Fragment>{user.email == 'admin@test.com' ? (adminLoggedIn) : (loggedIn)}</Fragment>) : notLoggedIn}
</Nav>
</Collapse>
</Container>
</Navbar>
</div>
)
}
}
NavigationBar.propTypes = {
authentication: PropTypes.object.isRequired
}
const mapStateToProps = (state) => ({
authentication: state.authentication
})
export default connect(mapStateToProps, {})(NavigationBar)
|
var baseFontSize = 5;
var generalAttributes = {
"font-size":baseFontSize,
"bias":0,
"max-width-focus": "34vw"
}
var initialAttributes = {
wrap_lena: {
left: "70%",
top: "10%",
bias: "280",
"scale":1,
"max-width": "8vw"
},
wrap_jasper: {
left: "50%",
top: "30%",
bias: "130",
"scale":1,
"max-width": "9vw"
},
wrap_luci: {
left: "11%",
top: "28%",
bias: "20",
"scale":1,
"max-width": "10vw"
},
wrap_luca: {
left: "38%",
top: "61%",
bias: "150",
"scale":1,
"max-width": "9vw"
},
wrap_amelie: {
left: "75%",
top: "45%",
bias: 350,
"scale":1,
"max-width": "16vw",
"max-width-focus": "45vw",
},
wrap_clara: {
left: "31%",
top: "5%",
bias: "80",
"scale":1,
"max-width": "13vw"
}
}
function ID(elem) {
return $(elem).attr("id")
}
var getAttributeAsNumber = function(id, attr) {
var attribute = getAttribute(id, attr);
var attribute = attribute.replace(/[a-zA-Z]/, "")
return parseFloat(attribute)
}
var getAttribute = function(id, attr) {
var specific = initialAttributes[id][attr];
if (specific === undefined)
return generalAttributes[attr];
return specific
}
var setAttribute = function (id, attr, value) {
return initialAttributes[id][attr] = value;
}
var hasClass = function (elem, someClass) {
var classList = $(elem).attr("class").split(/\s+/);
for (var i = 0; i < classList.length; i++) {
if (classList[i] === someClass) {
return true;
}
}
return false;
}
var setTextScale = function (elem, scale) {
let id = ID(elem)
setAttribute(id, "scale", scale)
return move("#" + id)
.ease("out")
.set("font-size", ""+baseFontSize*scale+"pt")
.duration("0.1")
}
var applyInitialStates = function (duration) {
$(".wrap").each(function () {
applyInitialState(this, duration).end()
})
}
var applyInitialState = function(elem, duration) {
let id = ID(elem)
attributes = initialAttributes[id]
moveFunc = move("#" + id)
.duration(duration)
.x(0)
.set("margin-left", 0)
for (var attribute in attributes) {
moveFunc = moveFunc
.set(attribute, attributes[attribute])
}
return moveFunc
}
var calcCenterOfObject = function(elem){
var pos = $(elem).position()
var height = $(elem).height()
var width = $(elem).width()
var result = {x:pos.left + width/2,
y:pos.top + height/2}
// console.log("pos: "+pos)
// console.log("height, width:"+height+", "+width)
// console.log("center of element: "+result)
return result
}
$(document).ready(function () {
// initially move each text to its position
applyInitialStates("0.0s")
$(".wrap").each(function () {
move("#" + ID(this))
.set("opacity", "1")
.ease("out")
.delay("0.4s")
.duration("1.2s")
.end()
move("#" + ID(this)).delay("0s").end()
})
// fade-out schriftzug "ohne routine"
move(".gross")
.ease("out")
.set("opacity", "0.05")
.delay("0.4s")
.duration("1.2s")
.end()
// reaction of small texts on hover
$(".wrap").hover(function () {
let id = ID(this)
if (!hasClass(this, "focus")) {
move("#" + id)
.set("font-size", getAttribute(id, "scale")*(baseFontSize+1)+"pt")
.duration("0.25")
.end();
}
}, function () {
let id = ID(this);
move("#" + id)
.set("font-size", getAttribute(id, "scale") * baseFontSize + "pt")
.duration("0.25")
.end();
})
// click on any text -
$(".wrap").click(function () {
let idClicked = ID(this);
// todo: transform to using moveObject instead of triggering every animation straight away - might solve some problems
let moveObjects = {
wrap_lena: move('#'+"wrap_lena"),
wrap_jasper: move('#'+"wrap_jasper"),
wrap_luci: move('#'+"wrap_luci"),
wrap_luca: move('#'+"wrap_luca"),
wrap_amelie: move('#'+"wrap_amelie"),
wrap_clara: move('#'+"wrap_clara")
}
// all texts change scale to small
$(".wrap").each(function () {
$(this).removeClass("focus")
setTextScale(this, 1).end()
applyInitialState(this, "0.15s").end()
})
// clicked text toggles scale
if (!hasClass(this, "focus")) {
$(this).addClass("focus")
move("#" + idClicked)
.x(0)
.set("font-size", getAttribute(idClicked, "scale") * baseFontSize + "pt")
.duration("0.15")
.end();
setTextScale(this, 3.2)
.set("top", "2%")
.sub("margin-left", getAttribute(idClicked, "bias"))
.set("max-width", getAttribute(idClicked, "max-width-focus"))
.end()
} else {
$(this).removeClass("focus")
setTextScale(this, 1.0).end()
applyInitialState(this, "0.15s");
return
}
// all other texts are moved to the side
const centerBeforeClick = calcCenterOfObject(this)
const windowWidth = jQuery(window).width()
const leftBorderClicked = $(this).position().left - getAttribute(idClicked, "bias")
const widthClicked = getAttributeAsNumber(idClicked, "max-width-focus") / 100 * windowWidth
const rightBorderClicked = leftBorderClicked + widthClicked
// console.log("viewport: " + jQuery(window).width()+", leftBorderClicked: "+leftBorderClicked+", rightBorderClicked: "+rightBorderClicked+", widthClicked: "+widthClicked)
$(".wrap").each(function () {
if (hasClass(this, "focus"))
return;
thisMove = applyInitialState(this, "0.1s").end()
const center = calcCenterOfObject(this)
if (center.x < centerBeforeClick.x){
let newPositionX = center.x/centerBeforeClick.x*leftBorderClicked*0.9
let change = newPositionX - center.x
move('#'+ID(this))
.ease("out")
.x(change-20)
.duration("0.15s")
.end()
} else {
const w = windowWidth
// todo: calculate
let newPositionX = w - (w - center.x)/(w - centerBeforeClick.x)*(w - rightBorderClicked) * 0.9
let change = newPositionX - center.x
move('#' + ID(this))
.ease("out")
.x(change + 20)
.duration("0.15s")
.end()
}
})
})
// clicking background minimizes all texts
$("body .gross").click(function () {
$(".wrap").each(function () {
setTextScale(this, 1).end()
$(this).removeClass("focus")
applyInitialState(this, "0.15s").end()
})
})
// todo: when you mark text, it recognizes it as a click
});
|
require('angular');
require('angular-material');
require('angular-material/angular-material.css');
require('angular-ui-router');
require('./general.style.scss');
require('./app.style.scss');
var dependencies = ['ngMaterial', 'ui.router'];
var moduleName = 'myApp';
var ngModule = angular.module(moduleName, dependencies);
require('./app.component')(ngModule);
require('./components/viewOne/viewOne.component')(ngModule);
require('./components/viewTwo/viewTwo.component')(ngModule);
|
import React, { Component } from 'react';
import Slider from 'react-slick';
class Gallery extends Component {
constructor(props) {
super(props);
this.state = {paintings:this.props.images}
}
render() {
const settings = {
infinite: true,
centerMode: true,
responsive:[
{
breakpoint: 600,
settings: {
slidesToShow: 1,
slidesToScroll: 1
},
},
{
breakpoint: 900,
settings: {
slidesToShow: 2,
slidesToScroll: 2
},
},
{
breakpoint: 1200,
settings: {
slidesToShow: 3,
slidesToScroll: 3
},
},{
breakpoint: 1500,
settings: {
slidesToShow: 4,
slidesToScroll: 4
},
},{
breakpoint: 1800,
settings: {
slidesToShow: 5,
slidesToScroll: 5
},
},
{
breakpoint: 2100,
settings: {
slidesToShow: 6,
slidesToScroll: 6
},
},
{
breakpoint: 10000,
settings: {
slidesToShow: 7,
slidesToScroll: 7
},
}
]
};
var paintings = this.props.images;
if(paintings.length==0){
return(<div></div>)
}else{
return (
<Slider {...settings}>
{paintings.map((image, index) => {
return(
<div key={index}><img key={index} src={image} className="slideshow-size" /></div>
)
})}
</Slider>
);
}
}
}
export default Gallery
|
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/styles';
import Grid from '@material-ui/core/Grid';
import Avatar from '@material-ui/core/Avatar';
import { get } from '../../../../RESTful_API';
const MemberTypeIconStatus = (props) => {
// const [share, setShare] = useState(null)
// useEffect((updateShare))
// const updateShare = () => {
// get.share.id(props.status.share.id).then((data) => {
// setShare(data)
// })
// }
return (
<React.Fragment>
<Grid container style={{
width: 'min-content',
position: 'absolute',
top: '100px',
}} >
<Avatar
alt="Remy Sharp"
src={props.share !== null ? props.share.owner.profile.photoURL : null}
className={props.classes.mediumAvatar}
style={{
border: '4px solid #fff',
boxShadow: '0px 1px 5px 0px rgba(0,0,0,0.2), 0px 2px 2px 0px rgba(0,0,0,0.14), 0px 3px 1px -2px rgba(0,0,0,0.12)'
}}
/>
{props.share !== null
? (<React.Fragment>
{props.share.member !== undefined
? (<React.Fragment>
{Object.keys(props.share.member).map((key) => (
<React.Fragment>
{key !== props.share.owner.id
?(<Avatar
alt="Remy Sharp"
src={props.share.member[key].profile.photoURL}
className={props.classes.mediumAvatar}
style={{
border: '4px solid #fff',
boxShadow: '0px 1px 5px 0px rgba(0,0,0,0.2), 0px 2px 2px 0px rgba(0,0,0,0.14), 0px 3px 1px -2px rgba(0,0,0,0.12)'
}}
/>)
:(<React.Fragment></React.Fragment>)
}
</React.Fragment>
))}
</React.Fragment>)
: (<React.Fragment></React.Fragment>)}
</React.Fragment>)
: (<React.Fragment></React.Fragment>)}
</Grid>
</React.Fragment>
)
}
const styles = {
mediumAvatar: {
margin: '5px 10px',
width: 45,
height: 45,
}
}
MemberTypeIconStatus.propTypes = {
uid: PropTypes.string
}
export default withStyles(styles)(MemberTypeIconStatus)
|
'use strict'
const multiaddr = require('multiaddr')
const TCP = require('libp2p-tcp')
const tcp = new TCP()
module.exports = cb => {
const server = tcp.createListener()
server.listen(multiaddr('/ip4/127.0.0.1/tcp/0'))
server.once('listening', () => {
server.getAddrs((err, addr) => {
if (err) return cb(err)
const client = tcp.dial(addr[0])
server.on('connection', sclient => cb(null, client, sclient))
})
})
}
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use script';
/* Record layout:
* 00: MessageType
* 01: Length MSB
* 02: Length (continued)
* 03: Length LSB
* 04: Message Sequence MSB
* 05: Message Sequence LSB
* 06: Fragment Offset MSB
* 07: Fragment Offset (continued)
* 08: Fragment Offset LSB
* 09: Fragment Length MSB
* 10: Fragment Length (continued)
* 11: Fragment Length LSB
* 12+: Message
*/
let enums = require('../enums.js');
// constants
const HEADER_LENGTH = 12;
//
const MAX_LENGTH = (1 << 24) - 1;
const MAX_FRAGMENT_OFFSET = (1 << 24) - 1;
const MAX_FRAGMENT_LENGTH = (1 << 24) - 1;
function DtlsHandshakeRecord() {
this.messageType = null;
this.length = null;
this.messageSequence = null; // 16 bit (handshake sequence # which does not change during retransmission/fragmentation, not to be confused with the session's underlying epoch+sequenceNumber combination which must generate a new number during transmission)
this.fragmentOffset = null; // 24 bit
this.fragmentLength = null; // 24 bit
this.message = null;
}
exports.createFromMessageBuffer = function(type, length, messageSequence, fragmentOffset, fragmentLength, messageBuffer) {
// validate inputs
//
// type
if (!enums.isMessageTypeValid(type)) {
throw new RangeError();
}
// length
// note: all positive integers up to (2^24)-1 are valid for length
if (typeof length !== "number") {
throw new TypeError();
} else if ((length < 0) || (length > MAX_LENGTH) || (Math.floor(length) != length)) {
throw new RangeError();
}
// messageSequence
// note: all positive integers up to (2^16)-1 are valid for messageSequence
if (typeof messageSequence !== "number") {
throw new TypeError();
} else if ((messageSequence < 0) || (messageSequence > Math.pow(2, 16) - 1) || (Math.floor(messageSequence) != messageSequence)) {
throw new RangeError();
}
// fragmentOffset
// note: all positive integers up to (2^24)-1 are valid for fragmentOffset
if (typeof fragmentOffset !== "number") {
throw new TypeError();
} else if ((fragmentOffset < 0) || (fragmentOffset > MAX_FRAGMENT_OFFSET) || (Math.floor(fragmentOffset) != fragmentOffset)) {
throw new RangeError();
}
// fragmentLength
// note: all positive integers up to (2^24)-1 are valid for fragmentLength
if (typeof fragmentLength !== "number") {
throw new TypeError();
} else if ((fragmentLength < 0) || (fragmentLength > MAX_FRAGMENT_LENGTH) || (Math.floor(fragmentLength) != fragmentLength)) {
throw new RangeError();
}
// messageBuffer
if (Object.prototype.toString.call(messageBuffer) != "[object Uint8Array]") {
throw new TypeError();
} else if (messageBuffer.length > MAX_FRAGMENT_LENGTH) {
throw new RangeError();
} else if (messageBuffer.length < fragmentLength) {
throw new RangeError();
}
// also validate that our total length is at least as large as the fragmentOffset + fragmentLength
if (length < fragmentOffset + fragmentLength)
{
throw new RangeError();
}
// create and initialize the new DtlsHandshake record object
let result = new DtlsHandshakeRecord();
result.length = length;
result.messageType = type;
result.messageSequence = messageSequence;
result.fragmentOffset = fragmentOffset;
result.fragmentLength = fragmentLength;
result.message = messageBuffer;
// return the new DtlsHandshake record object
return result;
}
// NOTE: this function returns null if a complete record could not be parsed (and does not validate any data in the returned record)
// NOTE: offset is optional (default: 0)
exports.fromBuffer = function(buffer, offset) {
// use currentOffset to track the current offset while reading from the buffer
let initialOffset;
let currentOffset;
// validate inputs
//
// offset
if (typeof offset === "undefined") {
initialOffset = 0;
} else if (typeof offset !== "number") {
// if the offset is provided, but is not a number, then return an error
throw new TypeError();
} else if (offset >= buffer.length) {
throw new RangeError();
} else {
initialOffset = offset;
}
currentOffset = initialOffset;
// buffer
if (typeof buffer === "undefined") {
throw new TypeError();
} else if (buffer === null) {
// null buffer is NOT acceptable
} else if (Object.prototype.toString.call(buffer) != "[object Uint8Array]") {
throw new TypeError();
} else if (buffer.length - currentOffset < HEADER_LENGTH) {
// buffer is not long enough for a full record; return null.
return null;
}
// create the new DtlsHandshakeRecord object
let result = new DtlsHandshakeRecord();
// parse buffer
//
// type (octet 0)
result.messageType = buffer[currentOffset];
currentOffset += 1;
// length (octets 1-3)
result.length = buffer.readUIntBE(currentOffset, 3);
currentOffset += 3;
// messageSequence (octets 4-5)
result.messageSequence = buffer.readUInt16BE(currentOffset);
currentOffset += 2;
// fragmentOffset (octets 6-8)
result.fragmentOffset = buffer.readUIntBE(currentOffset, 3);
currentOffset += 3;
// fragmentLength (octets 9-11)
result.fragmentLength = buffer.readUIntBE(currentOffset, 3);
currentOffset += 3;
// verify that the buffer length is long enough to fit the message
if (buffer.length - currentOffset < result.fragmentLength) {
// if the buffer is not big enough, return null
return null;
}
// message
result.message = Buffer.alloc(result.fragmentLength);
buffer.copy(result.message, 0, currentOffset, currentOffset + result.fragmentLength);
currentOffset += result.fragmentLength;
// return the new DtlsHandshakeRecord object
return {record: result, bytesConsumed: currentOffset - initialOffset};
}
DtlsHandshakeRecord.prototype.toBuffer = function() {
// create our buffer (which we will then populate)
let result = Buffer.alloc(HEADER_LENGTH + this.message.length);
// use offset to track the current offset while writing to the buffer
let offset = 0;
// populate record header
//
// type (octet 0)
result[offset] = this.messageType;
offset += 1;
// length (octets 1-3)
result.writeUIntBE(this.length, offset, 3);
offset += 3;
// messageSequence (octets 4-5)
result.writeUInt16BE(this.messageSequence, offset);
offset += 2;
// fragmentOffset (octets 6-8)
result.writeUIntBE(this.fragmentOffset, offset, 3);
offset += 3;
// fragmentLength (octets 9-11)
result.writeUIntBE(this.fragmentLength, offset, 3);
offset += 3;
// message
this.message.copy(result, offset, 0, this.message.length);
offset += this.message.length;
// return the buffer (result)
return result;
}
|
/// <reference name="MicrosoftAjax.js"/>
Type.registerNamespace("Fenetre.Sitefinity.FormHandler");
Fenetre.Sitefinity.FormHandler.FormHandler = function (element) {
Fenetre.Sitefinity.FormHandler.FormHandler.initializeBase(this, [element]);
};
Fenetre.Sitefinity.FormHandler.FormHandler.prototype = {
/* --------------------------------- set up and tear down --------------------------------- */
initialize: function () {
Fenetre.Sitefinity.FormHandler.FormHandler.callBaseMethod(this, 'initialize');
},
dispose: function () {
Fenetre.Sitefinity.FormHandler.FormHandler.callBaseMethod(this, 'dispose');
}
};
Fenetre.Sitefinity.FormHandler.FormHandler.registerClass('Fenetre.Sitefinity.FormHandler.FormHandler', Telerik.Sitefinity.Modules.Forms.Web.UI.FormsControl);
|
module.exports = {
exec: function () {
console.log('dep3-1-1');
}
};
|
export default class GraphService {
constructor() {
this.graphUrl = 'https://graph.windows.net/f01e0225-ee80-4bf3-bfda-e665281c6534';
this.getUserInfo = this.getUserInfo.bind(this);
}
getUserInfo(token, displayName) {
const headers = new Headers({ Authorization: `Bearer ${token}` });
const options = {
headers
};
return fetch(`${this.graphUrl}/users?api-version=1.6`, options)
.then(response => response.json())
.catch(response => {
throw new Error(response.text());
});
};
}
|
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
import RestaurantCards from "./RestaurantCards";
describe("Smoke test", () => {
it("RestaurantCards component renders without crashing", () => {
const div = document.createElement("div");
ReactDOM.render(
<BrowserRouter>
<RestaurantCards />
</BrowserRouter>,
div
);
ReactDOM.unmountComponentAtNode(div);
});
});
|
class TestResult {
constructor(name, isSuccess) {
this.name = name;
this.isSuccess = isSuccess;
}
toString() {
if (this.isSuccess) {
return `[success] ${this.name}`;
} else {
return `[failed] ${this.name}`;
}
}
}
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const User = require('./user');
const scoreSchema = mongoose.Schema(
{
userId: {
type: mongoose.ObjectId
},
point: {
type: Number
},
user: { type: Schema.Types.ObjectId, ref: User }
},
{
collection: 'score'
}
);
const Score = mongoose.model('score', scoreSchema);
module.exports = Score;
|
const { entity, field } = require('@herbsjs/gotu')
const Repository = require('../../src/repository')
const assert = require('assert')
describe('Query Find', () => {
context('Find all data', () => {
const givenAnEntity = () => {
const ParentEntity = entity('A Parent Entity', {})
return entity('A entity', {
id: field(String),
numberTest: field(Number),
stringTest: field(String),
booleanTest: field(Boolean),
entityTest: field(ParentEntity),
entitiesTest: field([ParentEntity]),
})
}
const givenAnRepositoryClass = (options) => {
return class ItemRepositoryBase extends Repository {
constructor(options) {
super(options)
}
}
}
const mongoNoFilter = (ret, spy = {}) =>
({
collection: (f) => {
spy.collectionName = f
return {
find: (p,o) => {
spy.payload = p
return {
toArray: () => {
return ret
},
count: () => {
return 2
}
}
}
}
}
})
it('should return entities using table field', async () => {
//given
let spy = {}
const retFromDeb = [
{ _id: "60edc25fc39277307ca9a7ff", number_test: 100, boolean_test: true, string_test: 'aString' },
{ _id: "70edc25fc39277307ca9a700", number_test: 200, boolean_test: false }
]
const anEntity = givenAnEntity()
const ItemRepository = givenAnRepositoryClass()
const itemRepo = new ItemRepository({
entity: anEntity,
collection: 'aCollection',
ids: ['id'],
mongodb: mongoNoFilter(retFromDeb, spy)
})
//when
const ret = await itemRepo.find({})
//then
assert.strictEqual(ret.length, 2)
})
})
context('Find with conditions', () => {
const givenAnEntity = () => {
const ParentEntity = entity('A Parent Entity', {})
return entity('A entity', {
id: field(String),
stringTest: field(String),
numberTest: field(Number),
booleanTest: field(Boolean),
entityTest: field(ParentEntity),
entitiesTest: field([ParentEntity]),
})
}
const givenAnRepositoryClass = (options) => {
return class ItemRepositoryBase extends Repository {
constructor(options) {
super(options)
}
}
}
const mongo = (ret, spy = {}) =>
({
collection: (f) => {
spy.collectionName = f
return {
find: (p,o) => {
spy.payload = p
return {
toArray: () => {
return ret
},
count: () => {
return 2
}
}
}
}
}
})
it('should return entities using table field', async () => {
//given
let spy = {}
const retFromDeb = [
{ _id: "60edc25fc39277307ca9a7ff", number_test: 100, boolean_test: true, string_test: 'aString' },
{ _id: "70edc25fc39277307ca9a700", number_test: 200, boolean_test: false }
]
const anEntity = givenAnEntity()
const ItemRepository = givenAnRepositoryClass()
const itemRepo = new ItemRepository({
entity: anEntity,
collection: 'aCollection',
ids: ['id'],
mongodb: mongo(retFromDeb, spy)
})
//when
const ret = await itemRepo.find({ filter: { stringTest: ["aString"] } })
//then
assert.deepStrictEqual(ret[0].toJSON(), { id: '60edc25fc39277307ca9a7ff', stringTest: "aString", numberTest: 100, booleanTest: true , entityTest: undefined, entitiesTest: undefined })
assert.deepStrictEqual(ret[0].isValid(),true )
})
it('should return error because a wrong search', async () => {
//given
let spy = {}
const retFromDeb = [
{ _id: "60edc25fc39277307ca9a7ff", number_test: 100, boolean_test: true, string_test: 'aString' },
{ _id: "70edc25fc39277307ca9a700", number_test: 200, boolean_test: false }
]
const anEntity = givenAnEntity()
const ItemRepository = givenAnRepositoryClass()
const itemRepo = new ItemRepository({
entity: anEntity,
collection: 'aCollection',
ids: ['id'],
mongodb: mongo(retFromDeb, spy)
})
try {
//when
const ret = await itemRepo.find({ filter: "wrong" })
} catch (error) {
//then
assert.deepStrictEqual(error, "condition term is invalid")
}
})
})
})
|
console.log('O Objeto')
console.log(typeof Object)
console.log('ou com new instanciando')
console.log(typeof new Object())
console.log('----------------')
console.log('A Função')
const Cliente = function() {}
console.log(typeof Cliente)
console.log('ou com new instanciando')
console.log(typeof new Cliente)
console.log('----------------')
console.log('A Classe')
class Produto {}
console.log(typeof Produto)
console.log('ou com new instanciando')
console.log(typeof new Produto())
|
/***
NetTalk Mobile Database
***/
var database={
name: "invoice",
version:1,
handle:{},
open:0,
error:"",
errorcode:0,
synchost: "http://192.168.1.6",
synctimer: 15, // seconds
deviceid: "",
user:"",
password:"",
token:"",
status:0,
tables:[
{ name: "invoice",
syncproc: "syncinvoice",
objectStore:{},
everythingafter:0,
primarykeyfield: "guid",
timestampfield: "ts",
servertimestampfield: "sts",
deletedtimestampfield: "dts",
indexes: [
{name:"'inv_servertimestampkey'",unique: false, fields:["sts"]},
{name:"'inv_timestampkey'",unique: false, fields:["ts"]},
{name:"'inv_numberkey'",unique: false, fields:["invoicenumber"]},
{name:"'inv_customerkey'",unique: false, fields:["customerguid"]}
],
relations: [
{type:"manytoone",table:"customer",links:{customerguid:"guid"}}
,{type:"onetomany",table:"lineitems",links:{guid:"invoiceguid"}}
],
record: {
guid:"",
ts:0,
sts:0,
dts:0,
invoicenumber:0,
customerguid:"",
date:"",
paid:0,
terms:0
}
},
{ name: "shippers",
syncproc: "syncshippers",
objectStore:{},
everythingafter:0,
primarykeyfield: "guid",
timestampfield: "ts",
servertimestampfield: "sts",
deletedtimestampfield: "dts",
indexes: [
{name:"'shi_shipperkey'",unique: true, fields:["shipper"]},
{name:"'shi_servertimestampkey'",unique: false, fields:["tst"]},
{name:"'shi_timestampkey'",unique: false, fields:["ts"]}
],
relations: [
{type:"onetomany",table:"linkcountriesshippers",links:{guid:"shipperguid"}}
,{type:"onetomany",table:"customer",links:{guid:"shipperguid"}}
],
record: {
guid:"",
ts:0,
tst:0,
dts:0,
shipper:"",
email:"",
phone:""
}
},
{ name: "product",
syncproc: "syncproduct",
objectStore:{},
everythingafter:0,
primarykeyfield: "guid",
timestampfield: "ts",
servertimestampfield: "sts",
deletedtimestampfield: "dts",
indexes: [
{name:"'pro_timestampkey'",unique: false, fields:["ts"]},
{name:"'pro_servertimestampkey'",unique: false, fields:["sts"]},
{name:"'pro_namekey'",unique: false, fields:["name"]}
],
relations: [
{type:"onetomany",table:"lineitems",links:{guid:"productguid"}}
],
record: {
guid:"",
ts:0,
sts:0,
dts:0,
name:"",
rrp:0
}
},
{ name: "lineitems",
syncproc: "synclineitems",
objectStore:{},
everythingafter:0,
primarykeyfield: "guid",
timestampfield: "ts",
servertimestampfield: "sts",
deletedtimestampfield: "dts",
indexes: [
{name:"'lin_timestampkey'",unique: false, fields:["ts"]},
{name:"'lin_servertimestampkey'",unique: false, fields:["sts"]},
{name:"'lin_productkey'",unique: false, fields:["productguid"]},
{name:"'lin_invoicekey'",unique: false, fields:["invoiceguid"]}
],
relations: [
{type:"manytoone",table:"invoice",links:{invoiceguid:"guid"}}
,{type:"manytoone",table:"product",links:{productguid:"guid"}}
],
record: {
guid:"",
ts:0,
sts:0,
dts:0,
invoiceguid:"",
productguid:"",
price:0,
quantity:0
}
},
{ name: "customer",
syncproc: "synccustomer",
objectStore:{},
everythingafter:0,
primarykeyfield: "guid",
timestampfield: "ts",
servertimestampfield: "sts",
deletedtimestampfield: "dts",
indexes: [
{name:"'cus_timestampkey'",unique: false, fields:["ts"]},
{name:"'cus_servertimestampkey'",unique: false, fields:["sts"]},
{name:"'cus_namekey'",unique: false, fields:["lastname","firstname"]},
{name:"'cus_countrykey'",unique: false, fields:["countrycode"]},
{name:"'cus_shipperkey'",unique: false, fields:["shipperguid"]}
],
relations: [
{type:"manytoone",table:"shippers",links:{shipperguid:"guid"}}
,{type:"manytoone",table:"countries",links:{countrycode:"guid"}}
,{type:"onetomany",table:"invoice",links:{guid:"customerguid"}}
],
record: {
guid:"",
ts:0,
sts:0,
dts:0,
firstname:"",
lastname:"",
company:"",
phone:"",
email:"",
countrycode:"",
shipperguid:""
}
},
{ name: "countries",
syncproc: "synccountries",
objectStore:{},
everythingafter:0,
primarykeyfield: "guid",
timestampfield: "ts",
servertimestampfield: "sts",
deletedtimestampfield: "dts",
indexes: [
{name:"'cou_timestampkey'",unique: false, fields:["ts"]},
{name:"'cou_servertimestampkey'",unique: false, fields:["sts"]},
{name:"'cou_countrycodekey'",unique: true, fields:["countrycode"]},
{name:"'cou_countrykey'",unique: false, fields:["country"]}
],
relations: [
{type:"onetomany",table:"linkcountriesshippers",links:{countrycode:"countryguid"}}
,{type:"onetomany",table:"customer",links:{guid:"countrycode"}}
],
record: {
guid:"",
ts:0,
sts:0,
dts:0,
countrycode:"",
country:""
}
},
{ name: "linkcountriesshippers",
syncproc: "synclinkcountriesshippers",
objectStore:{},
everythingafter:0,
primarykeyfield: "guid",
timestampfield: "ts",
servertimestampfield: "sts",
deletedtimestampfield: "dts",
indexes: [
{name:"'lcs_timestampkey'",unique: false, fields:["ts"]},
{name:"'lsc_servertimestampkey'",unique: false, fields:["sts"]},
{name:"'lsc_countrykey'",unique: true, fields:["countryguid","shipperguid"]},
{name:"'lcs_shipperkey'",unique: false, fields:["shipperguid","countryguid"]}
],
relations: [
{type:"manytoone",table:"countries",links:{countryguid:"countrycode",shipperguid:""}}
,{type:"manytoone",table:"shippers",links:{shipperguid:"guid",countryguid:""}}
],
record: {
guid:"",
ts:0,
sts:0,
dts:0,
countryguid:"",
shipperguid:""
}
},
{ name: "thisdevice",
syncproc: "syncthisdevice",
objectStore:{},
everythingafter:0,
primarykeyfield: "guid",
timestampfield: "ts",
servertimestampfield: "sts",
deletedtimestampfield: "dts",
indexes: [
{name:"'tdh_timestampkey'",unique: false, fields:["ts"]},
{name:"'thd_servertimestampkey'",unique: false, fields:["sts"]}
],
relations: [
],
record: {
guid:"",
sts:0,
ts:0,
dts:0,
clientdeviceid:"",
phonenumber:"",
password:"",
salt:"",
synchost:""
}
}
],
invoice:{
table: {},
record: {},
view: function(){idbSelect(database,database.tables[0],['guid'],true,0,0,0,function(resultset){idbShowResult(database.tables[0],resultset)})},
empty: function(){idbEmpty(database,database.tables[0]);}
},
shippers:{
table: {},
record: {},
view: function(){idbSelect(database,database.tables[1],['guid'],true,0,0,0,function(resultset){idbShowResult(database.tables[1],resultset)})},
empty: function(){idbEmpty(database,database.tables[1]);}
},
product:{
table: {},
record: {},
view: function(){idbSelect(database,database.tables[2],['guid'],true,0,0,0,function(resultset){idbShowResult(database.tables[2],resultset)})},
empty: function(){idbEmpty(database,database.tables[2]);}
},
lineitems:{
table: {},
record: {},
view: function(){idbSelect(database,database.tables[3],['guid'],true,0,0,0,function(resultset){idbShowResult(database.tables[3],resultset)})},
empty: function(){idbEmpty(database,database.tables[3]);}
},
customer:{
table: {},
record: {},
view: function(){idbSelect(database,database.tables[4],['guid'],true,0,0,0,function(resultset){idbShowResult(database.tables[4],resultset)})},
empty: function(){idbEmpty(database,database.tables[4]);}
},
countries:{
table: {},
record: {},
view: function(){idbSelect(database,database.tables[5],['guid'],true,0,0,0,function(resultset){idbShowResult(database.tables[5],resultset)})},
empty: function(){idbEmpty(database,database.tables[5]);}
},
linkcountriesshippers:{
table: {},
record: {},
view: function(){idbSelect(database,database.tables[6],['guid'],true,0,0,0,function(resultset){idbShowResult(database.tables[6],resultset)})},
empty: function(){idbEmpty(database,database.tables[6]);}
},
thisdevice:{
table: {},
record: {},
view: function(){idbSelect(database,database.tables[7],['guid'],true,0,0,0,function(resultset){idbShowResult(database.tables[7],resultset)})},
empty: function(){idbEmpty(database,database.tables[7]);}
},
last:0
};
database.invoice.table = database.tables[0];
database.invoice.record = database.tables[0].record;
database.shippers.table = database.tables[1];
database.shippers.record = database.tables[1].record;
database.product.table = database.tables[2];
database.product.record = database.tables[2].record;
database.lineitems.table = database.tables[3];
database.lineitems.record = database.tables[3].record;
database.customer.table = database.tables[4];
database.customer.record = database.tables[4].record;
database.countries.table = database.tables[5];
database.countries.record = database.tables[5].record;
database.linkcountriesshippers.table = database.tables[6];
database.linkcountriesshippers.record = database.tables[6].record;
database.thisdevice.table = database.tables[7];
database.thisdevice.record = database.tables[7].record;
//------------------------
var syncTimer;
//------------------------
function syncDatabase(){
idbSyncAll(database,0)
}
//------------------------
function syncTimerOn(){
if(database.synctimer){
syncTimer = setInterval(syncDatabase,database.synctimer*1000); // sync database on a timer
}
}
//------------------------
function syncTimerOff(){
clearInterval(syncTimer);
}
//------------------------
$(document).ready(function() {
setTimeout(syncDatabase,5000); // sync database soon after program starts
syncTimerOn()
});
//------------------------
|
const Command = require('../structures/Command');
const GenericPrompt = require('../structures/GenericPrompt');
const GenericPager = require('../structures/GenericPager');
const Util = require('../util');
const lodash = require('lodash');
const prisma = require('../prisma');
module.exports = class Locale extends Command {
get name() { return 'locale'; }
get _options() { return {
aliases: ['l', 'lang', 'locales'],
cooldown: 0,
}; }
async findLocale(query, localePairs, message, _) {
const foundLocale = localePairs.find(locale => locale[0] === query);
if (foundLocale) return foundLocale;
else {
const prompter = new GenericPrompt(this.client, message, {
items: localePairs, itemTitle: 'locale.start',
header: _('locale.choose'),
display: locale => {
if (locale[0] === 'unset')
return `\`unset\` ${_('locale.unset_l')}`;
else return this.formatLine(...locale);
},
_
});
const promptResult = await prompter.search(query,
{ channelID: message.channel.id, userID: message.author.id }, item => {
if (item[0] === 'unset')
return _('locale.unset_l');
else return lodash.get(item, '[1]._.name');
});
if (promptResult && promptResult._noresults) {
await message.channel.createMessage(_('prompt.no_search'));
return;
} else
return promptResult;
}
}
formatLine(locale, json) {
const sourceLines = Object.keys(Util.flattenObject(this.client.locale.source)).length;
const jsonLines = Object.keys(Util.flattenObject(json)).length;
return `${
json._.emoji.startsWith('$') ? `:${json._.emoji.slice(1)}:` : `:flag_${json._.emoji}:`
} \`${locale}\` ${json._.name} \`${Math.min((jsonLines / sourceLines) * 100, 100).toFixed(2)}%\``;
}
async exec(message, { args, _, userData, serverData }) {
const lines = [];
this.client.locale.locales.forEach((json, locale) => {
const line = this.formatLine(locale, json);
lines.push(_.locale === locale ? `**${line}**` : line);
});
const userLocale = userData && userData.locale ?
(this.client.locale.locales.get(userData.locale) || null) : null;
const serverLocale = serverData && serverData.locale ?
(this.client.locale.locales.get(serverData.locale) || null) : null;
const localeArray = [...this.client.locale.array(), ['unset', null]];
let paginator, locale, _n = _;
switch (args[0] ? args[0].toLowerCase() : null) {
case 'setuser':
case 'set':
case 'su':
case 's':
locale = await this.findLocale(args[1], localeArray, message, _);
if (!locale) return;
await prisma.user.upsert({
where: { userID: message.author.id },
create: {
userID: message.author.id,
locale: locale[1] ? locale[0] : null
},
update: { locale: locale[1] ? locale[0] : null }
});
if (locale[1])
_n = this.client.locale.createModule(locale[0], _.prefixes);
return message.channel.createMessage(_n(
locale[1] ? 'locale.user_set' : 'locale.user_unset', {
name: locale[1] ? locale[1]._.name : null
}));
case 'setserver':
case 'ss':
if (!message.guildID)
return message.channel.createMessage(_('locale.no_guild'));
if (!Util.CommandPermissions.trelloRole(this.client, message))
return message.channel.createMessage(_('command_permissions.trelloRole'));
locale = await this.findLocale(args[1], localeArray, message, _);
if (!locale) return;
await prisma.server.upsert({
where: { serverID: message.guildID },
create: {
serverID: message.guildID,
maxWebhooks: 5,
prefix: this.client.config.prefix,
locale: locale[1] ? locale[0] : null
},
update: { locale: locale[1] ? locale[0] : null }
});
if (locale[1])
_n = this.client.locale.createModule(locale[0], _.prefixes);
return message.channel.createMessage(_n(
locale[1] ? 'locale.server_set' : 'locale.server_unset', {
name: locale[1] ? locale[1]._.name : null
}));
default:
paginator = new GenericPager(this.client, message, {
items: lines,
itemTitle: 'locale.start',
_, header: _('locale.user_locale', {
locale: userLocale ? userLocale._.name : '*' + _('locale.unset') + '*'
}) + '\n' + (message.guildID ? _('locale.server_locale', {
locale: serverLocale ? serverLocale._.name : '*' + _('locale.unset') + '*'
}) + '\n' : '') +
'\n' + _('locale.header')
});
if (args[0])
paginator.toPage(args[0]);
return paginator.start(message.channel.id, message.author.id);
}
}
get metadata() { return {
category: 'categories.general',
}; }
};
|
import {StyleSheet} from 'react-native';
import {scalePx2dp} from '@/src/utils/index';
export default StyleSheet.create({
'help-link__item': {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'row',
width: '100%',
backgroundColor: '#fff',
},
'help-link__icon': {
flexGrow: 1,
flexShrink: 1,
flexBasis: 0,
width: '100%',
},
'help-link__icon-help': {
width: scalePx2dp(70),
height: scalePx2dp(70),
marginTop: 0,
marginRight: 'auto',
marginBottom: 0,
marginLeft: 'auto',
},
'help-link__ask': {
flexGrow: 3,
flexShrink: 1,
flexBasis: 0,
width: '100%',
},
'help-link__title': {
width: 'auto',
paddingLeft: scalePx2dp(15),
borderWidth: scalePx2dp(1),
borderStyle: 'solid',
borderColor: '#f7f7f9',
},
help: {
width: '100%',
minHeight: '100%',
backgroundColor: '#f7f7f9',
},
'help-link__title-text': {
fontSize: scalePx2dp(14),
color: '#666',
lineHeight: scalePx2dp(60),
},
'help-link__arrow': {
width: scalePx2dp(25),
},
'help-link__arrow--active': {
width: scalePx2dp(25),
height: scalePx2dp(25),
},
'help-link__separator': {
height: scalePx2dp(5),
backgroundColor: '#f7f7f9',
},
'help-link__subtitle': {
paddingTop: scalePx2dp(5),
paddingRight: scalePx2dp(10),
paddingBottom: scalePx2dp(5),
paddingLeft: scalePx2dp(10),
},
'help-link__subtitle--text': {
fontSize: scalePx2dp(13),
color: '#666',
},
});
|
'use strict'
/*
|--------------------------------------------------------------------------
| Routes
|--------------------------------------------------------------------------
|
| Http routes are entry points to your web application. You can create
| routes for different URLs and bind Controller actions to them.
|
| A complete guide on routing is available here.
| http://adonisjs.com/docs/4.1/routing
|
*/
/** .type {typeof import('.adonisjs/framework/src/Route/Manager')} */
const Route = use('Route')
Route.get('/', () => {
return { greeting: 'Hello world in JSON' }
})
Route.group(() => {
Route.post('registrar', 'Paquexpress/UsuarioController.registrar');
// Generar y Revocar token
Route.post('iniciar', 'Paquexpress/UsuarioController.iniciar');
Route.get('cerrar', 'Paquexpress/UsuarioController.cerrar').middleware(['auth:api'])
// Usuarios testeado
Route.get('Usuarios', 'Paquexpress/UsuarioController.index');
Route.post('Usuarios', 'Paquexpress/UsuarioController.Insert');
Route.get('Usuarios/:id', 'Paquexpress/UsuarioController.edit');
Route.put('Usuarios/:id', 'Paquexpress/UsuarioController.update');
Route.delete('Usuarios/:id', 'Paquexpress/UsuarioController.delete');
// // // Ciudades testeado
Route.get('Ciudades', 'Paquexpress/CiudadeController.index');
Route.post('Ciudades', 'Paquexpress/CiudadeController.Insert');
Route.get('Ciudades/:id', 'Paquexpress/CiudadeController.edit');
Route.put('Ciudades/:id', 'Paquexpress/CiudadeController.update');
Route.delete('Ciudades/:id', 'Paquexpress/CiudadeController.delete');
// // // Productos testeado
Route.get('Productos', 'Paquexpress/ProductoController.index');
Route.post('Productos', 'Paquexpress/ProductoController.Insert');
Route.get('Productos/:id', 'Paquexpress/ProductoController.edit');
Route.put('Productos/:id', 'Paquexpress/ProductoController.update');
Route.delete('Productos/:id', 'Paquexpress/ProductoController.delete');
// // // Transportes testeado
Route.get('Transportes', 'Paquexpress/TransporteController.index');
Route.post('Transportes', 'Paquexpress/TransporteController.Insert');
Route.get('Transportes/:id', 'Paquexpress/TransporteController.edit');
Route.put('Transportes/:id', 'Paquexpress/TransporteController.update');
Route.delete('Transportes/:id', 'Paquexpress/TransporteController.delete');
// // // Vendedores testeado
Route.get('Vendedores', 'Paquexpress/VendedoreController.index');
Route.post('Vendedores', 'Paquexpress/VendedoreController.Insert');
Route.get('Vendedores/:id', 'Paquexpress/VendedoreController.edit');
Route.put('Vendedores/:id', 'Paquexpress/VendedoreController.update');
Route.delete('Vendedores/:id', 'Paquexpress/VendedoreController.delete');
// // // Envios testeado
Route.get('Envios', 'Paquexpress/EnvioController.index');
Route.post('Envios', 'Paquexpress/EnvioController.Insert');
Route.get('Envios/:id', 'Paquexpress/EnvioController.edit');
Route.put('Envios/:id', 'Paquexpress/EnvioController.update');
Route.delete('Envios/:id', 'Paquexpress/EnvioController.delete');
Route.get('Dashboard', 'Paquexpress/EnvioController.dashboard');
// // // Envios testeado
Route.get('Categorias', 'Paquexpress/CategoriaController.index');
Route.post('Categorias', 'Paquexpress/CategoriaController.Insert');
Route.get('Categorias/:id', 'Paquexpress/CategoriaController.edit');
Route.put('Categorias/:id', 'Paquexpress/CategoriaController.update');
Route.delete('Categorias/:id', 'Paquexpress/CategoriaController.delete');
// // // Envios testeado
Route.get('TipoEnvios', 'Paquexpress/TipoEnvioController.index');
Route.post('TipoEnvios', 'Paquexpress/TipoEnvioController.Insert');
Route.get('TipoEnvios/:id', 'Paquexpress/TipoEnvioController.edit');
Route.put('TipoEnvios/:id', 'Paquexpress/TipoEnvioController.update');
Route.delete('TipoEnvios/:id', 'Paquexpress/TipoEnvioController.delete');
// // Clima
Route.post('Clima', 'Paquexpress/ClimaController.consultar');
}).prefix('api')
|
function flag(id) {
$.ajax({
url: "http://localhost:8888/flag?ID="+id,
success : function() {
$("#flag"+id).html("Read");
}
});
}
function update() {
var addMessage = function(data, err) {
jQuery.each(data, function(i) {
$("<div />", {
"class": "msg",
text: data[i]["post"],
"id": data[i]["_id"],
"class": "message"
}).prependTo("#divMessages");
var postRead = "Not read";
if (data[i]["read"] == 1) {
postRead = "Read";
}
$("<div />", {
"class": "msgRead",
"id": "flag"+data[i]["_id"],
text: postRead,
click: function() {
flag(data[i]["_id"]);
}
}).appendTo("#"+data[i]["_id"]);
});
};
$.ajax({
url: "http://localhost:8888/getall",
dataType : "json",
success : addMessage
});
}
function clear() {
$("#divMessages").html("");
}
function save(post) {
$.ajax({
url: "http://localhost:8888/save?POST="+post,
success : function(err,data) {
clear();
update();
}
});
}
$(document).ready(function() {
update();
$("#btnPost").click(function() {
var statusM = "";
var input = $("#txtInput").val();
if(input.length == 0) {
statusM = "No message, please write one before posting.";
}
else if(input.length > 140) {
statusM = "Message to long, only 140 characters is allowed!";
}
else {
save(input);
statusM = "Message succuessfully posted!";
}
$("#divStatus").html(statusM);
});
});
|
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const ruta = express.Router();
const DecoyDuck = require('./src/DecoyDuck');
const MallardDuck = require('./src/MallardDuck');
const RedheadDuck = require('./src/RedheadDuck');
const RubberDuck = require('./src/RubberDuck');
const _DecoyDuck = new DecoyDuck;
const _MallardDuck = new MallardDuck;
const _RedheadDuck = new RedheadDuck;
const _RubberDuck = new RubberDuck;
//const Duck = new Duck;
ruta.route('/pato')
.get((req,res) => {
res.json(_MallardDuck.fly())
})
app.use(ruta)
app.listen(port, () => {
console.log(`Runing on port ${port}`)
});
|
var db = require('./db');
var crypto = require('crypto');
var async = require('async');
var config = require('./config');
var ejs = require('ejs');
var fs = require('fs');
var heckler = require('heckler');
var regTemplate = __dirname + '/email-templates/reg-paid.ejs';
var winTemplate = __dirname + '/email-templates/winner-paid.ejs';
module.exports = {
registration: function(req, res) {
// get bpreceipt from the post body
var bprId = req.body.token;
var bpReceipt;
var regUser;
async.waterfall([
// get Basic Pay Receipt from the DB
function(cb) {
getBPReceipt(bprId, cb);
},
// get the RegisteredUser using the BPReceipt
function(receipt, cb) {
bpReceipt = receipt;
getRegUser(receipt, cb);
},
// update the RegisteredUser
function(user, cb) {
regUser = user;
updateRegUser(user, cb);
}],
// heckler admin with payment and invoice info
function(err, results) {
if (err) { return res.send(500, err.message); }
// build registration email template
var data = {
username: regUser.username,
invoiceId: bpReceipt.invoiceId,
invoiceUrl: config.baron.url
};
var str = fs.readFileSync(regTemplate, 'utf8');
var html = ejs.render(str, data);
// heckle the admin that reg fee was paid
console.log("Emailing Admin: Registration Cleared for " + regUser.username);
heckler.email({
from: config.senderEmail,
to: config.admin.emails,
subject: "Registration Fee Paid for " + regUser.username,
html: html
});
// handshake token
var toHash = bprId + bpReceipt._id;
var newToken = crypto.createHash('sha256').update(toHash).digest('hex');
return res.json({ token: newToken });
}
);
},
winner: function(req, res) {
// get bpreceipt from the post body
var bprId = req.body.token;
var auctionId = req.params.auctionId;
async.waterfall([
// get Basic Pay Receipt from the DB
function(cb) {
getBPReceipt(bprId, cb);
}],
// heckler admin with payment and invoice info
function(err, bpReceipt) {
if (err) { return res.send(500, err.message); }
// secondary vaildation
if (bpReceipt.auctionId !== auctionId) {
return res.send(500, "Invalid Request");
}
// build registration email template
var data = {
username: bpReceipt.username,
userId: bpReceipt.userId,
auctionId: auctionId,
invoiceId: bpReceipt.invoiceId,
invoiceUrl: config.baron.url,
site: config.site.url,
browsePrefix: req.browsePrefix
};
var str = fs.readFileSync(winTemplate, 'utf8');
var html = ejs.render(str, data);
// heckle the admin that an auction payment was made
console.log("Emailing Admin: Payment Cleared for " + bpReceipt.username + " For Auction: " + auctionId);
heckler.email({
from: config.senderEmail,
to: config.admin.emails,
subject: "Payment on Auction: " + auctionId + " by user: " + bpReceipt.username,
html: html
});
// handshake token
var toHash = bprId + bpReceipt._id;
var newToken = crypto.createHash('sha256').update(toHash).digest('hex');
return res.json({ token: newToken });
}
);
}
};
function getBPReceipt(bprId, cb) {
db.getBPReceiptBySHA(bprId, function(err, receipt) {
if (err) { cb(err, undefined); }
cb(null, receipt);
});
}
function getRegUser(receipt, cb) {
db.getRegisteredUser(receipt.userId, function(err, user) {
if (err) { cb(err, undefined); }
cb(null, user);
});
}
function updateRegUser(user, cb) {
user.registered = true;
delete user.registrationStatus;
db.insertRegisteredUser(user, cb);
}
|
var sys = require('sys'),
mite_server = require('../../lib/mite_server').mite_server,
assert = require('assert');
(function test_projects() {
var response = stub_response();
var client = stub_client('projects', ['[{"project":{"name":', '"project1"}}]'], ['[{"project":{"name":', '"project2"}},{"project":{"name":', '"project3"}}]']);
mite_server(client)({url: '/projects?accounts[]=upstream|12345&accounts[]=kriesse|65762'}, response);
assert.deepEqual(response.data,
'[{"name":"project1","subdomain":"upstream","api_key":"12345"},{"name":"project2","subdomain":"kriesse","api_key":"65762"},{"name":"project3","subdomain":"kriesse","api_key":"65762"}]');
assert.equal(response.headers["Content-Type"], 'application/json');
assert.equal(response.headers["Content-Length"], 182);
assert.equal(response.status, 200);
assert.ok(response.closed);
assert.deepEqual(client.subdomains, ['upstream', 'kriesse']);
assert.deepEqual(client.api_keys, ['12345', '65762']);
})();
(function test_time_entries_for_one_project() {
var response = stub_response();
var client = stub_client('time_entries', ['[{"time_entry":{"time": "2010-01-01"}}]']);
mite_server(client)({url: '/time_entries?from=2010-01-01&to=2010-03-01&projects%5B%5D=upstream|12345|3'}, response);
assert.equal(response.headers["Content-Type"], 'application/json');
assert.equal(response.headers["Content-Length"], 23);
assert.equal(response.data, '[{"time":"2010-01-01"}]');
assert.equal(response.status, 200);
assert.ok(response.closed);
assert.deepEqual(client.subdomains, ['upstream']);
assert.deepEqual(client.api_keys, ['12345']);
assert.deepEqual(client.parameters, [{from: '2010-01-01', to: '2010-03-01', project_id: '3'}]);
})();
(function test_time_entries_for_many_projects() {
var response = stub_response();
var client = stub_client('time_entries', ['[{"time_entry":{"time":"2010-01-01"}}]'], ['[{"time_entry":{"time":"2010-02-01"}},{"time_entry":{"time":"2010-04-01"}}]']);
mite_server(client)({url: '/time_entries?projects%5B%5D=upstream|abxy|3&projects%5B%5D=kriesse|bnmh|4'}, response);
assert.equal(response.data, '[{"time":"2010-01-01"},{"time":"2010-02-01"},{"time":"2010-04-01"}]');
assert.deepEqual(client.parameters.map(function(item) {return item.project_id;}), ['3', '4']);
assert.deepEqual(client.api_keys, ['abxy', 'bnmh']);
assert.deepEqual(client.subdomains, ['upstream', 'kriesse']);
})();
(function test_time_entries_csv() {
var response = stub_response();
var client = stub_client('time_entries', ['[{"time_entry":{"project_name":"project 1","service_name":"programming 90","minutes":192,"user_name":"Thilo","date_at":"2010-03-09","note":"done work","revenue":28800}}]']);
mite_server(client)({url: '/time_entries.csv?projects%5B%5D=upstream|abxy|3'}, response);
assert.equal(response.data, 'Project;Service;Minutes;User;Date;Note;Revenue\nproject 1;programming 90;192;Thilo;2010-03-09;done work;28800');
assert.equal(response.headers["Content-Type"], 'text/csv');
assert.equal(response.headers["Content-Length"], 108);
assert.equal(response.status, 200);
assert.ok(response.closed);
})();
function stub_response() {
return({
sendHeader: function(status, headers) {
this.status = status;
this.headers = headers;
},
write: function(data) {
this.data = (this.data || '') + data;
},
close: function() {
this.closed = true;
}
});
};
function stub_client(function_name) {
var data = extract_data(arguments);
var client = {subdomains: [], api_keys: [], parameters: []};
var i = 0;
client[function_name] = function(subdomain, api_key, parameters_callback) {
this.subdomains.push(subdomain);
this.api_keys.push(api_key);
this.parameters.push(arguments.length == 4 ? parameters_callback : {});
var callback = arguments.length == 4 ? arguments[3] : arguments[2];
for(var j in data[i]) {
callback(data[i][j]);
};
i++;
callback(null);
};
return client;
function extract_data(args) {
var data = [];
for(var i in args) {
if(i > 0) {
data[i-1] = args[i];
};
};
return data;
}
};
|
var express = require('express');
var router = express.Router();
const companyController = require("../controller/company.js")
const company = new companyController();
const productImage = require("../controller/productImageMulter");
//공급업체 마이페이지
router.get('/', company.selectCount, company.selectProduct, company.selectOrder, company.selectTotal, (req, res, next) => {
res.render('company/companyMypage.ejs', {sess:req.session.user_id, companyinfo: req.companyinfo, productCount:req.productCount, orderCount:req.orderCount, directCount:req.directCount, product:req.product, refund: req.refund, directY: req.directY, directN: req.directN, total : req.total})
})
//공급업체 상품 등록
router.get('/insertProduct', (req, res, next) => {
res.render('company/insertProduct.ejs')
})
//company.insertProduct,
router.post('/insertProduct', productImage.send, company.insertProduct, (req, res, next) => {
res.send('<script type="text/javascript">alert("상품이 등록 되었습니다.");location.href="/company";</script>');
})
//공급업체 판매 종료
router.post('/updateProductState/:product_num', company.updateProductState, (req, res, next) => {
res.send('<script type="text/javascript">alert("판매 종료 처리 되었습니다.");location.href="/company";</script>');
})
//공급업체 수정
router.get('/updateProduct/:product_num', (req, res, next) => {
res.render('company/updateProduct.ejs',{product_num : req.params.product_num})
})
router.post('/updateProduct/:product_num', company.updateProduct, (req, res, next) => {
res.send('<script type="text/javascript">alert("상품이 수정 되었습니다.");location.href="/company";</script>');
});
// //공급업체 배송 주문, 직거래 주문 목록
// router.get('/selectOrder', company.selectOrder, (req, res, next) => {
// res.render('company/company_orderList.ejs', {sess:req.session.user_id, directY: req.directY, directN: req.directN})
// })
//배송 주문, 직거래 주문 항목
router.get('/selectOrder/:order_num', company.selectOrderDetail, (req, res, next) => {
res.render('company/company_orderListDetail.ejs', {detail: req.detail})
})
//주문 상태 변경
router.post('/updateOrderState/:order_num', company.updateOrderState, (req, res, next) => {
res.send('<script type="text/javascript">alert("완료 되었습니다.");location.href="/company";</script>')
})
// //환불 목록
//router.get('/selectRefund', company.selectRefund, (req, res, next) => {
// res.render('company_refundList.ejs', {refund : req.refund})
// })
//환불 상세
router.get('/selectRefund/:order_num', company.refundDetail, (req, res, next) => {
res.render('company/company_refundDetail.ejs', {refund: req.refund})
})
router.post('/updateRefund/:order_num', company.updateRefund, (rea, res, next) => {
res.send('<script type="text/javascript">alert(환불처리 되었습니다.);location.href="/company";</script>')
})
// // 정산 목록
// router.get('/selectTotal', company.selectTotal, (req, res, next) => {
// res.render('company_refundList', {total : req.total})
// })
module.exports = router;
|
export default {
fetchAccounts (state, accounts) {
state.accounts = accounts
},
search (state, { searchKey, searchString }) {
state[searchKey] = searchString
}
// fetchAccount (state, { sfid, contacts }) {
// const account = _.findWhere(state.accounts, { sfid })
// account.contacts = contacts
// }
// addTodo (state, todo) {
// state.todos.push(todo)
// },
// editTodo (state, { todo, updatedTodo }) {
// todo.text = updatedTodo.text
// },
// removeTodo (state, todo) {
// state.todos = _.reject(state.todos, (t) => t.id === todo.id)
// },
// toggleDone (state, todo) {
// todo.done = !todo.done
// }
}
|
import React, { Component } from 'react';
import axios from 'axios';
import DisplayPost from './DisplayPost';
class Data extends Component {
constructor(props) {
super(props);
this.state = {
isFetching: false,
data: [],
pages: [],
activePage: 2,
}
}
componentDidMount() {
this.getPosts();
}
async getPosts() {
this.setState({ isFetching: true })
await sleep(2000);
axios.get(`https://jsonplaceholder.typicode.com/posts/`)
.then(res => {
this.setState((oldState, props) => {
const parseData = res.data.slice(0, 5);
return { isFetching: false, data: parseData };
})
})
.catch(err => {
console.log(err);
});
this.setState({ isFetching: false })
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
render() {
return (
<div style={{ margin: '20px' }}>
<div>
{!this.state.isFetching ?
this.state.data.map(post => (
<DisplayPost post={post} key={post.id} />
))
:
<div>
Getting Posts.........
</div>
}
</div>
</div>
);
}
}
export default Data;
|
console.log('Listener.js on Page');
// ,
// "content_scripts": [
// {
// "matches": ["http://*/*", "https://*/*"],
// "js": "listener.js"
// }
// ]
// "*://*.myshopify.com/*"
|
'use strict'
/* */
var P = require('./p.js')
function percentilCinquenta (arr) {
return (50 * P)
}
module.exports = percentilCinquenta
|
import styled from 'styled-components';
const SvgStyle = styled.div`
padding: 9px;
min-width: 260px;
max-width: 280px;
position: relative;
box-sizing: border-box;
margin: 0 auto;
flex: auto;
`;
export default SvgStyle;
|
export const LOAD_TESTS = 'LOAD_TESTS';
export const LOAD_TEST = 'LOAD_TEST';
export const LOAD_FRIENDS = 'LOAD_FRIENDS';
const tests = [
{ id: 1, title: 'Examen de Historia del Peru'},
{ id: 2, title: 'Examen de Literatura'},
{ id: 3, title: 'Examen de Familia y Civismo'},
{ id: 4, title: 'Examen de Religion'},
{ id: 5, title: 'Examen de Literatura'},
{ id: 6, title: 'Examen de Cienias Naturales'}
];
const friends = [
{ name: 'Erikson'},
{ name: 'Franchesca'},
{ name: 'Sayury'},
{ name: 'Gabriela'},
{ name: 'Miguel'},
{ name: 'Meladith'},
{ name: 'Jose'},
{ name: 'Elizabeth'},
{ name: 'Sixto'},
{ name: 'Itachi'},
{ name: 'Doris'},
{ name: 'Mario'}
]
const test = {
title: 'Examen de Historia del Peru',
questions: [
{ number: "1", question: "Quien descubrio America?", answer: { type: "simple", answer: "Cristobal Colon" } },
{ number: "2", question: "Cual es el mejor atractiovo turistico del peru?", answer: { type: "simple", answer: "MAcchu Picchu" } },
{ number: "3", question: "Quien fue el declarador de la Independencia en el Peru?", answer: { type: "simple", answer: "Jose de San Martin" } },
{ number: "4", question: "Como se llama la mujer de Manco Capac?", answer: { type: "simple", answer: "Mama Ocllo" } },
{ number: "5", question: "Quien descubrio America?", answer: { type: "simple", answer: "Cristobal Colon" } },
{ number: "6", question: "Cual es el mejor atractiovo turistico del peru?", answer: { type: "simple", answer: "MAcchu Picchu" } },
{ number: "7", question: "Quien fue el declarador de la Independencia en el Peru?", answer: { type: "simple", answer: "Jose de San Martin" } },
{ number: "8", question: "Como se llama la mujer de Manco Capac?", answer: { type: "simple", answer: "Mama Ocllo" } },
{ number: "11", question: "Quien descubrio America?", answer: { type: "simple", answer: "Cristobal Colon" } },
{ number: "21", question: "Cual es el mejor atractiovo turistico del peru?", answer: { type: "simple", answer: "MAcchu Picchu" } },
{ number: "31", question: "Quien fue el declarador de la Independencia en el Peru?", answer: { type: "simple", answer: "Jose de San Martin" } },
{ number: "41", question: "Como se llama la mujer de Manco Capac?", answer: { type: "simple", answer: "Mama Ocllo" } },
{ number: "51", question: "Quien descubrio America?", answer: { type: "simple", answer: "Cristobal Colon" } },
{ number: "61", question: "Cual es el mejor atractiovo turistico del peru?", answer: { type: "simple", answer: "MAcchu Picchu" } },
{ number: "71", question: "Quien fue el declarador de la Independencia en el Peru?", answer: { type: "simple", answer: "Jose de San Martin" } },
{ number: "82", question: "Como se llama la mujer de Manco Capac?", answer: { type: "simple", answer: "Mama Ocllo" } },
{ number: "13", question: "Quien descubrio America?", answer: { type: "simple", answer: "Cristobal Colon" } },
{ number: "23", question: "Cual es el mejor atractiovo turistico del peru?", answer: { type: "simple", answer: "MAcchu Picchu" } },
{ number: "33", question: "Quien fue el declarador de la Independencia en el Peru?", answer: { type: "simple", answer: "Jose de San Martin" } },
{ number: "43", question: "Como se llama la mujer de Manco Capac?", answer: { type: "simple", answer: "Mama Ocllo" } },
{ number: "53", question: "Quien descubrio America?", answer: { type: "simple", answer: "Cristobal Colon" } },
{ number: "63", question: "Cual es el mejor atractiovo turistico del peru?", answer: { type: "simple", answer: "MAcchu Picchu" } },
{ number: "73", question: "Quien fue el declarador de la Independencia en el Peru?", answer: { type: "simple", answer: "Jose de San Martin" } },
{ number: "83", question: "Como se llama la mujer de Manco Capac?", answer: { type: "simple", answer: "Mama Ocllo" } }
]
}
export function loadTests() {
return {
type: LOAD_TESTS,
payload: tests
};
}
export function loadTest(testId) {
return {
type: LOAD_TEST,
payload: test
};
}
export function loadFriends() {
return {
type: LOAD_FRIENDS,
payload: friends
};
}
|
plantimg=[];
function loadPlantImgs(){
plantimg["beet"]=loadImage("https://i.ibb.co/zHD9tz6/beet.png");
plantimg["carrot"]=loadImage("https://i.ibb.co/0M5dcmK/carrot.png");
plantimg["broccoli"]=loadImage("https://i.ibb.co/QMfPDkf/broccoli.png");
plantimg["cauliflower"]=loadImage("https://i.ibb.co/HxC2Pf3/cauliflower.png");
plantimg["celery"]=loadImage("https://i.ibb.co/dL8N0Km/celery.png");
plantimg["daffodil"]=loadImage("https://i.ibb.co/hHBsGR1/daffodil.png");
plantimg["garlic"]=loadImage("https://i.ibb.co/mFj80WB/garlic.png");
plantimg["lettuce"]=loadImage("https://i.ibb.co/8sHqLkk/lettuce.png");
plantimg["rosebush"]=loadImage("https://i.ibb.co/ZHsJG83/rosebush.png");
plantimg["snapdragon"]=loadImage("https://i.ibb.co/FDNYycv/snapdragon.png");
}
/*
https://ibb.co/Hp3w9jh
https://ibb.co/3c7pRv7
https://ibb.co/85kS0Nb
https://ibb.co/F0XWYLC
https://ibb.co/MGFzDNB
https://ibb.co/ct6JWcX
https://ibb.co/Z1jmSDJ
https://ibb.co/V9sRc66
https://ibb.co/HNv2Bz0
https://ibb.co/3CGFjVX
*/
|
function t(t) {
return t && t.__esModule ? t : {
default: t
};
}
var r = require("../lib/Fish_UserData"),
n = t(require("../lib/Common_Data")),
i = t(require("../lib/EChannelPrefix"));
cc.Class({
extends: cc.Component,
properties: {
Score: cc.Label,
TimeTex: cc.Label,
TimeNum: null,
has: cc.Label,
enablelable: cc.Node,
fistGameLable: cc.Label,
game: cc.Node,
_SeeAvState: !1,
gobt: cc.Node,
shareBt: cc.Node,
shareBt2: cc.Node,
reliveGoldLabel: cc.Label,
reliveBt: cc.Node,
shareCoid: 1,
shareCoidDob: 1
},
start: function() {
this.node.setLocalZOrder(4), this.enablelable.setLocalZOrder(4), this.GameCtrl = this.game.getComponent("Fish_Main"),
this.reliveNeedGold = this.GameCtrl.reliveNeedGold || 120, this.TimeNum = 10, this.TimeTex.string = this.TimeNum,
this.timeOut = !1, this.CountDownClick(1e3);
var t = r.Fish_UserData.getFristGame();
console.log("state======", t), t && (this.fistGameLable.string = "免费复活"), this.gobt.on("touchstart", this.ShowSkipBtn, this);
},
ShowSkipBtn: function() {
this.ShowView(!1), console.log("ShowSkipBtn!!!!!!!!!!!!"), this.GameCtrl.RealGameOver();
},
ShowView: function(t) {
console.log("分享视图显示", t), this.node.active = t;
},
CountDownClick: function() {},
DeleteTimeNum: function() {
this._SeeAvState || (this.TimeNum -= 1, this.TimeTex.string = this.TimeNum, this.TimeNum);
},
SetScoreLabel: function(a) {
this.Score.string = a, this.has.string = r.Fish_UserData.getGold();
var e = r.Fish_UserData.getHeightScore();
console.log("score===", a, e);
var t = r.Fish_UserData.getShareOpen(),
o = r.Fish_UserData.getFristGame();
t && !o ? e < a ? (this.shareCoidDob = 0, this.shareBt.active = !1, this.shareBt2.active = !0) : (this.shareCoidDob = .5,
this.shareBt.active = !0, this.shareBt2.active = !1) : (this.shareBt.active = !1,
this.shareBt2.active = !1);
},
ShareBtnClick: function() {
var o = this.reliveNeedGold * this.shareCoid,
e = r.Fish_UserData.getGold();
return r.Fish_UserData.getFristGame() ? (this.ShowView(!1), this.GameCtrl.ReliveGame("你已原地复活", 2),
void r.Fish_UserData.setFristGame(!1)) : void(o <= e ? (this.ShowView(!1), this.GameCtrl.ReliveGame("你已原地复活", 1, o)) : (this.enablelable.active = !0,
this.scheduleOnce(function() {
this.enablelable.active = !1;
}, .5)));
},
ShareBtnClick2: function() {
var e = this,
t = this;
n.default.share(i.default.resurrection, "", null, function() {
console.log("发送复活成功!"), .5 == e.shareCoidDob ? (e.shareCoid = .5, e.reliveGoldLabel.string = "50金币复活") : 0 == e.shareCoidDob && (e.shareCoid = 0,
t.GameCtrl.ReliveGame("你已原地复活", 2), e.ShowView(!1)), e.shareBt.active = !1, e.shareBt2.active = !1;
});
},
cancelBtnClick: function() {
this.unschedule(this.DeleteTimeNum), this.GameCtrl.RealGameOver(), this.ShowView(!1);
},
onSeeAv: function() {
var a = this,
t = !0,
o = wx.createRewardedVideoAd({
adUnitId: "adunit-789e83626f95c274"
});
o.load().then(function() {
o.show(), a._SeeAvState = !0, a.GameCtrl.pauseGame(!0);
}).catch(function(t) {
console.log(t.errMsg);
}), o.onClose(function(o) {
o && o.isEnded || null == o ? t && (a.GameCtrl.ReliveGame("你已原地复活", 2), a.ShowView(!1),
t = !1) : a._SeeAvState = !1;
});
}
});
|
import React, { Component } from 'react'
import { Field, reduxForm } from 'redux-form'
import TextField from 'material-ui/TextField'
import Button from 'material-ui/Button'
import { withStyles } from 'material-ui/styles'
import compose from 'recompose/compose'
import asyncValidate from '../asyncValidate'
import { CircularProgress } from 'material-ui/Progress'
const styles = theme => ({
button: {
marginRight: theme.spacing.unit,
},
actionsContainer: {
marginTop: theme.spacing.unit,
},
})
const validate = values => {
const errors = {}
const requiredFields = ['eventName', 'eventDescription']
requiredFields.forEach(field => {
if (!values[field]) {
errors[field] = 'Required'
}
})
return errors
}
const renderTextField = ({ input, label, meta: { asyncValidating, touched, error }, ...custom }) => (
<div>
<TextField
margin="normal"
label={label}
placeholder={label}
error={touched && error ? true : false}
helperText={touched && error}
{...input}
{...custom}
/>{' '}
{asyncValidating && (
<CircularProgress
style={{
margin: 0,
}}
size={20}
/>
)}
</div>
)
const eventDescription = ({ input, label, meta: { touched, error }, ...custom }) => (
<TextField
margin="normal"
multiline
rowsMax="4"
label={label}
placeholder={label}
error={touched && error ? true : false}
helperText={touched && error}
{...input}
{...custom}
/>
)
export class HandleInformations extends Component {
render() {
const { classes, activeStep, handleBack, handleSubmit } = this.props
return (
<form onSubmit={handleSubmit}>
<div>
<Field name="eventName" component={renderTextField} label="Event name" />
</div>
<div>
<Field name="eventDescription" component={eventDescription} label="Description" />
</div>
<div className={classes.actionsContainer}>
<div>
<Button disabled={activeStep === 0} onClick={handleBack} className={classes.button}>
Back
</Button>
<Button type="submit" raised color="primary" className={classes.button}>
Next
</Button>
</div>
</div>
</form>
)
}
}
export default compose(
withStyles(styles),
reduxForm({
form: 'AddEventForm',
destroyOnUnmount: false,
forceUnregisterOnUnmount: true,
validate,
asyncValidate,
asyncBlurFields: ['eventName'],
})
)(HandleInformations)
|
var proxy = new Proxy({}, {
});
|
var inherits = require('util').inherits;
var debug = require('debug')('homebridge-logic');
module.exports = function (Service, Characteristic, CustomCharacteristic, CustomUUID) {
VariableAddTextService = function(displayName, subtype) {
Service.call(this, displayName, CustomUUID.VariableAddTextService, subtype);
this.addCharacteristic(CustomCharacteristic.VariableName);
this.addCharacteristic(CustomCharacteristic.TextReadonly);
this.addCharacteristic(CustomCharacteristic.VariableAdd);
};
inherits(VariableAddTextService, Service);
CustomCharacteristic.TextReadonly = function() {
Characteristic.call(this, '› Readonly', CustomUUID.TextReadonlyCharacteristic);
this.setProps({
format: Characteristic.Formats.BOOL,
perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE]
});
this.value = this.getDefaultValue();
}
inherits(CustomCharacteristic.TextReadonly, Characteristic);
return VariableAddTextService;
}
|
const router = require("express").Router();
const {
expressResponsehandler,
expressErrorHandler,
roleBaseJWT,
} = require("./middlewares");
const authRoutes = require("./routes/auth");
const employeeRoutes = require("./routes/employee");
const employerRoutes = require("./routes/employer");
router.use(expressResponsehandler);
router.use("/auth", authRoutes);
router.use("/employee", roleBaseJWT(["employee"]), employeeRoutes);
router.use("/employer", roleBaseJWT(["employer"]), employerRoutes);
router.use(expressErrorHandler);
module.exports = router;
|
/**
* Layout component that queries for data
* with Gatsby's useStaticQuery component
*
* See: https://www.gatsbyjs.com/docs/use-static-query/
*/
import React from "react"
import PropTypes from "prop-types"
import { useStaticQuery, graphql } from "gatsby"
import Footer from "./footer"
import "../sass/style.scss"
import Header from "./header"
const Layout = ({ children }) => {
const data = useStaticQuery(
graphql`
{
wpMenu {
id
menuItems {
nodes {
id
parentId
label
path
childItems {
nodes {
id
path
label
}
}
}
}
}
site {
siteMetadata {
title
}
}
}
`
)
const menuItems = data.wpMenu.menuItems.nodes
? data.wpMenu.menuItems.nodes
: null
const siteTitle = data.site.siteMetadata.title
? data.site.siteMetadata.title
: "Title"
return (
<>
<Header siteTitle={siteTitle} menuItems={menuItems} />
<div className="container">
<main>{children}</main>
</div>
<Footer siteTitle={siteTitle} menuItems={menuItems} />
</>
)
}
Layout.propTypes = {
children: PropTypes.node.isRequired,
}
export default Layout
|
// Comparar dos números
var numero1 = Number(prompt("Introduce el primer número:"));
var numero2 = Number(prompt("Introduce el segundo número:"));
if (numero1 < numero2) {
console.log(numero1 + " es más pequeño que " + numero2);
} else if (numero1 > numero2) {
console.log(numero1 + " es más grande que " + numero2);
} else {
console.log(numero1 + " y " + numero2 + " son iguales");
}
// Muestra la hora un segundo más tarde
var horas = Number(prompt("Introduce las horas:"));
var minutos = Number(prompt("Introduce los minutos:"));
var segundos = Number(prompt("Introduce los segundos:"));
// Verificamos todos los casos que pueden dar lugar a error
if ((horas >= 0) && (horas <= 23) && (minutos >= 0) && (minutos <= 59) &&
(segundos >= 0) && (segundos <= 59)) {
segundos++; // Se incrementan los segundos
if (segundos === 60) {
// Hay que pasar los segundos a 0 y sumar una hora más
segundos = 0;
minutos++;
if (minutos === 60) {
// Hay que pasar los minutos a 0 y sumar una hora más
minutos = 0;
horas++;
if (horas === 24) { // La siguiente hora es medianoche, empieza un nuevo día
horas = 0;
}
}
}
console.log("En un segundo, serán las " + horas + " horas, " +
minutos + " minutos y " + segundos + " segundos");
} else {
console.log("Hora incorrecta");
}
|
import React from 'react';
import {shallow, mount} from 'enzyme';
import {SearchPage} from '../searchPage';
import {SearchBar} from '../searchBar';
import {ResultsDisplay} from '../resultsDisplay';
import {FeaturedGames} from '../featuredGames';
import Banner from '../banner';
import {bannerToggle, searchAllGames} from '../../actions/joystick';
describe('<SearchPage />', () => {
it('Renders without crashing', () => {
const props = {
joystick: {
banner: false
}
}
shallow(<SearchPage {...props} />);
});
it('Should render the Banner', () => {
const props = {
joystick: {
banner: true
},
loggedIn: false
}
const wrapper = shallow(<SearchPage {...props} />);
const banner = wrapper.find(Banner);
expect(banner.length).toEqual(1);
});
it('Should render SearchBar, ResultsDisplay, and FeaturedGames', () => {
const props = {
joystick: {
banner: false
}
};
const wrapper = shallow(<SearchPage {...props} />);
expect(wrapper.children().length).toEqual(3);
});
})
|
/**
* Created by liu 2018/6/5
**/
import React, {Component} from 'react';
import {Spin, Form, Button, Input, message, Modal, Switch, Radio} from 'antd';
import TableView from '../../components/TableView'
import Breadcrumb from '../../components/Breadcrumb.js'
import {
roleUpdate,
resourcesById,
roleList,
getByName,
roleCreate,
deleteRole,
roleResourcesAll
} from '../../requests/http-req.js'
import {
Link
} from 'react-router-dom'
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
export default class RoleList extends Component {
constructor(props) {
super(props);
this.state = {
showLoading: false,
pageNo: 0,
pageSize: 10,
inputValue: '',
showModal: false,
total: 0,
listData: [],
editDescribe: null,
editName: null,
editState: 1
}
}
editId = null
onSelectedList = []
componentDidMount() {
//提现类型接口
this.getData()
this.getResourcesAll()
}
getResourcesAll = () => {
roleResourcesAll().then(res => {
//console.log(res)
})
}
handleSearch = () => {
// if (this.state.inputValue == '') {
// message.warning('输入角色名称')
// return
// }
getByName({name: this.state.inputValue.trim()}).then((req) => {
//console.log(req)
if (req.status == 200) {
let tem = []
req.data.data.forEach((item, index) => {
item.index = this.state.pageNo == 0 ? (index + 1) : (this.state.pageNo - 1) * 10 + index + 1
tem.push(item)
})
this.setState({
listData: tem,
pageNo: 0,
total: req.data.total
}, () => {
//console.log(this.state.total)
})
}
this.setState({showLoading: false})
}).catch(e => {
if (e) {
message.warning(e.data.message)
}
})
}
getData() {
let temArr = {
page: this.state.pageNo || 0,
size: 10,
// describe: data && data,
}
this.setState({showLoading: true})
roleList(temArr).then((req) => {
//console.log(req)
if (req.status == 200) {
let tem = []
req.data.data.forEach((item, index) => {
item.index = this.state.pageNo == 0 ? (index + 1) : (this.state.pageNo - 1) * 10 + index + 1
tem.push(item)
})
this.setState({
listData: tem,
total: req.data.total
}, () => {
//console.log(this.state.total)
})
}
this.setState({showLoading: false})
})
}
onChangePagintion = (e) => {
this.setState({
pageNo: e
}, () => {
this.getData()
})
}
closeModal = () => {
this.setState({editId: null, editDescribe: null, editName: null, showModal: false, editState: 1})
}
renderModal = () => {
return (
<Modal
destroyOnClose={true}
onCancel={this.closeModal}
title={this.editId ? "修改角色" : "新建角色"}
visible={this.state.showModal}
onChange={this.closeModal}
footer={null}
>
<div style={{display: 'flex', flexDirection: 'row', margin: '10px'}}>
<div style={{width: '120px'}}>角色名称:</div>
<Input value={this.state.editName} onChange={(e) => {
this.setState({editName: e.target.value})
}}/>
</div>
<div style={{display: 'flex', flexDirection: 'row', margin: '10px'}}>
<div style={{width: '120px'}}>角色描述:</div>
<Input value={this.state.editDescribe} onChange={(e) => {
this.setState({editDescribe: e.target.value})
}}/>
</div>
<div style={{display: 'flex', flexDirection: 'row', margin: '10px'}}>
<div style={{width: '120px'}}>启动:</div>
<RadioGroup onChange={(e) => {
this.setState({
editState: e.target.value
})
}} value={this.state.editState}>
<Radio value={1}>启动</Radio>
<Radio value={0}>禁用</Radio>
</RadioGroup>
</div>
<div style={{display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'center'}}>
<Button style={{width: '100px', marginLeft: '30px'}}
onClick={() => this.postData()}>确认</Button>
</div>
</Modal>
)
}
postData = () => {
let formData = {
name: this.state.editName,
describe: this.state.editDescribe,
role: this.state.editName,
status: this.state.editState
}
// var formData = new FormData()
// formData.append('name', this.state.editName)
// formData.append('describe', this.state.editDescribe)
if (this.editId) {
//修改
formData.id = this.editId
roleUpdate(this.editId, formData).then((req) => {
if (req.status == 200) {
message.success('成功')
} else {
message.error('失败')
}
//console.log(req)
this.setState({editId: null, editDescribe: null, editName: null, showModal: false, editState: 1})
this.getData()
})
} else {
//新建
roleCreate(formData).then((req) => {
//console.log(req)
if (req.status == 200) {
message.success('成功')
} else {
message.error('失败')
}
this.setState({editId: null, editDescribe: null, editName: null, editState: null, showModal: false})
this.getData()
})
}
}
onSelectedRowKeys = (e) => {
//console.log(e)
this.onSelectedList = e
}
showModal = (e) => {
//选择更新必须选中
if (e) {
if (this.onSelectedList.length == 0 || this.onSelectedList.length > 1) {
message.warning('选择一个')
return
} else {
let itemData = this.state.listData[this.onSelectedList[0]]
this.editId = itemData.id
this.setState({
showModal: true,
editDescribe: itemData.describe,
editName: itemData.name,
editState: itemData.status
})
}
} else {
this.onSelectedList = []
this.editId = null
this.setState({
showModal: true,
})
}
}
delRole = () => {
if (this.onSelectedList.length == 0 || this.onSelectedList.length > 1) {
message.warning('请选择一个')
} else {
deleteRole(this.state.listData[this.onSelectedList[0]].id).then(res => {
message.success('操作成功')
this.getData()
}).catch(e => {
if (e) {
message.warning(e.data.message)
}
})
}
}
renderUserList = () => {
return (
<Spin spinning={this.state.showLoading}>
<div className='row-user'>
<Button onClick={() => this.showModal()} style={{marginRight: '5px', marginLeft: '5px'}}>新增</Button>
<Button onClick={() => this.showModal('update')}
style={{marginRight: '5px', marginLeft: '5px'}}>修改</Button>
<Button onClick={this.delRole}
style={{marginRight: '5px', marginLeft: '5px'}}>删除</Button>
</div>
<div style={{display: 'flex', flexDirection: 'column', marginTop: '20px', marginBottom: '20px'}}>
<TableView columns={columns} data={this.state.listData} total={this.state.total}
pageNo={this.state.pageNo}
pageSize={this.state.pageSize}
onSelectedRowKeys={this.onSelectedRowKeys}
onChangePagintion={this.onChangePagintion}/>
</div>
</Spin>
)
}
inputChange = (e) => {
//console.log(e.target.value)
let tem = e.target.value.replace(/(^\s*)|(\s*$)/g, "");
this.setState({
inputValue: tem
})
}
renderSearch = () => {
return (
<Form
style={{
flexDirection: 'row',
paddingLeft: '20px',
paddingRight: '20px',
display: 'flex',
height: '60px',
width: '100%',
alignItems: 'center'
}}
className="ant-advanced-search-form"
onSubmit={this.handleSearch}
>
<FormItem
style={{margin: 'auto', flex: 1, paddingRight: '15px'}}
label="角色名称"
// hasFeedback
// validateStatus="warning"
>
<Input onChange={this.inputChange} value={this.state.inputValue} style={{width: '100%'}}/>
</FormItem>
<div style={{flex: 3}}/>
<Button onClick={this.handleSearch} type="primary" icon="search" style={{
marginRight: '15px',
}}>搜索
</Button>
</Form>
)
}
render() {
return (
<div className='center-user-list'>
{this.renderModal()}
<Breadcrumb data={window.location.pathname}/>
{this.renderSearch()}
{this.renderUserList()}
</div>
)
}
}
const columns = [
{
width: 70,
title: '序号',
fixed: 'left',
dataIndex: 'index',
},
{
title: 'ID',
key: 'id',
dataIndex: 'id',
}
,
{
title: '角色名称',
dataIndex: 'name',
key: 'tradePrice',
},
{
title: '描述',
key: '提现地址',
dataIndex: 'describe',
},
{
title: "编辑",
key: '权限',
render: (text, record) => (
<Link to={{
pathname: '/index/AdminManagement/PermissionsEdit',
state: {data: record, selectStep: 1}
}}>权限</Link>
)
}
];
|
/**
* Handle record selected.
*
* @param {JSEvent} event the event that triggered the action
* @param _form
*
* @private
*
* @properties={typeid:24,uuid:"70E07864-2587-4DE6-A7F9-B60048D0EB45"}
*/
function onRecordSelection(event, _form)
{
_super.onRecordSelection(event, _form);
if(ditte_ratei_to_ditte_rateiscadenziario && ditte_ratei_to_ditte_rateiscadenziario.liquidaap === globals.TIPO_LIQUIDAZIONE.sinoal)
{
elements.fld_periodoprecedente.visible = true;
elements.fld_percentualematurato.visible = false;
elements.fld_sinoalmese.visible = false;
}
else if(ditte_ratei_to_ditte_rateiscadenziario && ditte_ratei_to_ditte_rateiscadenziario.liquidaap !== globals.TIPO_LIQUIDAZIONE.sinoal)
{
elements.fld_periodoprecedente.visible = false;
elements.fld_percentualematurato.visible = true;
elements.fld_sinoalmese.visible = true;
}
else
{
elements.fld_periodoprecedente.visible = false;
elements.fld_percentualematurato.visible = false;
elements.fld_sinoalmese.visible = false;
}
}
|
var mongoose = require("mongoose");
var DB = "mongodb+srv://paras:paras@cluster0.sdjrf.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
mongoose.connect(DB,{
useNewUrlParser: true
})
.then(conn=>{
console.log("Connected to DB")
})
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
const walletSchema = new mongoose.Schema({
walletId: String,
userId: String,
transactions: Array,
balance:Number,
lastUpdated:String
});;
const walletModel = mongoose.model("walletModel",walletSchema);
module.exports = walletModel;
|
var redis = require("redis"),
client = redis.createClient(6379, 'db01');
var async = require('async');
var _ = require('underscore');
//client.set('MyName', 'TreantPanda', function(e, d){
// console.log(d);
// client.expire('MyName', 100, function(err, r){
// setInterval(function(){
// client.TTL('MyName', function(e, r){
// console.log(r);
// });
// }, 1000);
// });
//});
//
//client.SET('name', 'Panda', 'EX', 30, function(err, result){
// console.log(result);
// setInterval(function(){
// client.ttl('name', function(err, result){
// console.log(result);
// });
// }, 1000);
// });
client.HGETALL("zjdx_msg:hash_pool:key", function(e, r){
var keys = _.keys(r);
var values = _.values(r);
var total = keys.length === values.length ? keys.length : 0;
var count = 0;
// async.whilst(
// function(){ return count < total; },
// function(cycle){
// client.HSET('zjdx_msg:hash_pool_inverse:key', values[count], keys[count], function(eee, rrr){
// console.log('HSET Result: ' + rrr);
// });
//
// count++;
// cycle();
// },
// function(ee){
// console.log("keys length: " + _.keys(r).length);
// console.log("values length: " + _.values(r).length);
// console.log('Total Size: ' + total);
// }
// );
var arg = new Array();
for(var i=0; i<total; i++){
arg.push(values[i]);
arg.push(keys[i]);
}
console.log('After push size: ' + arg.length);
arg.unshift('zjdx_msg:hash_pool_inverse:key');
console.log('After unshift size: ' + arg.length);
client.HMSET(arg, function(eee, rrr){
console.log('HMSET Result: ' + rrr);
});
});
|
let str = 'Natural language has no dominate paradigm, and neither does javasascript, developers can slect from a grab bag approaches - - procedural, functional, and object oriented -- and blem them as appropriaten t 0';
let wordArray = str.split("-",10)
console.log(wordArray);
|
const router = require("express").Router();
const path = require("path");
const passport = require("passport");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
require("dotenv").config();
const secret = process.env.SECRET;
//models
const { User, Product } = require("../models/index");
// stores the new image genreate
let newImage;
let finalProduct;
// User api endpoints
router.post("/register", (req, res) => {
// check to see if the email exist in the database
User.findOne({ email: req.body.email }).then(user => {
if (user) {
let error = "Email Address Exists in Database.";
return res.status(400).json(error);
} else {
const newUser = new User({
firstName: req.body.firstName,
lastName: req.body.lastName,
phone: req.body.phone,
userName: req.body.userName,
email: req.body.email,
password: req.body.password
});
bcrypt.genSalt(10, (err, salt) => {
if (err) throw err;
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser
.save()
.then(user => res.json(user))
.catch(err => res.status(400).json(err));
});
});
}
});
});
// login routes
router.post("/login", (req, res) => {
const email = req.body.email;
const password = req.body.password;
let errors = {};
User.findOne({ email }).then(user => {
if (!user) {
errors.email = "No Account Found";
return res.status(404).json(errors);
}
bcrypt.compare(password, user.password).then(isMatch => {
if (isMatch) {
const payload = {
id: user._id,
name: user.email
};
jwt.sign(payload, secret, { expiresIn: 36000 }, (err, token) => {
if (err)
res.status(500).json({ error: "Error signing token", raw: err });
res.json({
success: true,
user: user,
token: `Bearer ${token}`
});
});
} else {
errors.password = "Password is incorrect";
res.status(400).json(errors);
}
});
});
});
// user routes
router.post("/addProduct", async (req, res) => {
// handle file renaming
const rename = image => {
const timeStamp = Date.now();
let imageName;
if (image.mimetype === "image/jpeg") imageName = `${timeStamp}.jpeg`;
if (image.mimetype === "image/png") imageName = `${timeStamp}.png`;
if (image.mimetype === "image/jpg") imageName = `${timeStamp}.jpg`;
console.log(imageName);
return imageName;
};
try {
if (req.files) {
const name = rename(req.files.image);
console.log(req.files);
newImage = name;
req.files.image.mv(path.join(__dirname, `../../uploads`, name));
}
if (Object.keys(req.body)) {
if (newImage && Object.keys(req.body)) {
let data = req.body;
data.imagePath = newImage;
finalProduct = data;
console.log(finalProduct);
if (finalProduct && Object.keys(finalProduct).length > 1) {
const product = new Product(finalProduct);
const result = await product.save();
console.log(result);
res.send(result).status(200);
}
}
}
} catch (error) {
console.log(error.stack);
}
});
// get courses
router.get("/getProducts", (req, res) => {
Product.find({}, (err, data) => {
if (err) throw err;
res.status(200).send(data);
});
});
router.get(`/getProductsById/:id`, (req, res) => {
console.log(req.params.id);
Product.findById(req.params.id)
.then(note => {
if (!note) {
return res.status(404).send({
message: "Note not found with id " + req.params.noteId
});
}
res.send(note);
})
.catch(err => {
if (err.kind === "ObjectId") {
return res.status(404).send({
message: "Note not found with id " + req.params.noteId
});
}
return res.status(500).send({
message: "Error retrieving note with id " + req.params.noteId
});
});
});
router.get(
"/homepage",
passport.authenticate("jwt", { session: false }),
(req, res) => res.send("This is our homepage")
);
module.exports = router;
|
import config from './config'
import {call, put, select, takeEvery, all} from 'redux-saga/effects'
import {omit} from 'lodash'
import { Actions, ActionCreators } from './actions'
import { createBaseSaga, createBaseSagaWatcher } from '../common/sagas'
import {getService} from '../app/selectors'
import Selectors from './selectors'
import { handleError } from '../commonHandlers'
// Saga
const baseSaga = createBaseSaga(config.entityName, Actions, ActionCreators, getService, Selectors, handleError)
const specificFormSaga = function * baseSaga (action) {
let errorAction = null
switch (action.type) {
case Actions.FETCH_EDITED_FORM:
yield put(ActionCreators.setFetchingEntity(true))
try {
const svc = yield select(getService, config.entityName)
const entity = yield call(svc.get, action.id)
const formData = omit(entity, 'fields')
yield all([
put(ActionCreators.setEditedEntity(formData)),
put(ActionCreators.setEditedFormFields(entity.fields)),
put(ActionCreators.resetEditedEntity())
])
} catch (error) {
errorAction = handleError(config.entityName, error)
}
yield put(ActionCreators.setFetchingEntity(false))
break
case Actions.ADD_FIELD:
yield put(ActionCreators.setEditedField(action.field))
break
case Actions.DELETE_FIELD:
yield put(ActionCreators.setEditedField(null))
break
default:
throw new Error('Unsupported trigger action in default saga', action)
}
if (errorAction) {
yield put(errorAction)
}
}
export default [
takeEvery([
Actions.FETCH_EDITED_FORM,
Actions.ADD_FIELD,
Actions.DELETE_FIELD
], specificFormSaga),
createBaseSagaWatcher(Actions, baseSaga)
]
|
// @flow
import type { StandardTx, SwapFuncParams } from './checkSwapService.js'
const js = require('jsonfile')
const confFileName = './config.json'
const CONFIG = js.readFileSync(confFileName)
const { checkSwapService } = require('./checkSwapService.js')
const axios = require('axios')
const SIMPLEX_CACHE = './cache/simRaw.json'
const API_START_DATE = new Date('2020-08-10T00:00:00.000Z').getTime() / 1000
async function doSimplex (swapFuncParams: SwapFuncParams) {
return checkSwapService(fetchSimplex,
SIMPLEX_CACHE,
'SIM',
swapFuncParams
)
}
async function fetchSimplex (swapFuncParams: SwapFuncParams) {
if (!swapFuncParams.useCache) {
console.log('Fetching Simplex...')
}
let diskCache = { txs: [], lastTxTimestamp: 0 }
const transactionMap = {}
const ssFormatTxs: Array<StandardTx> = []
try {
diskCache = js.readFileSync(SIMPLEX_CACHE)
// console.log('diskCache: ', diskCache)
} catch (e) {}
// flag for fresh vs already-populated cache
const initialLastTxTimestamp = diskCache.lastTxTimestamp || 0
let maxTimestamp = diskCache.lastTxTimestamp || 0
let continueFromSyntax = ''
let has_more_pages = false
let next_page_cursor = ''
let retry = 4
try {
while (1 && !swapFuncParams.useCache) {
// console.log('----------------')
// console.log('initiallastTxTimestamp: ', initiallastTxTimestamp)
// console.log('lastTxTimestamp: ', lastTxTimestamp)
// console.log('maxTimestamp: ', maxTimestamp)
// console.log('minTimestamp: ', minTimestamp)
if (next_page_cursor) continueFromSyntax = `continue_from=${next_page_cursor}&`
const url = `https://turnkey.api.simplex.com/transactions?${continueFromSyntax}limit=1000&starting_at=${initialLastTxTimestamp}`
console.log('url: ', url)
const csvData = await axios({
url,
headers: {
'X-API-KEY': CONFIG.simplex.apiKey
}
}).catch(e => {
if (!--retry) {
throw e
}
return null
})
if (!csvData) {
continue
}
has_more_pages = csvData.data.has_more_pages
next_page_cursor = csvData.data.next_page_cursor
const responseTxs = csvData.data.data
for (const order of responseTxs) {
if (!order.fiat_total_amount || !order.amount_crypto) {
continue
}
const timestamp = order.created_at
if (timestamp < API_START_DATE) {
continue
}
const uniqueIdentifier = order.order_id
const ssTx: StandardTx = {
status: 'complete',
inputTXID: uniqueIdentifier,
inputAddress: '',
inputCurrency: 'USD',
inputAmount: parseFloat(order.amount_usd),
outputAddress: '',
outputCurrency: order.crypto_currency,
outputAmount: order.amount_crypto,
timestamp: timestamp
}
if (timestamp > maxTimestamp) maxTimestamp = timestamp
transactionMap[uniqueIdentifier] = ssTx
// if transaction is before the cutoff timestamp
// then stop the loop
if (timestamp < initialLastTxTimestamp) {
has_more_pages = false
}
}
if (has_more_pages === false) {
console.log('responseTxs.length: ', responseTxs.length)
// set the lastTxTimestamp for the cache to two weeks before latest tx
diskCache.lastTxTimestamp = maxTimestamp - 60 * 60 * 24 * 7
break
}
}
} catch (error) {
console.log('error: ', error)
}
for (const id in transactionMap) {
ssFormatTxs.push(transactionMap[id])
ssFormatTxs.sort((a, b) => a.timestamp - b.timestamp)
}
// console.log('ssFormatTxs is: ', ssFormatTxs)
const out = {
diskCache,
newTransactions: ssFormatTxs
}
return out
}
module.exports = { doSimplex }
|
console.log = function(message) {$('.overlay').prepend(message+"<br>");};
console.error = console.debug = console.info = console.log
var proton, emitter;
var camera, scene, renderer, dat, clock, spring, controls, gui,scl,genCld;
var group, item, cube, mesh, mesh2, randomBehaviour, gravity, pointLight2 ,pointLight,pointLight3, rectLight;
var s = 0;
var objects = [];
var group = new THREE.Object3D();
var angle = 0, angl = 0;
var radius = 140;
var genObj=[];
var genGr, genSymbl, spot;
var model = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/68049/map.js";
$( document ).ready(function() {
console.log( "jQ ready..." );
$('body').on("mouseup",function() {
// alignCloud(objects);
//genVertices(mesh.geometry.vertices);
});
$('.dat').on("mouseup",function() {
combineCloud(mesh.geometry.vertices,group);
});
$('.dat2').on('mouseup',function(){
spreadCloud(genObj);
});
});
initAll();
function initAll() {
initScene();
loadModel();
initLights();
//initHelpers();
addControls();
//genCloud();
//datGui();
animate();
}
function genCloud(){
scl = 1;
var mat = new THREE.MeshStandardMaterial( { color: 0x000000, wireframe:true} );
var geometry = new THREE.BoxGeometry(20, 1, this.scl, 1, 1, 1);
for(var i=0 ; i<= 2000; i++){
var symbol = new THREE.Object3D();
item = new THREE.Mesh (geometry,mat);
symbol.add(item);
objects.push(symbol);
}
spreadCloud(objects);
}
function genBars(){
var mat = new THREE.MeshStandardMaterial( { color: 0x000000} );
var geometry = new THREE.BoxGeometry(2, 2, 2, 2, 2, 2);
}
function spreadCloud(arr){
for (var i = 0, len = arr.length; i < len; i++) {
var sym = arr[i];
//sym.lookAt(scene.position);
new TWEEN.Tween(sym.position).to({
x: 200 * Math.random() - 100,
y: 200 * Math.random() - 100,
z: 200 * Math.random() - 100
}, 1000)
.easing(TWEEN.Easing.Quintic.InOut,).start();
//sym.position.set(100 * Math.random() - 50, 100 * Math.random() - 50, 100 * Math.random() - 50);
group.add(sym);
}
scene.add(group);
}
function combineCloud(mod,group){
var scale = 100;
for(var g = 0, len = mod.length; g<len; g++){
var sym = genObj[g];
//sym.lookAt(scene.position);
new TWEEN.Tween(sym.position).to({
x: mod[g].x/scale,
y: mod[g].y/scale,
z: mod[g].z/scale
}, 1000)
.easing(TWEEN.Easing.Quintic.InOut,).start();
}
}
function genVertices(mod){
console.log(mod.length);
var mat = new THREE.MeshBasicMaterial({color:0x000000});
var scale = 10;
for(var g = 0, len = mod.length; g<len; g++){
var symbl = new THREE.Object3D();
var geometry = new THREE.SphereGeometry( Math.random(0.2,2), 5, 5);
spot = new THREE.Mesh (geometry,mat);
spot.position.set(mod[g].x/scale,mod[g].y/scale,mod[g].z/scale);
symbl.add(spot);
genObj.push(symbl);
}
spreadCloud(genObj);
}
function alignCloud(gr){
for (var i = 0, len = gr.length; i < len; i++) {
var sym = gr[i];
var curVer = 100 * Math.random() - 50;
new TWEEN.Tween(sym.position).to({
x: 200 * Math.random() - 50,
y: 200 * Math.random() - 50,
z: 200 * Math.random() - 50
}, 1000)
.easing(TWEEN.Easing.Quintic.InOut,).start();
new TWEEN.Tween(sym.scale).to({
x: 1 * Math.random(),
y: 2* Math.random(),
z: 1 * Math.random()
}, 1000)
.easing(TWEEN.Easing.Quintic.InOut,).start();
}
}
// function datGui(){
// genCld = new genCloud();
// gui = new dat.GUI();
// gui.add(genCld, 'scl', 0, 10);
// }
function initScene(){
clock = new THREE.Clock();
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.z = 100;
camera.position.y = 20;
camera.position.x = 100;
scene = new THREE.Scene();
scene.fog = new THREE.Fog(0xffffff, 1, 10000);
renderer = new THREE.WebGLRenderer({alpha:true,antialias: true});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
window.addEventListener('resize', onWindowResize, false);
window.addEventListener('mousedown', onMouseDown,false);
}
function onMouseDown() {
}
function addControls() {
controls = new THREE.TrackballControls( camera,renderer.domElement );
controls.rotateSpeed = 1.2;
controls.minDistance = 10;
controls.maxDistance = 1000;
controls.noRotate = false;
controls.addEventListener( 'change', render );
controls.noZoom = false;
}
function initLights() {
var dlight = new THREE.DirectionalLight( 0xffffff, 1 );
dlight.position.set( -1, 1, -1); //default; light shining from top
dlight.castShadow = true; // default false
scene.add( dlight );
var dlight2 = new THREE.DirectionalLight( 0xffffff, 1 );
dlight2.position.set( 1, -1, 1 ); //default; light shining from top
dlight2.castShadow = true; // default false
scene.add( dlight2 );
// rectLight = new THREE.RectAreaLight( 0xffffff, 1, 10, 10 );
// rectLight.intensity = 70.0;
// rectLight.position.set( 20, 20, 20 );
// scene.add( rectLight )
// pointLight3 = new THREE.PointLight( 0xffffff, 5, 1000 );
// pointLight3.position.set( 50, 10, -50 );
// scene.add( pointLight3 );
// pointLight = new THREE.PointLight( 0x0000ff, 5, 1000 );
// pointLight.position.set( 20, 20, 20 );
// scene.add( pointLight );
// pointLight2 = new THREE.PointLight( 0x00ff00, 2, 1000 );
// pointLight2.position.set( -20, 10, -20 );
// scene.add( pointLight2 );
}
function initHelpers(){
var sphereSize = 1;
var box = new THREE.BoxHelper( cube, 0xffff00 );
scene.add( box );
var axisHelper = new THREE.AxisHelper( 1000 );
scene.add( axisHelper );
// var rectLightHelper = new THREE.RectAreaLightHelper( rectLight );
// scene.add( rectLightHelper );
var pointLightHelper = new THREE.PointLightHelper( pointLight3, sphereSize );
scene.add( pointLightHelper );
var pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
scene.add( pointLightHelper );
var pointLightHelper2 = new THREE.PointLightHelper( pointLight2, sphereSize );
scene.add( pointLightHelper2 );
scene.add(new THREE.GridHelper(100,10));
}
function loadModel() {
var objectLoader = new THREE.JSONLoader();
var material1 = new THREE.MeshPhongMaterial( { color: 0xffffff, wireframe:true});
objectLoader.load(model, function(obj) {
obj.computeFaceNormals();
mesh = new THREE.Mesh( obj, material1);
mesh.scale.x = mesh.scale.y = mesh.scale.z = 0.11;
genVertices(mesh.geometry.vertices);
scene.add(mesh);
});
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
render();
}
function animate(){
requestAnimationFrame(animate);
controls.update();
s++
$('.time').text(s);
TWEEN.update();
render();
}
function render(){
renderer.render(scene,camera);
camera.lookAt(scene.position);
camera.updateProjectionMatrix();
angle += 0.001;
// angl += 0.1;
// for(var g = 0, len = genObj.length; g<len; g++){
// var sym = genObj[g];
// var rnd = Math.random(0.1,0.1);
// sym.scale.x = rnd;
// sym.scale.z = rnd;
// sym.scale.y = rnd;
// }
// mesh.position.x = 1 * Math.cos( angl);
// mesh.position.z = 1 * Math.sin( angl);
camera.position.x = radius * Math.cos( angle );
camera.position.z = radius * Math.sin( angle );
}
|
import Namespace from './namespace';
import {ATTRIBUTE} from './types';
export default class Attribute extends Namespace {
constructor (opts = {}) {
super(opts);
this.type = ATTRIBUTE;
this.raws = this.raws || {};
this._constructed = true;
}
get qualifiedAttribute () {
return this.qualifiedName(this.raws.attribute || this.attribute);
}
get insensitiveFlag () {
return this.insensitive ? 'i' : '';
}
get value () {
return this._value;
}
set value (v) {
this._value = v;
if (this._constructed) {
delete this.raws.value;
}
}
get value () {
return this._value;
}
set value (v) {
this._value = v;
if (this._constructed) {
delete this.raws.value;
}
}
get namespace () {
return this._namespace;
}
set namespace (v) {
this._namespace = v;
if (this._constructed) {
delete this.raws.namespace;
}
}
get namespace () {
return this._namespace;
}
set namespace (v) {
this._namespace = v;
if (this._constructed) {
delete this.raws.namespace;
}
}
get attribute () {
return this._attribute;
}
set attribute (v) {
this._attribute = v;
if (this._constructed) {
delete this.raws.attibute;
}
}
_spacesFor (name) {
let attrSpaces = {before: '', after: ''};
let spaces = this.spaces[name] || {};
let rawSpaces = (this.raws.spaces && this.raws.spaces[name]) || {};
return Object.assign(attrSpaces, spaces, rawSpaces);
}
_valueFor (name) {
return this.raws[name] || this[name];
}
_stringFor (name, spaceName = name, concat = defaultAttrConcat) {
let attrSpaces = this._spacesFor(spaceName);
return concat(this._valueFor(name), attrSpaces);
}
/**
* returns the offset of the attribute part specified relative to the
* start of the node of the output string.
*
* * "ns" - alias for "namespace"
* * "namespace" - the namespace if it exists.
* * "attribute" - the attribute name
* * "attributeNS" - the start of the attribute or its namespace
* * "operator" - the match operator of the attribute
* * "value" - The value (string or identifier)
* * "insensitive" - the case insensitivity flag;
* @param part One of the possible values inside an attribute.
* @returns -1 if the name is invalid or the value doesn't exist in this attribute.
*/
offsetOf (name) {
let count = 1;
let attributeSpaces = this._spacesFor("attribute");
count += attributeSpaces.before.length;
if (name === "namespace" || name === "ns") {
return (this.namespace) ? count : -1;
}
if (name === "attributeNS") {
return count;
}
count += this.namespaceString.length;
if (this.namespace) {
count += 1;
}
if (name === "attribute") {
return count;
}
count += this._valueFor("attribute").length;
count += attributeSpaces.after.length;
let operatorSpaces = this._spacesFor("operator");
count += operatorSpaces.before.length;
let operator = this._valueFor("operator");
if (name === "operator") {
return operator ? count : -1;
}
count += operator.length;
count += operatorSpaces.after.length;
let valueSpaces = this._spacesFor("value");
count += valueSpaces.before.length;
let value = this._valueFor("value");
if (name === "value") {
return value ? count : -1;
}
count += value.length;
count += valueSpaces.after.length;
let insensitiveSpaces = this._spacesFor("insensitive");
count += insensitiveSpaces.before.length;
if (name === "insensitive") {
return (this.insensitive) ? count : -1;
}
return -1;
}
toString () {
let selector = [
this.spaces.before,
'[',
];
selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
if (this.operator && this.value) {
selector.push(this._stringFor('operator'));
selector.push(this._stringFor('value'));
selector.push(this._stringFor('insensitiveFlag', 'insensitive', (attrValue, attrSpaces) => {
if (attrValue.length > 0
&& !this.quoted
&& attrSpaces.before.length === 0
&& !(this.spaces.value && this.spaces.value.after)) {
attrSpaces.before = " ";
}
return defaultAttrConcat(attrValue, attrSpaces);
}));
}
selector.push(']');
selector.push(this.spaces.after);
return selector.join('');
}
}
function defaultAttrConcat (attrValue, attrSpaces) {
return `${attrSpaces.before}${attrValue}${attrSpaces.after}`;
}
|
//init
$(document).ready(function(){
$('.sidenav').sidenav();
$('select').formSelect();
window.name = JSON.stringify({
current: 'IBM',
list: []
});
// myLineChart = new Chart($('#stockChart'), {
// type: 'line',
// data: data_g,
// options: options_g
// })
tik = window.location.href.split('?')[1];
sel = document.getElementById('tscale');
op2 = sel.options[sel.selectedIndex].text.toLowerCase();
if(!(tik===undefined)){
updateStock(tik, op2);
}
updateStock('IBM', 'day')
});
data_g = {
labels: ['8 a.m.', '9 a.m.', '10 a.m.', '11 a.m.', '12 p.m.', '1 p.m.'],
datasets: [{
label: 'Price ($)',
data: [12, 19, 3, 5, 2, 15]
}]
}
options_g = {
scales: {
yAxes: [{
ticks: {
beginAtZero: false
}
}]
}
}
twts = [""];//['This stock ruined my life! Don\'t buy!!!!!', 'Best Stock ever!', 'Anyone know if this stock is good???', 'it\'s climbing slowly', 'I just made a million bucks by shorting this stock', 'Good company, I like their ____', 'covfefe']
var myLineChart = null
function addTweets(ticker, arr){
document.getElementById("tweets").innerHTML = "";
arr.forEach(function(e){
var qt = document.createElement("blockquote");
qt.innerHTML = e;
document.getElementById("tweets").appendChild(qt);
});
updateSentiment(arr);
}
function addData(label, data, name ) {
if(myLineChart !== null){
myLineChart.destroy();
}
data_g.datasets[0].label = name;
data_g.datasets[0].data = data;
data_g.labels = label;
myLineChart = new Chart($('#stockChart'), {
type: 'line',
data: data_g,
options: options_g
});
query(data_g.datasets[0].label, 10);
tmp = JSON.parse(window.name)
tmp.current = name;
window.name = JSON.stringify(tmp);
document.getElementById('search').value = name;
select(timeScale);
// chart = myLineChart;
// chart.data.labels.push(label);
// chart.data.datasets.forEach((dataset) => {
// dataset.data.push(data);
// });
// chart.update();
}
function addSentiment(arr, twtarr, avgarr) {
var i = 0;
var positive = 0;
var negative = 0;
var neutral = 0;
var arrlengthstring = arr.length.toString();
var cntnt = document.getElementById("sentiments");
while (cntnt.childNodes.length > 2) {
cntnt.removeChild(cntnt.lastChild);
}
arr.forEach(function(e){
if (i == 0 && arr.length > 10) {
var qt2 = document.createElement("blockquote");
qt2.innerHTML = "Showing analysis of 10 tweets out of ".bold() + arrlengthstring.bold() + " total tweets".bold();
document.getElementById("sentiments").appendChild(qt2);
} else if (i == 0) {
var qt2 = document.createElement("blockquote");
qt2.innerHTML = "Showing analysis of all ".bold() + arrlengthstring.bold() + " tweets".bold();
document.getElementById("sentiments").appendChild(qt2);
}
if (i < 10) {
var qt = document.createElement("blockquote");
qt.innerHTML = twtarr[i].italics() + ": " + e.bold();
document.getElementById("sentiments").appendChild(qt);
}
if (e == "positive") {
positive += 1;
} else if (e == "negative") {
negative += 1;
} else {
neutral += 1;
}
i++;
});
var prevalent;
if (positive > negative && positive > neutral) {
prevalent = "Positive";
} else if (negative > positive && negative > neutral) {
prevalent = "Negative";
} else if (neutral > positive && neutral > negative) {
prevalent = "Neutral";
} else if (neutral == positive && neutral > negative) {
prevalent = "Positive and Neutral";
} else if (neutral > positive && neutral == negative) {
prevalent = "Negative and Neutral";
} else if (negative == positive && neutral < negative) {
prevalent = "Divided (Positive and Negative)";
} else {
prevalent = "No prevalent sentiment";
}
var qt = document.createElement("blockquote");
qt.innerHTML = "Prevalent Sentiment: ".bold() + prevalent.bold() + " (Based on amount of sentiment)".bold();
document.getElementById("sentiments").appendChild(qt);
var qt2 = document.createElement("blockquote");
qt2.innerHTML = "Confidence Score Percentage (Average of confidence scores across all tweets): ".bold() + "Positive: ".bold() + avgarr[0].toFixed(2) + "% " +
"Neutral: ".bold() + avgarr[1].toFixed(2) + "% " + "Negative: ".bold() + avgarr[2].toFixed(2) + "%";
document.getElementById("sentiments").appendChild(qt2);
anychart.onDocumentReady(function() {
//delete previous chart
document.getElementById("sentimentPie").innerHTML = "";
// set the data
var data = [
{x: "Positive", value: positive, normal: {
fill: "#009933",
}
},
{x: "Negative", value: negative, normal: {
fill: "#990000",
}
},
{x: "Neutral", value: neutral, normal: {
fill: "#ffcc00",
}
},
];
// create the chart
var sentimentChart = anychart.pie();
//chart.radius("100%");
// set the chart title
sentimentChart.title("Sentiment Analysis (Amount of each sentiment)");
// add the data
sentimentChart.data(data);
// display the chart in the container
sentimentChart.container('sentimentPie');
sentimentChart.draw();
});
}
document.getElementById("search-btn").onclick = function(){
sel = document.getElementById('tscale');
op2 = sel.options[sel.selectedIndex].text.toLowerCase();
mystr = document.getElementById("search").value; updateStock(mystr, op2); /*twitter update goes here*/;
}
function addSearchSuggestions(ticks, names){
let myCollection = document.getElementById("search-sugg");
myCollection.innerHTML = ""
for (i=0; i<ticks.length; i++)
{
e = ticks[i] + ": "+names[i];
var s = document.createElement("a");
s.className = "collection-item ssugg-item";
s.innerHTML = e;
var att = document.createAttribute("tickerName"); // Create a "class" attribute
att.value = ticks[i];
s.setAttributeNode(att);
myCollection.appendChild(s);
suggarr = document.getElementsByClassName('ssugg-item');
suggarr[suggarr.length-1].onclick = function(){
sel = document.getElementById('tscale');
op2 = sel.options[sel.selectedIndex].text.toLowerCase();
updateStock(this.getAttribute('tickername'), op2);
$('.ssugg').css("display", "none");
}
}
}
document.getElementById("search").oninput = function(){
if(document.getElementById("search").value.length%3 === 2){
searchFill(document.getElementById("search").value)
}
}
document.getElementById("search").onfocus = function(){$('.ssugg').css("display", "block");}
document.getElementById("search-sugg").onblur = function(){$('.ssugg').css("display", "none");document.getElementById("search-sugg").innerHTML="";}
document.getElementById('tscale').onchange = function(){
sel = document.getElementById('tscale');
op2 = sel.options[sel.selectedIndex].text.toLowerCase();
updateStock(data_g.datasets[0].label, op2);
}
document.getElementById('addStock').onclick = function(){
st = JSON.parse(window.name);
if(st.list.indexOf(st.current) === -1){
st.list.push(st.current);
}
window.name = JSON.stringify(st);
$
}
//loop
//end
function select(optionValToSelect){
//Get the select element by it's unique ID.
var selectElement = document.getElementById('tscale');
//Get the options.
var selectOptions = selectElement.options;
//Loop through these options using a for loop.
for (var opt, j = 0; opt = selectOptions[j]; j++) {
//If the option of value is equal to the option we want to select.
if (opt.value == optionValToSelect) {
//Select the option and break out of the for loop.
selectElement.selectedIndex = j;
break;
}
}
$('select').formSelect();
}
|
var gulp = require('gulp');
var minifyCSS = require('gulp-clean-css');
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');
var less = require('gulp-less');
var gcmq = require('gulp-group-css-media-queries');
var autoprefixer = require('gulp-autoprefixer');
var spritesmith = require('gulp.spritesmith');
var remember = require('gulp-remember');
var gs = gulp.series;
var cached = require('gulp-cached');
var dependents = require('gulp-dependents');
var lessSrc = ['./local/assets/less/inc/*.less', './local/assets/less/*.less', './local/assets/less/blocks/*.less'];
gulp.task('Build CSS', function () {
return gulp.src(lessSrc)
.pipe(sourcemaps.init())
.pipe(cached('css'))
//.pipe(dependents())
.pipe(less())
.pipe(remember('css'))
.pipe(concat('build.css'))
.pipe(sourcemaps.write())
.pipe(gulp.dest('./local/assets/css'));
});
gulp.task('Build CSS Prod', function () {
return gulp.src(lessSrc)
.pipe(less())
.pipe(autoprefixer({
cascade: false
}))
.pipe(concat('build.css'))
.pipe(gcmq())
.pipe(minifyCSS({level: {1: {specialComments: 0}}}))
.pipe(gulp.dest('./local/assets/css'));
});
gulp.task('Watch', function () {
gulp.watch(lessSrc, gs('Build CSS'))
.on('change', function (event) {
console.log("event happened:"+JSON.stringify(event));
if (event.type === 'deleted') {
//delete from gulp-remember cache
//emember.forget('sass', event.path);
//delete from gulp-cached cache
delete cache.caches['css'][event.path];
}
});
});
gulp.task('Sprites', function () {
var spriteData = gulp.src('local/assets/sprites/*.png').pipe(spritesmith({
imgName: '../img/sprites.png',
cssName: '../less/inc/sprites.less',
imgPath: '/local/assets/img/sprites.png?' + Math.floor(Date.now() / 1000)
}));
return spriteData.pipe(gulp.dest('local/assets/css'));
});
|
const User = require('../../../mongoose/models/Users/Users');
const Board = require('../../../mongoose/models/Boards/Boards');
// The following methods are for the /user/:userId/confirm route
// Model used to get update the users permissions
exports.updateUserPermission = async (userId) => {
await User.updateOne({ _id: userId }, { $set: { permission: 4 } });
};
// The following methods are for the /user/:userId route
// Model used to get a users data
exports.getUserData = async (userId) => {
const data = await User.findOne({ _id: userId }, {
gender: 1,
bio: 1,
profilePicture: 1,
boards: 1,
permission: 1,
email: 1,
firstName: 1,
lastName: 1,
});
return data;
};
// Model used to delete a users data
exports.deleteUserData = async (userId) => {
await Board.deleteMany({ adminUser: userId });
await User.deleteOne({ _id: userId });
};
// Model used to patch a users data
exports.patchUserData = async (userId, userData) => {
await User.updateOne({ _id: userId }, {
$set:
{
gender: userData.gender,
bio: userData.bio,
firstName: userData.firstName,
lastName: userData.lastName,
},
});
};
// The following methods are for /user/:userId/upload
// Model used to set an upload link from AWS
exports.addUserProfilePicture = async (userId, link) => {
await User.updateOne({ _id: userId }, {
$set:
{
profilePicture: link,
},
});
};
// The following methods are for the /user/:userId/profilepicture route
// Model used to get a users profile picture
exports.getUserProfilePicture = async (userId) => {
const profilePicture = await User.findOne({ _id: userId }, { profilePicture: 1 });
return profilePicture;
};
// Model used to delete a users profile picture
exports.deleteUserProfilePicture = async (userId) => {
const old = await User.findOneAndUpdate({ _id: userId }, {
$set:
{
profilePicture: 'ProfilePicture/16f3a340-645e-11e9-9882-510b31653fcb.png',
},
});
return old.profilePicture;
};
// The following methods are for the /user/:userId/profilepicture route
// Model used to get a users boards
exports.getUserBoards = async (userId) => {
const boards = await User.findOne({ _id: userId }, { boards: 1 });
return boards;
};
// Model used to delete users boards
exports.deleteUserBoards = async (userId) => {
await User.updateOne({ _id: userId }, {
$set:
{
boards: [],
},
});
};
// Model used to patch a users boards
exports.patchUserBoards = async (userId, userData) => {
await User.updateOne({ _id: userId }, {
$set:
{
boards: userData.boards,
},
});
};
// Model used to add a single board id to the array
exports.addUserBoard = async (userId, boardId) => {
await User.updateOne({ _id: userId }, {
$push:
{
boards: boardId,
},
});
};
// The following method are used to validate a user is allowed to access a given
// board
// Method used to check if a given board exists inside a users array of boards
exports.userBoardPermission = async (userId, boardId) => {
const board = await User.findOne({ boards: boardId, _id: userId });
return board;
};
// The following method are used to add the board to the users list when creating
// a new one
// Method used to add board
exports.addNewBoard = async (userId, boardId) => {
await User.updateOne({ _id: userId }, {
$push: { boards: boardId },
});
};
// Method used to delete a board
exports.deleteBoard = async (userId, boardId) => {
await User.updateOne(
{ _id: userId },
{ $pull: { boards: boardId } },
);
};
// The following methods are for the /user/profile/:userId
// Model used to get a users profile data
exports.getProfileData = async (userId) => {
const data = await User.findOne({ _id: userId }, {
gender: 1,
bio: 1,
profilePicture: 1,
email: 1,
firstName: 1,
lastName: 1,
});
return data;
};
// Model used to get a users profile data by email
exports.getProfileDataByEmail = async (email) => {
const data = await User.findOne({ email }, {
gender: 1,
bio: 1,
profilePicture: 1,
email: 1,
firstName: 1,
lastName: 1,
});
return data;
};
|
import React from "react";
import Img from "components/Common/Img";
import Link from "gatsby-link";
import ResumeBadge from "components/SuccessfulResumes/ResumeBadge";
import { shuffle, flow, slice, map } from "lodash/fp";
import barackObama from "assets/img/new-successful-resumes/avatars/barack_obama/avatar.jpg";
import barackCompany from "assets/img/new-successful-resumes/avatars/barack_obama/company.png";
import hoverResume from "assets/img/new-successful-resumes/placeholders/hover-cv.png";
export default function FooterList({ list, famousPrefix = "" }) {
const items = flow(shuffle, slice(0, 3), map("node"))(list);
return (
<section className="resumes--others m-sm-top-4 m-md-top-13 m-sm-bottom-3 m-md-bottom-7">
<div className="resumes--list">
<p className="big-p text-center text-gray-2 text-gray-1">
Other successful resumes made on Enhancv
</p>
</div>
<div className="resumes--others-wrap noBackground Grid">
{items.map((node, index) => (
<Link
key={node.url + index}
to={`/successful-resumes/${famousPrefix + node.url}`}
className="resumes--box-holder Grid-cell--md-4 Grid-cell--sm-4 Grid-cell--xs-12 p-md-3 p-sm-1">
<div className="resumes--box">
{node.label ? <ResumeBadge label={node.label} /> : null}
<span className="resumes--person-avatar">
<Img
className="m-xs-left-1 m-md-left-2"
resolutions={node.avatar.childImageSharp.resolutions}
alt={`${node.name}'s photo`}
/>
</span>
<div className="resumes--others-person-info">
<h4 className="resumes--person-name m-top-1 m-bottom-0">
{node.name}
</h4>
{node.tags ? (
<h5 className="resumes--person-jobtitle m-no">
{node.tags.join(", ")}
</h5>
) : null}
{node.description ? (
<div className="resumes--person-description">
<p className="m-top-2">{node.description}</p>
</div>
) : null}
{node.companyLogo ? (
<div className="resumes--hired resumes--hired-list-item m-xs-top-2 m-md-top-3">
<span className="label">Hired at</span>
<Img
style={{ display: "inline-block" }}
className="m-top-0"
resolutions={node.companyLogo.childImageSharp.resolutions}
alt="Company logo"
/>
</div>
) : null}
</div>
</div>
<div className="resumes--hovered">
<Img
className="m-xs-left-1 m-md-left-2"
resolutions={node.resumes[0].image.childImageSharp.resolutions}
alt={`${node.name}'s resume preview`}
/>
</div>
</Link>
))}
</div>
</section>
);
}
|
import React from 'react';
import { Link } from 'react-router-dom';
const StudentActions = props => {
if (props.addStudent) {
return (
<div className="center-align section">
<Link to="/students/add" className="blue waves-effect waves-light btn">
<i className=" material-icons left">add_circle</i>Add New Student
</Link>
</div>
);
} else {
return (
<div className="right-align">
<div className="float-right">
<Link
to="/students/edit"
className="section blue waves-effect waves-light btn"
>
<i className=" material-icons left">edit</i>Update Student
</Link>
</div>
<span>{' '} </span>
<div className="section col 6">
<div
onClick={() => props.deleteStudent(props.id)}
className="section red waves-effect waves-light btn"
>
<i className="material-icons left">delete</i>Delete Student (THERE
IS NO CONFIRM!!!)
</div>
</div>
</div>
);
}
};
export default StudentActions;
|
import React, { Component } from 'react'
import { Drawer, List, ListItem, ListItemText } from '@material-ui/core'
class AppDrawer extends Component{
render()
{
return (
<div>
<Drawer variant='permanent' anchor='left'>
<List>
<ListItem button>
<ListItemText primary='Load Data'></ListItemText>
</ListItem>
<ListItem button>
<ListItemText primary='Save Data'></ListItemText>
</ListItem>
<ListItem button>
<ListItemText primary='New Corpus'></ListItemText>
</ListItem>
</List>
</Drawer>
</div>
);
}
}
export default AppDrawer;
|
import { STRESS_FACTORS_SAVE_INTERPRETATION } from './constants';
export function saveTest(answers) {
return {
type: STRESS_FACTORS_SAVE_INTERPRETATION,
answers
};
}
|
/**
* @author v.lugovsky
* created on 16.12.2015
*/
(function () {
'use strict';
angular.module('BlurAdmin.pages.security', [])
.config(routeConfig);
/** @ngInject */
function routeConfig($stateProvider) {
$stateProvider
.state('security', {
url: '/security',
template: '<ui-view autoscroll="true" autoscroll-body-top></ui-view>',
// templateUrl: 'app/pages/security/security.html',
abstract: true,
title: '安全检查',
controller: 'securityPageCtrl',
sidebarMeta: {
icon: 'ion-qr-scanner',
order: 1000,
},
})
.state('security.account', {
url: '/account',
templateUrl: 'app/pages/security/account/security.html',
// abstract: true,
title: '安全检查台账',
sidebarMeta: {
order: 500,
},
})
.state('security.add', {
url: '/add',
templateUrl: 'app/pages/security/add/add.html',
// abstract: true,
title: '安全检查台账添加',
// controller:'securityPageCtrl',
sidebarMeta: {
order: 500,
},
})
.state('security.department', {
url: '/department',
templateUrl: 'app/pages/security/department.html',
// abstract: true,
title: '部门安全检查',
// controller:'securityPageCtrl',
sidebarMeta: {
order: 500,
}
})
.state('security.company', {
url: '/company',
templateUrl: 'app/pages/security/company.html',
// abstract: true,
title: '企业安全检查',
// controller:'securityPageCtrl',
sidebarMeta: {
order: 500,
}
})
.state('security.daily', {
url: '/daily',
templateUrl: 'app/pages/security/daily.html',
// abstract: true,
title: '日常安全检查',
// controller:'securityPageCtrl',
sidebarMeta: {
order: 500,
}
});
}
})();
|
const getPostsByCategory = require('utilities/operations/post/getPostsByCategory');
const { redisSetter } = require('utilities/redis');
const { LANGUAGES, HOT_NEWS_CACHE_SIZE, TREND_NEWS_CACHE_SIZE } = require('utilities/constants');
async function getDbPostsIds(type) {
let idsByWithLocales = [];
switch (type) {
case 'hot':
idsByWithLocales = await Promise.all(LANGUAGES.map(async (locale) => {
const { posts, error } = await getPostsByCategory({
category: 'hot',
skip: 0,
limit: HOT_NEWS_CACHE_SIZE,
user_languages: [locale],
keys: '_id children',
});
if (error) {
return console.error(error);
}
return { locale, ids: posts.map((post) => `${post.children}_${post._id}`) };
}));
break;
case 'trending':
idsByWithLocales = await Promise.all(LANGUAGES.map(async (locale) => {
const { posts, error } = await getPostsByCategory({
category: 'trending',
skip: 0,
limit: TREND_NEWS_CACHE_SIZE,
user_languages: [locale],
keys: '_id net_rshares',
});
if (error) {
return console.error(error);
}
return { locale, ids: posts.map((post) => `${post.net_rshares}_${post._id}`) };
}));
break;
}
return idsByWithLocales.filter((arr) => arr.ids.length > 0);
}
exports.updateFeedsCache = async () => {
// get array with ids by each language(locale)
// array of objects {locale:'en-US', ids:['123_asdf'...]}
const hotFeedCache = await getDbPostsIds('hot');
const trendFeedCache = await getDbPostsIds('trending');
// update id lists in redis
await Promise.all(hotFeedCache.map(async (localeFeed) => {
await redisSetter.updateHotLocaleFeedCache(localeFeed);
}));
await Promise.all(trendFeedCache.map(async (localeFeed) => {
await redisSetter.updateTrendLocaleFeedCache(localeFeed);
}));
};
|
/**
* @provides javelin-behavior-line-chart
* @requires javelin-behavior
* javelin-dom
* javelin-vector
* phui-chart-css
*/
JX.behavior('line-chart', function(config) {
function fn(n) {
return n + '(' + JX.$A(arguments).slice(1).join(', ') + ')';
}
var h = JX.$(config.hardpoint);
var d = JX.Vector.getDim(h);
var padding = {
top: 24,
left: 48,
bottom: 48,
right: 32
};
var size = {
frameWidth: d.x,
frameHeight: d.y,
};
size.width = size.frameWidth - padding.left - padding.right;
size.height = size.frameHeight - padding.top - padding.bottom;
var x = d3.time.scale()
.range([0, size.width]);
var y = d3.scale.linear()
.range([size.height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient('bottom');
var yAxis = d3.svg.axis()
.scale(y)
.orient('left');
var svg = d3.select('#' + config.hardpoint).append('svg')
.attr('width', size.frameWidth)
.attr('height', size.frameHeight)
.attr('class', 'chart');
var g = svg.append('g')
.attr('transform', fn('translate', padding.left, padding.top));
g.append('rect')
.attr('class', 'inner')
.attr('width', size.width)
.attr('height', size.height);
var line = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.count); });
var data = [];
for (var ii = 0; ii < config.x[0].length; ii++) {
data.push(
{
date: new Date(config.x[0][ii] * 1000),
count: +config.y[0][ii]
});
}
x.domain(d3.extent(data, function(d) { return d.date; }));
var yex = d3.extent(data, function(d) { return d.count; });
yex[0] = 0;
yex[1] = yex[1] * 1.05;
y.domain(yex);
g.append('path')
.datum(data)
.attr('class', 'line')
.attr('d', line);
g.append('g')
.attr('class', 'x axis')
.attr('transform', fn('translate', 0, size.height))
.call(xAxis);
g.append('g')
.attr('class', 'y axis')
.attr('transform', fn('translate', 0, 0))
.call(yAxis);
var div = d3.select('body')
.append('div')
.attr('class', 'chart-tooltip')
.style('opacity', 0);
g.selectAll('dot')
.data(data)
.enter()
.append('circle')
.attr('class', 'point')
.attr('r', 3)
.attr('cx', function(d) { return x(d.date); })
.attr('cy', function(d) { return y(d.count); })
.on('mouseover', function(d) {
var d_y = d.date.getFullYear();
var d_m = d.date.getMonth();
var d_d = d.date.getDate();
div
.html(d_y + '-' + d_m + '-' + d_d + ': ' + d.count)
.style('opacity', 0.9)
.style('left', (d3.event.pageX - 60) + 'px')
.style('top', (d3.event.pageY - 38) + 'px');
})
.on('mouseout', function() {
div.style('opacity', 0);
});
});
|
const router = require('koa-router')()
const { getBlogList,delBlogById,updataBlog } = require('../../controller/admin')
router.prefix('/api/admin')
router.post('/getBlogList', async (ctx, next) => {
const { pageIndex, pageSize, userName } = ctx.request.body
ctx.body = await getBlogList(userName,pageIndex-1,pageSize)
})
// 删除博客
router.get('/deleteBlog',async(ctx,next)=>{
const { id } = ctx.query
ctx.body = await delBlogById(id)
})
// 修改博客
router.post('/updataBlogContent',async(ctx,next)=>{
const { id,content } = ctx.request.body
ctx.body = await updataBlog(id,content)
})
module.exports = router
|
import Table from "react-bootstrap/Table";
import { Link, useDispatch } from "../../lib/imported";
import { getTeamById } from "../../js/TeamsSlice";
const Item = ({ teams }) => {
const dispatch = useDispatch();
const handleClick = (id) => {
console.log("IIID", id);
dispatch(getTeamById(id));
};
return (
<div className="itemTable">
<Table striped bordered hover variant="dark">
<thead>
<tr>
<th>#ID</th>
<th>Icon</th>
<th>Team Name</th>
</tr>
</thead>
<tbody>
{teams.map((team) => (
<tr key={team.id}>
<td key={team.id} onClick={() => handleClick(team.id)}>
<Link to={`/teams/${team.id}`}>{team.id}</Link>
</td>
<td>
<img alt="sm" src={team.image_url} className="image" />
</td>
<td>{team.name}</td>
</tr>
))}
</tbody>
</Table>
</div>
);
};
export default Item;
|
import {APP_NAME} from '../../../config';
export const REDUCERS_GROUP_PREFIX = `${APP_NAME}/auth`;
const ENDPOINT_AUTH = '/auth';
export const ENDPOINT_SIGN_IN = ENDPOINT_AUTH + '/login';
export const ENDPOINT_LOGOUT = ENDPOINT_AUTH + '/logout';
export const ENDPOINT_SIGN_UP = ENDPOINT_AUTH + '/sign-up';
export const ENDPOINT_RESET_PASSWORD = '/auth/reset-password';
|
//person object with various properties
let person = {
firstName: 'Nishant',
lastname: 'Arora',
age: 21,
hometown: 'Delhi',
college: 'Manipal University Jaipur',
company: 'Celigo'
};
console.log('Name: ' + person.firstName + ' ' + person.lastname);
console.log('Age: ' + person.age);
console.log('From ' + person.hometown);
console.log('Studied at ' + person.college);
console.log('Works at ' + person.company);
|
import Vue from 'vue'
import App from './App.vue'
import 'bootstrap'
import 'bootstrap/dist/css/bootstrap.min.css'
window.$ = require('jquery');
window.PlateList={
1:{
item:'الف',
code:'01'
},
2:{
item:'ب',
code:'02'
},
3:{
item:'پ',
code:'03'
},
4:{
item:'ت',
code:'04'
},
5:{
item:'ث',
code:'05'
},
6:{
item:'ج',
code:'06'
},
7:{
item:'چ',
code:'07'
},
8:{
item:'ح',
code:'08'
},
9:{
item:'خ',
code:'09'
},
10:{
item:'د',
code:'10'
},
11:{
item:'ذ',
code:'11'
},
12:{
item:'ر',
code:'12'
},
13:{
item:'ز',
code:'13'
},
15:{
item:'س',
code:'15'
},
16:{
item:'ش',
code:'16'
},
17:{
item:'ص',
code:'17'
},
18:{
item:'ض',
code:'18'
},
19:{
item:'ط',
code:'19'
},
20:{
item:'ظ',
code:'20'
},
21:{
item:'ع',
code:'21'
},
22:{
item:'غ',
code:'22'
},
23:{
item:'ف',
code:'23'
},
24:{
item:'ق',
code:'24'
},
25:{
item:'ک',
code:'25'
},
26:{
item:'گ',
code:'26'
},
27:{
item:'ل',
code:'27'
},
28:{
item:'م',
code:'28'
},
29:{
item:'ن',
code:'29'
},
30:{
item:'و',
code:'30'
},
31:{
item:'هـ',
code:'31'
},
32:{
item:'ی',
code:'32'
},
33:{
item:'<i class="fas fa-wheelchair"></i>',
code:'14'
},
};
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
|
/* common */
export const NUM_HREF = 'num_href';
export const SIMULATION_LOGIN = 'simulation_login'
/* agent 下面两个 是示例 实际没有使用 */
export const AGENT_CHANGE_TYPE = 'agent_change_type';
export const AGENT_CHANGE_DATE = 'agent_change_date';
|
//-*- coding: utf-8 -*-
//############################################################################
//
// OpenERP, Open Source Management Solution
// This module copyright (C) 2015 Therp BV <http://therp.nl>.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
//############################################################################
openerp.web_ir_actions_act_window_message = function(instance)
{
instance.web.ActionManager.include({
ir_actions_act_window_message: function(action, options)
{
var self = this,
buttons = [];
if(action.close_button_title !== false)
{
buttons.push({
text: action.close_button_title ||
instance.web._t('Close'),
click: function() { dialog.close() },
oe_link_class: 'oe_highlight',
})
}
var dialog = new instance.web.Dialog(
this,
{
size: 'medium',
title: action.title,
buttons: buttons.concat(
this.ir_actions_act_window_message_get_buttons(
action, function() { dialog.close() })
),
},
jQuery(instance.web.qweb.render(
'web_ir_actions_act_window_message',
{
'this': this,
'action': action,
}))
)
return dialog.open();
},
ir_actions_act_window_message_get_buttons: function(action, close_func)
{
// return an array of button definitions from action
var self = this;
return _.map(action.buttons || [], function(button_definition)
{
return {
text: button_definition.name || 'No name set',
oe_link_class: button_definition.oe_link_class ||
'oe_highlight',
click: function() {
if(button_definition.type == 'method')
{
(new instance.web.Model(button_definition.model))
.call(
button_definition.method,
button_definition.args,
button_definition.kwargs
).then(function(result)
{
if(_.isObject(result))
{
self.do_action(result);
}
else
{
if(
self.inner_widget &&
self.inner_widget.views
)
{
self.inner_widget
.views[self.inner_widget.active_view]
.controller.recursive_reload();
}
}
});
}
else
{
self.do_action(button_definition);
}
close_func();
},
}
});
},
});
}
|
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import './style.css'
export default class Card extends Component {
render () {
let classList = this.props.size ? this.props.size : ''
return (
<div className={`card ${classList}`}>
<Link to={this.props.projectLink} className='card-cta'>
<picture>
<source
type='image/webp'
srcSet={this.props.image.replace(/\.[^/.]+$/, '.webp')}
/>
<img src={this.props.image} alt={this.props.name} />
</picture>
</Link>
<div className='project-info-wrapper'>
<Link to={this.props.projectLink}>
<div className='project-info'>
<span>{this.props.projectLink}</span>
<h3>{this.props.name}</h3>
{this.props.languageIcon && (
<img src={this.props.languageIcon} alt='Project Language' />
)}
</div>
</Link>
<div className='project-meta'>
<a href={this.props.githubLink}>
<img src='/svg/github-circle.svg' alt='Github Profile' />
<span>view code</span>
</a>
<Link to={this.props.projectLink}>
<img src='/svg/play.svg' alt='View Project' />
<span>view project</span>
</Link>
</div>
</div>
</div>
)
}
}
Card.defaultProps = {
size: 'one-by-one'
}
|
var pjson = require('../../package.json');
function mensaje(){
return "API de Notificaciones ver " +pjson.version;
}
module.exports = {
mensaje: mensaje,
};
|
const fs = require('fs');
const input = fs.readFileSync('./day3_input.txt', { encoding: 'utf8' })
.trim()
.split('\n');
function part1() {
const input1 = input.map(item => {
return item.trim().split(/\s+/).map(Number).sort((a, b) => b - a);
});
let sum = 0;
for (const item of input1) {
if (item[0] < (item[1] + item[2])) {
sum++;
}
}
return sum;
}
function part2() {
const input2 = input.map(item => {
return item.trim().split(/\s+/).map(Number);
})
.reduce((result, item) => {
result[0].push(item[0]);
result[1].push(item[1]);
result[2].push(item[2]);
return result;
}, [ [], [], [] ])
.reduce((result, item) => {
return result.concat(item);
}, []);
let result = [];
while (input2.length) {
const item = [
input2.shift(),
input2.shift(),
input2.shift()
];
result.push(item.sort((a, b) => b - a));
}
let sum = 0;
for (const item of result) {
if (item[0] < (item[1] + item[2])) {
sum++;
}
}
return sum;
}
console.log('Part 1: %d', part1());
console.log('Part 2: %d', part2());
|
//import { useSelector } from "react-redux"
//import { useParams } from "react-router"
//import { ReactComponent as NothingHereImage } from "../../Assets/Images/empty.svg"
//import SideBar from "../SideBar/SideBar"
const Ride = (props) => {
//const {id} = useParams()
return (
<>
<h1>Hello</h1>
</>
)
}
export default Ride
|
var currtop;
var tar;
/**
*
*/
function init() {
currtop = 0;
tar = 0;
//setInterval("show()",1000);
show();
showline();
}
/**
* @returns
*/
function reheight() {
return document.getElementById("Slider")["offsetHeight"];
}
/**
*
*/
function show() {
if (tar == 0) {
$("#Slider").fadeOut(1000);
setTimeout("changeht()", 1100);
tar = 1;
setTimeout("show()", 1200);
} else {
$("#Slider").fadeIn(600);
tar = 0;
setTimeout("show()", 2500);
}
}
/**
*
*/
function changeht() {
if (currtop > -957) {
move(currtop - 319);
currtop -= 319;
} else {
move(0);
currtop = 0;
}
}
/**
* @param count
*/
function move(count) {
document.getElementById("Slider").style.top = count + "px";
}
var ptxt = new Array(6);
ptxt[0] = "战国时候。。";
ptxt[1] = "某人有了第一台手机。。";
ptxt[2] = "他的尾号后四位是1234。。。";
ptxt[3] = "结果,他的下辈子。。。。";
ptxt[4] = "所以。。";
ptxt[5] = "人的手机号码和下辈子的Ta有关系。。";
var pobj = new Array("p1", "p2", "p3", "p4", "p5", "p6");
//pobj[0] = "p1";
//pobj[1] = "p2";
//pobj[2] = "p3";
var obj;
/**
*
*/
function showline() {
//alert("OK");
for ( var ii = 0; ii < ptxt.length; ii++) {
//alert(ptxt.length);
//alert(pobj.length);
obj = document.getElementById(pobj[ii]);
//alert(obj);
setTimeout("showword(" + ii + ")", 2000 * ii);
//alert("OK");
//showword(ptxt[ii],obj);
}
}
/**
* @param count
*/
function showword(count) {
var words = ptxt[count];
//alert(words);
for ( var jj = 0; jj < words.length; jj++) {
//alert(words.length);
setTimeout("pwchange(" + count + "," + jj + ")", 60 * jj);
}
}
/**
* @param count
* @param jj
*/
function pwchange(count, jj) {
var ap = document.getElementById(pobj[count]);
ap.innerHTML = ptxt[count].substr(0, jj);
}
function dosubmit(){
var form = document.getElementById('form');
form.submit();
}
|
exports.up = knex => {
return knex.schema.table('recordings', table => {
table.enum('status', ['in_progress', 'finished', 'error']);
});
};
exports.down = knex => {
return knex.schema.table('recordings', table => {
table.dropColumn('status');
});
};
|
// @flow
import React, { Component } from "react";
import { connect } from "react-redux";
import {
type AsyncStatusType,
type NotificationType,
} from "shared/types/General";
import Layout from "components/layout";
import Input from "components/Input";
import Button from "components/button";
import Row from "components/Row";
import Col from "components/Col";
import Select from "components/Select";
import Alert from "components/Alert";
import uuid from "uuid";
import Textarea from "components/TextArea";
import Crew from "constants/crew";
import Actors from "constants/actors";
import MultiSelect from "components/MultiSelect";
import Loader from "components/loader";
import { getAllScripts, initializeScript } from "action/script";
import {
initializeScene,
getAllScenes,
onChangeSceneField,
updateScene,
onAddNewLayer,
} from "action/scene";
import { getAllInventory } from "action/inventory";
import { queryParamsParse } from "shared/helpers/url";
import { ASYNC_STATUS } from "constants/async";
import "./styles.scss";
type ScriptsPageProps = {
getAllInventory: Function,
onAddNewLayer: Function,
updateScene: Function,
onChangeSceneField: Function,
initializeScene: Function,
getAllScenes: Function,
initializeScript: Function,
getAllScripts: Function,
scriptNotification: NotificationType,
scriptStatus: AsyncStatusType,
scripts: Array<any>,
sceneNotification: NotificationType,
sceneStatus: AsyncStatusType,
scenes: Array<any> | null,
location: {
search: string,
},
inventoryNotification: NotificationType,
inventoryStatus: AsyncStatusType,
inventory: Array<any>,
};
type ScriptsPageState = {
scriptName: string,
data: Array<any>,
};
class ScriptsPage extends Component<ScriptsPageProps, ScriptsPageState> {
state = {
selectedScript: "",
};
componentDidMount() {
const {
location: { search },
getAllScripts,
initializeScript,
initializeScene,
} = this.props;
let filter = queryParamsParse(search);
initializeScript();
initializeScene();
if (filter.scriptName) {
this.onSelectScript(filter.scriptName);
} else {
getAllScripts();
}
}
onSelectScript = (scriptId) => {
this.setState(
{
...this.state,
selectedScript: scriptId,
},
this.getDependents(scriptId)
);
};
getDependents = (scriptId) => {
this.props.getAllScenes(scriptId);
this.props.getAllInventory(scriptId);
};
addNewLayer = () => {
const { scenes } = this.props;
const { selectedScript } = this.state;
const newLayer = {
id: uuid.v4(),
sceneNumber: (scenes.length + 1).toString(),
scriptId: selectedScript,
location: "",
dayPart: "",
description: "",
time: "",
actors: [],
inventory: [],
crew: [],
stories: [],
weatherstatus: "",
};
this.props.onAddNewLayer(newLayer);
this.setState({
newLayer,
});
};
onChangeSceneField = (sceneId, field) => {
this.props.onChangeSceneField({ sceneId, field });
};
onSelectActors = (sceneId, actors) => {
const selectedActors = actors.map((actor) => {
let details = Actors.filter(({ actorName }) => actorName === actor.name);
return details[0];
});
this.props.onChangeSceneField({
sceneId,
field: { actors: selectedActors },
});
};
onSelectCrew = (sceneId, crew) => {
const selectedCrew = crew.map((member) => {
let details = Crew.filter(
({ employeeName }) => employeeName === member.name
);
return details[0];
});
this.props.onChangeSceneField({
sceneId,
field: { crew: selectedCrew },
});
};
onSelectInventory = (sceneId, inInventory) => {
const { inventory } = this.props;
const selectedInventory = inInventory.map((item) => {
let details = inventory.filter(({ itemId }) => itemId === item.value);
return details[0];
});
this.props.onChangeSceneField({
sceneId,
field: { inventory: selectedInventory },
});
};
onSubmit = (sceneId) => {
const { scenes } = this.props;
let sceneToBeSubmit = scenes.filter((scene) => scene.id === sceneId);
this.props.updateScene(sceneToBeSubmit[0]);
};
render() {
const {
scriptNotification,
scripts,
scriptStatus,
sceneNotification,
sceneStatus,
scenes,
inventory,
inventoryStatus,
} = this.props;
const { scriptName } = this.state;
let scriptOptions =
scripts.length > 0
? [
...scripts.map(({ id, script }) => {
return { name: script, value: id };
}),
]
: [];
let actorOptions = Actors.map(({ actorName }) => actorName);
let crewOptions = Crew.map(({ employeeName }) => employeeName);
let inventoryOptions =
inventory && inventory.length > 0
? inventory.map(({ itemId, itemName }) => {
return { name: itemName, value: itemId };
})
: [];
return (
<Layout>
{scriptNotification && (
<Alert type={scriptNotification.type}>
{scriptNotification.message}
</Alert>
)}
{sceneNotification && (
<Alert type={sceneNotification.type}>
{sceneNotification.message}
</Alert>
)}
{scriptStatus === ASYNC_STATUS.LOADING ||
sceneStatus === ASYNC_STATUS.LOADING ||
inventoryStatus === ASYNC_STATUS.LOADING ? (
<Loader isLoading />
) : (
<div className="scripts">
<div className="scripts-header">
<Row>
<Col>
<div className="scripts-header-label">Select Script Name</div>
</Col>
<Col>
<div className="scripts-header-select">
<Select
placeholder="select"
options={scriptOptions}
selected={this.state.scriptName}
onChange={this.onSelectScript}
/>
</div>
</Col>
</Row>
</div>
{scenes && (
<div className="scripts-content">
<div className="scripts-content-name">{scriptName}</div>
{scenes.length > 0 &&
scenes.map((scene) => {
return (
<div key={scene.id} className="scripts-content-item">
<Row>
<Col>
<Input
id={`${scene.id}-number`}
text={scene.sceneNumber}
disabled
/>
</Col>
<Col>
<Select
placeholder="Day type"
selected={scene.dayPart}
options={[
"Morning",
"Afternoon",
"Evening",
"Night",
]}
onChange={(dayPart) =>
this.onChangeSceneField(scene.id, { dayPart })
}
/>
</Col>
<Col>
<Input
id={`${scene.id}-location`}
placeholder="script location"
text={scene.location}
onChange={(location) =>
this.onChangeSceneField(scene.id, { location })
}
/>
</Col>
<Col>
<Input
type="time"
placeholder={`${scene.id}-time`}
text={scene.time}
onChange={(time) =>
this.onChangeSceneField(scene.id, { time })
}
/>
</Col>
</Row>
<Row>
<Col>
<MultiSelect
placeholder="Actors"
options={actorOptions}
onChange={(selectedActors) =>
this.onSelectActors(scene.id, selectedActors)
}
/>
</Col>
<Col>
<MultiSelect
placeholder="Crew"
options={crewOptions}
onChange={(selectedCrew) =>
this.onSelectCrew(scene.id, selectedCrew)
}
/>
</Col>
<Col>
<MultiSelect
placeholder="Inventory"
options={inventoryOptions}
onChange={(selectedInventory) =>
this.onSelectInventory(
scene.id,
selectedInventory
)
}
/>
</Col>
</Row>
<Row>
<Col>
<Textarea
id={`${scene.id}-detail`}
text={scene.description}
onChange={(description) =>
this.onChangeSceneField(scene.id, {
description,
})
}
/>
</Col>
</Row>
<Row>
<Col>
<Button
type={Button.TYPE.SUCCESS}
onClick={() => this.onSubmit(scene.id)}
>
Save
</Button>
</Col>
</Row>
</div>
);
})}
<div className="scripts-content-add">
<Button onClick={this.addNewLayer}>Add Layer</Button>
</div>
</div>
)}
</div>
)}
</Layout>
);
}
}
const mapStateToProps = (state) => {
return {
scriptNotification: state.script.notification,
scripts: state.script.scripts,
scriptStatus: state.script.status,
sceneNotification: state.scene.notification,
sceneStatus: state.scene.status,
scenes: state.scene.scenes,
inventoryNotification: state.inventory.notification,
inventoryStatus: state.inventory.status,
inventory: state.inventory.inventory,
};
};
const Actions = {
initializeScript,
getAllScripts,
initializeScene,
getAllScenes,
onChangeSceneField,
updateScene,
onAddNewLayer,
getAllInventory,
};
export default connect(mapStateToProps, Actions)(ScriptsPage);
|
var url = "https://api.twitch.tv/kraken/channels/trumpsc";
var target, index;
$(function() {
$(".go").click(function() {
target = event.target.id;
index = target.substr(target.length - 1);
console.log(index);
channelInfo($("#searchbox" + index).val(), index);
});
$(".searchbox").click(function(event) {
$("#" + event.target.id).val("");
});
$(".searchbox").keydown(function(e) {
if (e.keyCode == 13) {
target = event.target.id;
index = target.substr(target.length -1);
channelInfo($("#" + target).val(), index);
}
});
channelInfo("freeCodeCamp", 1);
});
function channelInfo(channelName, boxNumber) {
$.ajax({
//url: 'https://wind-bow.gomix.me/twitch-api/users/freecodecamp',
url: 'https://api.twitch.tv/kraken/streams/' + channelName,
/*
xhrFields: {
withCredentials: "include"
},
*/
headers: {
"Client-ID": "jrkdkjsfjthn2oc2flhfw3c3zlwzyt",
//"Accept": "application/vnd.twitchtv.v5+json",
},
success: function(response){
console.log(response);
var currentDesc = "#channel-desc" + boxNumber;
var currentArt = "#channel-art" + boxNumber;
if (response.stream !== null) {
$("#channel-preview" + boxNumber).css({
"background-image": "url(\"" + response.stream.preview.large + "\")",
"background-size": "cover",
"filter": "opacity(80%)"
//"background-color": "#7c7"
});
$(currentDesc).css("background-color", "#000");
$(currentArt).css({
"background-image": "url(\"" + response.stream.channel.logo + "\")",
"background-size": "contain",
"background-repeat": "no-repeat"
});
$("#channel-name" + boxNumber).html(response.stream.channel.display_name);
$(currentDesc + " .streamer-name").attr("href", response.stream.channel.url);
$(currentDesc + " .game-name").attr("href", "https://www.twitch.tv/directory/game/" + response.stream.game.replace(" ", "%20"));
$("#channel-game" + boxNumber).html(response.stream.game);
//$(currentDesc).html("<p><span id=\"channel1-name\">" + response.stream.channel.display_name + "</span> is playing <span id=\"channel1-game\">" + response.stream.channel.game +"</span></p>");
$("#channel" + boxNumber).animate({"opacity": "1"}, 250);
} else {
$("#offline" + boxNumber).html(channelName + " is offline.");
$("#channel" + boxNumber).animate({"opacity": "0"}, 250);
}
}
});
}
|
(function(){
angular
.module('everycent.setup.institutions', ['everycent.common'])
.config(RouteConfiguration);
RouteConfiguration.$inject = ['$stateProvider'];
function RouteConfiguration($stateProvider){
$stateProvider
.state('institutions', {
url: '/institutions',
templateUrl: 'app/setup/institutions/list.html',
controller: 'InstitutionsCtrl as vm',
resolve:{
auth: ['$auth', function($auth){
return $auth.validateUser();
}]
}
})
.state('institutions.new', {
url: '/institutions/new',
templateUrl: 'app/setup/institutions/new.html'
})
.state('institutions.edit', {
url: '/institutions/edit',
templateUrl: 'app/setup/institutions/edit.html'
})
;
}
})();
|
const { setHeadlessWhen } = require('@codeceptjs/configure');
// turn on headless mode when running with HEADLESS=true environment variable
// export HEADLESS=true && npx codeceptjs run
setHeadlessWhen(process.env.HEADLESS);
exports.config = {
tests: './tests/*_test.js',
output: './output',
helpers: {
Puppeteer: {
url: 'https://app.futuresimple.com',
show: true,
windowSize: '1920x1080',
restart: false,
keepCookies: true,
"chrome": {
"args": ['--start-maximized']
},
}
},
include: {
I: './steps_file.js',
loginSubdomainPage: './pages/loginSubdomainPage.js',
loginAccountPage: './pages/loginAccountPage.js',
createLeadPage: './pages/createLeadPage.js',
leadStatusPage: './pages/leadStatusPage.js',
homeworkStep: './steps/homeworkStep.js'
},
bootstrap: null,
mocha: {},
name: 'testerHomeworkZendesk',
plugins: {
pauseOnFail: {},
retryFailedStep: {
enabled: true
},
tryTo: {
enabled: true
},
screenshotOnFail: {
enabled: true
}
}
}
|
/* **************************************************************************
* $Workfile:: webkernel.js $
* *********************************************************************/ /**
*
* @fileoverview Wrapper around Hapi framework.
*
*
* Created on Jan 18, 2015
* @author Young-Suk Ahn Park
*
* **************************************************************************/
var os = require("os");
var fs = require("fs");
var bunyan = require('bunyan');
var http = require('http');
var Hapi = require('hapi');
var Joi = require('joi');
var configSchema = require('../configSchema.js');
var loggy = require('./loggy.js');
var Q = require('q'); // Promise pattern library
module.exports = function(appName, opt_config) {
var appName_ = appName;
var server_;
var config_;
var startTime_;
if (opt_config === undefined)
{
config_ = require('config');
}
else if (typeof opt_config === 'string')
{
config_ = require(opt_config);
}
else
{
console.log('Error: config must be a valid filename');
}
//Validate the config before we start the app
// @todo - this probably isn't a great way at getting at the config
var error = Joi.validate(config_.getConfigSources()[0].parsed, configSchema);
if(error) {
throw new Error('Application config did not match the schema: ' + error);
}
if (!config_.controller)
{
config_.controller = './controller.js';
}
config_.logger = loggy.getLogger(config_, appName);
var logger = config_.logger;
var Controller = require(config_.controller);
this.getAppName = function ()
{
return appName_;
};
this.getConfig = function ()
{
return config_;
};
/**
* Returns the status of the application.
*
* @return {Object} The status of the application
*/
this.getStatus = function() {
//return info about the app
return {};
};
/**
* Sets up the application, a Hapi server.
*
* @return {Object} The reference to the http server (created by Hapi)
*/
this.appStartUp = function() {
startTime_ = new Date();
http.globalAgent.maxSockets = config_.maxSockets;
var serverOptions = {
debug: {
request: ['error', 'uncaught']
},
router: {
isCaseSensitive: false
},
cors: true
};
server_ = new Hapi.Server(config_.host, config_.port, serverOptions);
var controller = new Controller(appName_);
controller.initRoutes();
extendRoutes(this, controller);
server_.route(controller.routes);
logger.info('Starting server on port ' + config_.port);
server_.start();
return server_;
};
/**
* Extends the controller routes to include management routes:
* /ping, /index.html, and /log
* @param {Webservice} self Reference to this.
* @param {Controller} controller Reference to the controller that contains the list of routes
*/
var extendRoutes = function(self, controller) {
controller.routes.push(
controller.createRoute('GET', '/ping', function(request){
return self.handlePing();
}, null, false)
);
// This endpoint be used by HA health checker
controller.routes.push({
method: 'GET',
path: '/index.html',
handler: function (request) {
logger.debug('Handling /index.html');
var nodeEnv = process.env.NODE_ENV ? process.env.NODE_ENV.toUpperCase() : "NODE_ENV undefined";
var message = "I'm " + self.getAppName() + " with controller version " +controller.VERSION+ " on host " + os.hostname() + " (" + nodeEnv + ").";
message = message + "\nRunning since " + startTime_.toISOString();
request.reply(message).code(200);
}
});
// This endpoint for public assets
if (self.getConfig().publicDir) {
logger.info('Public directory set to ', self.getConfig().publicDir);
controller.routes.push({
method: 'GET',
path: '/public/{param*}',
handler:
{
directory: { path: self.getConfig().publicDir, listing: true, index: true }
}
});
}
/**
* This route displays the log's n last lines.
* In order to trigger this route, you can use browser to point
* http://<host>:<port>/log[&lines=<n>]
* endpoint.
*
* @todo - Do proper unit test. =)
*
*/
controller.routes.push({
method: 'GET',
path: '/log',
handler: function (request) {
if (!config_.logAllowWebAccess) {
request.reply('Oh no, you cannot do this!').code(403);
return;
}
// obtain logFile config.
if (config_.logToFile) {
// http://nodejs.org/api.html#_child_processes
var sys = require('sys');
var exec = require('child_process').exec;
var numLines = (request.query.lines) ? request.query.lines : 10;
if (numLines > 200) {
request.reply("Please lines < 200").code(200);
return;
}
var logDir = (config_.logDir) ? config_.logDir : './';
if (logDir.match('/$') != '/') {
logDir = logDir+ '/';
}
// The log filename is <appname>.log[.<rotation_num>]
var rotationNum = (request.query.r) ? "."+request.query.r : "";
var logFilename = appName_ + '.log' + rotationNum;
var commandLine = 'tail -' + numLines + ' ' + logDir + logFilename;
if (!fs.existsSync(logDir + logFilename)) {
request.reply("Log file " + logFilename + " does not exist.").code(404);
return;
}
//console.log(commandLine);
var fetchLogAndReturn = function (error, stdout, stderr)
{
if (!error) {
request.reply(stdout).code(200);
} else {
request.reply(JSON.stringify(error)).code(500);
}
};
exec(commandLine, fetchLogAndReturn);
} else {
callback(null, "logToFile disabled");
}
}
});
};
/**
* Shuts down the application.
*
*/
this.appShutDown = function(evt, err) {
// @todo: release Caches
server_.stop({ timeout: 1 * 1000 }, function () {
logger.warn('Shutting down server.');
process.exit(0);
});
};
/**
* Starts the http server
*/
this.start = function() {
server.start();
};
/**
* Retrieves a content by it's type and guid
*
* @param {string} type The content type: activity or assignment
* @param {string} guid The guid of the content
* @return {Promise} with then() and fin()
*/
this.handlePing = function(guid) {
var deferred = Q.defer();
var response = {
"code": 200,
"data": os.hostname()
};
deferred.resolve(response);
return deferred.promise;
};
};
|
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const mongoose = require('mongoose');
mongoose.Promise = Promise;
mongoose.connect('mongodb://10.31.18.213:27017/noAngular')
.then(() => console.log('Mongoose Up'));
const User = require('./models/users');
app.use(bodyParser.json());
app.post('/api/login',async (req,res) => {
const {username, password} = req.body;
console.log(username, password);
const resp = await User.findOne({username, password});
console.log(resp);
if(!resp){
console.log("Incorrect details");
//user login is incorrect
}else{
console.log("logging you in");
//make a session and set user to logged in
}
res.send("K");
});
app.post('/api/register', async (req,res) => {
const {username, password} = req.body;
const user = new User({username:username,password:password});
const result = await user.save();
console.log(result);
//store this date on database
//Usermodel.save({})
});
app.get('/api/test',(req,res)=>{
console.log(req.body)
});
app.listen(1234,() => console.log('Server listening at 1234'));
|
const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const { secret } = require('../../config/keys');
router.post('/', async (req, res) => {
const { uid, email } = req.body;
try {
const jwtSign = await signJwtWithData(email, uid);
res.json({ status: 'Success', token: jwtSign });
} catch (error) {
res.status(400).json({ status: 'Failed', errorMessage: error.toString() });
}
});
const signJwtWithData = async (userData, username) => {
const data = {
username,
userData
};
return jwt.sign(data, secret, {
expiresIn: '1 days' // expires in 24 hours
});
};
module.exports = router;
|
const express = require('express');
const app = express();
const path = require('path');
const data = require('./proj-data.json');
app.set('view engine', 'pug');
app.use('/static', express.static(path.join(__dirname, 'public')));
app.get('/', function (req, res) {
res.render('index', { projects: data.projects });
});
app.get('/about', function (req, res) {
res.render('about');
});
app.get('/projects', function (req, res) {
res.render('project');
});
app.get('/projects/:projectID', function (req, res) {
const id = req.params.projectID;
const project = data.projects[id];
res.render('project', {title: project.project_name, description: project.description})
});
app.listen(3000, () => console.log('Example app listening on port 3000!'));
|
import React, { useState } from 'react'
import ReactDOM from 'react-dom'
const Header = (props) =>(
<div>
<h2>{props.text}</h2>
</div>
)
const StatisticLine = ({name, type}) => (
<div>
<table>
<tr>
<td>{name}</td>
<td>{type}</td>
</tr>
</table>
</div>
)
const Button = ({handleClick, text}) => (
<button onClick={handleClick}>
{text}
</button>
)
const App = () => {
const [clicks, setClicks] = useState ({
good: 0, neutral: 0, bad: 0, all: 0
})
const handleGoodClick = () =>
setClicks({ ...clicks, good:clicks.good +1, all:clicks.all +1})
const handleNeutralClick = () =>
setClicks({ ...clicks, neutral:clicks.neutral +1, all:clicks.all +1})
const handleBadClick = () =>
setClicks({ ...clicks, bad:clicks.bad +1, all:clicks.all +1})
let average = (clicks.good - clicks.bad) / clicks.all
let positive = clicks.good / clicks.all * 100
if (clicks.all == 0){
return (
<>
<Header text= "Give feedback"/>
<Button handleClick={handleGoodClick} text="good"/>
<Button handleClick={handleNeutralClick} text="neutral"/>
<Button handleClick={handleBadClick} text= "bad"/>
<Header text="Statistics"/>
<p> No feedback given</p>
</>
)
} else {
return (
<>
<Header text= "Give feedback"/>
<Button handleClick={handleGoodClick} text="good"/>
<Button handleClick={handleNeutralClick} text="neutral"/>
<Button handleClick={handleBadClick} text= "bad"/>
<Header text="Statistics"/>
<StatisticLine name="good" type={clicks.good}/>
<StatisticLine name="neutral" type={clicks.neutral}/>
<StatisticLine name="bad" type={clicks.bad}/>
<StatisticLine name="all" type={clicks.all}/>
<StatisticLine name="average" type={average}/>
<StatisticLine name="positive" type={positive}/>
</>
)
}
}
ReactDOM.render(<App />,
document.getElementById('root')
)
|
'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var chalk = require('chalk');
var mkdirp = require('mkdirp');
var AngularWebPackAngularJs = yeoman.generators.Base.extend({
promptUser: function() {
var done = this.async();
// have Yeoman greet the user
var prompts = [{
name: 'appName',
message: 'Enter your project name?'
}];
this.prompt(prompts, function(props) {
this.appName = props.appName;
done();
}.bind(this));
},
createFolders: function() {
mkdirp.sync(path.join("build"), function (err) {
if (err) console.error(err);
});
mkdirp.sync(path.join( "test"), function (err) {
if (err) console.error(err);
});
mkdirp.sync(path.join("src"), function (err) {
if (err) console.error(err);
});
mkdirp.sync(path.join("src", "core"), function (err) {
if (err) console.error(err);
});
mkdirp.sync(path.join("src", "pages"), function (err) {
if (err) console.error(err);
});
mkdirp.sync(path.join("src", "views"), function (err) {
if (err) console.error(err);
});
},
copyFiles: function() {
this.copy('editorconfig', '.editorconfig');
this.copy('jshintrc', '.jshintrc');
this.copy('travis.yml', '.travis.yml');
this.copy('bowerrc', '.bowerrc');
this.copy('gitignore', '.gitignore');
this.copy('_webpack.config.js', "webpack.config.js");
this.copy('_package.json', "package.json");
this.copy('_bower.json', "bower.json");
this.copy('test/_karma.config.js', path.join("test", "karma.config.js"));
this.copy('test/_test-context.js', path.join("test", "test-context.js"));
this.copy('test/_karma.config.js', path.join("test", "karma.config.js"));
this.copy('core/_bootstrap.js', path.join("src", "core", "bootstrap.js"));
this.copy('core/_core.directives.js', path.join("src", "core", "core.directives.js"));
this.copy('core/_core.factories.js', path.join("src", "core", "core.factories.js"));
this.copy('core/_core.providers.js', path.join("src", "core", "core.providers.js"));
this.copy('core/_core.services.js', path.join("src", "core", "core.services.js"));
this.copy('views/app.html', path.join("src", "views", "app.html"));
this.copy('views/login.html', path.join("src", "views", "login.html"));
this.copy('pages/home/_home.routing.js', path.join("src", "pages", "home", "home.routing.js"));
this.copy('pages/home/controllers/_home.controller.js', path.join("src", "pages", "home", "controllers", "home.controller.js"));
this.copy('pages/home/controllers/_home.controller.spec.js', path.join("src", "pages", "home", "controllers", "home.controller.spec.js"));
this.copy('pages/home/views/_home.html', path.join("src", "pages", "home", "views", "home.html"));
this.copy('pages/login/views/_login.html', path.join("src", "pages", "login", "views", "login.html"));
this.copy('pages/login/_login.routing.js', path.join("src", "pages", "login", "login.routing.js"));
this.copy('pages/login/controllers/_login.controller.js', path.join("src", "pages", "login", "controllers", "login.controller.js"));
this.copy('pages/login/controllers/_login.controller.spec.js', path.join("src", "pages", "login", "controllers", "login.controller.spec.js"));
var context = {
app_name: this.appName
};
this.template("build/_index.html", path.join("build", "index.html"), context);
this.template('_app.js', path.join( "src", "app.js") , context);
},
runNpm: function() {
console.log("\n Done loading files! \nInstalling Node modules and Bower packages...\n");
this.npmInstall("", function() {
console.log("\n Done installing node modules!\n Run 'npm start' to build and serve the project");
});
this.bowerInstall("", function() {
console.log("\n Done installing bower Packages\n");
});
}
});
module.exports = AngularWebPackAngularJs;
|
import React, { Component } from "react";
import PropTypes from "prop-types";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import { fetchCities } from "../actions/citiesActions";
import { getCurrentProfile } from "./../actions/profileActions";
import { debounce } from "lodash";
import Header from "../components/layout/Header";
// import Card from "@material-ui/core/Card";
// import CardContent from "@material-ui/core/CardContent";
// import Typography from "@material-ui/core/Typography";
import TextField from "@material-ui/core/TextField";
import ComplexCityButton from "./../components/layout/ComplexCityButton";
class Cities extends Component {
constructor(props) {
super(props);
this.state = {
cities: [],
city: "",
country: "",
query: "",
error: null,
text: ""
// filteredCities: []
};
}
componentDidMount() {
this.props.fetchCities();
}
// SEARCH WITH DEBOUNCE
handleSearch = debounce(text => {
this.setState({
query: text
});
}, 500);
render() {
let filteredCities = this.props.cities.cities.filter(city => {
return (
city.cityname.toLowerCase().includes(this.state.query.toLowerCase()) ||
city.country.toLowerCase().includes(this.state.query.toLowerCase())
);
});
return (
<div>
<Header title={"Cities List"} />
<div className="citysearchflex">
<TextField
id="filled-with-placeholder"
label="Search Destinations"
type="text"
placeholder="Type to Search Destinations"
onChange={e => this.handleSearch(e.target.value)}
margin="normal"
className="cityfilter"
variant="outlined"
/>
</div>
{/* CITIES */}
<div>
{filteredCities.length < 1 ? (
<div className="paragraphText">
There are no destinations matching your search query.
</div>
) : (
<React.Fragment>
{filteredCities.map(city => {
return (
<React.Fragment key={city._id}>
<Link
to={{
pathname: "/cities/" + city.url,
state: {
city: city.cityname,
country: city.country,
url: city.flagimg
}
}}
className="citylist"
>
<div className="flexIcons">
<div className="flexLink">
<ComplexCityButton
city={city.cityname}
country={city.country}
title={city.cityname}
src={city.flagimg}
url={city.url}
/>
</div>
</div>
<div className="itineraryCard" />
</Link>
</React.Fragment>
);
})}
</React.Fragment>
)}
</div>
</div>
);
}
}
const mapStateToProps = state => {
return {
cities: state.cities,
favid: state.favid,
profile: state.profile
};
};
Cities.propTypes = {
cities: PropTypes.object,
fetchCities: PropTypes.func,
getCurrentProfile: PropTypes.func
};
export default connect(
mapStateToProps,
{ fetchCities, getCurrentProfile }
)(Cities);
|
module.exports = {
apps: [
{
name: "Gemini",
script: "server.js",
max_memory_restart: "1024M", //超过1024内存自动重启
log_date_format: "YYYY-MM-DD HH:mm Z",
error_file: "/usr/local/logs/error.log",
out_file: "/usr/local/logs/out.log",
env: {
"NODE_ENV": "production",
}
}
]
}
|
function voltar(){
window.history.back()
}
function informacao(){
window.location.href = "Projeto/Paginas_Infos/info.html"
'Peter Parker (Tom Holland) está em uma viagem de duas semanas pela Europa, ao lado de seus amigos de escola, quando é surpreendido pela visita de Nick Fury (Samuel L. ... Até que Nick o procura para resolver um problema: Homem-Aranha precisa combater os monstros Elementais, que estão destruindo tudo pela frente.'
}
function assistir(){
window.location.href = "Projeto/Paginas_Infos/assistir.html"
}
|
// This is the main entry point of the application.
// It starts by requiring the Dependencies needed to run a reddit bot in the 'config/snoo-config.js' file.
// It then grabs a list of services from the 'service/_Services.js' file.
// These micro-services contain functions that allow a user to query, manipulate, and save externally [the data from the Reddit API].
// Require Configuration Files
require('dotenv').config({
path: "./pw.env"
});
// Require and Initialize The Snoo-Pendencies With Authentication Credentials
require('./config/snoo-config');
// Get List of Available Services
const Services = require('./service/_Services').get
const ascii_art = require('./ascii_art')
const SnooReaper = Services.snooReaper
ascii_art.displayMarquee(process.env.MASTER_SUB)
SnooReaper.checkMentions()
|
import React from 'react';
import './Footer.css';
import {withRouter} from 'react-router-dom';
import Logout from '../../../logout.png';
import axios from 'axios';
const Footer = (props) => {
const handleLogout = () => {
axios.post('/api/logout').then(res => {
props.history.push('/')
})
.catch(err => console.log(err))
}
return (
<div className='footer'>
<div>
<button onClick={handleLogout}><img src={Logout} alt='' className='logout' /></button>
</div>
</div>
)
}
export default withRouter(Footer);
|
import React, { Component } from 'react';
import * as Yup from 'yup';
import { Formik } from 'formik';
import { login } from '../../actions/auth';
import { connect } from 'react-redux';
import FormGroup from '@material-ui/core/FormGroup';
import { FormInput } from '../Form/Form';
import Button from '@material-ui/core/Button';
import ButtonGroup from '@material-ui/core/ButtonGroup';
import Box from '@material-ui/core/Box';
const initialValues = {
email: '',
password: '',
};
const validationSchema = Yup.object().shape({
email: Yup.string().required('Required'),
password: Yup.string().required('Required'),
});
class SignInForm extends Component {
onSubmit = (values) => {
const data = {
email: values.email,
password: values.password,
};
this.props.login(data);
};
render() {
return (
<Formik initialValues={initialValues} validationSchema={validationSchema} onSubmit={this.onSubmit}>
{(props) => (
<form noValidate onSubmit={props.handleSubmit}>
<FormGroup>
<FormInput name="email" type="email" label="E-mail" placeholder="E-mail address" props={props} />
</FormGroup>
<br />
<FormGroup>
<FormInput name="password" type="password" label="Password" placeholder="Password" props={props} />
</FormGroup>
<Box my={2}>
<ButtonGroup fullWidth>
<Button type="submit" color="primary">
Sign in
</Button>
{this.props.onCancel && <Button onClick={this.props.onCancel}>Cancel</Button>}
</ButtonGroup>
</Box>
</form>
)}
</Formik>
);
}
}
const mapStateToProps = (state) => ({});
const mapDispatchToProps = (dispatch) => ({
login: (data) => dispatch(login(data)),
});
export default connect(mapStateToProps, mapDispatchToProps)(SignInForm);
|
export function FareCalculator(distance, time, rateDetails, fleetsPrices) {
let price = null;
console.log('flettttttttttttttttttttts pricesssssssssssssssss', fleetsPrices);
if (fleetsPrices && fleetsPrices.items.length && fleetsPrices.items[0].fields) {
const dis = parseFloat(distance) / 1000;
console.log('dissssssssssssssssssssssssss', dis);
const data = fleetsPrices.items.find((item) => item.fields.fleetName === rateDetails.name);
const filterPrice =
data &&
data.fields &&
data.fields.fleetPrices.find((fleet) => dis >= fleet.fields.start && dis <= fleet.fields.end);
if (!filterPrice) {
price = { fields: { price: 0, returnPrice: 0 } };
console.log('priceeeeeeeeeee innnnnnnnnnnnnnn', price);
} else {
price = filterPrice;
}
console.log('priceeeeeeeeeeeeeeeeeeeeeeeeeeeee', price);
}
// let baseCalculated = ((parseFloat(rateDetails.rate_per_kilometer) * (parseFloat(distance) / 1000))) + ((parseFloat(rateDetails.rate_per_hour) * (parseFloat(time) / 3600)));
// let total = baseCalculated > parseFloat(rateDetails.min_fare) ? baseCalculated : parseFloat(rateDetails.min_fare);
// let convenienceFee = (total*parseFloat(rateDetails.convenience_fees)/100);
// let grand = total + convenienceFee;
return {
priceDetails: price
};
}
|
//TODO:缺少运行测试
function decorator(target) {
target.prototype.isTest = true;
}
@decorator()
class MyTestClass {
constructor() {
}
}
let obj = new MyTestClass();
console.log(`
@decorator()
class MyTestClass{
constructor(){
}
}
new MyTestClass() :
`, obj);
//---------------------------------------
function testable(isTestable) {
return function (target) {
target.isTestable = isTestable; //静态函数
target.prototype.isTestable = isTestable;
}
};
function readonly(target, name, descriptor) {
// descriptor对象原来的值如下
// {
// value: specifiedFunction,
// enumerable: false,
// configurable: true,
// writable: true
// };
console.log('propertyName:', name);
descriptor.writable = false;
return descriptor;
}
function log(target,name,descriptor) {
let oldValue=descriptor.value;
descriptor.value=function () {
console.log(`Calling ${name} with`,arguments);
return oldValue.apply(this,arguments);
}
return descriptor;
}
@testable(true)
class MyTestClass2 {
constructor(){
}
// readonly(Person.prototype, 'name', descriptor);
@readonly()
level(){
return 0;
}
@log
getValue(value='test'){
}
}
// @readonly
let obj1 = new MyTestClass2();
console.log(`
@decorator()
class MyTestClass2{
constructor(){
}
}
new MyTestClass2() :
`, obj1);
|
var acc = document.getElementsByClassName("btn");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function () {
this.classList.toggle("content");
// this.classList.toggle("fa-minus");
});
}
|
var fs = require("fs");
//Return all movies as array of Movie objects
function getMovies(callBack) {
let movies = "[{}]";
fs.readFile(__dirname + "/../data/movieList.json", "utf8", function(err, data) {
if (err) {
throw err;
} else {
movies = JSON.parse(data);
callBack(movies);
}
});
}
//Export functions
// module.exports = { getMovies: movies };
module.exports = getMovies;
|
/**
* Задача 4.
*
* Реализуйте класс Stringer, который будет иметь следующие методы (каждый принимает строку в качестве аргумента):
*
* - reverse(string) — возвращает строку в перевернутом виде;
* - uppercaseFirst(string) — возвращает строку, сделав ее первую букву заглавной;
* - uppercaseAll(string) — делает заглавной первую букву каждого слова строки и возвращает её.
*
* Условия:
* - Реализация решения — это синтаксис современных классов JavaScript.
*/
// Решение
class Stringer {
// constructor(string) {
// this.string = string;
// }
reverse(value) {
return [...value].reverse().join('');
}
uppercaseFirst(value) {
return value[0].toUpperCase() + value.slice(1);
}
uppercaseAll(value) {
const array = value.split(' ');
const arrayWithUpper = array.map(string => this.uppercaseFirst(string));
return arrayWithUpper.join(' ');
}
}
const stringer = new Stringer();
console.log(stringer.reverse('good morning!')); // !gninrom doog
console.log(stringer.uppercaseFirst('good morning!')); // Good morning!
console.log(stringer.uppercaseAll('good morning!')); // Good Morning!
exports.Stringer = Stringer;
|
import React from 'react';
import '../styles/App.css';
import '../styles/experience.css'
export class SAS extends React.Component {
render () {
return (
<React.Fragment>
<div id="sas-tile">
<p>
During the summer of 2018, I developed an unmoderated testing tool using React and Express JavScript
frameworks designed to conduct remote usability testing. I worked with another software developer
intern to implement designs and coordinate our project tasks through agile development.
</p>
<p>
This internship began as such a positive experience and continues to be one. I was
so thankful when I was given the opportunity to become a year-round intern with SAS.
At SAS, my confidence in my Computer Science abilities grew immensely. I felt supported by my mentors
and managers, and enjoyed collaborating with others who had a similar passion for Computer Science
and were also glad to be at SAS.
</p>
<p>
I am currently continuing work on the unmoderated testing tool through refactoring and converting the class
components to functional components using React hooks. I have really enjoyed the opportunity
to refactor the complex code that I built up from scratch. Each week I discover ways in which the code
I pieced together this summer while using the frameworks I was in the process of learning can now be
improved with new additions to those frameworks.
</p>
</div>
</React.Fragment>
);
}
}
|
console.log('test px loader aaa')
|
/**
* Drawers
*/
import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import Drawer from '@material-ui/core/Drawer';
import Button from '@material-ui/core/Button';
import List from '@material-ui/core/List';
import Divider from '@material-ui/core/Divider';
//Components
import PermanentDrawer from './component/PermanentDrawer';
import PersistentDrawer from './component/PersistentDrawer';
import { mailFolderListItems, otherMailFolderListItems } from './component/tileData';
// page title bar
import PageTitleBar from 'Components/PageTitleBar/PageTitleBar';
// rct card box
import RctCollapsibleCard from 'Components/RctCollapsibleCard/RctCollapsibleCard';
// intl messages
import IntlMessages from 'Util/IntlMessages';
const styles = {
list: {
width: 300,
},
listFull: {
width: 'auto',
},
};
class DrawerComponent extends React.Component {
state = {
top: false,
left: false,
bottom: false,
right: false,
};
toggleDrawer = (side, open) => () => {
this.setState({
[side]: open,
});
};
render() {
const { classes } = this.props;
const sideList = (
<div className={classes.list}>
<List>{mailFolderListItems}</List>
<Divider />
<List>{otherMailFolderListItems}</List>
</div>
);
const fullList = (
<div className={classes.listFull}>
<List>{mailFolderListItems}</List>
<Divider />
<List>{otherMailFolderListItems}</List>
</div>
);
return (
<div className="drawer-wrapper">
<PageTitleBar title={<IntlMessages id="sidebar.drawers" />} match={this.props.match} />
<RctCollapsibleCard
heading={<IntlMessages id="widgets.temporaryDrawers" />}
>
<Button color="primary" className="text-white mr-10 mb-10" variant="raised" onClick={this.toggleDrawer('left', true)}>Open Left</Button>
<Button color="primary" className="text-white mr-10 mb-10" variant="raised" onClick={this.toggleDrawer('right', true)}>Open Right</Button>
<Button color="primary" className="text-white mr-10 mb-10" variant="raised" onClick={this.toggleDrawer('top', true)}>Open Top</Button>
<Button color="primary" className="text-white mr-10 mb-10" variant="raised" onClick={this.toggleDrawer('bottom', true)}>Open Bottom</Button>
<Drawer open={this.state.left} onClose={this.toggleDrawer('left', false)}>
<div tabIndex={0} role="button" onClick={this.toggleDrawer('left', false)}
onKeyDown={this.toggleDrawer('left', false)} >
{sideList}
</div>
</Drawer>
<Drawer anchor="top" open={this.state.top} onClose={this.toggleDrawer('top', false)}>
<div tabIndex={0} role="button"
onClick={this.toggleDrawer('top', false)}
onKeyDown={this.toggleDrawer('top', false)}>
{fullList}
</div>
</Drawer>
<Drawer
anchor="bottom"
open={this.state.bottom}
onClose={this.toggleDrawer('bottom', false)}>
<div tabIndex={0} role="button" onClick={this.toggleDrawer('bottom', false)}
onKeyDown={this.toggleDrawer('bottom', false)}>
{fullList}
</div>
</Drawer>
<Drawer anchor="right" open={this.state.right} onClose={this.toggleDrawer('right', false)}>
<div tabIndex={0} role="button" onClick={this.toggleDrawer('right', false)}
onKeyDown={this.toggleDrawer('right', false)}>
{sideList}
</div>
</Drawer>
</RctCollapsibleCard>
<RctCollapsibleCard
heading={<IntlMessages id="widgets.permanentDrawers" />}
>
<PermanentDrawer />
</RctCollapsibleCard>
<RctCollapsibleCard
heading={<IntlMessages id="components.persistentDrawer" />}
>
<PersistentDrawer />
</RctCollapsibleCard>
</div>
);
}
}
export default withStyles(styles)(DrawerComponent);
|
const { router } = require("../../config/expressconfig");
const { sql } = require("../../config/dbConfig")
let changeUserStatus = router.post("/change-userSelection-status", (req, res) => {
let { id, status } = req.body;
let obj = {
status
};
sql.updateQuery('user', id, obj, (result) => {
return res.json({ message: "USER STATUS CHANGED", responseCode: 200, result });
});
});
module.exports = { changeUserStatus }
|
import cookie from 'js-cookie';
import config from './config';
export const getLocale = () => cookie.get(config.LOCALE_KEY);
export default {
getLocale,
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.