text stringlengths 7 3.69M |
|---|
import { prismaObjectType } from 'nexus-prisma'
export const User = prismaObjectType({
name: 'User',
definition: t => {
// Forwarding prisma type fields
t.prismaFields([
'id',
'createdAt',
'updatedAt',
'email',
'name'
])
}
})
export const UserConnection = prismaObjectType({
name: 'UserConnection',
definition (t) {
t.prismaFields(['*'])
t.field('aggregate', {
...t.prismaType.aggregate,
resolve (root, args, ctx) {
return ctx.prisma.usersConnection(args).aggregate()
}
})
}
})
|
var User = require('./../models/user.model');
var config = require('./../config/internalConfigs').defaultAdmin;
const newObject = new User({
nombre: config.name,
apellidos: config.lastname,
correo: config.email,
password: config.password,
tipo: config.type
});
// Check if the user already exists
User.getByEmail(newObject.correo,(err, object)=>{
if(!object){
// If the user does not exist, create a new one
User.createObject(newObject, null, (err, object)=>{
console.log("Admin user created");
});
}
});
|
import React from 'react';
import styles from './ModulePage.module.css';
import avatar from '../MainGrid/img/userAva.png';
import {NavLink} from 'react-router-dom';
const EditModulePage = (props) => {
let searchKey = props.searchKey;
let changeKey = 0;
if (searchKey === props.editUser.firstName) {
changeKey = 'userName';
} else if (searchKey === props.editUser.lastName ) {
changeKey = 'userSurname';
} else if (searchKey === props.editUser.position) {
changeKey = 'userPosition';
} else if (searchKey === props.editUser.city) {
changeKey = 'userCity';
}
let oldUserId = props.editUser.id;
let insertName = React.createRef();
let insertSurname = React.createRef();
let insertDateOfBirth = React.createRef();
let insertPosition = React.createRef();
let insertCity = React.createRef();
let insertStreet = React.createRef();
let insertHouse = React.createRef();
let insertApartment = React.createRef();
let checkboxRemoteWorking = React.createRef();
let insertUserRemoteworking = props.editUser.remoteWorking;
let setUserRemoteWorking = () => {
insertUserRemoteworking = 1;
}
let deleteUserRemoteWorking = () => {
insertUserRemoteworking = 0;
}
let onPushEditedUser = () => {
let newUserName = insertName.current.value;
let newUserSurname = insertSurname.current.value;
let newUserBirth = insertDateOfBirth.current.value;
let newUserPosition = insertPosition.current.value;
let newUserCity = insertCity.current.value;
let newUserStreet = insertStreet.current.value;
let newUserHouse = insertHouse.current.value;
let newUserApartment = insertApartment.current.value;
let newUserRemoteworking = insertUserRemoteworking;
props.pushEditedUser(oldUserId, newUserName, newUserSurname, newUserBirth, newUserPosition, newUserRemoteworking,
newUserCity, newUserStreet, newUserHouse, newUserApartment, changeKey);
changeKey = 0;
}
return (
<div className={styles.rootWrapper}>
<div className={styles.mainWrapper}>
<div className={styles.header}>Редактирование</div>
<div className={styles.moduleWrapper}>
<div className={styles.profileWrapper}>
<div className={styles.imageWrapper}>
<img src={avatar}/>
</div>
<div className={styles.infoWrapper}>
<div className={styles.mainInfoWrapper}>
<div className={styles.nameWrapper}>
<input className={styles.name} ref={insertName} defaultValue={props.editUser.firstName} placeholder='Имя' required autoFocus/>
</div>
<div className={styles.surnameWrapper}>
<input className={styles.surname} ref={insertSurname} defaultValue={props.editUser.lastName} placeholder='Фамилия' required/>
</div>
<div className={styles.birthdayWrapper}>
<input className={styles.birthday} ref={insertDateOfBirth} defaultValue={props.editUser.dateOfBirth} placeholder='Дата рождения'
type='date' required/>
</div>
<div className={styles.positionWrapper}>
<form>
<select className={styles.position} ref={insertPosition}>
<option>{props.editUser.position}</option>
<option>Разработчик</option>
<option>Dev-Ops инженер</option>
<option>Тестировщик</option>
<option>Верстальщик</option>
<option>Менеджер</option>
<option>Тех. поддержка</option>
<option>Стажёр</option>
</select>
</form>
<div>
{ (insertUserRemoteworking === 1
? <div><input type='checkbox' onClick={deleteUserRemoteWorking} ref={checkboxRemoteWorking} checked/> <a>Удалёнка</a></div>
: <div><input type='checkbox' onClick={setUserRemoteWorking} ref={checkboxRemoteWorking} /> <a>Удалёнка</a></div>)}
</div>
</div>
</div>
<div className={styles.adressInfoWrapper}>
<div className={styles.cityWrapper}>
<input className={styles.city} ref={insertCity} defaultValue={props.editUser.city} placeholder='Город' required/>
</div>
<div className={styles.streetWrapper}>
<input className={styles.street} ref={insertStreet} defaultValue={props.editUser.street} placeholder='Улица' required/>
</div>
<div className={styles.houseWrapper}>
<input className={styles.house} ref={insertHouse} defaultValue={props.editUser.house} placeholder='Дом' required/>
</div>
<div className={styles.roomWrapper}>
<input className={styles.room} ref={insertApartment} defaultValue={props.editUser.apartment} placeholder='Квартира' required/>
</div>
</div>
</div>
</div>
<div className={styles.restWrapper}>
<div className={styles.addButtonWrapper}>
<button>
<NavLink to='/MainPage' onClick={onPushEditedUser} className={styles.addLink}>Сохранить</NavLink>
</button>
</div>
<div className={styles.undoButtonWrapper}>
<button>
<NavLink to='/MainPage' className={styles.addLink}>Назад</NavLink>
</button>
</div>
</div>
</div>
<div className={styles.header}></div>
</div>
</div>
)
}
// pattern='\d[0-9]{2}(\.\d[0-9]{2}(\.\d[0-9]{4}))'
export default EditModulePage; |
// pages/feedback/detail/detail.js
const App = getApp();
const utils = require('../../common/utils.js')
Page({
/**
* 页面的初始数据
*/
data: {
openid: App.globalData.openid,
type: '', // 反馈类型
images: [], // 截图存储
describe: '', // 问题描述
concat: '', // 联系方式
maxImagesLength: 4, // 最大截图上传数量
message: {
message: '',
type: ''
},
canUpload: false // 是否可提交,默认不可以提交
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
const { type } = options
if (type) {
this.setData({
type
})
}
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 验证提交
*/
check() {
const { describe, concat } = this.data
if (!describe) {
this.setData({
message: {
message: '请输入反馈描述!',
type: 'error'
}
})
return false
}
if (!concat) {
this.setData({
message: {
message: '请输入联系方式!',
type: 'error'
}
})
return false
}
if (concat) {
if (!utils.checkPhone(concat) && !utils.checkEmail(concat)) {
this.setData({
message: {
message: '请输入正确的联系方式!',
type: 'error'
}
})
return false
}
}
this.uploadFeedback()
},
/**
* 提交
*/
async uploadFeedback() {
const db = wx.cloud.database()
const { openid, type, images, describe, concat } = this.data
const data = {
type,
images,
describe,
concat
}
await db.collection('feedback').add({
data
})
this.setData({
message: {
message: '保存成功!',
type: 'success'
}
})
setTimeout(() => {
wx.navigateBack({
delta: 1,
})
}, 1000);
},
/**
* 上传头像
*/
chooseImage() {
const _this = this
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success (res) {
// tempFilePath可以作为img标签的src属性显示图片
const tempFilePath = res.tempFilePaths[0]
console.log(tempFilePath)
_this.uploadFileImage(tempFilePath)
}
})
},
/**
* 图片上传到服务器
* @param {String} filePath 小程序临时文件路径
*/
uploadFileImage(filePath) {
const cloudPath = `feedback/${Date.now()}-${Math.floor(Math.random(0, 1) * 1000)}` + filePath.match(/.[^.]+?$/)[0]
const _this = this
wx.cloud.uploadFile({
cloudPath, // 上传至云端的路径
filePath, // 小程序临时文件路径
success: res => {
const { images } = _this.data
images.push(res.fileID)
_this.setData({
images
})
},
fail: console.error
})
},
/**
* 描述改变
* @param {*} e
*/
inputChange(e) {
const { type } = e.currentTarget.dataset
this.setData({
[type]: e.detail.value
})
let { describe, concat, canUpload } = this.data
if (describe && concat) {
canUpload = true
} else {
canUpload = false
}
this.setData({
canUpload
})
},
/**
* 删除反馈图片
*/
deleteImage(e) {
const { index } = e.currentTarget.dataset
const { images } = this.data
images.splice(index, 1)
this.setData({
images
})
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
}) |
angular.module('rameauApp',[])
.controller('rameauController',['$scope', function($scope){
$scope.rameauNotas = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B'];
$scope.rameauModfiers = {
modes:{
dorian:{name:'Dorian',description:'Dorian test descriptions'},
eolian:{name:'Eolian',description:'Eolian teste description'}},
graus:{
minor:{name:'Minor',description:'Minor test descriptions'},
major:{name:'Major',description:'Major teste description'}},
tipos:{
natural:{name:'Natural',description:'Natural test descriptions'},
harmonic:{name:'Harmonic',description:'Harmonic teste description'},
melodic:{name:'Melodic',description:'Melodic teste description'}}
};
$scope.rameauSelectedModfiers = {
mode:'dorian',
grau:'minor',//major, minor
tipo:'natural'//harmonic, natural, melodic
};
$scope.currentDescription = $scope.rameauModfiers.modes.dorian.description;
$scope.select = function(i) {
$scope.selected = i;
};
$scope.itemClass = function(i) {
return i === $scope.selected ? 'active' : undefined;
};
$scope.showDescription = function(e){
$scope.currentDescription = e;
};
var biblioteca = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B'];
// Aqui há todas as progressões das escalas
// O retorno desse função
function rameauLogics(){
var l = angular.lowercase($scope.rameauSelectedModfiers.mode+$scope.rameauSelectedModfiers.grau+$scope.rameauSelectedModfiers.tipo);
switch(l){
case 'dorianminornatural':
return [3,5,10];
break;
case 'dorianmajornatural':
return [3,5,10];
break;
default:
return 'error';
break;
}
}
$scope.generateProgression = function(n){
$scope.output = [n];
var noteIndex = jQuery.inArray(n,biblioteca),
logic = rameauLogics(),
notes = [];
for (var i = 0; i < logic.length; i++) {
if( logic === 'error' ){
$scope.output = ['A combinação escolhida, '+$scope.rameauSelectedModfiers.mode+', '+$scope.rameauSelectedModfiers.grau+' e '+$scope.rameauSelectedModfiers.tipo+' não gerou resultado. Use outra combinação.'];
} else {
notes[i] = noteIndex + logic[i];
if(notes[i] >= biblioteca.length){notes[i] = notes[i] - biblioteca.length}
$scope.output.push(biblioteca[notes[i]]);
}
};
}
}]); |
var express = require('express');
var router = express.Router();
var path = require('path');
var TaskCtrl = require("./../app/controller/task");
var passport = require('passport');
var Strategy = require('passport-http-bearer').Strategy;
var jsonwebtoken = require('jsonwebtoken');
passport.use(new Strategy(
function(token, callback) {
jsonwebtoken.verify(token, 'shhhhh', function(err, decoded) {
if(err){
console.log(err);
callback('Invalid token');
}else{
console.log(decoded)
callback(false,decoded);
}
});
}));
router.get('/auth', passport.authenticate('bearer', { session: false }),TaskCtrl.auth);
router.get('/myaccount', passport.authenticate('bearer', { session: false }), TaskCtrl.getAtask)
router.get('/ques/:id',TaskCtrl.getAques);
router.get('/',passport.authenticate('bearer', { session: false }), TaskCtrl.getAlltask);
router.get('/:id',TaskCtrl.updatetask)
router.post('/addtask',TaskCtrl.addtask);
router.post('/editUser',passport.authenticate('bearer', { session: false }),TaskCtrl.edittask)
router.delete('/:id',TaskCtrl.deletetask);
router.post('/login',TaskCtrl.login);
router.get('/gt/',TaskCtrl.greater);
router.get('/lt/',TaskCtrl.getMin);
router.get('/max/',TaskCtrl.getMax);
router.get('/avg/',TaskCtrl.getAvg);
router.get('/push/',TaskCtrl.getPushData);
router.get('/sum/',TaskCtrl.getSum);
module.exports = router;
|
import React from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';
import styles from './index.module.scss';
const Easing = ({ animation }) => {
return (
<div className={styles.root}>
<div
className={classNames({
[styles.bar]: true,
[styles.easeIn]: animation === 'easeIn',
[styles.easeOut]: animation === 'easeOut',
[styles.easeInOut]: animation === 'easeInOut',
})}
/>
</div>
);
};
Easing.propTypes = {
animation: PropTypes.oneOf(['easeIn', 'easeOut', 'easeInOut']),
};
Easing.defaultProps = {
animation: null,
};
export default Easing;
|
import React from 'react'
import { StyleSheet } from 'quantum'
const styles = StyleSheet.create({
self: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
flex: '0 auto',
flexDirection: 'column',
margin: '5% auto',
position: 'relative',
maxWidth: '480px',
background: '#ffffff',
maxHeight: '80%',
zIndex: 5,
},
scale: {
transform: 'scale(0.9)',
},
})
const Container = ({ children, scale }) => (
<div className={styles({ scale })}>
{children}
</div>
)
export default Container
|
let experience = 0;
let allTimeExperience = 0;
let currentLevelRequirements = 15;
let expTxt = document.querySelector("#experienceBar");
expTxt.innerHTML = experience + "/" + currentLevel(experience) + " XP";
function currentLevel(experience) {
allTimeExperience += experience;
if (allTimeExperience < 15) {
currentLevelRequirements = 15;
}
if (allTimeExperience >= 15 && allTimeExperience < 30) {
currentLevelRequirements = 30;
health += 25;
healthTxt.innerHTML = health + " HP";
}
return currentLevelRequirements;
}
function updateCurrentLevel(amount) {
if (amount >= currentLevelRequirements) {
experience = 0;
return expTxt.innerHTML = experience + "/" + currentLevel(amount) + " XP";
}
else {
experience += amount;
return expTxt.innerHTML = experience + "/" + currentLevel(amount) + " XP";
}
}
|
const express = require('express');
const router = express.Router();
const user = require('./user-controller'); //User class
const obj = new user;
const { check, validationResult } = require('express-validator')
const Validate = require('./validator'); //Validator class
const validateObj = new Validate;
const { Twilio, getOTP } = require('../helper/twilio'); //Twilio class
const twilioObj = new Twilio;
const CSV = require('../helper/CSV'); //CSV class
const CSVobj = new CSV;
const PDF = require('../helper/createPDF'); //CreatePdf class
const PDFobj = new PDF;
//const multer = require('../helper/multer');
const multer = require('multer');
var path = require('path');
//creating html to pdf
router.get('/pdf', PDFobj.createPdf, (req, res) => {
res.status(200).download('views/html-To-pdf.pdf');
});
//exporting csv
router.get('/exportcsv', async (req, res) => {
try {
await CSVobj.exportCSV();
res.status(200).download('export.csv');
} catch (error) {
console.log(error);
}
});
//importing csv
router.get('/importcsv', CSVobj.importCSV, async (req, res) => {
res.status(200).send('CSV imported sucessfully');
});
//get user form
router.route('/adduser').get((req, res) => {
try {
res.status(200).render('add-user');
} catch (error) {
res.status(404).send(error) //not found
}
})
var Storage = multer.diskStorage({
destination: "public/upload",
filename: (req, file, cb) => {
cb(null, file.fieldname + "_" + Date.now() + path.extname(file.originalname))
}
})
//file upload
var upload = multer({ storage: Storage }).single('file');
//register user details
router.route('/adduser').post(upload, validateObj.checkValidate(), validateObj.showErrors, async (req, res) => {
try {
let phone = req.body.phone;
let otp = getOTP(); //getting OTP
twilioObj.sendOTP(phone, otp);
let myJson = {
name: req.body.name,
image: req.file.filename,
imageurl: req.body.imageurl,
salary: req.body.salary,
email: req.body.email,
password: req.body.password,
phone: req.body.phone,
date: req.body.date,
address1: req.body.address1,
address2: req.body.address2,
city: req.body.city,
state: req.body.state,
zip: req.body.zip,
otp: otp
}
let result = await obj.insert(myJson);
if (result) {
res.status(200).render('add-user', { msg: 'Email already exist, Please try again!' });
} else {
res.status(401).redirect('/otpForm/' + req.body.email); //unauthorized
}
} catch (error) {
console.log(error);
}
});
//render dashboard
router.route('/').get(async (req, res) => {
try {
const total = await obj.countUsers(); //total number of users
res.status(200).render('dashboard', { total: total.count });
} catch (error) {
res.status(404).send(error); //not found
}
});
//list all users
router.route('/list').get(async (req, res) => {
try {
let data = await obj.listUsers();
res.render('section', { title: "All Users Details", details: data, msg: req.flash('message') });
} catch (error) {
res.status(501).send(error); //not implemented
}
});
//render users page
router.route('/salary').get((req, res) => {
try {
res.render('salary_tab');
} catch (error) {
res.status(404).send(error); //not found
}
})
//display users with their salaries
router.route('/salaries').get(async (req, res) => {
try {
let result = await obj.displaySalaries();
res.render('salary_table', { title: "Users Salary", details: result });
} catch (error) {
res.status(501).send(error); //not implemented
}
});
//get edit user form
router.route('/edit/:id').get(async (req, res) => {
let userid = req.params.id;
let user = await obj.getUserData(userid);
if (user) {
let details = user[0];
res.status(200).render('edit-user', { data: details });
} else {
res.status(404).send('Error in rendering user data'); //not found
}
})
//save user details
router.route('/edit/:id').post(obj.editUserData, async (req, res) => {
//editUserData(req.body.id);
})
//delete user
router.route('/delete/:id').get(async (req, res) => {
let id = req.params.id;
let data = obj.deleteUser(id);
if (data) {
res.status(200).redirect('/list');
} else {
res.statud(501).send('Error in deleting data'); //not implemented
}
})
//render OTPform
router.route('/otpForm/:email').get((req, res) => {
try {
res.status(200).render('otp-form', { msg: 'Please check your phone for OTP' });
} catch (error) {
res.status(404).send(error); //not found
}
});
//submit OTP
router.route('/otpForm/:email').post(twilioObj.verifyOTP, (req, res) => {
req.flash('message', 'Your account and phone number verified successfully');
res.status(200).redirect('/list');
});
module.exports = router; |
import React from "react"
import {
Appear,
BlockQuote,
CodePane,
Cite,
Deck,
Fill,
Heading,
Image,
ListItem,
List,
Quote,
S,
Slide,
Text } from "spectacle"
import preloader from "spectacle/lib/utils/preloader"
import createTheme from "spectacle/lib/themes/default"
import { map, filter } from 'lodash'
import Diagram from './diagram'
import InterLeaving from './interleaving'
import { width, height, radius, padding } from './config'
import { layouts, links, timelineData, diagramTitles } from './layouts'
// Require CSS
require("normalize.css")
require("spectacle/lib/themes/default/index.css")
const stackProps = {
width,
height,
radius,
padding,
layouts,
links,
diagramTitles
}
const interleavingProps = { width: 1000, height, padding }
const images = {
conversation: require('../assets/conversation.jpg'),
end: require('../assets/my-work-here-is-done.jpg'),
chineseRoom: require('../assets/ChineseRoom2009_CRset.jpg'),
intro: require('../assets/mix-t4nt.jpg'),
pairing: require('../assets/josh-focus.jpg'),
mob: require('../assets/mob-programming.jpg'),
class: require('../assets/class.png'),
demo: require('../assets/student-demo.jpg'),
iamdevloper: require('../assets/iamdevloper.png'),
homer: require('../assets/homer.gif'),
collage: require('../assets/eda-collage2.jpg'),
concepts: require('../assets/concepts.jpg'),
edaGroup: require('../assets/eda-group.jpg'),
roNJosh: require('../assets/eda-group-ro-josh.jpg'),
aladdin: require('../assets/1992-Aladdin.jpg'),
ygritte: require('../assets/ygritte-callbacks.jpg'),
ygritteYet: require('../assets/ygritte-callbacks-yet.jpg')
}
preloader(images)
const theme = createTheme({
primary: 'black',
secondary: "#2d2d2d",
tertiary: "#ccc",
quartenary: "#CECECE"
}, {
primary: "Montserrat",
secondary: "Montserrat"
})
const boxStyle = {
padding: 25,
background: 'rgba(0,0,0,.7)'
}
const Presentation = () => (
<Deck
progress='none'
controls={false}
transitionDuration={0}
transition={['fade']}
textColor='white'
theme={theme}>
<Slide maxWidth={1500} >
<Heading margin={50} textSize={100}>{'"Mutable Identities and Coupled Concepts"'}</Heading>
<Heading margin={50} textSize={50}>Teaching a FullStack JavaScript Bootcamp</Heading>
<Heading textSize={35}>@simontegg</Heading>
</Slide>
<Slide maxWidth={1500} >
<Heading textSize={100}>Mutable Identity</Heading>
<Heading textSize={100}>Challenges</Heading>
<Heading textSize={100}>Teaching</Heading>
</Slide>
<Slide maxWidth={1500} >
<Heading textSize={100}>Mutable Identity</Heading>
<Heading textColor='grey' textSize={100}>Challenges</Heading>
<Heading textColor='grey' textSize={100}>Teaching</Heading>
</Slide>
<Slide
transitionDuration={1}
bgColor='black'
notes={`
indulge developer stereotype;
squishy human problems in code;
diversity in tech
take our experiences -> cohesivve story
self-limiting;
sometimes others define our identity for us;
sometime we believe them;
global problem
one approach is to critique and deconstruct global sterotype;
`}>
<CodePane
style={{
transform: 'scale(1.5)',
marginLeft: 100
}}
lang="js"
source={require("raw-loader!../assets/stereotype.example")}
margin="20px auto"
/>
</Slide>
<Slide textColor='tertiary' >
<BlockQuote>
<Quote
textColor='white'
textSize={50} >
{`
the individual attempts to understand life
events as systematically related .... one's present
identity is thus not a sudden and mysterious event, but a sensible
result of a life story
`}
</Quote>
<Cite>Gergen and Gergen, 1988</Cite>
</BlockQuote>
</Slide >
<Slide
bgColor='black'
notes={`
add experiences;
extremely challenging and succeeded;
more than a for loop;
`}>
<CodePane
style={{
transform: 'scale(1.5)',
marginLeft: 100
}}
lang="js"
source={require("raw-loader!../assets/refactor.example")}
margin="20px auto"
/>
</Slide>
<Slide>
<Image src={images.iamdevloper} width={700} />
</Slide>
<Slide maxWidth={1500} >
<Heading textSize={100} textColor='grey'>Mutable Identity</Heading>
<Heading textSize={100}>Challenges</Heading>
<Heading textSize={100} textColor='grey'>Teaching</Heading>
</Slide>
<Slide bgImage={images.collage} bgDarken={0.6}>
<div style={boxStyle} >
<Heading> Challenge #1: </Heading>
<Heading> Different starting points</Heading>
</div>
</Slide>
<Slide bgColor='primary'>
<Heading textColor='white' size={2} >
Challenge #2:
</Heading>
<Text textSize={100} textColor='white' >
C# / .NET
</Text>
<Text textSize={70} textColor='white' >
Ruby / Rails
</Text>
<Text textSize={60} textColor='white' >
Node
</Text>
<Text textSize={50} textColor='white' >
Frontend JavaScript
</Text>
<Text textSize={40} textColor='white' >
PHP
</Text>
</Slide>
<Slide maxWidth={1500} bgColor="tertiary">
<Diagram {...stackProps} />
</Slide>
<Slide bgImage={images.collage} bgDarken={0.6}>
<div style={boxStyle} >
<Heading> Challenge #4:</Heading>
<Heading textSize={80} >People</Heading>
<Heading textSize={80} >- harder than code</Heading>
</div>
</Slide>
<Slide maxWidth={900}>
<Text margin={20} textSize={50} textColor='white'>https://beepboopbot.com/</Text>
<Text margin={20} textSize={50} textColor='white'>https://goflat.co.nz/</Text>
<Text margin={20} textSize={50} textColor='white'>https://enspiral-sim-academy.firebaseapp.com/</Text>
<Text margin={20} textSize={50} textColor='white'>https://topoftheflops.github.io/</Text>
</Slide>
<Slide maxWidth={1500} >
<Heading textSize={100} textColor='grey'>Mutable Identity</Heading>
<Heading textSize={100} textColor='grey' >Challenges</Heading>
<Heading textSize={100} >Teaching</Heading>
</Slide>
<Slide textColor='white' maxWidth={1500} >
<Text textColor='white' textSize={70} > The mysterious case of the disappearing teacher </Text>
<Text style={{opacity: 0}} textSize={70} >What came first the ability or the concept?</Text>
<Text style={{opacity: 0}} textColor='white' textSize={70} > Any sufficiently abstract layer is indistinguishable from magic</Text>
<Text style={{opacity: 0}} textColor='white' textSize={70} >{`Stack 'em high and keep 'em coming`}</Text>
</Slide>
<Slide textColor='white' maxWidth={1500} >
<Text style={{opacity: 0}} textColor='white' textSize={70} > The mysterious case of the disappearing teacher </Text>
<Text textColor='white' textSize={70} >What came first? - the ability or the concept ?</Text>
<Text style={{opacity: 0}} textColor='white' textSize={70} > Any sufficiently abstract layer is indistinguishable from magic</Text>
<Text style={{opacity: 0}} textColor='white' textSize={70} >{`Stack 'em high and keep 'em coming`}</Text>
</Slide>
<Slide textColor='white' maxWidth={1500} >
<Text style={{opacity: 0}} textColor='white' textSize={70} > The mysterious case of the disappearing teacher </Text>
<Text style={{opacity: 0}} textColor='white' textSize={70} >What came first? - the ability or the concept ?</Text>
<Text textColor='white' textSize={70} > Any sufficiently abstract layer is indistinguishable from magic</Text>
<Text style={{opacity: 0}} textColor='white' textSize={70} >{`Stack 'em high and keep 'em coming`}</Text>
</Slide>
<Slide textColor='white' maxWidth={1500} >
<Text style={{opacity: 0}} textColor='white' textSize={70} > The mysterious case of the disappearing teacher </Text>
<Text style={{opacity: 0}} textColor='white' textSize={70} >What came first? - the ability or the concept ?</Text>
<Text style={{opacity: 0}} textColor='white' textSize={70} > Any sufficiently abstract layer is indistinguishable from magic</Text>
<Text textColor='white' textSize={70} >{`Stack 'em high and keep 'em coming`}</Text>
</Slide>
<Slide textColor='white' maxWidth={1500} >
<Text textColor='white' textSize={70} > The mysterious case of the disappearing teacher </Text>
<Text textColor='white' textSize={70} >What came first? - the ability or the concept ?</Text>
<Text style={{opacity: 0}} textColor='white' textSize={70} > Any sufficiently abstract layer is indistinguishable from magic</Text>
<Text style={{opacity: 0}} textColor='white' textSize={70} >{`Stack 'em high and keep 'em coming`}</Text>
</Slide>
<Slide maxWidth={1200} bgImage={images.intro} bgDarken={0.6}>
<div style={boxStyle}>
<Heading textSize={150} >9am:</Heading>
<Heading textSize={100} >a new concept </Heading>
<Heading textSize={100} style={{opacity: 0}} >a hidden heading</Heading>
</div>
</Slide>
<Slide transition={['slide']} maxWidth={900} bgImage={images.pairing} bgDarken={0.7}>
<div style={boxStyle}>
<Heading textColor='white' textSize={150} >10-12.30:</Heading>
<Heading textColor='white' textSize={100} >toy example</Heading>
<Heading textColor='white' textSize={100} >+ challenge </Heading>
</div>
</Slide>
<Slide
textColor='white'
maxWidth={1500}
padding={50}
bgImage={images.mob}
bgDarken={0.7}
notes={`
set a timer;
nowhere to hide;
active role;
collective problem solving;
`}>
<div style={boxStyle}>
<Heading textSize={150} >2-3pm:</Heading>
<Heading textSize={100} >mob programming</Heading>
<Heading textSize={100} > || pair show-and-tell </Heading>
</div>
</Slide>
<Slide>
<Text textColor='white' textSize={70} > The mysterious case of the disappearing teacher </Text>
<Image src={images.homer} height={300} />
</Slide>
<Slide bgColor='black'>
<Heading> Students ask Teacher questions </Heading>
</Slide>
<Slide bgColor='black'>
<Heading> Teacher asks Students questions </Heading>
</Slide>
<Slide maxWidth={1200} bgImage={images.pairing} bgDarken={0.7}>
<div style={boxStyle}>
<Heading textSize={150} >3-5pm:</Heading>
<Heading textSize={100}>the challenge</Heading>
<Heading textSize={100}>continues</Heading>
</div>
</Slide>
<Slide maxWidth={1200} bgImage={images.intro} bgDarken={0.5}
notes={`
Socratic method;
draw it out of them;
relate back to yesterdays intro;
students create representations;
teacher adjusts and asks questions;
`}>
<div style={boxStyle}>
<Heading textSize={120} >next day:</Heading>
<Heading textSize={100} >recap</Heading>
<Heading textSize={100} > + next concept</Heading>
</div>
</Slide>
<Slide maxWidth={1200} bgImage={images.demo} bgDarken={0.7}>
<div style={boxStyle}>
<Heading textSize={120} >[wed, thur], fri:</Heading>
<Heading textSize={100} >Group projects</Heading>
</div>
</Slide>
<Slide textColor='white' maxWidth={1500} >
<Text textColor='white' textSize={70} >What came first? - the ability or the concept ?</Text>
</Slide>
<Slide bgImage={images.concepts} bgDarken={0.7} maxWidth={1500} >
<div style={boxStyle}>
<Text textColor='white' textSize={70} >
Ability ➡️️ Concept ?
</Text>
<Heading textSize={100} margin={30} > OR </Heading>
<Text textColor='white' textSize={70} margin={20} >
Concept ➡️️ Ability ?
</Text>
</div>
</Slide>
<Slide bgColor='black'>
<Image src={images.class} width={600} />
</Slide>
<Slide textColor='white' maxWidth={1500} >
<Text style={{opacity: 0}} textColor='white' textSize={70} > The mysterious case of the disappearing teacher </Text>
<Text style={{opacity: 0}} textColor='white' textSize={70} >What came first? - the ability or the concept ?</Text>
<Text textColor='white' textSize={70} > Any sufficiently abstract layer is indistinguishable from magic</Text>
<Text style={{opacity: 0}} textColor='white' textSize={70} >{`Stack 'em high and keep 'em coming`}</Text>
</Slide>
<Slide
bgColor='black'
notes={`
`}>
<CodePane
style={{
transform: 'scale(1.5)',
marginLeft: 100
}}
lang="js"
source={require("raw-loader!../assets/abstraction.example")}
margin="20px auto"
/>
</Slide>
<Slide>
<Text textColor='white' textSize={70} >{`Stack 'em high and keep 'em coming`}</Text>
</Slide>
<Slide transition={["fade"]} bgColor="tertiary"
notes={`
story about final week realization;
`}>
<InterLeaving {...interleavingProps} />
</Slide>
<Slide transition={["fade"]} textColor="tertiary" bgImage={images.ygritte}>
</Slide>
<Slide transition={["fade"]} textColor="tertiary" bgImage={images.ygritteYet}>
</Slide>
<Slide bgImage={images.conversation} bgDarken={0.5}>
</Slide>
<Slide bgImage={images.end} bgDarken={0.5}>
<div style={boxStyle} >
<Text textColor='white' textSize={70} >my work here is done</Text>
<Text textColor='white' margin={30} >@simontegg</Text>
</div>
</Slide>
</Deck>
)
export default Presentation
|
/**
* 页面最初先加载页面html结构,
* 再加载页面link引入的样式,这时候页面所有的结构与样式都有了,后续只要有了bootstrap就ok了。
* 页面先加载require.js,
* 然后再加载main.js,
* 如果是首页那么根据页面pathname加载了index.js,
* 然后index.js存在很多依赖,这些依赖项同时异步加载,他们的执行顺序是不确定的,
* 那么现在有一个aside模块,它依赖与jquery与jquery_cookie,所以需要在aside模块编写时进行配置
* */
define(['bootstrap', 'jquery', 'aside', 'header','util','nprogress'], function(ud, $, ud, ud,util,nprogress) {
// 检测登陆状态
util.checkLoginStatus();
// 配置网站进度条
nprogress.start();
//window.onlod是页面所有的HTML,JS,CS加载完成后才执行
//所有的HTML页面加载完成后在执行
$(function(){
nprogress.done();
})
//配置ajax全局请求的loading效果
util.loading()
}); |
export default {
// addToCart (state, item) {
// // 判断item是否已经存在于购物车
// const isInCart = state.cart.some(cartItem => cartItem.id === item.id)
// if (isInCart) {
// state.cart = state.cart.map(cartItem => {
// if (cartItem.id === item.id) {
// cartItem.count += 1
// }
// return cartItem
// })
// } else {
// state.cart.push({
// ...item,
// isChecked: false,
// count: 1
// })
// }
// },
// addCartItemCount (state, id) {
// state.cart = state.cart.map(cartItem => {
// if (cartItem.id === id) {
// cartItem.count += 1
// }
// return cartItem
// })
// },
// reduceCartItemCount (state, id) {
// state.cart = state.cart.map(cartItem => {
// if (cartItem.id === id && cartItem.count > 1) {
// cartItem.count -= 1
// }
// return cartItem
// })
// },
// toggleChecked (state, id) {
// state.cart = state.cart.map(cartItem => {
// if (cartItem.id === id) {
// cartItem.isChecked = !cartItem.isChecked
// }
// return cartItem
// })
// },
// changeAllCheck (state, checked) {
// state.cart = state.cart.map(cartItem => {
// cartItem.isChecked = checked
// return cartItem
// })
// },
// changePageTitle (state, title) {
// state.pageTitle = title
// },
// 将token保存到sessionStorage里,token表示登录状态
// SET_TOKEN: (state, data) => {
// state.token = data;
// window.sessionStorage.setItem('token', data)
// },
// 获取用户名
// GET_USER: (state, data) => {
// state.user = data;
// window.sessionStorage.setItem('user', data)
// },
// 用户登录状态
changeLoginStatus (state) {
state.isLogin = true
state.user = window.sessionStorage.user
},
// 退出登录
logout (state) {
window.sessionStorage.removeItem('user');
window.sessionStorage.removeItem('user_id');
window.sessionStorage.removeItem('cart');
state.user = ''
state.isLogin = false
}
}
|
//初始化
//---------获取相关元素--------------
//获取sliderDIV以注册移入移出事件
var sliderDiv = document.querySelector(".slider");
// 获取一组带超链接的图像
var imagesA = document.getElementById("images").children;
//获取一组li文本
var txtList = document.querySelectorAll(".top>li");
//上一张下一张控制按钮
var leftButton = document.querySelector('.leftButton');
var rightButton = document.querySelector('.rightButton');
//-------------初始化控制变量------------------
//当前显示图片编号
var currentNo = 0;
//图片/文本总数
const nodeLength = 8;
//--------------构建功能函数----------------
//显示高亮当前某张图片/文本
function changeImg() {
//排他原理1将同类设置为同意状态
// var nodeLength=txtList.length
for (var i = 0; i < nodeLength; i++) {
//同类图片透明度0(.hiddenImg)
imagesA[i].className = "hiddenImg";
//同类文本设置正常非高亮
txtList[i].className = "normalColor"
}
//排他原理2,突出自己,当前图片透明度1(.displayImg)
imagesA[currentNo].className = "displayImg"
//排他原理2,文本高亮
txtList[currentNo].className = "heighlightColor";
}
//--------------左向控制编号变化(当前编号)-------------
function leftImg() {
if (currentNo > 0) { currentNo--; }
else {
currentNo = nodeLength - 1;
}
}
//--------------右向控制编号变化(当前编号++)--------------
function rightImg() {
if (currentNo < nodeLength - 1) { currentNo++; }
else {
currentNo = 0;
}
}
//---------左向换片/文本------------
function leftImgGo() {
leftImg();
changeImg();
}
//--------换向换片/文本------------
function rightImgGo() {
rightImg();
changeImg();
}
//停止计时器
function stopChange() {
window.clearInterval(timer);
}
//启动记时器
function startChange() {
timer = window.setInterval(changeImgGo, 1000);
}
//切换到编号文本/图片
function gotoImg() {
currentNo = this.no;
changeImg();
}
//---------------为各大元素增加事件------------
//为sliderDIV注册移入移出事件
sliderDiv.addEventListener('mouseover', stopChange);
sliderDiv.addEventListener('mouseout', startChange);
//为所有文本li注册鼠标移入事件
for (var i = 0; i < txtList.length; i++) {
txtList[i].addEventListener('mouseover', gotoImg);
//添加自定义属性no 记录当前li的编号
txtList[i].no = i;
}
//上下一张注册事件
leftButton.addEventListener('click', leftImgGo);
rightButton.addEventListener('click', rightImgGo);
//网页加载后启动定时器,每隔1秒调用changeImgGo()换片
var timer = window.setInterval(rightImgGo, 1000); |
const mysql = require("mysql");
const inquirer = require("inquirer");
// create the connection information for the sql database
const connection = mysql.createConnection({
host: "localhost",
// Your port; if not 3306
port: 3306,
// Your username
user: "root",
// Your password
password: "password",
database: "employee_db",
});
connection.connect(function (err) {
if (err) throw err;
console.log("\n=============================")
console.log("------ EMPLOYEE TRACKER -----");
console.log("=============================\n")
start();
});
function start() {
inquirer
.prompt({
name: "userInput",
type: "list",
message:
"What would you like to do?",
choices: ["VIEW_DEPARTMENTS", "VIEW_ROLES", "VIEW_EMPLOYEES", "VIEW_MANAGERS", "ADD_DEPARTMENTS", "ADD_ROLES", "ADD_EMPLOYEES", "UPDATE_EMPLOYEE_ROLE", "UPDATE_MANAGER", "DELETE_EMPLOYEE", "EXIT"],
})
.then(function (answer) {
switch (answer.userInput) {
case "VIEW_DEPARTMENTS":
viewDepartments();
break;
case "VIEW_ROLES":
viewRoles();
break;
case "VIEW_EMPLOYEES":
viewEmployees();
break;
case "VIEW_MANAGERS":
viewManagers();
break;
case "ADD_DEPARTMENTS":
addDepartment();
break;
case "ADD_ROLES":
addRole();
break;
case "ADD_EMPLOYEES":
addEmployee();
break;
case "UPDATE_EMPLOYEE_ROLE":
update_Employee();
break;
case "UPDATE_MANAGER":
update_Manager();
break;
case "DELETE_EMPLOYEE":
delEmployee();
break;
case "EXIT":
default:
connection.end();
}
});
}
function viewDepartments() {
connection.query("SELECT * FROM department", function (err, results) {
if (err) throw err;
console.table(results);
start();
});
}
function viewRoles() {
connection.query(
`select title, salary, name from role
inner join department on role.department_id=department.id`,
function (err, results) {
if (err) throw err;
console.table(results);
start();
}
);
}
function viewEmployees() {
connection.query(
`select first_name, last_name, manager_id, title, salary, name from employee
inner join role on employee.role_id=role.id
inner join department on role.department_id=department.id`,
function (err, results) {
if (err) throw err;
console.table(results);
start();
}
);
}
function printResults(err, result) {
if (err) throw err;
console.log(result);
start();
}
async function addDepartment() {
const department = await inquirer.prompt([
{
name: "name",
message: "What is the name of the department"
}
])
connection.query(`insert into department (name) values ('${department.name}')`, printResults)
}
function addRole() {
connection.query("select * from department", async function (err, results) {
const departments = results.map((result) => ({
name: result.name,
value: result.id
}))
const roleInfo = await inquirer.prompt([
{
name: "title",
message: "What is the title for the position"
},
{
name: "salary",
message: "What is the salary for the position"
},
{
type: "list",
name: "department_id",
message: "Which Department does the role belong to?",
choices: departments
}
])
connection.query(`insert into role (title, salary, department_id) values('${roleInfo.title}','${roleInfo.salary}','${roleInfo.department_id}' )`, printResults)
})
}
function addEmployee() {
connection.query("select * from role", async function (err, results) {
const roles = results.map((result) => ({
name: result.title,
value: result.id
}))
const employeeInfo = await inquirer.prompt([
{
name: "first_name",
message: "What is the first name of the employee"
},
{
name: "last_name",
message: "What is the last name of the employee"
},
{
type: "list",
name: "role_id",
message: "What is the employee's role?",
choices: roles
}
])
connection.query(`insert into employee (first_name, last_name, role_id) values('${employeeInfo.first_name}','${employeeInfo.last_name}','${employeeInfo.role_id}' )`, printResults)
})
}
function update_Employee() {
connection.query("select * from employee", function (err, employees) {
connection.query("select * from role", async function (err, roles) {
const roleChoices = roles.map((role) => ({
name: role.title,
value: role.id
}))
const employeeChoices = employees.map((employee) => ({
name: employee.first_name + " " + employee.last_name,
value: employee.id
}))
const updateEmployee = await inquirer.prompt([
{
type: "list",
name: "employee_id",
message: "Which employee would you like to update?",
choices: employeeChoices
},
{
type: "list",
name: "role_id",
message: "What would you like their new role to be?",
choices: roleChoices
}
])
connection.query(`update employee set role_id=${updateEmployee.role_id} where id=${updateEmployee.employee_id}`, printResults)
})
})
}
function viewManagers() {
connection.query(
`SELECT
CONCAT(m.last_name, ', ', m.first_name) AS Manager,
CONCAT(e.last_name, ', ', e.first_name) AS 'Direct report'
FROM employee m
INNER JOIN employee e ON
m.id = e.manager_id
ORDER BY Manager ASC`,
function (err, results) {
if (err) throw err;
console.table(results);
start();
}
);
}
function update_Manager() {
connection.query("select * from employee", async function (err, employees) {
const employeeChoices = employees.map((employee) => ({
name: employee.first_name + " " + employee.last_name,
value: employee.id
}))
const updateManager = await inquirer.prompt([
{
type: "list",
name: "employee_id",
message: "Which employee would you like to update?",
choices: employeeChoices
},
{
type: "list",
name: "manager_id",
message: "Who would you like their new manager to be?",
choices: employeeChoices
}
])
connection.query(`UPDATE employee SET manager_id=${updateManager.manager_id} where id=${updateManager.employee_id}`, printResults)
})
}
function delEmployee() {
connection.query("SELECT * FROM employee", async function (err, employees) {
const employeeChoices = employees.map((employee) => ({
name: employee.first_name + " " + employee.last_name,
value: employee.id
}))
const deleteEmployee = await inquirer.prompt([
{
type: "list",
name: "employee_id",
message: "Which employee would you like to delete?",
choices: employeeChoices
}
])
connection.query(`DELETE FROM employee WHERE id=${deleteEmployee.employee_id}`, printResults);
})
}
|
import React, { useState } from "react";
import styled from "styled-components";
import AddCircleIcon from "@material-ui/icons/AddCircle";
import EditIcon from "@material-ui/icons/Edit";
import DoneIcon from "@material-ui/icons/Done";
import CloseIcon from "@material-ui/icons/Close";
import { Link } from "react-router-dom";
function ClassList({ classes, changeNotes, createNewClass, renameClass }) {
const [newClassInput, setNewClassInput] = useState(false);
const [newClassName, setNewClassName] = useState("");
const [renameClassActive, setRenameClassActive] = useState("");
const [renameClassInput, setRenameClassInput] = useState("");
const addNewClassHandler = () => {
createNewClass(newClassName);
setNewClassName("");
};
return (
<Container>
<ClassListHeader>
<HeaderH1>Classes</HeaderH1>
<AddNewClassContainer>
<AddCircleIcon
onClick={() => {
setNewClassInput(!newClassInput);
}}
/>
</AddNewClassContainer>
</ClassListHeader>
{newClassInput ? (
<NewClassInputContainer>
<NewClassInput
type="text"
value={newClassName}
onChange={(e) => {
setNewClassName(e.target.value);
}}
/>
<NewClassButton onClick={addNewClassHandler}>
Add Class
</NewClassButton>
</NewClassInputContainer>
) : (
<></>
)}
<List>
{classes.length == 0 ? (
<EmptyClassListContainer>
<EmptyClassListMessage>No Classes made yet. Click on '+' icon to add new class</EmptyClassListMessage>
{/* <NewClassInputContainer>
<NewClassInput
type="text"
value={newClassName}
onChange={(e) => {
setNewClassName(e.target.value);
}}
/>
<NewClassButton onClick={addNewClassHandler}>
Add Class
</NewClassButton>
</NewClassInputContainer> */}
</EmptyClassListContainer>
) : (
classes.map((clss) => {
return (
<ListItemContainer key={clss._id}>
{!(renameClassActive == clss._id) ? (
<ClassNameContainer
onClick={() => {
changeNotes(clss._id);
}}
>
<Link to="/">
<ListItem
classid={clss._id}
>
{clss.classname}
</ListItem>
</Link>
<EditIcon
onClick={() => {
setRenameClassActive(clss._id);
}}
/>
</ClassNameContainer>
) : (
<RenameClassContainer>
<RenameClassInput
placeholder={clss.classname}
value={renameClassInput}
onChange={(e) => {
setRenameClassInput(e.target.value);
}}
/>
<RenameIconsContainer>
<CloseIcon
onClick={() => {
setRenameClassActive("");
setRenameClassInput("");
}}
/>
<DoneIcon
onClick={() => {
renameClass(clss._id, renameClassInput);
setRenameClassActive("");
setRenameClassInput("");
}}
/>
</RenameIconsContainer>
</RenameClassContainer>
)}
</ListItemContainer>
);
})
)}
</List>
</Container>
);
}
export default ClassList;
const Container = styled.div`
// flex-grow: 1;
display: flex;
flex-direction: column;
border-right: 1px solid grey;
padding: 1%;
width: 18vw;
`;
const ClassListHeader = styled.div`
display: flex;
`;
const HeaderH1 = styled.h1``;
const AddNewClassContainer = styled.div`
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
`;
const List = styled.div`
// display: flex;
// flex-direction: column;
// flex: 1;
// overflow-y: scroll;
// background-color: red;
// height: 100%;
`;
const ListItem = styled.div``;
const NewClassInputContainer = styled.div`
display: flex;
flex-direction: column;
`;
const NewClassInput = styled.input``;
const NewClassButton = styled.button``;
const ListItemContainer = styled.div`
cursor: pointer;
`;
const ClassNameContainer = styled.div`
display: flex;
justify-content: space-between;
padding: 2%;
:hover {
background: lightgrey;
border-radius: 4px;
}
`;
const RenameClassContainer = styled.div`
display: flex;
justify-content: space-between;
padding: 2%;
background-color: lightgrey;
border-radius: 4px;
`;
const RenameClassInput = styled.input`
outline: none;
border: none;
background-color: lightgrey;
padding: 1%;
`;
const RenameIconsContainer = styled.div`
display: flex;
`;
const EmptyClassListContainer = styled.div``;
const EmptyClassListMessage = styled.div``;
|
module.exports = client => {
console.log(`Bot foi iniciado, com ${client.users.size} usuários, em ${client.channels.size} canais, em ${client.guilds.size} servidores.`);
let status = [
{ name: `Meu prefixo e: m.ajuda`, type: 'STREAMING', url: 'https://www.twitch.tv/blackzinn0171'},
{ name: `Obrigado por utilizar mes comandos ❤️`, type: 'STREAMING', url: 'https://www.twitch.tv/blackzinn0171'},
{ name: `Encontrou falhas? Reporte para o suporte`, type: 'STREAMING', url: 'https://www.twitch.tv/blackzinn0171'},
{ name: `Saiba como me adicionar pelo s.ajuda`, type: 'STREAMING', url: 'https://www.twitch.tv/blackzinn0171'},
{ name: `Para ${client.users.size} usuarios`, type: 'STREAMING', url: 'https://www.twitch.tv/blackzinn0171'},
{ name: `Em ${client.guilds.size} servidores`, type: 'STREAMING', url: 'https://www.twitch.tv/blackzinn0171'}
]
setInterval(function() {
let randomStatus = status[Math.floor(Math.random() * status.length)];
client.user.setPresence({ game: randomStatus });
}, 1000)
}; |
var express = require('express'),
ClientAuth = require('./middlewares/ClientAuthWare'),
ViewController = require('./controllers/ViewController'),
CollectionController = require('./controllers/CollectionController');
module.exports = function (app, passport) {
app.use(ClientAuth);
var connectionRouter = express.Router();
app.use('/:_dump/c', connectionRouter);
connectionRouter.get('/:_con/views', ViewController.all);
connectionRouter.get('/:_con/view', ViewController.one);
connectionRouter.post('/:_con/view', ViewController.upsert);
connectionRouter.get('/:_con/collections', CollectionController.all);
connectionRouter.get('/:_con/collection', CollectionController.query);
connectionRouter.get('/:_con/collections/feed', CollectionController.feed);
connectionRouter.get('/:_con/collection/refresh', CollectionController.refresh);
connectionRouter.get('/:_con/collection/delete', CollectionController.delete);
};
|
var player1, player_running ;
var ground, groundImage,invisibleleft,invisibleright;
function preload() {
player_running = loadAnimation("Runner-1.png", "Runner-2.png");
groundImage = loadImage("path.png")
}
function setup() {
createCanvas(400, 400);
ground = createSprite(200,200,400,400);
ground.addImage("ground",groundImage);
ground.velocityY = +4;
player1 = createSprite(300,360,20,50);
player1.addAnimation("running", player_running);
player1.scale=0.1;
invisibleleft = createSprite(370,200,60,400);
invisibleleft.visible=false
invisibleright = createSprite(25,200,60,400);
invisibleright.visible=false
}
function draw() {
background('red');
createEdgeSprites();
if (ground.y>400) {
ground.y = ground.width / 2;
}
player1.x=World.mouseX
player1.collide(invisibleleft)
player1.collide(invisibleright)
drawSprites();
}
|
#!/usr/bin/env node
import fs from 'fs-extra';
import path from 'path';
import Generator from './generator.js';
import { seedFromFile } from './seedFileUtils.js';
const isNonAssertiveSchemaEntity = (entityObject) => {
const green = ['Class', 'DataProperty', 'ObjectProperty'];
return green.includes(entityObject.type);
}
const getFilePath = (pathString) => {
let seedFilePath = path.join(process.cwd(), pathString);
if (path.isAbsolute(pathString)) {
seedFilePath = pathString;
}
return seedFilePath;
}
const getFileRequired = (path) => {
if (!fs.existsSync(seedFilePath)) throw new Error(`${seedFilePath} does not exist`);
return require(path);
}
const program = require("yargs")
.env()
.option("seed-file-output", {
describe: "path to the file that contains the output of the rlay-seed command"
})
.option("seed-file", {
describe: "path to the file that served as input for the rlay-seed command"
})
.option("output", {
describe: "path to the file where the generated rlay client should be written to"
})
.default("seed-file-output", "./generated/seed.json")
.default("seed-file", "./seed.js")
.default("output", "./generated/rlay-client/index.js")
.argv;
// get the actual files for the options or print errors
// seed-file
const seedFilePath = getFilePath(program.seedFile);
const seedFile = getFileRequired(seedFilePath);
if (!seedFile.entities) {
throw new Error(`{seedFilePath} is not a valid Rlay seed file. Root object must have '.entities' property.`);
}
// seed-file-output
const seedFileOutputPath = getFilePath(program.seedFileOutput);
const seededSchema = getFileRequired(seedFileOutputPath);
const seedFileEntities = seedFromFile(seedFile.entities, seedFile);
const entities = Object.keys(seedFileEntities).
map(entityKey => ({ key: entityKey, assertion: seedFile.entities[entityKey] })).
filter(e => isNonAssertiveSchemaEntity(e.assertion));
const source = Generator.generate(
JSON.stringify(seededSchema),
JSON.stringify(entities)
);
const clientPathSplit = program.output.split('/');
const clientPathFile = './' + clientPathSplit.pop();
const clientPathDir = clientPathSplit.join('/') + '/';
const generatedDir = getFilePath(clientPathDir);
const generatedFile = path.join(generatedDir, clientPathFile);
fs.ensureDirSync(generatedDir);
fs.writeFileSync(generatedFile, source, 'utf8');
|
const removeFromFavorites = (favorites, item) => {
const index = favorites.findIndex(favorite => favorite.id === item.id)
return [...favorites.slice(0, index), ...favorites.slice(index + 1)]
}
const sortItems = (items, value) => {
switch(value){
case 'priceASC': {
return [...items].sort((a, b) => a.price_total - b.price_total)
}
case 'priceDESC': {
return [...items].sort((a, b) => b.price_total - a.price_total)
}
case 'squareASC': {
return [...items].sort((a, b) => a.square - b.square)
}
case 'squareDESC': {
return [...items].sort((a, b) => b.square - a.square)
}
}
}
const updateItemList = (state, action) => {
if(state === undefined){
return {
items: [],
itemsLoading: true,
itemsError: false,
viewType: "cards",
sortby: "priceASC",
favorites: []
}
}
switch(action.type){
case 'FETCH_ITEMS_REQUEST':
return{
...state.itemList,
items: [],
itemsLoading: true,
itemsError: null
}
case 'FETCH_ITEMS_SUCCESS':
return{
...state.itemList,
items: sortItems(action.payload, state.itemList.sortby),
itemsLoading: false,
itemsError: null
}
case 'FETCH_ITEMS_FAILURE':
return{
...state.itemList,
items: [],
itemsLoading: false,
itemsError: action.payload
}
case 'SET_VIEW_TYPE':
return{
...state.itemList,
viewType: action.payload
}
case 'SORT_ITEMS':
return{
...state.itemList,
items: sortItems(state.itemList.items, action.payload),
sortby: action.payload
}
case 'ADD_TO_FAVORITES':
return {
...state.itemList,
favorites: [...state.itemList.favorites, action.payload]
}
case 'REMOVE_FROM_FAVORITES':
return {
...state.itemList,
favorites: removeFromFavorites(state.itemList.favorites, action.payload)
}
default:
return state.itemList
}
}
export default updateItemList |
const mongoose = require("mongoose");
mongoose.connect('mongodb://localhost:27017/Test', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(()=>{
console.log("------连接成功!------");
}).catch(e=>{
console.log("连接异常");
});
const Article = require("./models/ArticleModel");
//initial data
async function initial(){
Article.create({
title:`Leaf${parseInt(Math.random()*100)}`,
content:"rocket",
author:"zheling",
tags:["js","nodeJs"],
views:parseInt(Math.random()*1000)
},function (err,doc) {
if (err)return console.log(err);
console.log(doc);
});
}
// initial();
//1.$where : where + MongoDB operators($lt/$gt...)无法满足查询需求时才用$where,因为查询效率不如前者
async function $whereQuery() {
Article.$where(function () {
return this.author === "ZHELING"
}).exec(function (err,result) {
if (err) return err;
console.log(result);
})
//$where(`this.author === "ZHELING" || this.author === "zheling"`)
}
// $whereQuery();
//2.all
async function allQuery() {
try {
let result = await Article.find().where("tags").all(["nodejs","js"]).select("tags _id");
console.log(result);
}catch (e) {
return console.log(e);
}
}
// allQuery();
//3.and
async function andQuery() {
Article.find().and([{author: "zheling"},{content:"rocket"}]).exec(function (err,res) {
if (err)return err;
console.log(res);
})
}
// andQuery();
//4.count
async function countQuery() {
Article.find().countDocuments({content:"rocket"},function (err,res) {
if (err)return err;
console.log(res);
})
}
// countQuery();
//5.deleteOne / deleteMany
//6.distinct
async function distinctQuery() {
Article.find().distinct("content",function (err,res) {
if (err)return err;
console.log(res);
})
}
// distinctQuery();
//7.equals
// User.where('age').equals(49);
// User.where('age', 49);
//8.find
async function findQuery() {
Article.find({views:{
$gte:300,
$lte:400
}},function (err,res) {
console.log(res);
})
}
// findQuery();
//9.findOneAndRemove
async function findOneAndReomveQuery() {
Article.findOneAndDelete({content:"rocket"},function (err,res) {
console.log(res);
});
}
// findOneAndReomveQuery();
//10.findOneAndReplace
//find and replace with new data, but keep the ObjectId same
async function findOneAndReplaceQuery() {
Article.where().findOneAndReplace({title:"Leaf56"},{title:"呵呵"},function (err,res) {
console.log(res);
});
}
// findOneAndReplaceQuery();
//11.findOneAndUpdate
async function findOneAndUpdateQuery() {
Article.findOneAndUpdate({title:"test"},{title:"fuckyou"},{
useFindAndModify:false
},function (err,res) {
console.log(res);
});
}
// findOneAndUpdateQuery();
//12.limit
//13.lt/gt : less than / greater than
//14.lte/gte : less than or equal / greater than or equal
//15.ne : not equal
//16.nin
//17.or / nor
//18.remove
//19.replaceOne
//20.select
//21.skip |
import React from 'react'
import styles from './Navigation.module.sass'
const Navigation = () => {
return (
<nav className={styles.Navigation}>
<ul className={styles.list}>
<li className={styles.list__item}>
<a href='##' className={styles.list__item__link}>
О комплексе
</a>
</li>
<li className={styles.list__item}>
<a href='##' className={styles.list__item__link}>
Особенности
</a>
</li>
<li className={styles.list__item}>
<a href='##' className={styles.list__item__link}>
Пентхаусы
</a>
</li>
<li className={styles.list__item}>
<a href='##' className={styles.list__item__link}>
Выбрать квартиру
</a>
</li>
</ul>
</nav>
)
}
export default Navigation
|
const mongoose= require('mongoose');
var Schema=mongoose.Schema;
const feeschema = Schema({
feename: {
type: String,
required: true
},
/*timestamp*/
ts: {
type: Date,
default: Date.now()
},
/*lastdate*/
ld: {
type: String,
required: true
},
tfee: {
type: Number,
required: true
},
fine: {
type: Number
}
});
let exportfunction= function func(coll_name) {
return mongoose.model(coll_name,feeschema,coll_name);
}
exports.exp=exportfunction;
|
'use strict'
const stringUtils = require('../utils/stringutils')
const {v4: uuidv4} = require('uuid');
module.exports = async function (fastify, opts) {
/**
* 兼容易支付接口
*/
fastify.post('/submit.php', async function (request, reply) {
let fromWhere = null
if (Object.keys(request.body).length > 0) {
fromWhere = request.body
} else if (Object.keys(request.query).length > 0) {
fromWhere = request.query
}
if (fromWhere == null) {
return fastify.resp.EMPTY_PARAMS('form')
}
let sign = fromWhere['sign'];
let money = fromWhere['money']
let name = fromWhere['name']
let notify_url = fromWhere['notify_url']
let return_url = fromWhere['return_url']
let out_trade_no = fromWhere['out_trade_no']
let pid = fromWhere['pid']
let type = fromWhere['type']
let ua = request.headers['user-agent']
let client_ip = request.ip
if (request.headers['x-real-ip']) {
client_ip = request.headers['x-real-ip']
}
// GOPay用户
let user = null;
if (stringUtils.isEmpty(ua)) {
return fastify.resp.EMPTY_PARAMS('UA')
}
if (stringUtils.isEmpty(type)) {
return fastify.resp.EMPTY_PARAMS('type')
}
if (stringUtils.isEmpty(pid)) {
return fastify.resp.EMPTY_PARAMS('pid')
}
if (stringUtils.isEmpty(name)) {
return fastify.resp.EMPTY_PARAMS('name')
}
if (stringUtils.isEmpty(notify_url)) {
return fastify.resp.EMPTY_PARAMS('notify_url')
}
if (stringUtils.isEmpty(return_url)) {
return fastify.resp.EMPTY_PARAMS('return_url')
}
if (stringUtils.isEmpty(money) || !/^[0-9.]+$/.test(money)) {
return fastify.resp.EMPTY_PARAMS('money')
}
if (stringUtils.isEmpty(out_trade_no) || !/^[a-zA-Z0-9._-|]+$/.test(out_trade_no)) {
return fastify.resp.EMPTY_PARAMS('out_trade_no')
}
if (stringUtils.isEmpty(sign)) {
return fastify.resp.EMPTY_PARAMS('sign')
}
if (!(user = fastify.user.getUser(pid))) {
return fastify.resp.PID_ERROR
}
let params = stringUtils.sortParams(stringUtils.filterParams(fromWhere))
// 校验签名是否是易支付发过来的
if (!stringUtils.checkSign(params, sign, user['key'])) {
return fastify.resp.SIGN_ERROR
}
let err = false;
let payurl = '';
let type_sgin = 'none'
let isMobile = stringUtils.checkMobile(ua)
if (type === 'alipay') {
// 支付宝支付
let alipay = fastify.alipay.newInstance()
if (alipay == null) {
return fastify.resp.ALIPAY_NO
}
let form = {
outTradeNo: out_trade_no, // 订单号
totalAmount: money,
subject: name,
body: '',
extendParams: {
appid: alipay.appId
}
}
// 重写表单参数
if (opts.form.subject && opts.form.subject.rewrite) {
let subjectText = opts.form.subject.text;
if (subjectText) {
if (subjectText instanceof Array) {
// 随机一个标题
if (subjectText.length > 0) {
form.subject = subjectText[Math.floor(Math.random() * subjectText.length)]
}
} else {
form.subject = subjectText
}
}
}
if (opts.form.body && opts.form.body.rewrite) {
let bodyText = opts.form.body.text;
if (bodyText) {
if (bodyText instanceof Array) {
// 随机一个body
if (bodyText.length > 0) {
form.body = bodyText[Math.floor(Math.random() * bodyText.length)]
}
} else {
form.body = bodyText
}
}
}
let notifyUrl = opts.web.payUrl + '/pay/alipay_notify'
let returnUrl = opts.web.payUrl + '/pay/alipay_return'
try {
payurl = await alipay.exec(form.outTradeNo, form.totalAmount, form.subject,
form.body, isMobile ? 'wap' : 'page', notifyUrl, returnUrl)
// 创建数据库订单信息
let sequelize = fastify.db;
let uuid = uuidv4().replace(/-/g, '').toUpperCase();
const payOrder = await sequelize.models.Order.create({
id: uuid,
out_trade_no: form.outTradeNo,
notify_url: notify_url,
return_url: return_url,
type: type,
pid: pid,
title: name,
money: form.totalAmount,
status: 0
});
fastify.log.info('创建 ' + type + ' 订单成功:' + JSON.stringify(payOrder))
} catch (e) {
err = true;
//console.log(e)
}
} else if (type === 'wxpay') {
//微信支付
// native扫码、h5支付
let wxpay = fastify.wxpay.newInstance()
let notifyUrl = opts.web.payUrl + '/pay/wxpay_notify/' + wxpay.getAppid()
let uuid = uuidv4().replace(/-/g, '').toUpperCase();
let wxOrderName = name;
if (opts.form.subject && opts.form.subject.rewrite) {
let subjectText = opts.form.subject.text;
if (subjectText) {
if (subjectText instanceof Array) {
// 随机一个标题
if (subjectText.length > 0) {
wxOrderName = subjectText[Math.floor(Math.random() * subjectText.length)]
}
} else {
wxOrderName = subjectText
}
}
}
let formData = wxpay.formData(isMobile ? 'h5' : 'native', {
total: parseInt(money) * 100,
description: wxOrderName,
notify_url: notifyUrl,
out_trade_no: uuid, // 使用自己的订单号
payer_client_ip: client_ip // 仅 h5 有效
})
try {
let wxresp = await wxpay.exec(formData)
console.log('isMobile ' + isMobile + ' isOnlyNavtive ' + wxpay.isOnlyNavtive())
if (!isMobile || wxpay.isOnlyNavtive()) {
// 扫码支付
payurl = opts.web.payUrl + '/pay/wxpay/native?cr=' + wxresp.data.code_url + '&out_trade_no=' + uuid + '&ua=' + (isMobile ? 'mobile' : 'pc')
payurl = Buffer.from(payurl).toString('base64')
type_sgin = 'base64';
} else {
// 进入h5支付
payurl = wxresp.data.h5_url
}
// 订单写入数据库
let order = await fastify.db.models.Order.create({
id: uuid,
out_trade_no: out_trade_no, // 源 网站生成的订单号
notify_url: notify_url,
return_url: return_url,
type: type,
pid: pid,
title: name,
money: money,
status: 0
})
fastify.log.info('创建 ' + type + ' 订单成功:' + uuid)
} catch (e) {
let errmsg = e.response['data']['message']
return fastify.resp.SYS_ERROR(errmsg ? errmsg : '创建微信订单错误')
}
} else {
return {code: 404, msg: '其他支付方式开发中'};
}
if (err) {
return fastify.resp.SYS_ERROR('创建订单失败,请返回重试。');
}
return reply.view('/templates/submit.ejs', {
payurl: payurl,
time: new Date().getTime(),
type: type_sgin
})
})
}
|
let marsApiButtons = document.querySelectorAll("button[id*='marsApi']")
marsApiButtons.forEach(button => button.addEventListener('click', function(){
const buttonId = this.id
const roverId = buttonId.split("marsApi")[1]
let apiData = document.getElementById('marsApiRoverData')
apiData.value = roverId
document.getElementById('formRoverType').submit()
})) |
import React from 'react'
import { StyledNav, StyledListItem, StyledLink } from "./NavMenu.style";
const NavMenu = () => (
<StyledNav>
<StyledListItem>
<StyledLink to="/">Home</StyledLink>
</StyledListItem>
<StyledListItem>
<StyledLink to="/autor">Autor</StyledLink>
</StyledListItem>
<StyledListItem>
<StyledLink to="/kontakt">Kontakt</StyledLink>
</StyledListItem>
</StyledNav>
);
export default NavMenu; |
export class Edge {
constructor(id1, id2, weight){
this.id1 = id1;
this.id2 = id2;
this.weight = weight;
}
} |
var Mark = function (name, lat, long, desc) {
var _ = this;
_.Name = name;
_.Latitude = lat;
_.Longitude = long;
_.Description = desc;
} |
import { loadScript } from "../Network/XLoader";
import Color from "../Color/Color";
import AElement from "../HTML5/AElement";
import Vec2 from "../Math/Vec2";
import Rectangle from "../Math/Rectangle";
import { copyJSVariable } from "../JSMaker/generator";
var fontIdOf = fontName => {
if (fontName.toLowerCase().indexOf('arial') >= 0) return 'arial';
if (fontName.toLowerCase().indexOf('times') >= 0) return 'times';
if (fontName === "Material Design Icons") return 'MDI_6_7_96';
return fontName;
}
var P2D = 72 / 96;
var color2RGB255 = color => {
try {
color = Color.parse(color + '');
return color.rgba.slice(0, 3).map(x => x * 255 >> 0);
} catch (e) {
return null;
}
};
function PaperPrinter(opt) {
this.opt = Object.assign(copyJSVariable(this.defaultOptions), opt);
this.objects = [];
this.processInfo = {
state: "STAND_BY"
};
this.subDocs = null;
this.pdfDoc = null;
this.pageFormat = null;
this.computedPages = 0;
this.sync = this.ready().then(() => {
this.processInfo.state = 'READY';
});
}
PaperPrinter.prototype.defaultOptions = {
size: 'a4',
margin: { top: 57, left: 57, bottom: 57, right: 57 },
footer: null,
header: null,
paddingEven: true,
lastPagePaddingEven: false
};
PaperPrinter.prototype.share = {
jsPDFUrl: 'https://absol.cf/vendor/jspdf.umd.js',
jsPDF: null,
readySync: null,
fonts: [
{
url: 'https://absol.cf/vendor/fonts/arial.ttf',
fileName: 'arial.ttf',
name: 'arial',
style: 'normal'
},
{
url: 'https://absol.cf/vendor/fonts/arialbd.ttf',
fileName: 'arialbd.ttf',
name: 'arial',
style: 'bold'
},
{
url: 'https://absol.cf/vendor/fonts/ariali.ttf',
fileName: 'ariali.ttf',
name: 'arial',
style: 'italic'
},
{
url: 'https://absol.cf/vendor/fonts/arialbi.ttf',
fileName: 'arialbi.ttf',
name: 'arial',
style: 'bold_italic'
},
{
url: 'https://absol.cf/vendor/fonts/times.ttf',
fileName: 'times.ttf',
name: 'times',
style: 'normal'
},
{
url: 'https://absol.cf/vendor/fonts/timesbd.ttf',
fileName: 'timesbd.ttf',
name: 'times',
style: 'bold'
},
{
url: 'https://absol.cf/vendor/fonts/timesi.ttf',
fileName: 'timesi.ttf',
name: 'times',
style: 'italic'
},
{
url: 'https://absol.cf/vendor/fonts/timesbi.ttf',
fileName: 'timesbi.ttf',
name: 'times',
style: 'bold_italic'
}
]
};
PaperPrinter.prototype.ready = function () {
var sync;
if (!this.share.readySync) {
sync = this.share.fonts.map((font) => {
return fetch(font.url).then(res => res.blob())
.then(blob => {
var reader = new window.FileReader();
return new Promise(rs => {
reader.onload = function () {
rs(this.result);
}
reader.readAsDataURL(blob);
})
})
.then(b64Url => {
var idx = b64Url.indexOf('base64,');
return b64Url.substring(idx + 'base64,'.length);
}).then(b64 => {
font.content = b64;
})
});
if (window.jspdf) {
this.share.jsPDF = window.jspdf.jsPDF;
}
else {
sync.push(loadScript(this.share.jsPDFUrl).then(() => {
this.share.jsPDF = window.jspdf.jsPDF;
}))
}
this.share.readySync = Promise.all(sync);
}
return this.share.readySync;
};
/***
*
* @param at
* @param opt
*/
PaperPrinter.prototype.addSubDocument = function (at, opt) {
this.objects.push({
type: 'sub_document',
at: at,
opt: opt
});
};
/***
*
* @param {string} text
* @param {Vec2 | Rectangle} pos
* @param {Object=}style
*/
PaperPrinter.prototype.text = function (text, pos, style) {
this.objects.push({
type: 'text',
pos: pos,
text: text,
style: style || {}
});
return this;
};
/***
*
* @param {string} text
* @param {Vec2} start
* @param {Vec2} end
* @param {Object=}style
*/
PaperPrinter.prototype.line = function (start, end, style) {
this.objects.push({
type: 'line',
start: start,
end: end,
style: style || {}
});
return this;
};
/***
*
* @param {Vec2} at
* @param {boolean=} paddingEven
*/
PaperPrinter.prototype.pageBreak = function (at, paddingEven) {
this.objects.push({
type: 'page_break',
at: at,
paddingEven: !!paddingEven
});
return this;
};
/***
*
* @param {Rectangle}rect
* @param {Object=}style
*/
PaperPrinter.prototype.rect = function (rect, style) {
this.objects.push({
type: 'rect',
rect: rect,
style: style || {}
});
};
/***
*
* @param {HTMLCanvasElement|AElement |Image} image
* @param {Rectangle}rect
* @param {Object=}style
*/
PaperPrinter.prototype.image = function (image, rect, style) {
this.objects.push({
type: 'image',
rect: rect,
style: style || {},
image: image
});
return this;
};
PaperPrinter.prototype.boundOf = function (objectData) {
return this.measures[objectData.type](objectData);
};
PaperPrinter.prototype.computeObjects = function () {
var objects = this.objects.slice();
if (!objects[0] || objects[0].type !== 'sub_document') {
objects.unshift({
type: 'sub_document',
at: Vec2.ZERO,
})
}
this.subDocs = objects.reduce((ac, obj) => {
switch (obj.type) {
case 'sub_document':
ac.push({
objects: [obj]
});
break;
default:
ac[ac.length - 1].objects.push(obj);
break;
}
return ac;
}, []);
this.subDocs.forEach((doc, i) => {
doc.objects.forEach((o, i) => {
o.idx = i;
o.bound = this.boundOf(o);
});
var newDocCmd = doc.objects.shift();
doc.objects.sort((a, b) => {
return a.bound.y - b.bound.y;
});
doc.opt = Object.assign(copyJSVariable(this.opt), newDocCmd.opt || {});
doc.objects.unshift(newDocCmd);
doc.startPage = i > 0 ? this.subDocs[i - 1].startPage + this.subDocs[i - 1].pages.length : this.computedPages;
if (this.opt.paddingEven && doc.startPage % 2 > 0) doc.startPage++;
var pageContentHeight = 1123 - doc.opt.margin.top - doc.opt.margin.bottom;
doc.pages = doc.objects.reduce((ac, cr) => {
var page = ac[ac.length - 1];
if (cr.bound.height > pageContentHeight) {
page.object.push(cr);
}
else {
if (cr.bound.y + cr.bound.height - page.y > pageContentHeight || cr.type === 'page_break') {
page = {
y: cr.bound.y,
objects: [cr]
};
ac.push(page);
}
else {
page.objects.push(cr);
}
}
return ac;
}, [{ objects: [], y: 0 }]);
doc.pages.forEach(page => page.objects.sort((a, b) => a.idx - b.idx));
this.computedPages = doc.startPage + doc.pages.length;
});
};
PaperPrinter.prototype.getDoc = function () {
if (this.docSync) return this.docSync;
this.docSync = this.sync.then(() => {
if (this.pdfDoc) return this.pdfDoc;
var jsPDF = jspdf.jsPDF;
this.pdfDoc = new jsPDF({
orientation: 'p',
unit: 'px',
format: 'a4',
putOnlyUsedFonts: true,
floatPrecision: 16,
dpi: 300,
hotfixes: ["px_scaling"]
});
this.share.fonts.forEach(font => {
this.pdfDoc.addFileToVFS(font.fileName, font.content);
this.pdfDoc.addFont(font.fileName, font.name, font.style);
});
return this.pdfDoc;
});
this.sync = this.docSync;
return this.docSync;
};
PaperPrinter.prototype.flush = function () {
this.sync = this.getDoc().then(pdfDoc => {
this.computeObjects();
var subDocs = this.subDocs;
this.subDocs = null;//reset
var onProcess = this.opt.onProcess;
var processInfo = this.processInfo;
processInfo.pdf = {
all: subDocs.reduce((ac, sD) => ac + sD.objects.length, 0),
done: 0
};
processInfo.onProcess = () => {
onProcess && onProcess(processInfo);
};
processInfo.state = 'RENDER_PDF';
return subDocs.reduce((sync, doc, i) => {
return sync.then(() => {
var startPage = doc.startPage;
while (pdfDoc.getNumberOfPages() <= startPage) {
pdfDoc.addPage();
}
return doc.pages.reduce((docSync, page, i) => {
return docSync.then(() => {
if (pdfDoc.getNumberOfPages() <= startPage + i) {
pdfDoc.addPage();
}
pdfDoc.setPage(startPage + i + 1);
page.O = new Vec2(this.opt.margin.left, this.opt.margin.top - page.y);
return page.objects.reduce((pageSync, obj) => {
return pageSync.then(() => {
var type = obj.type;
var res = this.pdfHandlers[type](page, pdfDoc, obj);
processInfo.pdf.done++;
if (res && res.then) {
res.then(() => processInfo.onProcess())
}
return res;
});
}, Promise.resolve()).then(() => {
pdfDoc.setTextColor(0, 0, 0);
pdfDoc.setFontSize(14 * P2D);
pdfDoc.setFont('arial', 'normal');
pdfDoc.text((i + 1) + '/' + doc.pages.length, 794 - 25, 1123 - 25, { align: 'right' });
if (typeof doc.opt.footer === 'string') {
pdfDoc.text(doc.opt.footer, 25, 1123 - 25, { align: 'left' });
}
});
})
}, Promise.resolve())
.then(() => {
if (this.opt.lastPagePaddingEven) {
while (pdfDoc.getNumberOfPages() % 2 > 0) {
pdfDoc.addPage();
}
}
})
})
}, Promise.resolve());
});
return this.sync;
};
PaperPrinter.prototype.exportAsPDF = function () {
return this.flush().then(() => this.pdfDoc);
};
PaperPrinter.prototype.pdfHandlers = {
text: function (context, doc, data) {
var fontFamily = data.style.fontFamily;
var lineHeight = data.style.lineHeight || 1.2;
var color = color2RGB255(data.style.color) || [0, 0, 0];
doc.setTextColor(color[0], color[1], color[2]);
var fontSize = data.style.fontSize || 14;
var textPos = data.pos.A().add(context.O);
doc.setLineHeightFactor(lineHeight);
doc.setFontSize(fontSize * P2D);
doc.setFont(fontIdOf(fontFamily), data.style.fontStyle);
var style = {
baseline: 'top',
maxWidth: data.pos.width
};
if (data.style.align) {
//todo: check align
style.align = { start: 'left', end: 'right', center: 'center' }[data.style.align] || 'left';
}
doc.text(data.text, textPos.x, textPos.y + fontSize * (lineHeight - 1) / 2, style);
},
rect: function (context, doc, data) {
var fillColor = null;
var strokeColor = null;
var strokeWidth = data.style.strokeWidth || 1;
var rounded = data.style.rounded;
if (typeof rounded === "number") rounded = [rounded, rounded];
if (data.style.fill) {
fillColor = color2RGB255(data.style.fill);
}
if (data.style.stroke) {
strokeColor = color2RGB255(data.style.stroke);
}
if (fillColor) doc.setFillColor(fillColor[0], fillColor[1], fillColor[2]);
if (strokeColor) {
doc.setLineWidth(strokeWidth);
doc.setDrawColor(strokeColor[0], strokeColor[1], strokeColor[2]);
}
var flat = 'F';
if (strokeColor && fillColor) flat = 'FD';
else if (strokeColor) flat = 'S';
else if (fillColor) flat = 'F';
else return;
var O = context.O;
var A = data.rect.A().add(O);
if (rounded) {
doc.roundedRect(A.x, A.y, data.rect.width, data.rect.height, rounded[0], rounded[1], flat);
}
else {
doc.rect(A.x, A.y, data.rect.width, data.rect.height, flat);
}
},
line: function (context, doc, data) {
var fillColor = null;
var strokeColor = null;
var strokeWidth = data.style.strokeWidth || 1;
if (data.style.stroke) {
strokeColor = color2RGB255(data.style.stroke);
}
if (strokeColor) {
doc.setLineWidth(strokeWidth);
doc.setDrawColor(strokeColor[0], strokeColor[1], strokeColor[2]);
}
var flat = 'S';
var O = context.O;
var A = data.start.add(O);
var B = data.end.add(O);
doc.line(A.x, A.y, B.x, B.y, flat);
},
image: function (context, doc, data) {
var handleImage = image => {
if (!image) return;
var rect = data.rect.clone();
rect.x += context.O.x;
rect.y += context.O.y;
doc.addImage(image, 'PNG', rect.x, rect.y, rect.width, rect.height)
}
if (data.image.then) {
return data.image.then(handleImage).catch(err => {
});
}
else return handleImage(data.image);
},
page_break: function (context, doc, data) {
},
sub_document: function (context, doc, data) {
}
};
PaperPrinter.prototype.measures = {
sub_document: data => {
return new Rectangle(0, 0, 0, 0);
}, rect: data => {
return data.rect;
},
text: data => {
return data.pos;
},
image: data => {
return data.rect;
},
line: data => {
return Rectangle.boundingPoints([data.start, data.end]);
},
page_break: data => {
return new Rectangle(0, data.at.y, 0, 0);
}
};
export default PaperPrinter;
|
function Carousel(obj, indexArr) {
this.init(obj, indexArr)
}
Carousel.prototype = {
//this.prototype.constructor : Carousel,
init : function(obj, indexArr) {
var oThis = this;
this.width = obj.querySelector('a').offsetWidth;
this.num = 4;
this.index = 0;
this.obj = obj;
this.indexArr = indexArr;
this.timer = null;
this.autoTminer = setInterval(function(){
oThis.next()
}, 3000);
this.left = this.obj.parentNode.querySelector('.left');
this.right = this.obj.parentNode.querySelector('.right');
this.left.onclick = function(){
oThis.prev()
};
this.right.onclick = function() {oThis.next()};
for (var i=0; i<this.indexArr.length; i++) {
this.indexArr[i].index = i;
this.indexArr[i].onclick = function() {
oThis.index = this.index;
oThis.move(this.index)
}
}
},
prev: function(){
this.index--;
if (this.index === -1) {
this.index = this.num;
this.obj.style.left = -this.index*this.Width + 'px';
this.index--
}
this.move(this.index)
},
next: function() {
this.index++;
if (this.index === this.num) {
this.index = 0;
this.obj.style.left = 0;
}
this.move(this.index)
},
move: function(index) {
var oThis = this;
var translate = -(index+1)*this.width;
clearInterval(this.timer);
for(var i=0; i<this.num; i++) {
this.indexArr[i].className = "";
}
index === -1 ? index = this.num-1 : '';
this.indexArr[index].className = "active";
this.timer = setInterval(function(){
var iSpeed = (translate - oThis.obj.offsetLeft)/6;
//iSpeed = (iSpeed>0) ? Math.floor(iSpeed) : Math.ceil(iSpeed);
if (iSpeed === 0) {
clearInterval(oThis.tmier);
}
oThis.obj.style.left = oThis.obj.offsetLeft + iSpeed +'px';
},60)
}
}
window.onload = function() {
var obj = document.getElementById('carousel-main');
var indexArr = document.getElementById('carousel-index').getElementsByTagName('li');
new Carousel(obj, indexArr)
} |
import fs from "fs";
import stringify from "json-stable-stringify";
import jsonminify from "jsonminify";
import path from "path";
import csv from "csvtojson";
import { ceil, floor } from "lodash-es";
import siteConfigData from "../../data/config/site.js";
import dataConfigData from "../../data/config/data.js";
const dataConfig = dataConfigData.default;
const siteConfig = siteConfigData.default;
/** Return true if `n` is convertible to a number. */
function isNumeric(n) {
return !Number.isNaN(Number.parseFloat(n)) && Number.isFinite(Number(n));
}
function truncateDecimals(numberMaybeStr, precision) {
const number = Number(numberMaybeStr);
if (number < 0) return ceil(number, precision);
return floor(number, precision);
}
/**
* Transform CSV array in v1 format to JSON object.
*
* Format of v1 CSV:
*
* - Each row represents all years of data for a particular FIPS region
* - The first column (`id`) is always present and represents the FIPS code
* - Subsequent columns are created for each year of data (y_2013, y_2014, etc.)
*
* For example:
*
* ```csv
* id, y_2013, y_2014, y_2015;
* 370630001011, 17, 17, 18;
* 370630001012, 13, 14, 13;
* ```
*
* The output JSON object is the same as for the v2 importer. It is keyed by the FIPS code, and
* contains values in the {y_2012: value, ...} format. For example:
*
* ```json
* {
* "370630001011": {
* "y_2013": 17,
* "y_2014": 17,
* "y_2015": 18
* },
* "370630001012": {
* ...
* }
* }
* ```
*/
function v1CsvToJson(csvArray) {
const jsonOut = {};
csvArray.forEach((row) => {
jsonOut[row.id] = {};
Object.keys(row).forEach((key) => {
if (key !== "id") {
jsonOut[row.id][key] = isNumeric(row[key]) ? truncateDecimals(row[key], 5) : null;
}
});
});
return jsonOut;
}
/**
* Transform CSV array in v2 format to JSON object.
*
* Format of v2 CSV:
*
* - Each row represents one year of data for a particular FIPS region
* - The columns are always `year, fips, value`
*
* For example:
*
* ```csv
* year, fips, value;
* 2013, 370630001011, 17;
* 2014, 370630001011, 17;
* 2015, 370630001011, 18;
* 2013, 370630001012, 13;
* 2014, 370630001012, 14;
* 2015, 370630001012, 13;
* ```
*
* The output JSON object is the same as for the v1 importer. It is keyed by the FIPS code, and
* contains values in the {y_2012: value, ...} format. For example:
*
* ```json
* {
* "370630001011": {
* "y_2013": 17,
* "y_2014": 17,
* "y_2015": 18
* },
* "370630001012": {
* ...
* }
* }
* ```
*/
function v2CsvToJson(csvArray) {
const jsonOut = {};
csvArray.forEach((row) => {
if (!("fips" in row && "year" in row && "value" in row)) {
throw new TypeError("Each row must have keys fips, year and value");
}
if (!row.fips || !row.year) {
throw new TypeError("Each row must have a valid fips and year value");
}
if (!(row.fips in jsonOut)) {
jsonOut[row.fips] = {};
}
jsonOut[row.fips][`y_${row.year}`] = isNumeric(row.value)
? truncateDecimals(row.value, 5)
: null;
});
return jsonOut;
}
/**
* @param {any} destPath
* @param {any} metric
* @param {any} json
*/
async function writeMetricFile(destPath, metric, json) {
const outFile = path.join(destPath, `m${metric.metric}.json`);
try {
await fs.promises.writeFile(outFile, jsonminify(stringify(json, null, " ")));
console.log(`Wrote ${outFile}`);
} catch (err) {
console.error(`Error on writing ${outFile}: ${err.message}`);
}
}
/**
* Asynchronously checks if given filenames represent files that are readable by the current user.
*
* Returns a `readabilityStatus` object of the form:
*
* {
* [fileName: string]: "readable" | "notReadable"
* }
*
* Does not throw.
*
* @param {string[]} fileNames
* @returns {Promise<({ [fileName: string]: "readable" | "notReadable" })[]}
*/
async function checkIfFilesAreReadable(fileNames) {
const readabilityStatusArray = await Promise.all(
fileNames.map(async (f) => {
try {
await fs.promises.access(f, fs.constants.R_OK);
return { [f]: "readable" };
} catch {
return { [f]: "notReadable" };
}
})
);
// Merge array of status objects into one object
return Object.assign({}, ...readabilityStatusArray);
}
/**
* Find existing metric input CSV files in the filesystem by searching for either v1 or v2 naming
* conventions of file names. Return the name of the first matching file found.
*
* @param {string} geography
* @param {string} metric
* @param {"r" | "d" | "n" | "accuracy"} type
*/
async function checkMetricFileName(geography, metric, type, inputFileBasePath) {
const basePath = path.join(inputFileBasePath, geography);
let fileNamePossibilities = [];
if (type === "accuracy") {
fileNamePossibilities = [
{
name: path.join(basePath, `m${metric.metric.toUpperCase()}-accuracy.csv`),
format: "v1",
},
{
name: path.join(basePath, `m${metric.metric.toLowerCase()}-accuracy.csv`),
format: "v1",
},
];
} else {
let suffix = "";
if (type === "r") {
suffix = "numerator";
} else if (type === "d") {
suffix = "denominator";
} else if (type === "n") {
suffix = "value";
}
fileNamePossibilities = [
{
name: path.join(basePath, `${metric.metric.toUpperCase()}_${suffix}.csv`),
format: "v2",
},
{
name: path.join(basePath, `${metric.metric.toLowerCase()}_${suffix}.csv`),
format: "v2",
},
{
name: path.join(basePath, `${type}${metric.metric.toUpperCase()}.csv`),
format: "v1",
},
{
name: path.join(basePath, `${type}${metric.metric.toLowerCase()}.csv`),
format: "v1",
},
];
}
const fileNames = fileNamePossibilities.map((f) => f.name);
const filesStatus = await checkIfFilesAreReadable(fileNames);
fileNamePossibilities = fileNamePossibilities.filter((f) => filesStatus[f.name] === "readable");
if (fileNamePossibilities.length > 0) {
return fileNamePossibilities[0];
}
return false;
}
/** Convert accuracy metric accuracy files from CSV to JSON and return the JSON. */
async function convertAccuracy(geography, metric, { inputFileBasePath }) {
const accuracyFile = await checkMetricFileName(geography, metric, "accuracy", inputFileBasePath);
if (!accuracyFile) {
console.error(`Could not find matching accuracy file for ${metric.metric} for ${geography}.`);
return;
}
try {
const accuracyCsvImport = await csv().fromFile(accuracyFile.name);
return await v1CsvToJson(accuracyCsvImport);
} catch (error) {
console.error(
`Error parsing accuracy file for ${metric.metric} for ${geography}: ${error.message}`
);
}
}
/**
* Convert sum or mean metrics from CSV to JSON and write out resulting file(s).
*
* Can throw errors.
*/
async function convertSumOrMeanMetric(
geography,
metric,
{ inputFileBasePath, outputFileBasePath }
) {
const outJSON = {};
const type = metric.type === "sum" ? "r" : "n";
const metricFile = await checkMetricFileName(geography, metric, type, inputFileBasePath);
if (!metricFile) {
throw Error(`Could not find ${metric.type} metric CSV files`);
}
let csvArray;
// Read CSV
try {
csvArray = await csv().fromFile(metricFile.name);
} catch (err) {
throw Error(`Error importing ${metric.type} metric CSV file: ${err.message}`);
}
// Convert metric
try {
if (metricFile.format === "v2") {
outJSON.map = v2CsvToJson(csvArray);
} else {
outJSON.map = v1CsvToJson(csvArray);
}
} catch (err) {
throw Error(`Error converting ${metric.type} metric CSV file to JSON: ${err.message}`);
}
// Convert accuracy
try {
if (metric.accuracy) {
outJSON.a = await convertAccuracy(geography, metric, { inputFileBasePath });
}
} catch (err) {
throw Error(
`Error converting ${metric.type} metric accuracy CSV file to JSON: ${err.message}`
);
}
// Write metric file
const dest = path.join(outputFileBasePath, geography);
return writeMetricFile(dest, metric, outJSON);
}
/**
* Convert weighted metric from CSV to JSON and write out resulting file(s).
*
* Can throw errors.
*/
async function convertWeightedMetric(geography, metric, { inputFileBasePath, outputFileBasePath }) {
const outJSON = {};
const files = [
await checkMetricFileName(geography, metric, "r", inputFileBasePath),
await checkMetricFileName(geography, metric, "d", inputFileBasePath),
];
if (!files[0]) {
throw Error(`Could not find numerator (R) CSV file for weighted metric.`);
}
if (!files[1]) {
throw Error(`Could not find denominator (D) CSV file for weighted metric.`);
}
let jsonArrayR, jsonArrayD;
// Read both R (numerator) and D (denominator) files
[jsonArrayR, jsonArrayD] = await Promise.all(
files.map(async (file) => {
let csvArray;
try {
csvArray = await csv().fromFile(file.name);
} catch (err) {
throw Error(`Error importing weighted metric CSV file ${file.name}`);
}
try {
if (file.format === "v2") {
return v2CsvToJson(csvArray);
}
return v1CsvToJson(csvArray);
} catch (err) {
throw Error(`Error converting weighted metric CSV to JSON ${file.name}`);
}
})
);
try {
// Divide each value in R by D
Object.keys(jsonArrayR).forEach((key) => {
Object.keys(jsonArrayR[key]).forEach((key2) => {
if (isNumeric(jsonArrayR[key][key2]) && isNumeric(jsonArrayD[key][key2])) {
let value = jsonArrayR[key][key2] / jsonArrayD[key][key2];
if (metric.suffix === "%") {
value *= 100;
}
jsonArrayR[key][key2] = truncateDecimals(value, 5);
} else {
jsonArrayR[key][key2] = null;
}
});
});
} catch (err) {
throw Error(`Error computing weighted metric value`);
}
outJSON.w = jsonArrayD;
outJSON.map = jsonArrayR;
if (metric.accuracy) {
outJSON.a = await convertAccuracy(geography, metric, { inputFileBasePath });
}
// Write metric file
const dest = path.join(outputFileBasePath, geography);
return writeMetricFile(dest, metric, outJSON);
}
/**
* Convert given metric from CSV to JSON and write out resulting file(s).
*
* Can throw errors.
*/
async function convertMetric(geography, metric, { inputFileBasePath, outputFileBasePath }) {
if (metric.type === "sum" || metric.type === "mean") {
await convertSumOrMeanMetric(geography, metric, { inputFileBasePath, outputFileBasePath });
}
if (metric.type === "weighted") {
await convertWeightedMetric(geography, metric, { inputFileBasePath, outputFileBasePath });
}
}
/**
* Process metrics defined in the data config.
*
* Never throws, all errors are caught.
*
* @param {Object} options
* @param {string} options.inputFileBasePath The base path from which input metrics will be read
* @param {string} options.outputFileBasePath The base path to which processed metrics will be
* written
*/
export default async function datagenMetrics({ inputFileBasePath, outputFileBasePath }) {
const siteGeographyIds = siteConfig.geographies.map((g) => g.id);
// Process all metrics defined in data config.
await Promise.all(
Object.values(dataConfig).map(async (metric) => {
// If metric has defined geographies, convert only the ones included in the site config.
if (metric.geographies) {
console.log(`Converting metric CSVs to JSON for ${metric.metric}`);
await Promise.all(
metric.geographies
.filter((g) => siteGeographyIds.includes(g))
.map(async (geography) => {
try {
await convertMetric(geography, metric, { inputFileBasePath, outputFileBasePath });
} catch (err) {
console.error(
`Metric conversion error: ${err.message} metric=${metric.metric} geography=${geography}:`
);
}
})
);
console.log(`Successfully converted metric CSV to JSON for ${metric.metric}`);
} else if (metric) {
// Omit geography if metric does not have any defined
try {
await convertMetric("", metric, { inputFileBasePath, outputFileBasePath });
} catch (err) {
console.error(
`Metric conversion error: ${err.message} metric=${metric.metric} geography=none:`
);
}
}
})
);
}
export const exportedForTesting = {
isNumeric,
v1CsvToJson,
v2CsvToJson,
checkMetricFileName,
};
|
const appear = {
hidden: { opacity: 1, scale: 0 },
visible: {
opacity: 1,
scale: 1,
transition: {
delayChildren: 1,
staggerChildren: 0.3,
},
},
};
export default appear;
|
const mongoose = require('mongoose');
let personaSchema = new mongoose.Schema({
nombre:{
type:String,
required:true
},
apellidos:{
type:String,
required:true
},
edad:Number
});
let Persona = mongoose.model('Persona',personaSchema);
module.exports = Persona;
|
// eslint-disable-next-line import/no-extraneous-dependencies
import chai from 'chai';
// eslint-disable-next-line import/no-extraneous-dependencies
import 'chai/register-should';
import db from '../main/utils/db';
const { assert } = chai;
const test = () => {
// eslint-disable-next-line no-undef
describe('Creation and dropping of tables', () => {
// eslint-disable-next-line no-undef
it('should create and drop tables without error', async () => {
try {
await db.destroy();
await db.initialize();
assert.ok(true);
} catch (err) {
assert.ok(false);
}
});
});
};
export default test;
|
angular.module('entraide').directive('animToaster', function(AnimToasterNotificationService){
return {
restrict: 'AE',
replace: true,
templateUrl: 'client/app/common/directives/anim-toaster/anim-toaster.ng.html',
controller: function($scope){
$scope.service = AnimToasterNotificationService;
},
link: function (scope) {
scope.$on("$destroy", function () {});
}
};
});
|
const todoData = sessionStorage.getItem("todo");
const val = todoData ? JSON.parse(todoData).length : 0;
const countReducer = (state = val, action) => {
switch (action.type) {
case "INCREASE":
return state + 1;
case "DECREASE":
return state - 1;
case "INITIAL":
return 0;
default:
return state;
}
};
export default countReducer;
|
(function(){
'use strict';
angular.module('myapp', ['ngRoute', 'ngResource', 'ngFileUpload', 'Devise'])
.config(configFunction)
.config(httpFunction);
configFunction.$inject = ['$routeProvider', '$locationProvider'];
httpFunction.$inject = ['$httpProvider'];
function configFunction($routeProvider, $locationProvider) {
$routeProvider
.when('/login', {
templateUrl: '/auth/_login.html',
controller: 'authController'
})
.when('/logout', {
controller: 'authController'
})
.when('/register', {
templateUrl: 'auth/_register.html',
controller: 'authController'
})
.when('/user/:id', {
templateUrl: 'user/profile.html',
controller: 'userController'
});
$locationProvider.html5Mode(false);
}
function httpFunction($httpProvider){
$httpProvider.defaults.headers.common['X-CSRF-Token'] =
$('meta[name=csrf-token]').attr('content');
}
})(); |
var GoogleSpreadsheet = require('google-spreadsheet');
var async = require('async');
var process = require('process')
var fs = require('fs')
function showUsage() {
console.log(
'Usage: ' + process.argv[1].split('/').pop() + " <Config file>\n" +
'\n' +
'Config file should be a JSON file w/ all values filled in. Here are the defaults:\n' +
'\n' +
'{\n' +
' "sheetID": null,\n' +
' "folder": "lang/",\n' +
' "header": "export default ",\n' +
' "hashName": "messages"\n' +
'}\n'
)
process.exit();
}
if (process.argv.length < 3) {
showUsage();
}
const configFilePath = process.argv[2];
console.log('Config: ' + configFilePath);
const config = JSON.parse(fs.readFileSync(configFilePath, "utf8"));
if (!config.sheetID) {
showUsage();
}
// spreadsheet key is the long id in the sheets URL
var doc = new GoogleSpreadsheet(config.sheetID);
var sheet;
var sheetRows;
Array.prototype.removeItems = function(array2) {
var array1 = this;
return array1.filter(value => -1 === array2.indexOf(value));
}
String.prototype.replaceAll = function (search, replacement) {
var target = this;
return target.split(search).join(replacement);
};
let locales = [];
let translations = {};
let appFolder = config.folder;
async.series([
function getInfoAndWorksheets(step) {
doc.getInfo(function(err, info) {
if (err) {
console.log(err);
process.exit();
}
console.log('Loaded doc: '+info.title+' by '+info.author.email);
sheet = info.worksheets[0];
console.log('sheet 1: '+sheet.title+' '+sheet.rowCount+'x'+sheet.colCount);
step();
})
},
function getRows(step) {
// google provides some query options
sheet.getRows({
offset: 1
}, function( err, rows ){
console.log('Read '+rows.length+' rows');
sheetRows = rows
step();
});
},
function surmiseLocales(step) {
locales = Object.keys(sheetRows[0]).removeItems(['id', 'key', 'save', 'del', '_links', '_xml']);
locales.forEach(locale => translations[locale] = {});
step();
},
function loadExistingFiles(step) {
locales.forEach(locale => {
const localeFilePath = appFolder + locale + '.js';
console.log('Reading ' + localeFilePath);
var script = fs.readFileSync(localeFilePath, "utf8");
script = script.replaceAll(config.header, '')
translations[locale] = JSON.parse(script)[config.hashName];
});
step();
},
function parseRows(step) {
sheetRows.forEach(row => {
locales.forEach(locale => {
if (row[locale].length === 0) {
// Keep existing translation
if (!translations[locale][row.key] || translations[locale][row.key].length == 0) {
// If no existing translation use English
translations[locale][row.key] = row['en'];
}
return;
}
translations[locale][row.key] = row[locale];
});
});
step();
},
function outputFiles(step) {
// Create localization files in each input file's output folder
for (let k = 0; k < locales.length; k++) {
const locale = locales[k];
const localeFilePath = appFolder + locale + '.js';
console.log('Writing ' + localeFilePath);
// contents should first begin export default
let fileContents = config.header + '{\n "' + config.hashName + '": ';
// stringify JSON contents
let translationsJson = JSON.stringify(translations[locale], Object.keys(translations[locale]).sort(), 2);
// Apply proper to each translation line
translationsJson = translationsJson.replaceAll(" ", " ");
// Apply proper padding to closing line
translationsJson = translationsJson.replace('}', " }");
// Add formatted file contents to file contents
fileContents += translationsJson;
// end export default
fileContents += "\n}\n";
// Write the contents to the file
fs.writeFileSync(localeFilePath, fileContents)
}
step();
}
], function(err){
if( err ) {
console.log(err);
}
});
|
import NewPollButton from './NewPollButton'
export default NewPollButton |
var merge = function(nums1, m, nums2, n) {
let start = m-1;
let otheridx = n-1;
for (let i = nums1.length - 1; i >= 0; i--) {
if (start < 0) {
nums1[i] = nums2[otheridx];
otheridx -=1;
} else if (otheridx < 0){
nums1[i] = nums1[start];
start-=1;
} else if (nums2[otheridx] > nums1[start]) {
nums1[i] = nums2[otheridx];
otheridx -=1;
} else if (nums2[otheridx] <= nums1[start]) {
nums1[i] = nums1[start];
start-=1;
}
}
};
console.log(merge([1], 1, [], 0))
|
'use strict';
const JScrewIt = require('..');
const { Feature, debug: { getEntries } } = JScrewIt;
const RAW_PREDEFS =
{
__proto__: null,
'BASE64_ALPHABET_HI_4:0': 'ABCD',
'BASE64_ALPHABET_HI_4:4': 'QRST',
'BASE64_ALPHABET_HI_4:5': 'UVWX',
'BASE64_ALPHABET_LO_4:1': ['0B', '0R', '0h', '0x'],
'BASE64_ALPHABET_LO_4:3': ['0D', '0T', '0j', '0z'],
FROM_CHAR_CODE: (encoder, str) => encoder.replaceString(str, { optimize: true }),
FROM_CHAR_CODE_CALLBACK_FORMATTER:
(encoder, fromCharCodeCallbackFormatter) =>
{
const str = fromCharCodeCallbackFormatter('0');
const replacement = encoder.replaceString(str, { optimize: true });
return replacement;
},
MAPPER_FORMATTER:
(encoder, mapperFormatter) =>
{
const expr = mapperFormatter('[undefined]');
const replacement = encoder.replaceExpr(expr);
return replacement;
},
OPTIMAL_B: (encoder, char) => encoder.resolveCharacter(char).replacement,
OPTIMAL_RETURN_STRING: (encoder, str) => encoder.replaceString(str, { optimize: true }),
};
function createFormatVariantByIndex(availableEntries)
{
const map = new Map();
availableEntries.forEach(({ definition }, index) => map.set(definition, index));
const formatVariant = Map.prototype.get.bind(map);
return formatVariant;
}
function define(definition, ...features)
{
const { mask } = Feature(features);
const entry = { definition, mask };
return entry;
}
function getPredef(predefName)
{
let predef;
{
let availableEntries;
let replaceVariant;
let formatVariant;
let variantToMinMaskMap;
const rawPredef = RAW_PREDEFS[predefName];
if (rawPredef[Symbol.iterator])
{
if (Array.isArray(rawPredef))
{
availableEntries =
rawPredef.map(entry => typeof entry === 'object' ? entry : define(entry));
replaceVariant = (encoder, str) => encoder.replaceString(str);
}
else
{
availableEntries = [...rawPredef].map(char => define(char));
replaceVariant = (encoder, char) => encoder.resolveCharacter(char).replacement;
}
formatVariant = variant => `'${variant}'`;
}
else
{
availableEntries = getEntries(`${predefName}:available`);
replaceVariant = rawPredef;
formatVariant = createFormatVariantByIndex(availableEntries);
variantToMinMaskMap = new Map();
availableEntries.forEach
(({ definition, mask }) => variantToMinMaskMap.set(definition, mask));
}
predef = { availableEntries, formatVariant, replaceVariant, variantToMinMaskMap };
}
predef.indent = 8;
predef.organizedEntries = getEntries(predefName);
return predef;
}
{
const PREDEF_TEST_DATA_MAP_OBJ = module.exports = { __proto__: null };
for (const predefName in RAW_PREDEFS)
{
Object.defineProperty
(
PREDEF_TEST_DATA_MAP_OBJ,
predefName,
{ enumerable: true, get: getPredef.bind(null, predefName) },
);
}
}
|
var vt = vt = vt || {};
vt.LogicClass_500349 = cc.Class.extend({
m_view: null,
ctor: function () {},
setTableView: function (view) {
this.m_view = view;
},
refreshTableView: function () {
//this.m_view.reloadData();
},
setVar: function (key, value) {
this[key] = value;
},
run: function (context, targetObject) {
var _this = this;
var localVar={}; //add by wang_dd
var logicName = "";
var tween = new TWEEN.Tween();
context.addTweenArray(tween);
tween.delay(2 * 1000);
tween.onComplete(function(){
this.stop();
context.removeFromTweenArray(this);
context.removeFromParent(true);
});
tween.start();
}
});
|
import React from 'react'
import styles from './../../styles'
const Avatar = ({ imgSrc }) => {
return (
<div style={styles.avatar}>
<img
src={imgSrc}
style={styles.avatarImg}
// #TODO proper alt value
alt={''}
/>
</div>
)
}
const ProfileBlock = ({ data }) => {
return (
<div style={styles.profileBlock}>
<Avatar imgSrc={data.owner.profile_pic_url} />
<div style={styles.profileBlockContent}>
<h3 style={styles.profileBlockTitle}>{data.owner.username}</h3>
<p style={styles.profileBlockLocation}>{data.location.name}</p>
</div>
</div>
)
}
export default ProfileBlock |
/*!
* SpreadSheetLoader
*
* @version 0.9
* @author mach3
* @require jQuery 1.7+
*/
(function($, undefined){
/**
* SpreadSheetLoader
* @class Load Google spreadhsheet as data collection.
* @constructor
* @param String url Publicshed URL of the spreadsheet
*/
var SpreadSheetLoader = function(url){
this.setUrl(url || "");
};
SpreadSheetLoader.prototype = {
type : "SpreadSheetLoader",
EVENT_READY : "ready",
url : "",
keys : [],
data : [],
/**
* Set URL
* @param String url
*/
setUrl : function(url){
this.url = url.split("?")[0];
return this;
},
/**
* Start loading process
*/
load : function(){
$.ajax({
url : this.url,
dataType : "jsonp",
data : { alt : "json" },
success : $.proxy(this._onLoaded, this)
});
return this;
},
_onLoaded : function(data, status){
var self = this;
$.each(data.feed.entry, function(i, item){
var m, r, c, t;
m = item.id.$t.match(/\/R(\d+)C(\d+)$/);
r = parseInt(m[1]) - 2;
c = parseInt(m[2]) - 1;
t = item.content.$t;
if( r < 0 ){
self.keys.push(t);
} else if( c < self.keys.length ){
self.data[r] = self.data[r] || {};
self.data[r][self.keys[c]] = t;
}
});
this.trigger(this.EVENT_READY);
},
/**
* Wrapper for jQuery.fn.on
*/
on : function(){
$.fn.on.apply($(this), arguments);
return this;
},
/**
* Wrapper for jQuery.fn.trigger
*/
trigger : function(){
$.fn.trigger.apply($(this), arguments);
return this;
},
/**
* Get all the data
*/
getData : function(){
return this.data;
},
/**
* Wrapper for jQuery.fn.each
*/
each : function(callback){
$.each(this.data, callback);
return this;
},
/**
* Get items match the condition
* @param Object cond Condition
* @return Array Result data set
*/
getItem : function(cond){
var result = [];
this.each(function(i, item){
var m = true;
$.each(cond, function(key, value){
if(item[key] != value){
m = false;
return false;
}
});
if( m ){
result.push(item);
}
});
return result;
}
};
window.SpreadSheetLoader = SpreadSheetLoader;
})(jQuery); |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Rider = exports.rider = void 0;
const location_model_1 = require("../model/location.model");
const record_model_1 = require("../model/record.model");
class Rider {
getHistory() {
return new Promise(async (res, rej) => {
});
}
getFilteredHistory(filterOptions) {
return new Promise(async (res, rej) => {
});
}
async getLastLocation(id) {
let locations = await location_model_1.location.findOne({
driverID: id
});
return locations;
}
async checkIFtheresPending(id) {
let info = await record_model_1.record.findOne({
driverID: id,
status: { $lt: 4 },
});
return info;
}
async updateDriversLocation(driverID, socketID, lat, lng) {
let response = await location_model_1.location.updateOne({
driverID: driverID
}, {
$set: {
location: {
type: "Point",
coordinates: [lng, lat]
},
socketID: socketID,
}
});
return response;
}
async disconnectDriver(driverID) {
let response = await location_model_1.location.updateOne({
driverID: driverID
}, {
$set: {
socketID: null,
}
});
return response;
}
}
exports.Rider = Rider;
let rider = new Rider();
exports.rider = rider;
|
export default async function commonHandler(view){
this.partials = {
navbar: await this.load('../Views/Common/navbar.hbs'),
footer: await this.load('../Views/Common/footer.hbs'),
notifications: await this.load('../Views/Common/notifications.hbs')
}
if (view) {
await this.partial(view)
}
} |
import React, { Component } from "react";
import { Row, Col, Container } from "react-bootstrap";
import Column from "../component/Column";
import Header from "../component/Header";
import './style.css'
class News extends Component {
state = {
}
render() {
<div>
<Header></Header>
<Col xs={2}>
<Column></Column>
</Col>
</div>
}
} |
import React from 'react'
import PropTypes from 'prop-types'
const BlogForm = ({
addBlog,
newTitle,
handleTitleChange,
newAuthor,
handleAuthorChange,
newLink,
handleLinkChange,
newLikes,
handleLikesChange,
}) => (
<form onSubmit={addBlog}>
<p>
Title: <input id="title" value={newTitle} onChange={handleTitleChange} />
</p>
<p>
Author: <input id="author" value={newAuthor} onChange={handleAuthorChange} />
</p>
<p>
Link: <input id="link" value={newLink} onChange={handleLinkChange} />
</p>
<p>
Likes:{' '}
<input id="likes" type="number" value={newLikes} onChange={handleLikesChange} />
</p>
<button type="submit">save</button>
</form>
)
BlogForm.propTypes = {
addBlog: PropTypes.func.isRequired,
newTitle: PropTypes.string.isRequired,
handleTitleChange: PropTypes.func.isRequired,
newAuthor: PropTypes.string.isRequired,
handleAuthorChange: PropTypes.func.isRequired,
newLink: PropTypes.string.isRequired,
handleLinkChange: PropTypes.func.isRequired,
newLikes: PropTypes.number.isRequired,
handleLikesChange: PropTypes.func.isRequired,
}
export default BlogForm
|
import { useState } from 'react';
import styles from '../../styles/contact.module.scss'
import ProgressIndicator from '../progress_indicator/progress_indicator'
import axios from 'axios';
export default function Contact({ API_END_POINT }){
const [formData, setFormData] = useState({
name: '',
email: '',
message: ''
});
const [errorStyles, setErrorStyles] = useState({
name: false,
email: false,
message: false
});
const [message, setMessage] = useState({
type: '',
value: ''
});
const [isSendingEmail, setIsSendingEmail] = useState(false)
const onInputChangedHandler = (event,field) =>{
const value = event.target.value;
switch(field){
case 'name':
setFormData({...formData,name:value})
break;
case 'email':
setFormData({...formData,email:value})
break;
case 'message':
setFormData({...formData,message:value})
break;
}
}
const isEmailValid = (email) =>{
const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
const validateForm = () =>{
if(!formData.name.trim() && !formData.email.trim() && !formData.message.trim()){
setMessage({type:'error', value:'All fields are required'})
setErrorStyles({name:true, email:true, message: true});
return false;
}
if(!formData.name.trim() && !formData.email.trim()){
setMessage({type:'error', value:'Name and email are required'})
setErrorStyles({name:true, email:true});
return false;
}
if(!formData.name.trim() && !formData.message.trim()){
setMessage({type:'error', value:'Name and message are required'})
setErrorStyles({name:true, message:true});
return false;
}
if(!formData.email.trim() && !formData.message.trim()){
setMessage({type:'error', value:'Email and message are required'})
setErrorStyles({email:true, message: true});
return false;
}
if(!formData.name.trim()){
setMessage({type:'error', value:'Name is required'})
setErrorStyles({name:true});
return false;
}
if(!formData.email.trim()){
setMessage({type:'error', value:'Email is required'})
setErrorStyles({email:true});
return false;
}
if(!formData.message.trim()){
setMessage({type:'error', value:'Message is required'})
setErrorStyles({message:true});
return false;
}
if(!isEmailValid(formData.email)){
setMessage({type:'error', value:'Invalid email'})
setErrorStyles({email:true});
return false;
}
setMessage({type:'error', value:''});
return true;
}
const hideMessageAfter5Seconds = ()=>{
setTimeout(()=>{
setMessage({type:'success', value:''})
},5000);
}
const onFormSubmittedHandler = event =>{
event.preventDefault();
if(validateForm()){
setIsSendingEmail(true)
setErrorStyles({name:false, email:false, message: false});
axios.post(API_END_POINT,{...formData, body:formData.message})
.then(res=>{
setIsSendingEmail(false);
setFormData({name:'',email:'',message:''})
setMessage({value:res?.data?.message || 'Email sent', type: 'success'})
hideMessageAfter5Seconds();
})
.catch(error=>{
setFormData({name:'',email:'',message:''})
setIsSendingEmail(false);
setMessage({value: error?.response?.data?.message || 'An error occurred, try again later', type: 'error'});
hideMessageAfter5Seconds();
});
}
}
return(
<section className={styles.contact_section} id='contact'>
<div className={styles.section_title}>
<h2 className={styles.title_text}>Contact</h2>
</div>
<div className={styles.contact_grid}>
<div className={styles.contact_info}>
<h2>Contact Information</h2>
<p> Tel: +256 777 558 984</p>
<p> Tel: +256 703 554 884</p>
<p> Email: Ken.kamo@yahoo.com</p>
</div>
<div className={styles.contact_form}>
<div className={styles.message}>
{
message.value?
<p className={ message.type === 'success' ? styles.success_message: styles.error_message}>
{message.value}
</p>
: null
}
</div>
<form>
<label htmlFor='name'>Name</label>
<input
type='text'
id='name'
value={formData.name}
onChange={(event) => onInputChangedHandler(event,'name')}
style={ { borderBottom: errorStyles.name? '2px solid red' : ''}}
/>
<label htmlFor='email'>Email</label>
<input
type='email'
id='email'
value={formData.email}
onChange={(event) => onInputChangedHandler(event,'email')}
style={ { borderBottom: errorStyles.email? '2px solid red' : ''}}
/>
<label htmlFor='message'>Message</label>
<textarea
cols='10'
rows = '5'
id='message'
value={formData.message}
onChange={(event) => onInputChangedHandler(event,'message')}
style={ { border: errorStyles.message? '2px solid red' : ''}}
>
</textarea>
<button onClick={onFormSubmittedHandler}>
{
isSendingEmail?
<ProgressIndicator/>
:
'Send Message'
}
</button>
</form>
</div>
</div>
</section>
)
}
|
import places from './tourData';
const tourData = [...places];
export default tourData;
|
var interface_c1_connector_get_session_options =
[
[ "isActivity", "interface_c1_connector_get_session_options.html#a7b475e68a17db1a26fa159d87eaa009e", null ]
]; |
import React, { useState, useEffect } from "react";
import { Text, View, StyleSheet, TextInput, TouchableOpacity, Alert, AsyncStorage } from "react-native";
import { Feather } from "@expo/vector-icons";
import { ScrollView } from "react-native-gesture-handler";
import { useNavigation } from "@react-navigation/native";
import { Montserrat_500Medium, Montserrat_400Regular } from "@expo-google-fonts/montserrat";
export default function Config() {
// VARIAVEIS
const navigation = useNavigation();
const [serverIp, setServerIp] = useState("")
const [activeServerIp, setActiveServerIp] = useState("")
const [hasIp, seHasIp] = useState(false)
const [canSetIP, setCanSetIP] = useState(false)
const [showActiveServer, setShowActiveServer] = useState(false)
// FUNCOES
useEffect(() => {
_getIpServer()
})
_saveIpServer = async (ip) => {
try {
await AsyncStorage.setItem(
'serverIP',
ip
);
Alert.alert("IP salvo com sucesso!!!")
setServerIp("")
_getIpServer();
} catch (error) {
console.log(error);
}
}
_getIpServer = async () => {
try {
const ip = await AsyncStorage.getItem('serverIP')
if (ip != null) {
setActiveServerIp(ip)
}else{
setActiveServerIp("")
}
} catch (error) {
console.log(error);
}
}
_editIpServer = () => {
setServerIp(activeServerIp)
}
_deleteIpServer = async () => {
try {
await AsyncStorage.removeItem('serverIP')
_getIpServer()
alert("Removido com sucesso!!!")
} catch (error) {
console.log(error);
}
}
return (
<View style={styles.container}>
<ScrollView>
{/* Barra fe titulo da pagina */}
<View style={styles.titleBar}>
<View style={styles.tbTemp}>
<Feather onPress={navigation.goBack}
name="arrow-left"
size={24}
color="#8F8F8F"
/>
</View>
<View style={styles.tbTitle}><Text style={styles.titleDesc}>CONFIGURACAO</Text></View>
<View style={styles.tbConfig}>
<Feather
name="settings"
size={24}
color="#8F8F8F"
/>
</View>
</View>
{/* Area para definicao (gravar) do servidor onde esta a aplicacao */}
<View style={styles.infoBlockCard}>
<Text style={styles.infoBlockTitle}>Url do servidor</Text>
<View style={styles.inputLine}>
<TextInput
keyboardType="number-pad"
placeholder="ex.: 192.168.0.1"
style={styles.input}
defaultValue={serverIp}
onChangeText={(e) => { setServerIp(e) }}
/>
<TouchableOpacity style={styles.btnSave} onPress={() => { _saveIpServer(serverIp) }}>
<Text style={styles.btnSaveText}>Salvar</Text>
</TouchableOpacity>
</View>
</View>
{/* Area para visualizacao do servidor e se ele esta online*/}
<View style={styles.infoBlockCard}>
<Text style={styles.infoBlockTitle}>Servidor ativo</Text>
<View style={styles.serverLine} >
<View style={styles.serverInformation}>
<Feather
name="circle"
size={24}
color="#39BF1C"
/>
<Text style={styles.serverIp}>{activeServerIp}</Text>
</View>
<View style={styles.serverActions}>
<Feather style={styles.actions}
name="edit"
size={24}
color="#B3BF1C"
onPress={() => { _editIpServer() }}
/>
<Feather style={styles.actions}
name="trash-2"
size={24}
color="#BF1C1C"
onPress={() => { _deleteIpServer() }}
/>
</View>
</View>
</View>
</ScrollView>
</View>
)
}
const styles = StyleSheet.create({
container: {
backgroundColor: "#353434",
width: '100%',
height: "100%",
paddingTop: 5,
flexDirection: "column",
alignItems: "flex-start",
justifyContent: "flex-start"
},
titleBar: {
flexDirection: "row",
marginLeft: 10,
marginRight: 10,
},
tbTemp: {
width: "25%",
flexDirection: "row",
alignItems: "center",
},
tbTitle: {
width: "50%",
flexDirection: "row",
alignItems: "center",
justifyContent: 'center'
},
tbConfig: {
width: "25%",
alignItems: "center",
flexDirection: "row",
justifyContent: 'flex-end',
},
titleDesc: {
fontFamily: "Teko_300Light",
fontSize: 30,
color: "#8F8F8F"
},
inputLine: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center"
},
input: {
fontFamily: "Montserrat_500Medium",
paddingHorizontal: 10,
fontSize: 13,
height: 30,
width: "80%",
backgroundColor: 'white',
borderRadius: 5,
textAlign: "center"
},
infoBlockCard: {
marginTop: 20,
marginHorizontal: 10,
},
infoBlockTitle: {
fontFamily: "Montserrat_500Medium",
color: "#8F8F8F"
},
btnSave: {
backgroundColor: "#1C1CBF",
borderRadius: 5,
height: 30,
width: "19%",
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
},
btnSaveText: {
color: "#D8D7D4",
fontFamily: "Montserrat_400Regular",
},
serverLine: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
marginTop: 10
},
serverInformation: {
flexDirection: "row",
justifyContent: "flex-start",
alignItems: "center"
},
serverIp: {
fontFamily: "Montserrat_500Medium",
marginLeft: 10,
color: "#D8D7D4",
fontSize: 24
},
serverActions: {
flexDirection: "row",
justifyContent: "flex-start",
alignItems: "center"
},
actions: {
marginHorizontal: 5
}
}) |
function fullname(fname, lname){
return fname + "" + lname;
}
console.log(fullName ("Farhan" , "Akhtar"))
|
import '../styles/globals.css';
import { useAuthState } from "react-firebase-hooks/auth";
import { auth, db } from '../firebase';
import Login from './login';
import Loading from '../components/Loading';
import { useEffect } from 'react';
import firebase from "firebase";
function MyApp({ Component, pageProps }) {
// Check if there is a user logged on (install react-firebase-hooks)
const [user, loading] = useAuthState(auth);
// store users details (pro pic, name, data etc ) in users collection at signIn
// useEffect used to triger piece of code at the components lifecycles (when ever the component in [] mounts in this case the "user")
useEffect(() => {
if (user) {
db.collection("users").doc(user.uid).set({
email: user.email,
lastSeen: firebase.firestore.FieldValue.serverTimestamp(),
photoUrl: user.photoURL,
}, { merge: true });
}
},[user]);
//fix loading at page refresh
if (loading) return <Loading />
//if there is no user redirect to the Loigin page
if (!user) return <Login />;
//if there is a user return rest of the app
return <Component {...pageProps} />
}
export default MyApp
|
import React, { useState, useEffect } from "react";
import "./rough.css";
import {
Radio,
RadioGroup,
FormControlLabel,
FormControl,
Button,
} from "@mui/material";
import music from "../../music.mp3";
import { Link, useParams } from "react-router-dom";
import VolumeUpIcon from "@mui/icons-material/VolumeUp";
import VolumeOffIcon from "@mui/icons-material/VolumeOff";
import wrong_answer from "../../Wrong-answer.mp3";
import correct_answer from "../../Correct-answer.mp3";
import axios from "axios";
import DelayComponent from "../DelayComponent";
import radial from "../../radial_ray2.mp4";
import NavigateNextIcon from "@mui/icons-material/NavigateNext";
import { useContext } from "react";
import { AuthContext } from "../../Context/AuthContext";
import io from "socket.io-client";
var socket = io("ws://13.233.83.134:8080/", { transports: ["websocket"] });
// socket.on("connect", () => {
// console.log(socket.connected);
// });
const useAudio = (url, userToken) => {
const [audio] = useState(new Audio(url));
const [playing, setPlaying] = useState(userToken);
const toggle = () => setPlaying(!playing);
useEffect(() => {
playing ? audio.play() : audio.pause();
}, [playing, audio]);
useEffect(() => {
audio.addEventListener("ended", () => setPlaying(false));
return () => {
audio.removeEventListener("ended", () => setPlaying(false));
};
}, [audio]);
return [playing, toggle];
};
function Rough({
question,
ResultId,
setQuestionIdx,
questionIdx,
setNextQues,
setchangeQuestion,
}) {
//console.log(question._id);
let { quizId } = useParams();
const userToken = JSON.parse(localStorage.getItem("user")) || null;
const { user } = useContext(AuthContext);
console.log(user.user._id);
const [playing, toggle] = useAudio(music, userToken);
const [color, setColor] = useState(false);
const [check, setcheck] = useState(-1);
const [score, setScore] = useState(0);
const [questionRem, setQuestionRem] = useState(25);
const [timer, setTimer] = useState(10000);
const [points, setPoints] = useState(0);
const [load, setLoad] = useState(null);
const [selected, setSelected] = useState(null);
const [classs, setClasss] = useState("");
const [show, setShow] = useState(false);
const [showNext, setNext] = useState(false);
// const [userId, setuserId] = useState(null);
// const [questionId, setQuestionId] = useState(null);
const [correctOption, setCorrectOption] = useState(null);
const [button, setButton] = useState({
one: "",
two: "",
three: "",
four: "",
});
if (!show && !showNext) {
setTimeout(function () {
setShow(true);
}, 14000);
}
if (showNext) {
setTimeout(function () {
setNext(false);
setShow(true);
}, 3000);
}
let userId = user?.user._id;
let roomId = quizId;
// useEffect(() => {
// if (showNext === true || show) {
// setTimeout(() => {
// if (timer > 0) setTimer(timer - 1);
// }, 100);
// }
// }, [show, timer, showNext]);
const next = async (e) => {
setTimer(11500);
e.preventDefault();
setSelected(null);
setClasss(null);
setButton({ one: "", two: "", three: "", four: "" });
setQuestionIdx((prev) => ++prev);
setPoints(timer);
setShow(false);
setNext(true);
};
const handleSelectOption = async (x, type) => {
let answer = x;
let questionId = question?._id;
let URL;
if (setNextQues === true) {
URL = `http://13.233.83.134:8010/common/quiz/submitAnswer?resultId=${ResultId}&quesId=${question._id}&answer=${x}&score=${points}`;
try {
const res = await axios.post(URL);
setCorrectOption(res.data.payload.correctOption);
setSelected(x);
console.log(res.data);
console.log(x);
console.log(res.data.payload.correctOption);
console.log(res.data.payload.isCorrect);
if (x == res.data.payload.correctOption) {
setButton((prev) => ({ ...prev, [type]: "select" }));
const audioTune = new Audio(correct_answer);
audioTune.play();
setColor(true);
setcheck(1);
setScore(res.data.payload.total);
//setClasss("select");
console.log(classs);
} else {
setButton((prev) => ({ ...prev, [type]: "wrong" }));
const audioTune = new Audio(wrong_answer);
audioTune.play();
console.log(x);
console.log(res.data.payload.correctOption);
setColor(false);
setClasss("wrong");
console.log(classs);
}
setQuestionRem(25 - questionIdx - 1);
} catch (error) {
console.log(error);
}
} else {
console.log("submitAnswer");
socket.emit("submitAnswer", { userId, roomId, answer, questionId });
socket.on("submitAnswerResponse", (data) => {
console.log(data);
if (data.isCorrect === true) {
//setButton((prev) => ({ ...prev, [type]: "select" }));
const audioTune = new Audio(correct_answer);
//audioTune.play();
setScore((prev) => prev + data.points);
//etClasss("select");
} else {
//setButton((prev) => ({ ...prev, [type]: "wrong" }));
const audioTune = new Audio(wrong_answer);
//audioTune.play();
setScore((prev) => prev + data.points);
//setClasss("wrong");
}
});
// setButton({ one: "", two: "", three: "", four: "" });
// setClasss(null);
}
};
return question ? (
<div>
<div className="detail__question">
<div className="detail__wrapper">
<div className="detail__wrapper2">
<div className="detail__wrapper3">
{!show && !showNext ? (
<div>
<video controls width="100%" height="100%" autoPlay={true}>
<source src={radial} type="video/mp4" />
<source src={radial} type="video/ogg" />
</video>
</div>
) : (
""
)}
<div className="answer__section detail__content">
{!show && !showNext ? (
<>
{/* <div id="bounce-in" className="bounce-in">
<h1 className="bounce-in-text">Get Ready</h1>
</div> */}
</>
) : showNext ? (
<div id="bounce-in" className="bounce-in">
<h1 className="bounce-in-text">Next Question</h1>
</div>
) : (
<>
<p className="question animated dts fadeInDown">
<span className="classic__question">
{question.content.question}
</span>
</p>
<div className="question_image_container">
<div className="answer__container">
<div className={`fade-in one `} id="one">
<button
className={`answer_animated animated flipInX ${button.one}`}
value={question.options[0]._id}
// control={<Radio />}
key={0}
onClick={() =>
handleSelectOption(question.options[0]._id, "one")
}
>
<p className="answer_number">1</p>
<p
className={`answer__text hoverAnswer ${button.one} `}
>
<span className={`ng_content ${button.one}`}>
{" "}
{question.options[0].text}
</span>
</p>
</button>
</div>
<div className={`fade-in two `} id="two">
<button
value={question.options[1]._id}
// control={<Radio />}
key={1}
name="two"
onClick={() =>
handleSelectOption(question.options[1]._id, "two")
}
className="answer_animated animated flipInX"
>
<p className="answer_number">2</p>
<p
className={`answer__text hoverAnswer ${button.two} `}
>
<span className={`ng_content ${button.two}`}>
{question.options[1].text}
</span>
</p>
</button>
</div>
<div className={`fade-in three `} id="three">
<button
className={`${button.three} answer_animated animated flipInX`}
value={question.options[2]._id}
// control={<Radio />}
key={2}
onClick={() =>
handleSelectOption(
question.options[2]._id,
"three"
)
}
>
<p className="answer_number">3</p>
<p
className={`answer__text hoverAnswer ${button.three} `}
>
<span className={`ng_content ${button.three}`}>
{" "}
{question.options[2].text}
</span>
</p>
</button>
</div>
<div className={`fade-in four `} id="four">
<button
className={`${button.four} answer_animated animated flipInX`}
value={question.options[3]._id}
// control={<Radio />}
key={3}
name="four"
onClick={() =>
handleSelectOption(
question.options[3]._id,
"four"
)
}
>
<p className="answer_number">4</p>
<p
className={`answer__text hoverAnswer ${button.four} `}
>
<span className={`ng_content ${button.four}`}>
{" "}
{question.options[3].text}
</span>
</p>
</button>
</div>
</div>
</div>
{setNextQues === true ? (
<Button
variant="contained"
onClick={next}
endIcon={<NavigateNextIcon sx={{ color: "#ffff" }} />}
>
Next
</Button>
) : (
" "
)}
</>
)}
</div>
</div>
</div>
</div>
<div className="wrapper_sound__on__off">
<div className="sound__on__off">
{playing ? <VolumeUpIcon /> : <VolumeOffIcon />}
{toggle}
<Button style={{ color: "var(--light)" }} onClick={toggle}>
{playing ? "Sound on" : "Sound off"}
</Button>
</div>
</div>
<div className="quiz_landing_container">
<div className="quiz_landing_info">
<div className="quiz_item_info">
<div className="inner_div">
<div className="text_large">{score}</div>
<div className="subtext">Your Current Score</div>
</div>
</div>
<div className="quiz_item_info">
<div className="inner_div">
<div className="text_large">{questionRem}/25</div>
<div className="subtext">Questions Remaining</div>
</div>
</div>
<div className="quiz_item_info">
<div className="inner_div">
{timer > 10000 ? (
<div className="text_large">10000</div>
) : (
<div className="text_large">{timer}</div>
)}
<div className="subtext">Points</div>
</div>
</div>
<div className="quiz_item_info">
<div className="inner_div">
<div className="text_large">0</div>
<div className="subtext">Your Best Score</div>
</div>
</div>
<div className="quiz_item_info">
<div className="inner_div">
<div className="text_large">0</div>
<div className="subtext">LeaderBoard First Place</div>
</div>
</div>
</div>
</div>
</div>
</div>
) : null;
}
export default Rough;
|
const request = require('request')
class request1 {
reqHandler() {
request('https://www.google.comm/', (error, response, body) => {
let err = new Error('ERROR!')
if (error) {
console.error(error)
throw err
}
console.log(body)//Print the HTML for http://google.com.
})
}
}
module.exports = new request1(); |
var searchData=
[
['failed',['failed',['../interface_c1_connector_flush_events_response.html#a27c85bf69af7c76797c576eb8a2a371a',1,'C1ConnectorFlushEventsResponse::failed()'],['../interface_c1_connector_flush_events_response_public.html#a692b388392e0e35c918ae9a3770dc816',1,'C1ConnectorFlushEventsResponsePublic::failed()']]],
['firstname',['firstName',['../interface_c1_connector_user_master_data.html#a4296689ac036044144025e0c84e7a8c6',1,'C1ConnectorUserMasterData']]]
];
|
import React from 'react'
export default function Menu({ Label, List }) {
return (
<div className='menu'>
<h4 className='menu-label has-text-link is-size-4 has-text-weight-semibold'>
{Label}
</h4>
<ul className='menu-list'>
{List.map((item, index) => (
<li key={index} className='py-1 is-capitalized is-size-6'>
<div className='box'>{item.title}</div>
</li>
))}
</ul>
</div>
)
}
|
import React, { Component } from 'react';
import NavigationBar from './navigation-bar';
export default class App extends Component {
render() {
return (
<div>
{/*Header*/}
{/*<nav>
<div className="dropdown">
<a className="dropdown-toggle" href="javascript:void(0)">Data Flow App</a>
<div className="dropdown-content">
<a href="http://storedashboardtest:8088">Test Case Auditor</a>
<a href="http://storedashboarddev02:52086/LiveSiteTracker.html">Live Site Tracker</a>
</div>
</div>
<div>Priority 1</div>
<div>Priority 2</div>
<div>Priority 3</div>
</nav>*/}
{/*Body*/}
{this.props.children}
{/*Footer*/}
</div>
);
}
} |
import _ from 'lodash'
import createStripe from 'stripe'
import {createAuthMiddleware} from 'fl-auth-server'
import createStripeCustomer from './models/createStripeCustomer'
import {
createCard,
listCards,
deleteCard,
setDefaultCard,
chargeCustomer,
listPlans,
getCoupon,
showSubscription,
subscribeToPlan,
} from './interface'
const defaults = {
route: '/api/stripe',
manualAuthorisation: false,
cardWhitelist: ['id', 'country', 'brand', 'last4'],
currency: 'aud',
maxAmount: 500 * 100, // $500
}
function sendError(res, err, msg) {
console.log('[fl-stripe-server] error:', err)
res.status(500).send({error: msg || err && err.toString()})
}
export default function createStripeController(_options) {
const options = _.defaults(_options, defaults)
const {app, User} = options
if (!app) return console.error('createStripeController requires an `app` option, got', _options)
if (!User) return console.error('createStripeController requires a `User` option, got', _options)
const StripeCustomer = options.StripeCustomer || createStripeCustomer(User)
const stripe = createStripe(options.apiKey || process.env.STRIPE_API_KEY)
// Authorisation check. Make sure we can only work with cards (StripeCustomer models) belonging to the logged in user
function canAccess(options, callback) {
const {user} = options
if (!user) return callback(null, false)
if (user.admin) return callback(null, true)
// No additional options; use the logged in user id as the context for all interactions wth Stripe
callback(null, true)
}
function handleCreateCard(req, res) {
const token = req.body.token // obtained with Stripe.js
const userId = req.user.id
createCard({stripe, userId, source: token, description: `User ${req.user.email}`, StripeCustomer}, (err, card) => {
if (err) return sendError(res, err)
res.json(_.pick(card, options.cardWhitelist))
})
}
function handleListCards(req, res) {
const userId = req.user.id
listCards({stripe, userId, StripeCustomer}, (err, cards) => {
if (err) return sendError(res, err)
res.json(cards)
})
}
function handleSetDefaultCard(req, res) {
const userId = req.user.id
const cardId = req.params.cardId
setDefaultCard({stripe, userId, cardId, StripeCustomer}, (err, status) => {
if (err) return sendError(res, err)
res.json(status)
})
}
function handleDeleteCard(req, res) {
const userId = req.user.id
const cardId = req.params.cardId
deleteCard({stripe, userId, cardId, StripeCustomer}, (err, status) => {
if (err) return sendError(res, err)
res.json(status)
})
}
function handleChargeCustomer(req, res) {
const userId = req.user.id
const amount = +req.body.amount
if (!amount) return res.status(400).send('[fl-stripe-server] Missing an amount to charge')
if (amount > options.maxAmount) return res.status(401).send('[fl-stripe-server] Charge exceeds the configured maximum amount')
chargeCustomer({stripe, userId, amount, currency: options.currency, StripeCustomer}, (err, status) => {
if (err) return sendError(res, err)
if (!status) return res.status(404).send('[fl-stripe-server] Customer not found')
res.json(status)
})
}
function handleListPlans(req, res) {
listPlans({stripe}, (err, plans) => {
if (err) return sendError(res, err)
res.json(plans)
})
}
function handleGetCoupon(req, res) {
getCoupon({stripe, coupon: req.params.id}, (err, coupon) => {
if (err) return sendError(res, err)
res.json(coupon)
})
}
function handleShowSubscription(req, res) {
const userId = req.user.id
showSubscription({stripe, userId, StripeCustomer}, (err, subscription) => {
if (err) return sendError(res, err)
if (!subscription) return res.status(404).send('[fl-stripe-server] Subscription not found for current user')
res.json(subscription)
})
}
function handleSubscribeToPlan(req, res) {
const {planId} = req.params
const {coupon} = req.body
const userId = req.user.id
subscribeToPlan({stripe, userId, planId, coupon, StripeCustomer, onSubscribe: options.onSubscribe}, (err, subscription) => {
if (err) return sendError(res, err)
if (!subscription) return res.status(404).send('[fl-stripe-server] Subscription not found for current user')
res.json(subscription)
})
}
const auth = options.manualAuthorisation ? options.auth : [...options.auth, createAuthMiddleware({canAccess})]
app.post(`${options.route}/cards`, auth, handleCreateCard)
app.get(`${options.route}/cards`, auth, handleListCards)
app.put(`${options.route}/cards/default`, auth, handleSetDefaultCard)
app.delete(`${options.route}/cards/:id`, auth, handleDeleteCard)
app.post(`${options.route}/charge`, auth, handleChargeCustomer)
app.get(`${options.route}/plans`, handleListPlans)
app.get(`${options.route}/coupons/:id`, handleGetCoupon)
app.get(`${options.route}/subscription`, auth, handleShowSubscription)
app.put(`${options.route}/subscribe/:planId`, auth, handleSubscribeToPlan)
return {
canAccess,
handleCreateCard,
handleListCards,
handleDeleteCard,
handleSetDefaultCard,
handleChargeCustomer,
handleListPlans,
handleGetCoupon,
handleShowSubscription,
handleSubscribeToPlan,
StripeCustomer,
}
}
|
// @flow
import * as React from 'react';
import { type AlertTranslationType } from '@kiwicom/mobile-localization';
const defaultState = {
warnings: [],
type: '%other',
actions: {
addWarningData: () => {},
},
};
const { Consumer, Provider: ContextProvider } = React.createContext<State>({
...defaultState,
});
export type BookingType =
| 'BookingReturn'
| 'BookingOneWay'
| 'BookingMulticity'
| '%other';
type Props = {|
+children: React.Node,
+type: BookingType,
|};
type TimelineTitle = {|
+localTime: ?Date,
+iataCode: ?string,
|};
type Warning = {| +text: AlertTranslationType, +timelineTitle: TimelineTitle |};
type State = {|
warnings: Warning[],
+type: BookingType,
+actions: {|
+addWarningData: (warning: Warning) => void,
|},
|};
class Provider extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
warnings: [],
type: props.type,
actions: {
addWarningData: this.addWarningData,
},
};
}
addWarningData = (warning: Warning) => {
const { warnings } = this.state;
this.setState({ warnings: [...warnings, warning] });
};
render() {
return (
<ContextProvider value={this.state}>
{this.props.children}
</ContextProvider>
);
}
}
export default { Consumer, Provider };
|
import { StackNavigator } from 'react-navigation'
import AddModalScreen from '../Containers/AddModalScreen'
import StatisticsScreen from '../Containers/StatisticsScreen'
import LaunchScreen from '../Containers/LaunchScreen'
import styles from './Styles/NavigationStyles'
// Manifest of possible screens
const PrimaryNav = StackNavigator({
AddModalScreen: { screen: AddModalScreen },
StatisticsScreen: { screen: StatisticsScreen },
LaunchScreen: { screen: LaunchScreen }
}, {
// Default config for all screens
headerMode: 'none',
initialRouteName: 'LaunchScreen',
navigationOptions: {
headerStyle: styles.header
}
})
export default PrimaryNav
|
import express from 'express';
import userController from '../controllers/user';
import auth from '../middleware/auth';
const router = express();
router.get('/v1/users', auth, userController.getAllUser);
router.post('/v1/auth/signup', userController.signupUser);
router.post('/v1/auth/signin', userController.signinUser);
export default router;
|
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
app.use(bodyParser.json());
mongoose.connect("mongodb://localhost/1955_API");
require("./server/config/schema.js");
require("./server/config/routes.js")(app);
const server = app.listen(8000, function() {
console.log("listening on port 8000");
}) |
import React from 'react';
import '../css/base.css';
import '../css/App.css';
import BottomBar from "./BottomBar";
import Toolbar from "./Toolbar";
import ArtistList from "./ArtistList";
import AlbumList from "./AlbumList";
import TrackList from "./TrackList";
import TrackInfo from "./TrackInfo";
import Playlist from "./Playlist";
import { ContextMenu, MenuItem } from "react-contextmenu";
import { kIsConfigReady } from "../config";
import { kArtist, kAlbum, kTrack } from "../model/browsingModel";
import {
kIsInfoModalOpen,
kIsSmallUI,
kUIConfig,
kUIConfigOptions,
closeInfoModal,
openInfoModal,
} from "../model/uiModel";
import KComponent from "../util/KComponent";
import "../css/modal.css";
class Modal extends React.Component {
render() {
return <div className="st-modal-container">
{this.props.children}
</div>;
}
}
import {
enqueueTrack,
playTracks,
removeTrackAtIndex,
} from "../model/playerModel";
const TrackInfoModal = () => {
return (
<Modal>
<div className="st-track-info-modal">
<div className="st-nav-bar">
Track Info
<div className="st-close-button" onClick={closeInfoModal}>
×
</div>
</div>
<TrackInfo />
</div>
</Modal>
);
}
const TrackListContextMenu = () => {
return (
<ContextMenu id="trackList">
<MenuItem onClick={(e, data) => openInfoModal(data.item)}>
info
</MenuItem>
<MenuItem onClick={(e, data) => enqueueTrack(data.item)}>
enqueue
</MenuItem>
<MenuItem onClick={(e, data) => playTracks(data.playerQueueGetter(data.i))}>
play from here
</MenuItem>
</ContextMenu>
);
}
const PlaylistContextMenu = () => {
return (
<ContextMenu id="playlist">
<MenuItem onClick={(e, data) => openInfoModal(data.item)}>
info
</MenuItem>
<MenuItem onClick={(e, data) => removeTrackAtIndex(data.i)}>
remove
</MenuItem>
</ContextMenu>
);
}
class App extends KComponent {
observables() { return {
isConfigReady: kIsConfigReady,
selectedArtist: kArtist,
selectedAlbum: kAlbum,
selectedTrack: kTrack,
isInfoModalOpen: kIsInfoModalOpen,
isSmallUI: kIsSmallUI,
uiConfig: kUIConfig,
uiConfigOptions: kUIConfigOptions,
}; }
render() {
if (!this.state.isConfigReady) {
return <div>Loading config...</div>;
}
const config = this.state.uiConfigOptions[this.state.uiConfig];
if (!config) return null;
const rowHeight = `${(1 / config.length) * 100}%`;
const outerClassName = (
`st-rows-${config.length} ` +
(this.state.isSmallUI ? "st-ui st-small-ui" : "st-ui st-large-ui")
);
return (
<div className="st-app">
<Toolbar stacked={this.state.isSmallUI} />
<div className={outerClassName}>
{config.map((row, i) => {
const innerClassName = `st-columns-${row.length}`;
return <div key={i} className={innerClassName} style={{height: rowHeight}}>
{row.map((item, j) => this.configValueToComponent(item, j))}
</div>
})}
</div>
<BottomBar />
{this.state.isInfoModalOpen && <TrackInfoModal />}
<TrackListContextMenu />
<PlaylistContextMenu />
</div>
);
}
configValueToComponent(item, key) {
switch (item) {
case 'albumartist': return <ArtistList key={key}/>;
case 'album': return <AlbumList key={key}/>;
case 'tracks': return <TrackList key={key}/>;
case 'queue': return <Playlist key={key}/>;
default: return null;
}
}
}
export default App;
|
const getCardsWithNumbers = (state) => state.cardsWithNumbers;
export default {
getCardsWithNumbers,
};
|
import React from 'react';
import {
AsyncStorage,
View,
Image,
ToastAndroid,
Alert,
Dimensions,
Keyboard,
} from 'react-native';
import { Textarea, Container, Content, Button, Text, Icon, FooterTab, Footer, Right, Left } from 'native-base';
import { LogoTitle, Menu } from '../../../components/header';
import { addControle, User, addArchive, cleanDone } from '../../../database/realm';
import Spinner from 'react-native-loading-spinner-overlay';
var ImagePicker = require('react-native-image-picker');
import Strings from '../../../language/fr';
import { FilePicturePath, writePicture, toDate, toYM, } from '../../../utilities/index';
import { styles } from '../../../utilities/styles';
import { imagePickerOptions } from '../../../utilities/image-picker';
export class FrontCleanDoneScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
drawerLabel: Strings.CURRENT_TASK,
drawerIcon: ({ tintColor }) => (
<Icon name='eye' style={{ color: tintColor, }} />
),
headerLeft: <Menu navigation={navigation} />,
headerTitle: <LogoTitle HeaderText={Strings.CURRENT_TASK} />,
};
};
constructor(props) {
super(props);
this.state = {
schedule: props.navigation.state.params,
source: null,
signature: null,
note: '',
date: toDate(new Date()),
YM: toYM((new Date())),
created_at: new Date(),
dimesions: { width, height } = Dimensions.get('window'),
};
this._bootstrapAsync();
}
_onLayout() {
this.setState({ dimesions: { width, height } = Dimensions.get('window') })
}
_bootstrapAsync = async () => {
const userID = await AsyncStorage.getItem('userSessionId');
const user = await User(userID);
this.setState({
userId: userID,
userObj: user,
});
this._hideLoader();
};
_showLoader() {
this.setState({ loader: 1 });
}
_hideLoader() {
this.setState({ loader: 0 });
}
_pickImage = () => {
ImagePicker.launchCamera(imagePickerOptions, (response) => {
if (response.data) {
writePicture(response.data).then(filename => {
this.setState({ source: filename });
});
}
});
};
_onSave = async (result) => {
writePicture(result.encoded).then(filename => {
this.setState({ signature: filename });
this._signatureView.show(false);
});
}
_save() {
if (!this.state.source) {
ToastAndroid.show(Strings.PLEASE_TAKE_A_PICTURE, ToastAndroid.LONG); return;
}
Alert.alert(
Strings.CONFIRM_CURRENT_TASK,
Strings.ARE_YOU_SURE,
[
{ text: Strings.CANCEL, style: 'cancel' },
{ text: Strings.OK, onPress: () => this._store() },
],
{ cancelable: false }
)
}
_store() {
const { source, note, userId, date, YM, created_at, schedule } = this.state;
this._showLoader();
setTimeout(() => {
addControle(userId, {
equipment: schedule.equipment,
source: source,
signature: '',
produit: '',
fourniser: '',
dubl: '',
aspect: 0,
du_produit: '',
intact: 0,
conforme: 0,
autres: note,
actions: '',
confirmed: 1,
temperatures: [],
type: 3,
quantity: 0,
valorisation: '',
causes: '',
devenir: '',
traitment: '',
date: date,
created_at: created_at,
}).then(() => {
cleanDone(schedule.equipment, schedule.department, schedule, userId).then(() => {
}).catch(error => {
alert(error);
});
addArchive(date, YM, true, userId);
this.props.navigation.navigate('FrontCleanIndex');
Keyboard.dismiss();
this._hideLoader();
ToastAndroid.show(Strings.SCHEDULE_SUCCESSFULL_SAVED, ToastAndroid.LONG);
}).catch(error => {
Keyboard.dismiss();
this._hideLoader();
alert(error);
});
}, 2000);
}
_onLayout() {
this.setState({ dimesions: { width, height } = Dimensions.get('window') })
}
render() {
return (
<Container style={{ flex: 1 }} onLayout={this._onLayout.bind(this)}>
<Spinner visible={this.state.loader} textContent={Strings.LOADING} textStyle={{ color: '#FFF' }} />
<Content style={{ width: this.state.dimesions.width, paddingLeft: 30, paddingRight: 30, paddingTop: 35, }}>
<View style={[styles.container, { justifyContent: 'center', alignItems: 'center' }]}>
<View style={{ width: 300, height: 300, marginBottom: 50, }}>
{!this.state.source && <Button style={{ flex: 1 }} full light onPress={this._pickImage} >
<Icon name='camera' fontSize={50} size={50} style={{ color: 'gray', fontSize: 80, }} />
</Button>}
{this.state.source && <View style={{ flex: 1, }}>
<View style={{ flex: 0.75, zIndex: 0 }}>
<Image
resizeMode={'cover'}
style={{ flex: 1 }}
source={{ uri: FilePicturePath() + this.state.source }}
/>
</View>
<Button style={[styles.button, { zIndex: 1, height: 70, width: 300, position: 'absolute', bottom: 0, }]} onPress={this._pickImage}>
<Left >
<Text style={[{ color: 'white', }, styles.text]}>{Strings.EDIT_IMAGE}</Text>
</Left>
<Right>
<Icon name='attach' style={{ color: 'white', }} />
</Right>
</Button>
</View>}
</View>
</View>
<Text style={[styles.text]}>{Strings.DEPARTMENT}: {this.state.schedule.department.name}</Text>
<Text style={[styles.text, { marginBottom: 30, }]}>{Strings.EQUIPMENTS}: {this.state.schedule.equipment.name}</Text>
<Textarea style={[styles.textarea, {}]} rowSpan={5} bordered placeholder={Strings.COMMENT} onChangeText={(value) => { this.setState({ note: value }) }} />
{/* <Text style={[{ color: 'gray', marginBottom: 85, }]}>Some additional comments goes here</Text> */}
</Content>
<Footer styles={{ height: 100 }}>
<FooterTab styles={{ height: 100 }}>
<Button full success onPress={_ => this._save()} >
<View style={{ flexDirection: 'row' }}>
<Text style={{ color: 'white', paddingTop: 5, }}>{Strings.DONE}</Text>
<Icon name='checkmark' style={{ color: 'white', }} />
</View>
</Button>
</FooterTab>
</Footer>
</Container >
);
}
}
// const styles = StyleSheet.create({
// input: {
// paddingBottom: 10,
// marginBottom: 25,
// },
// }); |
import React from 'react';
import renderer from 'react-test-renderer';
import {BrowserRouter as Router} from 'react-router-dom'
import LoginForm from '../components/LoginForm';
it('renders correctly', () => {
const tree = renderer.create(<Router><LoginForm /></Router>).toJSON();
expect(tree).toMatchSnapshot();
});
|
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { setSelectedTodo } from '../../actions/selectedTodo'
import { change } from 'redux-form'
import Todo from '../../services/Todo'
class TodosList extends Component {
deleteTodo(todoItem) {
const { dispatch, user } = this.props
console.log(user)
console.log(todoItem)
const todo = new Todo()
todo.deleteItem(todoItem, user)(dispatch)
}
render() {
const { todos, setTodo } = this.props
return (
<ul>
{
todos.map((todo, index) => {
return (
<li key={index}>
<p>{todo.body}</p>
<a onClick={() => setTodo(todo)}>Edit</a>
{" "}
<a onClick={() => this.deleteTodo(todo).bind(this)}>Delete</a>
</li>
)
})
}
</ul>
)
}
}
const mapStateToProps = (state) => {
return {
user: state.user
}
}
const mapDispatchToProps = (dispatch) => {
return {
setTodo: (todo) => {
dispatch(setSelectedTodo(todo))
dispatch(change('todoForm', 'body', todo.body))
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(TodosList)
|
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { map } from 'lodash';
import SideBar from './SideBar';
import { Title,SubTitle } from './ElemUtil';
import { Container,Row,Col } from 'reactstrap';
import { get } from 'axios';
class App extends Component {
state = {
content:undefined,
htmlFileName: "proto.html",
};
constructor(props){
super(props);
this.htmlElementsToState = this.htmlElementsToState.bind(this);
}
componentDidMount(){
this.htmlElementsToState();
}
htmlElementsToState(){
get("/api/data").then((data)=>{
console.log(data);
this.setState({
content: data.data
})
});
}
render() {
let { content } = this.state;
if(content !== undefined){
return (
<div>
<SideBar content={content}/>
<Container>
{
map(content.titles,(title)=> <Title> { title } </Title> )
}
</Container>
</div>
);
}else{
return(
<div>
loading
</div>
);
}
}
}
export default App;
|
import React, { useEffect } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import {
getPopularMovies,
} from "../actions/MovieActions";
import Header from "../components/Header";
import PopularMoviesTable from "../components/PopularMoviesTable";
export const IndexView = ({
dispatch,
key,
}) => {
useEffect(() => {
dispatch(getPopularMovies());
}, []);
return (<>
<Header />
<PopularMoviesTable />
</>);
};
IndexView.propTypes = {
dispatch: PropTypes.func.isRequired,
};
IndexView.defaultProps = {
};
export default connect(() => ({
/* Map state to props object:
/* foo: state.foo */
}))(IndexView);
|
var Backbone = require('backbone');
var model = require('../models/single-indicator');
var baseurl = require('../util/base-url');
module.exports = Backbone.Collection.extend({
url: baseurl + '/assets/static/indicators/',
model: model,
initialize: function (options) {
this.url += options.indicator + '.json';
},
parse: function (resp) {
this.indicatorId = resp.id;
this.indicatorName = resp.name;
this.indicatorFollow = resp.follow;
return resp.companies;
}
});
|
function delete_employee(ID) {
var EmployeeModel = Backbone.Model.extend({
defaults : {
id : null,
name : "",
password : "",
userrole : "",
contact : null,
email : ""
},
url : '/messenger/webapi/admin'
});
var EmployeeCollection = Backbone.Collection.extend({
model : EmployeeModel,
url : '/messenger/webapi/admin'
});
var employeeCollection = new EmployeeCollection();
employeeCollection.fetch().then(function() {
var id = Number(ID);
var res = employeeCollection.findWhere({
'id' : id
});
console.log(res);
if (res.get('id') == id) {
res.destroy({
data : JSON.stringify({
'id' : id
}),
contentType : "application/json"
},{
success:function(model,response){
console.log(response);
document.getElementById("status").innerHTML="Employee Deleted Succesfully";
},
error:function(model,response){
console.log(response);
document.getElementById("status").innerHTML="Failed to Delete";
}
});
document.getElementById("status").innerHTML="Employee Deleted Succesfully";
} else {
}
});
} |
import { modulus } from './hash-functions';
const DEFAULT_THRESHOLD = 0.6;
class HashNode {
constructor(key, value) {
this.key = key;
this.value = value;
this.next = null;
}
}
export default class HashTable {
constructor(hashFn = modulus, threshold = DEFAULT_THRESHOLD) {
this.capacity = 10;
this.size = 0;
this.bucket = new Array(this.capacity).fill(null);
this.hashFn = hashFn;
this.threshold = threshold;
}
#addHelper(key, value, bucket) {
const index = this.getIndex(key);
if (!bucket[index]) {
bucket[index] = new HashNode(key, value);
} else {
let target = bucket[index];
while (target.next) {
if (target.key === key) {
target.value = value;
break;
}
target = target.next;
}
target.next = new HashNode(key, value);
}
}
#resize() {
const newCapacity = this.capacity * 2;
this.capacity = newCapacity;
const newBucket = new Array(newCapacity).fill(null);
for (let i = 0; i < this.bucket.length; i++) {
let curr = this.bucket[i];
while (curr != null) {
this.#addHelper(curr.key, curr.value, newBucket)
curr = curr.next;
}
}
this.bucket = newBucket;
}
getSize() {
return this.size;
}
isEmpty() {
return !this.getSize();
}
getIndex(key) {
return this.hashFn(key, this.capacity);
}
insert(key, value) {
this.#addHelper(key, value, this.bucket);
this.size += 1;
const currentLoad = Number(this.size) / Number(this.capacity);
if (currentLoad >= this.threshold) {
this.#resize();
}
}
search(key) {
const index = this.getIndex(key);
let curr = this.bucket[index];
while (curr) {
if (curr.key === key) {
return curr.value;
}
curr = curr.next;
}
return curr;
}
delete(key) {
const index = this.getIndex(key);
let curr = this.bucket[index];
// No entries for the key
if (!curr) {
return;
}
// Key to delete at head of list
if (curr.key === key) {
this.bucket[index] = curr.next;
this.size -= 1;
return;
}
// Key not at head of list, check next
// node for match, delete by pointing
// current.next to the next.next
while (curr.next) {
if (curr.next.key === key) {
curr.next = curr.next.next;
this.size -= 1;
return;
} else {
curr = curr.next;
}
}
}
} |
import { StyleSheet, Dimensions } from 'react-native'
const { width, height } = Dimensions.get('window')
export default StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#e6e9ed'
},
viewContainer: {
flexDirection: 'row',
marginTop: 20,
marginLeft: 20,
borderRadius: 8,
backgroundColor: 'white',
width: width - 40
},
leftView: {
width: 10,
marginLeft: -5,
marginTop: 30,
marginBottom: 30,
backgroundColor: '#ff0000',
borderRadius: 8
},
rightView: {
flex: 1,
marginLeft: 10,
marginRight: 10,
marginTop: 30,
marginBottom: 30
},
lineView: {
height: 1,
marginTop: 5,
backgroundColor: '#e6e9ed'
},
childRowView: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
circleView: {
width: 14,
height: 14,
borderRadius: 7
},
switchView: {
flex: 1,
marginRight: 10,
flexDirection: 'row',
justifyContent: 'flex-end'
},
nameText: {
fontSize: 17
},
buttonText: {
fontSize: 15,
color: 'white'
},
saveButton: {
backgroundColor: '#ff0000',
height: 40,
marginLeft: 30,
borderRadius: 20,
justifyContent: 'center',
alignItems: 'center',
marginRight: 30,
marginTop: 20
}
}) |
import React from 'react';
import HeaderMain from '../HeaderMain/HeaderMain';
import Navbar from '../Navbar/Navbar';
import OurPartnerLogo from '../OurPartnerLogo/OurPartnerLogo';
import './Header.css';
const Header = () => {
return (
<div className="header-content">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="none">
<polygon fill="white" points="0,100 100,0 100,100" />
</svg>
<Navbar></Navbar>
<HeaderMain></HeaderMain>
<OurPartnerLogo></OurPartnerLogo>
</div>
);
};
export default Header; |
// ??? Change error to error[0], add error for private messaging
import React from "react";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import { getSocket } from "./socket";
import Online from "./online";
class Chat extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.handleInput = this.handleInput.bind(this);
this.submitChatMessage = this.submitChatMessage.bind(this);
this.hitEnter = this.hitEnter.bind(this);
this.socket = getSocket();
}
componentDidMount() {
this.chatWindow.scrollTop =
this.chatWindow.scrollHeight - this.chatWindow.clientHeight;
}
componentDidUpdate() {
this.chatWindow.scrollTop =
this.chatWindow.scrollHeight - this.chatWindow.clientHeight;
}
handleInput(e) {
this[e.target.name] = e.target.value;
}
submitChatMessage() {
if (this.message) {
this.socket.emit("newChatMessage", this.message.trim());
this.field.value = null;
} else {
this.socket.emit("newChatMessage", this.message);
this.field.value = null;
}
}
hitEnter(e) {
if (e.keyCode == 13) {
this.submitChatMessage();
}
}
render() {
return (
<div className="chat flex column">
<div
className="chatWindow public"
ref={chatWindow => (this.chatWindow = chatWindow)}
>
{this.props.chatMessages &&
this.props.chatMessages.map(message => {
return (
<div
className="message flex row"
key={message.id}
>
<div className="messageImage">
<img
className="profilePicSmall"
src={message.imgurl}
alt={message.firstname}
/>
</div>
<div className="messageInfo">
<Link to={"/user/" + message.user_id}>
<div className="messageName">
{message.firstname}{" "}
{message.lastname}
{":"}
</div>
</Link>
<div className="messageText">
{message.message}
</div>
<div className="messageDate">
on{" "}
{new Date(
message.created_at
).toLocaleDateString()}{" "}
at{" "}
{new Date(
message.created_at
).toLocaleTimeString()}
</div>
</div>
</div>
);
})}
</div>
<textarea
className="textareaPublic"
name="message"
onChange={this.handleInput}
ref={field => (this.field = field)}
placeholder="Write a message"
onKeyDown={e => this.hitEnter(e)}
/>
<div className="form">
<button onClick={this.submitChatMessage}>
Submit (or hit enter)
</button>
</div>
{this.props.error &&
this.props.error.map(error => {
return (
<div className="error" key={error.error}>
{error.error}
</div>
);
})}
<h3>Online right now</h3>
<Online />
</div>
);
}
}
const mapStateToProps = state => {
return {
chatMessages: state.chatMessages,
error: state.error
};
};
export default connect(mapStateToProps)(Chat);
|
"use strict"
//BOOKS REDUCERS
export function booksReducers(state = {
books: [{
_id:1,
title: "this is a book title",
description: "this is the book description",
price: 33.25
},
{
_id:2,
title: "this is the second book title",
description: "this is the second book description",
price: 343.25
}]
}, action) {
switch (action.type) {
case "POST_BOOK":
return {books: [...state.books, ...action.payload]}
break;
case "GET_BOOKS_BOOK":
return {...state, books:[...state.books]}
break;
case "DELETE_BOOK":
//create a copy of the current array of books
const currentBookToDelete = [...state.books];
//Determine at which index in books array is the book to be deleted
const indexToDelete = currentBookToDelete.findIndex(
function(book) {
return book._id === action.payload._id
}
);
//use slice to remove the book at the specified index
return {
books:[
...currentBookToDelete.slice(0, indexToDelete),
...currentBookToDelete.slice(indexToDelete + 1)
]}
break;
case "UPDATE_BOOK":
//create a copy of the current array of books
const currentBookToUpdate = [...state.books];
//Determine at which index in books array is the book to be deleted
const indexToUpdate = currentBookToUpdate.findIndex(
function(book) {
return book._id === action.payload._id
}
);
const newBookToUpdate = {
...currentBookToUpdate[indexToUpdate],
title: action.payload.title
}
//use slice to remove the book at the specified index
return {
books:[
...currentBookToUpdate.slice(0, indexToUpdate),
newBookToUpdate,
...currentBookToUpdate.slice(indexToUpdate + 1)
]}
break;
}
return state;
}
|
import React from "react";
import DropDownMenu from "../DropDownMenu/DropDownMenu";
import styles from "./Header.module.css";
const Header = () => (
<div className={styles.headerContainer}>
<DropDownMenu />
<h1 className={styles.title}>My portfolio</h1>
</div>
);
export default Header;
|
'use strict'
/* */
var maiorNum = require('./maiorNumero')
var menorNum = require('./menorNumero')
function amplitudeTotal (arr) {
maiorNum = maiorNum(arr);
menorNum = menorNum(arr);
console.log(arr);
return (maiorNum - menorNum)
}
var ttt = [5,2,3,1,4]
console.log(amplitudeTotal(ttt));
module.exports = amplitudeTotal
|
// Red.pokemon/iCasino.js
// Defines the event for this character in Napoleon's casino
var base = require("./base.js");
var Actor = require("tpp-actor");
var ActorCasino = window.ActorCasino || Actor; //defined in the casino.js file
add(new ActorCasino(base, {
dialog: [
"...",
"The Church of Helix is coming along nicely...",
"...",
"You should attend. Praise Helix.",
],
})); |
// @flow
import React, { Component } from 'react';
import {curry, map} from 'ramda'
import VisitorsListItem from './VisitorsListItem.js'
import type {Visitor} from '../../Model.js'
import Header from '../header/Header.js'
import NavBar from '../navbar/Navbar.js'
type Props = {
dispatch: Function,
location: Location,
visitors: Visitor[],
selectedVisitor: ?string
}
export default (props: Props) => {
const {dispatch, selectedVisitor, visitors, location} = props
return (
<div className="flex-column">
<Header title="Visitors"/>
<div className="flex-grow-1 scroll-y">
<div>
<div className="list-group-title">Current visitors</div>
<ul className="list-group">
{map(visitor => VisitorsListItem(dispatch, {visitor, selected: visitor.id === selectedVisitor}), visitors)}
</ul>
<div className="list-group-title">Old visitors</div>
<ul className="list-group">
{map(visitor => VisitorsListItem(dispatch, {visitor, selected: visitor.id === selectedVisitor}), visitors)}
</ul>
</div>
</div>
<NavBar {...{dispatch, location}} />
</div>
)
}
|
import "./WidgetSm.css";
import VisibilityIcon from '@material-ui/icons/Visibility';
const WidgetSm = () => {
return (
<div className="widget-sm">
<span className="widget-sm-title">New Joined Members</span>
<ul className="widget-sm-list">
<li className="widget-sm-list-item">
<img className="widget-sm-item-image" src="https://lh3.googleusercontent.com/ogw/ADea4I5Zmq8Da4GL7w1Bi0NPQTomAbVrc6oMrn_pZiEugw=s32-c-mo" alt="profile pic" />
<div className="widget-sm-user">
<span className="widget-sm-username">Kevin Thuita</span>
<span className="widget-sm-job">Jazz Muscian</span>
</div>
<button className="widget-sm-button">
<VisibilityIcon className="widget-sm-button-icon" />
Display
</button>
</li>
<li className="widget-sm-list-item">
<img className="widget-sm-item-image" src="https://lh3.googleusercontent.com/ogw/ADea4I5Zmq8Da4GL7w1Bi0NPQTomAbVrc6oMrn_pZiEugw=s32-c-mo" alt="profile pic" />
<div className="widget-sm-user">
<span className="widget-sm-username">Nyambura Ivy</span>
<span className="widget-sm-job">Chef</span>
</div>
<button className="widget-sm-button">
<VisibilityIcon className="widget-sm-button-icon" />
Display
</button>
</li>
<li className="widget-sm-list-item">
<img className="widget-sm-item-image" src="https://lh3.googleusercontent.com/ogw/ADea4I5Zmq8Da4GL7w1Bi0NPQTomAbVrc6oMrn_pZiEugw=s32-c-mo" alt="profile pic" />
<div className="widget-sm-user">
<span className="widget-sm-username">Spurgeon k</span>
<span className="widget-sm-job">Golfer</span>
</div>
<button className="widget-sm-button">
<VisibilityIcon className="widget-sm-button-icon" />
Display
</button>
</li>
<li className="widget-sm-list-item">
<img className="widget-sm-item-image" src="https://lh3.googleusercontent.com/ogw/ADea4I5Zmq8Da4GL7w1Bi0NPQTomAbVrc6oMrn_pZiEugw=s32-c-mo" alt="profile pic" />
<div className="widget-sm-user">
<span className="widget-sm-username">John Carlos</span>
<span className="widget-sm-job">Actor</span>
</div>
<button className="widget-sm-button">
<VisibilityIcon className="widget-sm-button-icon" />
Display
</button>
</li>
<li className="widget-sm-list-item">
<img className="widget-sm-item-image" src="https://lh3.googleusercontent.com/ogw/ADea4I5Zmq8Da4GL7w1Bi0NPQTomAbVrc6oMrn_pZiEugw=s32-c-mo" alt="profile pic" />
<div className="widget-sm-user">
<span className="widget-sm-username">Gathuita John</span>
<span className="widget-sm-job">GIS</span>
</div>
<button className="widget-sm-button">
<VisibilityIcon className="widget-sm-button-icon" />
Display
</button>
</li>
</ul>
</div>
)
}
export default WidgetSm; |
'use strict';
var config = require('config');
var redisConfig = {
port: config.get('redis').port,
host: config.get('redis').host
};
function getRedisConfig() {
return redisConfig;
}
module.exports = getRedisConfig;
|
var Web = (function() {
var express = require('express'),
app = express(),
hbs = require('hbs'),
port = 8080;
function init() {
app.set('view engine', 'hbs');
app.set('views', __dirname + '/app/views');
hbs.registerPartials(__dirname + '/app/views/partials');
hbs.registerHelper('row', function (name) {
return name;
});
app.use(express.static(__dirname + '/public'));
app.use(require('./app/routes'));
app.listen(port, function() {
console.log('Started server port:', port);
});
}
return {
'init': init
};
}());
module.exports = Web;
|
import { configureStore } from '@reduxjs/toolkit';
import { reducer as authReducer, initialState as authInitialState } from '../modules/auth';
import { reducer as filtersReducer, initialState as filtersInitialState } from '../modules/filters';
import { reducer as productsReducer, initialState as productsInitialState } from '../modules/products';
import { reducer as wishlistReducer, initialState as wishlistInitialState } from '../modules/wishlist';
const store = configureStore({
reducer: {
auth: authReducer,
filters: filtersReducer,
products: productsReducer,
wishlist: wishlistReducer
},
devTools: true,
preloadedState: {
auth: authInitialState,
filters: filtersInitialState,
products: productsInitialState,
wishlist: wishlistInitialState
}
});
export { store };
|
/*
* Copyright (c) 2015
*
* This file is licensed under the Affero General Public License version 3
* or later.
*
* See the COPYING-README file.
*
*/
/* global dav */
(function(OC, FileInfo) {
/**
* @class OC.Files.Client
* @classdesc Client to access files on the server
*
* @param {Object} options
* @param {String} options.host host name including port
* @param {boolean} [options.useHTTPS] whether to use https
* @param {String} [options.root] root path
* @param {String} [options.userName] user name
* @param {String} [options.password] password
*
* @since 8.2
*/
var Client = function(options) {
this._root = options.root;
if (this._root.charAt(this._root.length - 1) === '/') {
this._root = this._root.substr(0, this._root.length - 1);
}
var url = Client.PROTOCOL_HTTP + '://';
if (options.useHTTPS) {
url = Client.PROTOCOL_HTTPS + '://';
}
url += options.host + this._root;
this._host = options.host;
this._defaultHeaders = options.defaultHeaders || {
'X-Requested-With': 'XMLHttpRequest',
'requesttoken': OC.requestToken
};
this._baseUrl = url;
this._rootSections = _.filter(this._root.split('/'), function(section) { return section !== '';});
this._rootSections = _.map(this._rootSections, window.decodeURIComponent);
var clientOptions = {
baseUrl: this._baseUrl,
xmlNamespaces: {
'DAV:': 'd',
'http://owncloud.org/ns': 'oc'
}
};
if (options.userName) {
clientOptions.userName = options.userName;
}
if (options.password) {
clientOptions.password = options.password;
}
this._client = new dav.Client(clientOptions);
this._client.xhrProvider = _.bind(this._xhrProvider, this);
};
Client.NS_OWNCLOUD = 'http://owncloud.org/ns';
Client.NS_DAV = 'DAV:';
Client.PROPERTY_GETLASTMODIFIED = '{' + Client.NS_DAV + '}getlastmodified';
Client.PROPERTY_GETETAG = '{' + Client.NS_DAV + '}getetag';
Client.PROPERTY_GETCONTENTTYPE = '{' + Client.NS_DAV + '}getcontenttype';
Client.PROPERTY_RESOURCETYPE = '{' + Client.NS_DAV + '}resourcetype';
Client.PROPERTY_INTERNAL_FILEID = '{' + Client.NS_OWNCLOUD + '}fileid';
Client.PROPERTY_PERMISSIONS = '{' + Client.NS_OWNCLOUD + '}permissions';
Client.PROPERTY_SIZE = '{' + Client.NS_OWNCLOUD + '}size';
Client.PROPERTY_GETCONTENTLENGTH = '{' + Client.NS_DAV + '}getcontentlength';
Client.PROTOCOL_HTTP = 'http';
Client.PROTOCOL_HTTPS = 'https';
Client._PROPFIND_PROPERTIES = [
/**
* Modified time
*/
[Client.NS_DAV, 'getlastmodified'],
/**
* Etag
*/
[Client.NS_DAV, 'getetag'],
/**
* Mime type
*/
[Client.NS_DAV, 'getcontenttype'],
/**
* Resource type "collection" for folders, empty otherwise
*/
[Client.NS_DAV, 'resourcetype'],
/**
* File id
*/
[Client.NS_OWNCLOUD, 'fileid'],
/**
* Letter-coded permissions
*/
[Client.NS_OWNCLOUD, 'permissions'],
//[Client.NS_OWNCLOUD, 'downloadURL'],
/**
* Folder sizes
*/
[Client.NS_OWNCLOUD, 'size'],
/**
* File sizes
*/
[Client.NS_DAV, 'getcontentlength']
];
/**
* @memberof OC.Files
*/
Client.prototype = {
/**
* Root path of the Webdav endpoint
*
* @type string
*/
_root: null,
/**
* Client from the library
*
* @type dav.Client
*/
_client: null,
/**
* Array of file info parsing functions.
*
* @type Array<OC.Files.Client~parseFileInfo>
*/
_fileInfoParsers: [],
/**
* Returns the configured XHR provider for davclient
* @return {XMLHttpRequest}
*/
_xhrProvider: function() {
var headers = this._defaultHeaders;
var xhr = new XMLHttpRequest();
var oldOpen = xhr.open;
// override open() method to add headers
xhr.open = function() {
var result = oldOpen.apply(this, arguments);
_.each(headers, function(value, key) {
xhr.setRequestHeader(key, value);
});
return result;
};
OC.registerXHRForErrorProcessing(xhr);
return xhr;
},
/**
* Prepends the base url to the given path sections
*
* @param {...String} path sections
*
* @return {String} base url + joined path, any leading or trailing slash
* will be kept
*/
_buildUrl: function() {
var path = this._buildPath.apply(this, arguments);
if (path.charAt([path.length - 1]) === '/') {
path = path.substr(0, path.length - 1);
}
if (path.charAt(0) === '/') {
path = path.substr(1);
}
return this._baseUrl + '/' + path;
},
/**
* Append the path to the root and also encode path
* sections
*
* @param {...String} path sections
*
* @return {String} joined path, any leading or trailing slash
* will be kept
*/
_buildPath: function() {
var path = OC.joinPaths.apply(this, arguments);
var sections = path.split('/');
var i;
for (i = 0; i < sections.length; i++) {
sections[i] = encodeURIComponent(sections[i]);
}
path = sections.join('/');
return path;
},
/**
* Parse headers string into a map
*
* @param {string} headersString headers list as string
*
* @return {Object.<String,Array>} map of header name to header contents
*/
_parseHeaders: function(headersString) {
var headerRows = headersString.split('\n');
var headers = {};
for (var i = 0; i < headerRows.length; i++) {
var sepPos = headerRows[i].indexOf(':');
if (sepPos < 0) {
continue;
}
var headerName = headerRows[i].substr(0, sepPos);
var headerValue = headerRows[i].substr(sepPos + 2);
if (!headers[headerName]) {
// make it an array
headers[headerName] = [];
}
headers[headerName].push(headerValue);
}
return headers;
},
/**
* Parses the etag response which is in double quotes.
*
* @param {string} etag etag value in double quotes
*
* @return {string} etag without double quotes
*/
_parseEtag: function(etag) {
if (etag.charAt(0) === '"') {
return etag.split('"')[1];
}
return etag;
},
/**
* Returns the relative path from the given absolute path based
* on this client's base URL.
*
* @param {String} path href path
* @return {String} sub-path section or null if base path mismatches
*
* @since 10.1.0
*/
getRelativePath: function(path) {
return this._extractPath(path);
},
/**
* Parse sub-path from href
*
* @param {String} path href path
* @return {String} sub-path section
*/
_extractPath: function(path) {
var pathSections = path.split('/');
pathSections = _.filter(pathSections, function(section) { return section !== '';});
var i = 0;
for (i = 0; i < this._rootSections.length; i++) {
if (this._rootSections[i] !== decodeURIComponent(pathSections[i])) {
// mismatch
return null;
}
}
// build the sub-path from the remaining sections
var subPath = '';
while (i < pathSections.length) {
subPath += '/' + decodeURIComponent(pathSections[i]);
i++;
}
return subPath;
},
/**
* Parse Webdav result
*
* @param {Object} response XML object
*
* @return {Array.<FileInfo>} array of file info
*/
_parseFileInfo: function(response) {
var path = this._extractPath(response.href);
// invalid subpath
if (path === null) {
return null;
}
if (response.propStat.length === 0 || response.propStat[0].status !== 'HTTP/1.1 200 OK') {
return null;
}
var props = response.propStat[0].properties;
var data = {
id: props[Client.PROPERTY_INTERNAL_FILEID],
path: OC.dirname(path) || '/',
name: OC.basename(path),
mtime: (new Date(props[Client.PROPERTY_GETLASTMODIFIED])).getTime()
};
var etagProp = props[Client.PROPERTY_GETETAG];
if (!_.isUndefined(etagProp)) {
data.etag = this._parseEtag(etagProp);
}
var sizeProp = props[Client.PROPERTY_GETCONTENTLENGTH];
if (!_.isUndefined(sizeProp)) {
data.size = parseInt(sizeProp, 10);
}
sizeProp = props[Client.PROPERTY_SIZE];
if (!_.isUndefined(sizeProp)) {
data.size = parseInt(sizeProp, 10);
}
var contentType = props[Client.PROPERTY_GETCONTENTTYPE];
if (!_.isUndefined(contentType)) {
data.mimetype = contentType;
}
var resType = props[Client.PROPERTY_RESOURCETYPE];
var isFile = true;
if (!data.mimetype && resType) {
var xmlvalue = resType[0];
if (xmlvalue.namespaceURI === Client.NS_DAV && xmlvalue.nodeName.split(':')[1] === 'collection') {
data.mimetype = 'httpd/unix-directory';
isFile = false;
}
}
data.permissions = OC.PERMISSION_READ;
var permissionProp = props[Client.PROPERTY_PERMISSIONS];
if (!_.isUndefined(permissionProp)) {
var permString = permissionProp || '';
data.mountType = null;
for (var i = 0; i < permString.length; i++) {
var c = permString.charAt(i);
switch (c) {
// FIXME: twisted permissions
case 'C':
case 'K':
data.permissions |= OC.PERMISSION_CREATE;
if (!isFile) {
data.permissions |= OC.PERMISSION_UPDATE;
}
break;
case 'W':
data.permissions |= OC.PERMISSION_UPDATE;
break;
case 'D':
data.permissions |= OC.PERMISSION_DELETE;
break;
case 'R':
data.permissions |= OC.PERMISSION_SHARE;
break;
case 'M':
if (!data.mountType) {
// TODO: how to identify external-root ?
data.mountType = 'external';
}
break;
case 'S':
// TODO: how to identify shared-root ?
data.mountType = 'shared';
break;
}
}
}
// extend the parsed data using the custom parsers
_.each(this._fileInfoParsers, function(parserFunction) {
_.extend(data, parserFunction(response) || {});
});
return new FileInfo(data);
},
/**
* Parse Webdav multistatus
*
* @param {Array} responses
*/
_parseResult: function(responses) {
var self = this;
var fileInfos = [];
for (var i = 0; i < responses.length; i++) {
var fileInfo = self._parseFileInfo(responses[i]);
if (fileInfo !== null) {
fileInfos.push(fileInfo);
}
}
return fileInfos;
},
/**
* Returns whether the given status code means success
*
* @param {int} status status code
*
* @return true if status code is between 200 and 299 included
*/
_isSuccessStatus: function(status) {
return status >= 200 && status <= 299;
},
/**
* Parse the Sabre exception out of the given response, if any
*
* @param {Object} response object
* @return {Object} array of parsed message and exception (only the first one)
*/
_getSabreException: function(response) {
var result = {};
if (!response.body) {
return result;
}
var xml = response.xhr.responseXML;
var messages = xml.getElementsByTagNameNS('http://sabredav.org/ns', 'message');
var exceptions = xml.getElementsByTagNameNS('http://sabredav.org/ns', 'exception');
if (messages.length) {
result.message = messages[0].textContent;
}
if (exceptions.length) {
result.exception = exceptions[0].textContent;
}
return result;
},
/**
* Returns the default PROPFIND properties to use during a call.
*
* @return {Array.<Object>} array of properties
*/
getPropfindProperties: function() {
if (!this._propfindProperties) {
this._propfindProperties = _.map(Client._PROPFIND_PROPERTIES, function(propDef) {
return '{' + propDef[0] + '}' + propDef[1];
});
}
return this._propfindProperties;
},
/**
* Lists the contents of a directory
*
* @param {String} path path to retrieve
* @param {Object} [options] options
* @param {boolean} [options.includeParent=false] set to true to keep
* the parent folder in the result list
* @param {Array} [options.properties] list of Webdav properties to retrieve
*
* @return {Promise} promise
*/
getFolderContents: function(path, options) {
if (!path) {
path = '';
}
options = options || {};
var self = this;
var deferred = $.Deferred();
var promise = deferred.promise();
var properties;
if (_.isUndefined(options.properties)) {
properties = this.getPropfindProperties();
} else {
properties = options.properties;
}
this._client.propFind(
this._buildUrl(path),
properties,
1
).then(function(result) {
if (self._isSuccessStatus(result.status)) {
var results = self._parseResult(result.body);
if (!options || !options.includeParent) {
// remove root dir, the first entry
results.shift();
}
deferred.resolve(result.status, results);
} else {
result = _.extend(result, self._getSabreException(result));
deferred.reject(result.status, result);
}
});
return promise;
},
/**
* Fetches a flat list of files filtered by a given filter criteria.
* (currently only system tags is supported)
*
* @param {Object} filter filter criteria
* @param {Object} [filter.systemTagIds] list of system tag ids to filter by
* @param {bool} [filter.favorite] set it to filter by favorites
* @param {Object} [options] options
* @param {Array} [options.properties] list of Webdav properties to retrieve
*
* @return {Promise} promise
*/
getFilteredFiles: function(filter, options) {
options = options || {};
var self = this;
var deferred = $.Deferred();
var promise = deferred.promise();
var properties;
if (_.isUndefined(options.properties)) {
properties = this.getPropfindProperties();
} else {
properties = options.properties;
}
if (!filter || (!filter.systemTagIds && _.isUndefined(filter.favorite))) {
throw 'Missing filter argument';
}
// root element with namespaces
var body = '<oc:filter-files ';
var namespace;
for (namespace in this._client.xmlNamespaces) {
body += ' xmlns:' + this._client.xmlNamespaces[namespace] + '="' + namespace + '"';
}
body += '>\n';
// properties query
body += ' <' + this._client.xmlNamespaces['DAV:'] + ':prop>\n';
_.each(properties, function(prop) {
var property = self._client.parseClarkNotation(prop);
body += ' <' + self._client.xmlNamespaces[property.namespace] + ':' + property.name + ' />\n';
});
body += ' </' + this._client.xmlNamespaces['DAV:'] + ':prop>\n';
// rules block
body += ' <oc:filter-rules>\n';
_.each(filter.systemTagIds, function(systemTagIds) {
body += ' <oc:systemtag>' + escapeHTML(systemTagIds) + '</oc:systemtag>\n';
});
if (filter.favorite) {
body += ' <oc:favorite>' + (filter.favorite ? '1': '0') + '</oc:favorite>\n';
}
body += ' </oc:filter-rules>\n';
// end of root
body += '</oc:filter-files>\n';
this._client.request(
'REPORT',
this._buildUrl(),
{},
body
).then(function(result) {
if (self._isSuccessStatus(result.status)) {
var results = self._parseResult(result.body);
deferred.resolve(result.status, results);
} else {
result = _.extend(result, self._getSabreException(result));
deferred.reject(result.status, result);
}
});
return promise;
},
/**
* Returns the file info of a given path.
*
* @param {String} path path
* @param {Array} [options.properties] list of Webdav properties to retrieve
*
* @return {Promise} promise
*/
getFileInfo: function(path, options) {
if (!path) {
path = '';
}
options = options || {};
var self = this;
var deferred = $.Deferred();
var promise = deferred.promise();
var properties;
if (_.isUndefined(options.properties)) {
properties = this.getPropfindProperties();
} else {
properties = options.properties;
}
// TODO: headers
this._client.propFind(
this._buildUrl(path),
properties,
0
).then(
function(result) {
if (self._isSuccessStatus(result.status)) {
deferred.resolve(result.status, self._parseResult([result.body])[0]);
} else {
result = _.extend(result, self._getSabreException(result));
deferred.reject(result.status, result);
}
}
);
return promise;
},
/**
* Returns the contents of the given file.
*
* @param {String} path path to file
*
* @return {Promise}
*/
getFileContents: function(path) {
if (!path) {
throw 'Missing argument "path"';
}
var self = this;
var deferred = $.Deferred();
var promise = deferred.promise();
this._client.request(
'GET',
this._buildUrl(path)
).then(
function(result) {
if (self._isSuccessStatus(result.status)) {
deferred.resolve(result.status, result.body);
} else {
result = _.extend(result, self._getSabreException(result));
deferred.reject(result.status, result);
}
}
);
return promise;
},
/**
* Puts the given data into the given file.
*
* @param {String} path path to file
* @param {String} body file body
* @param {Object} [options]
* @param {String} [options.contentType='text/plain'] content type
* @param {bool} [options.overwrite=true] whether to overwrite an existing file
*
* @return {Promise}
*/
putFileContents: function(path, body, options) {
if (!path) {
throw 'Missing argument "path"';
}
var self = this;
var deferred = $.Deferred();
var promise = deferred.promise();
options = options || {};
var headers = {};
var contentType = 'text/plain;charset=utf-8';
if (options.contentType) {
contentType = options.contentType;
}
headers['Content-Type'] = contentType;
if (_.isUndefined(options.overwrite) || options.overwrite) {
// will trigger 412 precondition failed if a file already exists
headers['If-None-Match'] = '*';
}
this._client.request(
'PUT',
this._buildUrl(path),
headers,
body || ''
).then(
function(result) {
if (self._isSuccessStatus(result.status)) {
deferred.resolve(result.status, result);
} else {
result = _.extend(result, self._getSabreException(result));
deferred.reject(result.status, result);
}
}
);
return promise;
},
_simpleCall: function(method, path) {
if (!path) {
throw 'Missing argument "path"';
}
var self = this;
var deferred = $.Deferred();
var promise = deferred.promise();
this._client.request(
method,
this._buildUrl(path)
).then(
function(result) {
if (self._isSuccessStatus(result.status)) {
deferred.resolve(result.status, result);
} else {
result = _.extend(result, self._getSabreException(result));
deferred.reject(result.status, result);
}
}
);
return promise;
},
_moveOrCopy: function(operation, path, destinationPath, allowOverwrite, headers, options) {
if (!path) {
throw 'Missing argument "path"';
}
if (!destinationPath) {
throw 'Missing argument "destinationPath"';
}
if (operation !== 'MOVE' && operation !== 'COPY') {
throw 'Invalid operation';
}
var self = this;
var deferred = $.Deferred();
var promise = deferred.promise();
options = _.extend({
'pathIsUrl' : false,
'destinationPathIsUrl' : false
}, options);
headers = _.extend({}, headers, {
'Destination' : options.destinationPathIsUrl ? destinationPath : this._buildUrl(destinationPath)
});
if (!allowOverwrite) {
headers['Overwrite'] = 'F';
}
this._client.request(
operation,
options.pathIsUrl ? path : this._buildUrl(path),
headers
).then(
function(result) {
if (self._isSuccessStatus(result.status)) {
deferred.resolve(result.status, result);
} else {
result = _.extend(result, self._getSabreException(result));
deferred.reject(result.status, result);
}
}
);
return promise;
},
lock: function(path, options) {
if (!path) {
throw 'Missing argument "path"';
}
var self = this;
var deferred = $.Deferred();
var promise = deferred.promise();
options = _.extend({
'pathIsUrl' : false
}, options);
const lockBody = "<?xml version='1.0' encoding='UTF-8'?>\n" +
"<d:lockinfo xmlns:d='DAV:'>\n" +
" <d:lockscope>\n" +
" <d:exclusive/>\n" +
" </d:lockscope>\n" +
"</d:lockinfo>\n";
this._client.request(
'LOCK',
options.pathIsUrl ? path : this._buildUrl(path),
{},
lockBody
).then(
function(result) {
if (self._isSuccessStatus(result.status)) {
deferred.resolve(result.status, result);
} else {
result = _.extend(result, self._getSabreException(result));
deferred.reject(result.status, result);
}
}
);
return promise;
},
/**
* Creates a directory
*
* @param {String} path path to create
*
* @return {Promise}
*/
createDirectory: function(path) {
return this._simpleCall('MKCOL', path);
},
/**
* Deletes a file or directory
*
* @param {String} path path to delete
*
* @return {Promise}
*/
remove: function(path) {
return this._simpleCall('DELETE', path);
},
/**
* Moves path to another path
*
* @param {String} path path to move
* @param {String} destinationPath destination path
* @param {boolean} [allowOverwrite=false] true to allow overwriting,
* false otherwise
* @param {Object} [headers=null] additional headers
*
* @return {Promise} promise
*/
move: function(path, destinationPath, allowOverwrite, headers, options) {
return this._moveOrCopy('MOVE', path, destinationPath, allowOverwrite, headers, options);
},
/**
* Copies path to another path
*
* @param {String} path path to copy
* @param {String} destinationPath destination path
* @param {boolean} [allowOverwrite=false] true to allow overwriting,
* false otherwise
* @param {Object} [headers=null] additional headers
*
* @return {Promise} promise
* @since 10.0.5
*/
copy: function(path, destinationPath, allowOverwrite, headers, options) {
return this._moveOrCopy('COPY', path, destinationPath, allowOverwrite, headers, options);
},
/**
* Add a file info parser function
*
* @param {OC.Files.Client~parseFileInfo>}
*/
addFileInfoParser: function(parserFunction) {
this._fileInfoParsers.push(parserFunction);
},
/**
* Returns the dav.Client instance used internally
*
* @since 10.0
* @return {dav.Client}
*/
getClient: function() {
return this._client;
},
/**
* Returns the user name
*
* @since 10.0
* @return {String} userName
*/
getUserName: function() {
return this._client.userName;
},
/**
* Returns the password
*
* @since 10.0
* @return {String} password
*/
getPassword: function() {
return this._client.password;
},
/**
* Returns the base URL
*
* @since 10.0
* @return {String} base URL
*/
getBaseUrl: function() {
return this._client.baseUrl;
},
/**
* Returns the host
*
* @since 10.0.3
* @return {String} base URL
*/
getHost: function() {
return this._host;
}
};
/**
* File info parser function
*
* This function receives a list of Webdav properties as input and
* should return a hash array of parsed properties, if applicable.
*
* @callback OC.Files.Client~parseFileInfo
* @param {Object} XML Webdav properties
* @return {Array} array of parsed property values
*/
if (!OC.Files) {
/**
* @namespace OC.Files
*
* @since 8.2
*/
OC.Files = {};
}
/**
* Returns the default instance of the files client
*
* @return {OC.Files.Client} default client
*
* @since 8.2
*/
OC.Files.getClient = function() {
if (OC.Files._defaultClient) {
return OC.Files._defaultClient;
}
var client = new OC.Files.Client({
host: OC.getHost(),
root: OC.linkToRemoteBase('dav') + '/files/' + encodeURIComponent(OC.getCurrentUser().uid) + '/',
useHTTPS: OC.getProtocol() === 'https'
});
OC.Files._defaultClient = client;
return client;
};
OC.Files.Client = Client;
})(OC, OC.Files.FileInfo);
|
var searchData=
[
['fileopenexception',['FileOpenException',['../class_script.html#a1be7d65c8f9b0db216570980815aacb6',1,'Script']]],
['friday',['FRIDAY',['../class_action_settings.html#aa70504579778b73eb6627609d2360bf5',1,'ActionSettings']]]
];
|
export default {
get(id) {
return axios.get(`/api/sample/${id}`);
},
save(id, data) {
return axios.patch(`/api/sample/${id}`, data);
}
};
|
var CertificationController = {
init:function(){
$("#refuse_opt").find("input[type=radio]").change(function(){
if($(this).val() == 3){
$("#reason").val("");
}else{
$("#reason").val($(this).parent().text());
}
});
$("#search").click(function(){
CardReviewListServerRequest();
});
//成功提交
$("#reject_submit").click(function(){
var data = {
real_name:$("#real_name").text(),
store_id:$("#shop_id").val(),
start_time:$("#check_start_date").val(),
end_time:$("#check_end_date").val(),
type:true
};
var start_date =$("#check_start_date").val();
var end_date =$("#check_end_date").val();
if(!start_date){
ShowMsgTip($("#check_start_date"),"日期不能为空!");
return false;
}
if(!end_date){
ShowMsgTip($("#check_end_date"),"日期不能为空!");
return false;
}
var today = GetNowTime.GetToday();
var d1=today.replace(/[&\|\\\*^%$#@\-]/g,"");
var d2=end_date.replace(/[&\|\\\*^%$#@\-]/g,"");
d1=d1.substring(0,4)+"/"+d1.substring(4,6)+"/"+d1.substring(6);
d2=d2.substring(0,4)+"/"+d2.substring(4,6)+"/"+d2.substring(6);
var date1=Date.parse(d1);
var date2=Date.parse(d2);
var daylength=(date2-date1)/(1000 * 60 * 60 * 24);
//alert(daylength+"天");
if(daylength<31){
ShowMsgTip($("#check_end_date"),"有效期必须超过1个月");
return false;
}
CertificationController.submit(data);
});
//失败提交
$("#submit_refuse").click(function(){
var check_opt = $("#refuse_opt").find("input[type=radio]:checked");
var failure_desc = $("#reason").val();
if(!check_opt || check_opt.length == 0){
layer.alert("请先选择一个失败原因!");
return;
}
if(!failure_desc){
layer.alert("请输入审核不通过原因!");
return;
}
var data = {
real_name:$("#real_name_refuse").text(),
store_id:$("#shop_id_refuse").val(),
type:false,
failure_type:$("#refuse_opt").find("input[type=radio]:checked").val(),
failure_desc:$("#reason").val()
};
CertificationController.submit(data);
});
},
submit:function(data){
$.ajax({
type:"POST",
url:"../Home/Certification/AuthenticateCertification",
data:JSON.stringify(data),
async:false,
success:function(result){
var json_result = JSON.parse(result);
if(json_result["status"] == 1){
layer.alert("操作成功");
$("#reject_dialog_refuse").hide();
$("#reject_dialog").hide();
CardReviewListServerRequest();
}else{
layer.alert(json_result["msg"]);
}
}
});
},
//清空审核通过的输入框
clearDialog:function(){
$("#shop_id").val("");
$("#shop_name").text("");
$("#real_name").text("");
$("#id_card").text("");
$("#check_start_date").val("");
$("#check_end_date").val("");
$("#image_right img:first").attr("src","http://bwc.git.edu.cn/_mediafile/bwc/2013/08/03/1r7i93z6ec.jpg");
$("#image_right img:last").attr("src","http://bwc.git.edu.cn/_mediafile/bwc/2013/08/03/1r7i93z6ec.jpg")
},
//清空审核不通过的输入框
clearRefuseDialog:function(){
$("#shop_id_refuse").val("");
$("#shop_name_refuse").text("");
$("#real_name_refuse").text("");
$("#id_card_refuse").text("");
$("#refuse_opt").find("input[type='radio']").prop("checked",false);
$("#image_refuse img:first").attr("src","http://bwc.git.edu.cn/_mediafile/bwc/2013/08/03/1r7i93z6ec.jpg");
$("#image_refuse img:last").attr("src","http://bwc.git.edu.cn/_mediafile/bwc/2013/08/03/1r7i93z6ec.jpg")
$("#reason").val("");
}
}
var CardReviewTemplate={
CardReviewDetailTemp:function(result,flag) {
var dom='<div class="cus_info_div interval_shadow" data-id="'+result.store_id+'" data-store_name="'+result.store_name+'" data-real_name="'+result.real_name+'" data-id_number="'+result.id_number+'">'+
'<div class="wid15 fl tc pad_t45 min_hei">'+result.created_man+'</br>'+result.created_time+'</div>'+
'<div class="wid15 fl tc pad_t45 min_hei">'+result.store_name+'</br>'+result.created_man+'</div>'+
'<div class="wid15 fl tc pad_t45 min_hei">'+result.real_name+'</br>'+result.id_number+'</div>'+
'<div class="wid45 fl tc min_hei">'+'<img src="'+result.front_image+'" class="sf_img fl">'+'<img src="'+result.back_image+'" class="sf_img fl">'+'</div>'+
'<div class="wid10 fl tc pad_t45 min_hei">'+
'<span class="tongguo">通过</span>'+
'<span class="fenge">|</span>'+
'<span class="jujue">拒绝</span>'+
'</div>'+
'<div class="cle"></div>'+
'</div>';
$("#Certification_container").append(dom);
}
};
//渲染列表和页面
function CardReviewList(result){
if(result.data.data.length===0){
$("#cardReview_none").show()
}
for(var i=0;i<result.data.data.length;i++){
CardReviewTemplate.CardReviewDetailTemp(result.data.data[i]);
$("#cardReview_none").hide()
}
$("#cardReview_num").text(result.data.total);
var cardReview_tot_page=Math.ceil(result.data.total/$("#cardReview_pagenum").text());
if(cardReview_tot_page===0){
cardReview_tot_page=1;
}
$("#cardReview_tot_page").text(cardReview_tot_page);
}
function GetQueryPostData(){
var limit = $("#withdraw_pagenum").text();
var offset = ($("#withdraw_now_page").text()-1)*limit;
var post_data = {
"start_time":$("#pagetj_start_date").val(),
"end_time":$("#pagetj_end_date").val(),
"apply_account":$("#applicant_id").val(),
"store_name":$("#store_name").val(),
"offset":offset,
"limit":limit
};
return JSON.stringify(post_data);
}
function CheckExport(){
var start_time = $("#pagetj_start_date").val();
var end_time = $("#pagetj_end_date").val();
var store_name = $("#store_name").val();
var apply_man = $("#applicant_id").val();
$("input[name='start_time']").val(start_time);
$("input[name='end_time']").val(end_time);
$("input[name='store_name']").val(store_name);
$("input[name='apply_account']").val(apply_man);
return true;
}
//请求列表
function CardReviewListServerRequest(flag){
if(!flag){
$("#cardReview_now_page").text("1");
}
AjaxPostData("../Home/Certification/QueryAllUnCheckedRecords",GetQueryPostData(),function(result){
CardReviewList(result);
});
RemoveBalanceInfo();
}
//清空信息
function RemoveBalanceInfo(){
$("#Certification_container").children(".cus_info_div").remove();
}
//清空列表
function RemoveCardReviewInfo(){
$("#Certification_container").children(".cus_info_div").remove();
}
//清空拒绝原因
function ClearRejectReason(){
$("#reject_content").val('');
}
function CheckExport(){
var start_time = $("#pagetj_start_date").val();
var end_time = $("#pagetj_end_date").val();
var store_name = $("#store_name").val();
var apply_man = $("#applicant_id").val();
$("input[name='start_time']").val(start_time);
$("input[name='end_time']").val(end_time);
$("input[name='store_name']").val(store_name);
$("input[name='apply_man']").val(apply_man);
return true;
}
$(function($){
AddNaviListClass("dprzsh");
RemoveCardReviewInfo();
CardReviewListServerRequest();
CertificationController.init();
//日期选择
$("#pagetj_start_date").datepicker({
maxDate: "+0d",
onClose: function( selectedDate ) {
$( "#pagetj_end_date" ).datepicker( "option", "minDate", selectedDate );
}
});
$("#pagetj_end_date").datepicker({
maxDate: "+0d",
onClose: function( selectedDate ) {
$( "#pagetj_start_date" ).datepicker( "option", "maxDate", selectedDate );
}
});
$("#check_start_date").datepicker({
//minDate: "+0d",
changeMonth:"true",
changeYear:"true",
onClose: function( selectedDate ) {
$( "#check_end_date" ).datepicker( "option", "minDate", selectedDate );
}
});
$("#check_end_date").datepicker({
minDate: "+0d",
changeMonth:"true",
changeYear:"true",
onClose: function( selectedDate ) {
$( "#check_start_date" ).datepicker( "option", "maxDate", selectedDate );
}
});
$(".filter_days").click(function()
{
$(".filter_days").removeClass("on_chose");
$(this).addClass("on_chose");
var dataValue = $(".filter_days.on_chose").attr("data-value");
var start_date = "";
var end_date = "";
if(dataValue == "today"){
start_date = GetNowTime.GetToday();
end_date = GetNowTime.GetToday();
$("#pagetj_start_date").val(start_date);
$("#pagetj_end_date").val(end_date);
}else if(dataValue == "yesterday"){
start_date = GetNowTime.GetYesterday();
end_date = GetNowTime.GetYesterday();
$("#pagetj_start_date").val(start_date);
$("#pagetj_end_date").val(end_date);
}else if(dataValue == "7day"){
start_date = GetNowTime.GetOneweekAgoDay();
end_date = GetNowTime.GetYesterday();
$("#pagetj_start_date").val(start_date);
$("#pagetj_end_date").val(end_date);
}else if(dataValue == "30day"){
start_date = GetNowTime.Get30DaysAgoDay();
end_date = GetNowTime.GetYesterday();
$("#pagetj_start_date").val(start_date);
$("#pagetj_end_date").val(end_date);
}else{
$("#pagetj_start_date").val("");
$("#pagetj_end_date").val("");
}
CardReviewListServerRequest();
});
//设置每页行数
$("#cardReview_pagenum li").bind("click",function(){
var nlimit=$(this).text();
$("#cardReview_pagenum").text(nlimit);
$("#cardReview_limit").hide();
CardReviewListServerRequest();
});
//通过的取消、关闭拒绝提现窗口
$("#serv_dialog_close,#evaluate_cancle").click(function(){
$("#reject_dialog").hide();
});
//通过按钮
$("#Certification_container").delegate(".tongguo","click",function() {
$("#reject_dialog").show();
CertificationController.clearDialog();
//fill data
var temp = $(this).parents(".cus_info_div");
$("#shop_id").val(temp.attr("data-id"));
$("#shop_name").text(temp.attr("data-store_name"));
$("#real_name").text(temp.attr("data-real_name"));
$("#id_card").text(temp.attr("data-id_number"));
$("#image_right img:first").attr("src",temp.find("img:first").attr("src"));
$("#image_right img:last").attr("src",temp.find("img:last").attr("src"));
});
//拒绝按钮
$("#Certification_container").delegate(".jujue","click",function() {
$("#reject_dialog_refuse").show();
CertificationController.clearRefuseDialog();
//fill data
var temp = $(this).parents(".cus_info_div");
$("#shop_id_refuse").val(temp.attr("data-id"));
$("#shop_name_refuse").text(temp.attr("data-store_name"));
$("#real_name_refuse").text(temp.attr("data-real_name"));
$("#id_card_refuse").text(temp.attr("data-id_number"));
$("#image_refuse img:first").attr("src",temp.find("img:first").attr("src"));
$("#image_refuse img:last").attr("src",temp.find("img:last").attr("src"));
});
//拒绝的取消、关闭拒绝提现窗口
$("#close_refuse,#cancle_refuse").click(function(){
$("#reject_dialog_refuse").hide();
});
//上一页、下一页按钮
$("#cardReview_pre").bind("click",function(){
var nowpage=parseInt($("#cardReview_now_page").text());
nowpage-=1;
if(nowpage<=0){return;}
else{
$("#cardReview_now_page").text(nowpage);
CardReviewListServerRequest(1);
}
});
$("#cardReview_next").bind("click",function(){
var nowpage=parseInt($("#cardReview_now_page").text());
var totalpage=parseInt($("#cardReview_tot_page").text());
nowpage+=1;
if(nowpage>totalpage){
return;
}
else{
$("#cardReview_now_page").text(nowpage);
CardReviewListServerRequest(1);
}
});
$("#Certification_container").delegate("img","click",function(){
$("#big_pic img").attr("src",$(this).attr("src"));
$("#big_pic").show();
});
$(".close_circle").click(function(){
$("#big_pic").hide();
});
}); |
/*global Connection, authentication */
var Util = Phoenix.Util = {
latLng: function(value) {
// Reduce precision to 3 places, approximately 111m resolution at the equator.
// This produces cleaner urls and improves the odds of a warm cache hit for requests
return Math.floor(parseFloat(value) * 1000) / 1000;
},
ensureArray: function(item) {
if (!item) {
return item;
}
if (_.isArray(item)) {
return item;
} else {
return [item];
}
},
valueOf: function(obj, _this) {
_this = _this || window;
return _.isFunction(obj) ? obj.call(_this) : obj;
},
// Unlike $.param, this function doesn't replace spaces with pluses
serializeParams: function(params) {
return _.map(params, function(value, key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(value);
}).join('&');
},
appendParams: function(url, params) {
url = url || '';
params = _.isString(params) ? params : this.serializeParams(Util.removeUndefined(params));
if (!params) {
return url;
}
var base = url + (url.indexOf('?') === -1 ? '?' : '&');
return base + params;
},
stripParams: function(url) {
var index = url.indexOf('?');
return url.slice(0, index === -1 ? undefined : index);
},
// Returns a copy of the object containing only keys/values that passed truth test (iterator)
// TODO : Consider extending underscore with this method
pickBy: function(obj, iterator) {
var res = {};
_.each(obj, function(value, key) {
if (iterator(value, key)) {
res[key] = value;
}
});
return res;
},
removeUndefined: function(obj) {
return this.pickBy(obj, function(v) {
return v !== undefined;
});
},
cachedSingletonMixin: function(DataClass, type, expires) {
var instance;
var lastAccessTime = new Date().getTime();
DataClass.get = function(noCreate) {
if (noCreate) {
return instance;
}
var curTime = new Date().getTime();
if ((curTime - lastAccessTime) > (expires || authentication.SESSION_DURATION)) {
DataClass.release();
}
if (!instance) {
instance = new DataClass();
}
lastAccessTime = curTime;
return instance;
};
DataClass.release = function() {
lastAccessTime = 0;
// Clearing here rather than clearing the instance object so any long lived
// binds will survive and not leak.
if (instance) {
instance.reset && instance.reset();
instance.clear && instance.clear();
}
};
// Clear all data if any fatal error occurs, `resetData` event triggered
exports.on('fatal-error', DataClass.release);
exports.on('order:complete', DataClass.release);
exports.on('resetData', function(options) {
if (!options.type || options.type === 'all' || options.type === type) {
DataClass.release();
}
});
authentication.on('loggedout', DataClass.release);
authentication.on(Connection.SESSION_EXPIRED, DataClass.release);
authentication.on('session-activity', function() {
if (authentication.isAuthed() === false) {
DataClass.release();
}
});
}
};
|
var roleUpgrader = {
/** @param {Creep} creep **/
run: function(creep, village) {
if (BASE_CREEP.run(creep, village) == -1){
return;
}
//console.log(`${creep.name} -- Upgrading: ${creep.memory.upgrading}`);
if (creep.memory.getBoosted && creep.memory.getBoosted.length > 0) {
if (creep.memory.lab) {
let myLab = Game.getObjectById(creep.memory.lab);
let status = myLab.boostCreep(creep);
switch (status) {
case ERR_NOT_IN_RANGE:
creep.moveTo(myLab);
return;
case OK:
creep.memory.getBoosted.shift();
delete creep.memory.lab
return;
case ERR_NOT_ENOUGH_RESOURCES:
// Failed cause not enough minerals or energy
// TODO: create request to fill it up
//delete creep.memory.getBoosted;
creep.memory.getBoosted.shift();
delete creep.memory.lab
return;
}
} else {
if (village.labs && village.labs.reagentLabs) {
let labs = village.labs.reagentLabs;
for (l in labs) {
if (labs[l] == creep.memory.getBoosted[0]) {
creep.memory.lab = l;
creep.moveTo(Game.getObjectById(l));
return;
}
}
}
// no lab found
delete creep.memory.getBoosted;
}
}
if(creep.carry.energy == 0) {
creep.memory.upgrading = false;
}
if(creep.carry.energy >= creep.carryCapacity*.95) {
creep.memory.upgrading = true;
}
if(creep.memory.upgrading) {
creep.emote('upgrader', CREEP_SPEECH.UPGRADE)
const upgradeSpot = village.memoryAddr.flags['upgradeSpot'];
creep.upgradeController(village.controller);
if (upgradeSpot) {
const upgradeSpotFlag = Game.flags[upgradeSpot];
if (upgradeSpotFlag && !creep.pos.inRangeTo(Game.flags[upgradeSpot].pos,1)) {
creep.moveTo(upgradeSpotFlag, {visualizePathStyle: {stroke: '#ffffff'}});
return;
}
}
if (village.upgradeLinkObj && creep.pos.inRangeTo(village.controller,3) && creep.pos.inRangeTo(village.upgradeLinkObj,1)) {
return;
}
if (!creep.pos.inRangeTo(village.controller,1)) {
creep.moveTo(village.controller, {visualizePathStyle: {stroke: '#ffffff'}});
}
} else {
creep.emote('upgrader', CREEP_SPEECH.REFILL)
if (village.upgradeLinkHasEnergy(creep.carryCapacity)) {
creep.withdrawMove(village.upgradeLinkObj);
return;
}
// TODO: create a generic find target method that finds structures by type
if (village.storage && village.storage.store[RESOURCE_ENERGY] >= creep.carryCapacity) {
creep.withdrawMove(village.storage, RESOURCE_ENERGY);
} else {
let target = creep.pos.findClosestByRange(FIND_STRUCTURES, {
filter: (structure) => {
return ((structure.structureType == STRUCTURE_CONTAINER) && structure.store[RESOURCE_ENERGY] >= creep.carryCapacity);
}
});
if(target) {
creep.withdrawMove(target);
} else {
target = village.spawns.find(x=>x.energy > 0);
if (target) {
creep.withdrawMove(target);
}
}
}
}
}
};
module.exports = roleUpgrader; |
const readline = require('readline-sync');
const WINNING_CHOICES = {
rock: ['scissors'],
paper: ['rock'],
scissors: ['paper'],
// rock: ['scissors', 'lizard'],
// paper: ['rock', 'spock'],
// scissors: ['paper', 'lizard'],
// lizard: ['paper', 'spock'],
// spock: ['rock', 'scissors'],
};
function createPlayer() {
return {
move: null,
};
}
function createComputer() {
let playerObject = createPlayer();
let computerObject = {
choose() {
const choices = ['rock', 'paper', 'scissors'];
let randomIndex = Math.floor(Math.random() * choices.length);
this.move = choices[randomIndex];
},
};
return Object.assign(playerObject, computerObject);
}
function createHuman() {
let playerObject = createPlayer();
let humanObject = {
choose() {
let choice;
while (true) {
console.log('Choose a move, Rock, Paper or Scissors');
choice = readline.question();
if (['rock', 'paper', 'scissors'].includes(choice)) break;
console.log('Invalid Input');
}
this.move = choice;
}
};
return Object.assign(playerObject, humanObject);
}
function createScoreboard() {
return {
computerScore: 0,
humanScore: 0,
maxScore: 0,
roundWinner: null,
determineRoundWinner(humanMove, computerMove) {
if (humanMove === computerMove) {
this.roundWinner = 'tie';
} else if (WINNING_CHOICES[humanMove].includes(computerMove)) {
this.roundWinner = 'human';
} else {
this.roundWinner = 'computer';
}
},
updateScores(player) {
if (this.roundWinner === 'human') {
this.humanScore += 1;
} else if (this.roundWinner === 'computer') {
this.computerScore += 1;
}
},
resetScore() {
this.humanScore = 0;
this.computerScore = 0;
},
resetRoundWinner() {
this.roundWinner = null;
},
determineGameWinner() {
return this.humanScore > this.computerScore ? 'you' : 'Computer';
},
isGameOver() {
return (this.humanScore === this.maxScore ||
this.computerScore === this.maxScore);
},
setMaxScore() {
while (true) {
this.maxScore = parseInt(readline.question('=> Enter the max score for the game: '), 10);
if (Number.isInteger(this.maxScore) && this.maxScore > 0) {
console.clear();
break;
}
console.log('=> Sorry, invalid choice.');
}
},
};
return scoreboard;
}
const RPSGame = {
human: createHuman(),
computer: createComputer(),
message(text) {
console.log(`=> ${text}`);
},
displayWelcomeMessage() {
console.log('Welcome to Rock Papaer Scissiors');
},
displayGoodbyeMessage() {
console.log('Thank you for playing Rock, Paper, Scissors, Goodbye');
},
displayRules() {
console.log();
this.message('Here are the rules!');
this.message('Rock beats scissors and lizard.');
this.message('Paper beats rock and spock.');
this.message('Scissors beats paper and lizard.');
this.message('Lizard beats paper and spock.');
this.message('Spock beats rock and paper.');
console.log();
},
displayRoundWinner() {
let humanMove = this.human.move;
let computerMove = this.computer.move;
let winner = this.gameScore.roundWinner;
console.clear();
this.message(`You chose: ${humanMove}`);
this.message(`The computer chose: ${computerMove}`);
if (winner === 'human') {
this.message('You won the round!');
} else if (winner === 'computer') {
this.message('Computer won the round!');
} else {
this.message("It's a tie!");
}
console.log();
},
// displayWinner() {
// let humanMove = this.human.move;
// let computerMove = this.computer.move;
// console.log(`You choose ${this.human.move}.`);
// console.log(`The Computer choose ${this.computer.move}.`);
// if ((humanMove === 'rock' && computerMove === 'scissors') ||
// (humanMove === 'paper' && computerMove === 'rock') ||
// (humanMove === 'scissors' && computerMove === 'paper')) {
// console.log('You are the winner!');
// this.scoreboard.updateScore('human');
// } else if ((computerMove === 'rock' && humanMove === 'scissors') ||
// (computerMove === 'paper' && humanMove === 'rock') ||
// (computerMove === 'scissors' && humanMove === 'paper')) {
// console.log('Computer is the winner!');
// this.scoreboard.updateScore('computer');
// } else {
// console.log('It\'s a tie!');
// }
// },
playAgain() {
console.log('Would you like to play again (y or n)?');
let answer = readline.question();
return answer.toLowerCase()[0] === 'y';
},
matchWinner(scoreboard) {
if (scoreboard.computerScore === 5) {
console.log('The Computer is the champion!');
scoreboard.resetScore();
return true;
} else if (scoreboard.humanScore === 5) {
console.log('You are the champion!');
scoreboard.resetScore();
return true;
}
return false;
},
displayScore() {
console.log('\n');
console.log(`Computer score is ${this.gameScore.computerScore}.`);
console.log(`Human score is ${this.gameScore.humanScore}.`);
console.log('\n');
},
displayGameOver() {
console.log('*'.repeat(40));
this.message(`${this.gameScore.determineGameWinner()} won the game!`);
this.message('The final scores are:');
this.message(`Human Player: ${this.gameScore.humanScore} out of ${this.gameScore.maxScore}`);
this.message(`Computer Score: ${this.gameScore.computerScore} out of ${this.gameScore.maxScore}`);
},
playRound() {
this.human.choose();
this.computer.choose();
this.gameScore.determineRoundWinner(this.human.move, this.computer.move);
this.displayRoundWinner();
this.gameScore.updateScores();
this.gameScore.resetRoundWinner();
this.displayScore();
},
play() {
this.displayWelcomeMessage();
this.displayRules();
while (true) {
this.gameScore = createScoreboard();
this.gameScore.setMaxScore();
while (!this.gameScore.isGameOver()) {
this.playRound();
}
this.displayGameOver();
if (!this.playAgain()) {
break;
} else {
console.clear();
}
}
this.displayGoodbyeMessage();
},
};
RPSGame.play(); |
num_1 = 1;
let num_str;
{ // str_1 += "1";
num_1
};
actual = 1;
actual += "1;"
console.assert(num_str === actual, "fail: num_str");
|
function addInput(divName){
var counter = 1;
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div class='mdl-textfield mdl-js-textfield mdl-cell mdl-cell--12-col'><input class='mdl-textfield__input' type='text' id='"+(divName)+(counter)+"' name='"+(divName)+"[]'><label class='mdl-textfield__label' for='"+(divName)+(counter)+"'>"+(divName)+"</label></div>";
document.getElementById(divName).appendChild(newdiv);
counter++;
} |
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue';
import App from './App';
import router from './router';
import iView from 'iview';
import moment from 'moment';
import 'iview/dist/styles/iview.css';
import web3ContractUtil from '@/common/vue-util/web3-contract';
import TopMenu from '@components/top-menu/';
import XCFooter from '@components/footer/';
Vue.use(web3ContractUtil);
moment.locale('zh-cn');
Vue.config.productionTip = false;
Vue.use(iView);
Vue.component('xc-footer', XCFooter);
Vue.component('xc-menu', TopMenu);
Vue.config.productionTip = false;
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
components: {
App
}
});
|
import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router';
import axios from 'axios';
export default function MovieDetail() {
const [data, setData] = useState(0);
const { id } = useParams();
useEffect(() => {
axios.get(`https://api.tvmaze.com/shows/${id}`).then((res) => {
setData(res.data);
console.log(res.data);
});
}, [id]);
return data ? (
<div className="movieDetailPage">
<div className="title">{data.name}</div>
<div className="MovieDetail">
<div className="showImage">
<img alt="movie poster" src={data.image.medium} />
</div>
<div className="smallDetail">
<div className="ratings">
<span className="Average Rating">
Average Rating: {data.rating.average}
</span>
</div>
<div className="genre">
{data.genres.map((item, i) => {
return (
<div key={i} className="genreItem">
{item}
</div>
);
})}
</div>
<div className="language">{data.language}</div>
<div className="type">{data.type}</div>
<div className="premiered">{data.premiered}</div>
<div className="runtime">Runtime: {data.runtime}</div>
<div className="watchLink">
<a href={data.url} className="watchNow">
<button>Watch Now</button>
</a>
</div>
</div>
</div>
</div>
) : (
<div className="Error">Cannot Find</div>
);
}
|
var Qapp = Qapp || { Models: {}, Collections: {}, Views: {} };
Qapp.Views.AnswerView = Backbone.View.extend({
initialize: function(){
currentRecord = 0;
},
tagName: 'div',
// template: _.template($('answerGraphTemplate').html()),
renderResults: function(){
console.log("AnswerView being hit");
console.log("answerView model", this.model);
// this.$el.empty();
// this.$el.html(this.template(this.model.attributes));
var self = this;
// this.$el.html( this.template(this.model.attributes) );
console.log("renderGraph self", self);
$.ajax({
url: '/questions/' + this.model.attributes.id,
dataType: 'json',
method: 'GET',
async: false
}).done(function(data){
self.model.attributes.results = data;
console.log("rendergraph data success", data);
console.log("question self in answer renderGraph", self);
// self.addResults(data)
});
// $('#container').html(self.model.attributes.results);
function addGraphOptions() {
// * Grid-light theme for Highcharts JS
// * @author Torstein Honsi
// */
// Load the fonts
Highcharts.createElement('link', {
href: 'http://fonts.googleapis.com/css?family=Dosis:400,600',
rel: 'stylesheet',
type: 'text/css'
}, null, document.getElementsByTagName('head')[0]);
Highcharts.theme = {
colors: ["#7cb5ec", "#f7a35c", "#90ee7e", "#7798BF", "#aaeeee", "#ff0066", "#eeaaee",
"#55BF3B", "#DF5353", "#7798BF", "#aaeeee"],
chart: {
backgroundColor: null,
style: {
fontFamily: "Dosis, sans-serif"
}
},
title: {
style: {
fontSize: '16px',
fontWeight: 'bold',
textTransform: 'uppercase'
}
},
tooltip: {
borderWidth: 0,
backgroundColor: 'rgba(219,219,216,0.8)',
shadow: false
},
legend: {
itemStyle: {
fontWeight: 'bold',
fontSize: '13px'
}
},
xAxis: {
gridLineWidth: 0,
lineWidth: 0,
minorGridLineWidth: 0,
lineColor: 'transparent',
labels: {
enabled: false,
style: {
fontSize: '12px'
},
minorTickLength: 0,
tickLength: 0
}
},
yAxis: {
minorTickInterval: 'auto',
title: {
style: {
textTransform: 'uppercase'
}
},
labels: {
style: {
fontSize: '12px'
}
}
},
plotOptions: {
candlestick: {
lineColor: '#404048'
}
},
// General
background2: '#F0F0EA'
};
// Apply the theme
Highcharts.setOptions(Highcharts.theme);
}
function addGraphOptionAnswer() {
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: self.model.attributes.content
},
xAxis: {
categories: [self.model.attributes.option_1, self.model.attributes.option_2]
},
yAxis: {
title: {
text: 'Number of answers'
}
},
series: [{
name: self.model.attributes.option_1,
data: [self.model.attributes.results[0]]
}, {
name: self.model.attributes.option_2,
data: [self.model.attributes.results[1]]
}]
});
// Set up the chart
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column',
margin: 75,
options3d: {
enabled: true,
alpha: 15,
beta: 15,
depth: 50,
viewDistance: 25
}
},
title: {
text: self.model.attributes.content
},
subtitle: {
text: ''
},
plotOptions: {
column: {
depth: 25
}
},
series: [{
name: self.model.attributes.option_1,
data: [self.model.attributes.results[0]]
}, {
name: self.model.attributes.option_2,
data: [self.model.attributes.results[1]]
}]
});
}
function addGraphRangeAnswer() {
// Bubble chart:
$('#container').highcharts({
chart: {
type: 'bubble',
zoomType: 'xy'
},
title: {
text: self.model.attributes.content
},
series: [{
data: self.model.attributes.results
}]
});
console.log(self.model.attributes.results);
// return this;
}
// if (self.model.attributes.results.range_min === null && self.model.attributes.results.results[0] !== 0 && self.model.attributes.results.results[1] !== 0 && self.model.attributes.results.content !== "") {
// this.addGraphOptions();
// this.addGraphOptionAnswer();
// } else if (self.model.attributes.results.option_1 === null && self.model.attributes.results.content !== "") {
// this.addGraphOptions();
// this.addGraphRangeAnswer();
// } else if (self.model.attributes.results.results[0] === 0 && self.model.attributes.results.content !== "") {
// var newElement = $("<h1 class='question_list'>").html("The question: <br>'" + self.model.attributes.results.content + "' <br>doesn't have any answers yet.<br> Be the first to answer!")
// $('#container').html(newElement);
// } else if (self.model.attributes.results.results[0][0] === 0 && self.model.attributes.results.content !== "") {
// var newElement = $("<h1 class='question_list'>").html("The question: <br>'" + self.model.attributes.results.content + "' <br>doesn't have any answers yet.<br> Be the first to answer!")
// $('#container').html(newElement);
// } else {
// questionsCollection.nextQuestion();
// }
addGraphOptions();
addGraphOptionAnswer();
return this;
}
});
|
/**
* Created by sunzg on 16/3/3.
*/
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res){
res.send('<h1>年轻人,你本不应该来到这里!!!</h1>');
});
var socketPort=8088;
http.listen(socketPort, function(){
console.log("socket server listening on : ",socketPort);
});
var jsonStr='{"name":"tom","age":18,"family":[{"father":{"name":"tomFather","age":40}},{"mother":{"name":"tomMother","age":41}}]}';
var jsonObject=JSON.parse(jsonStr);
parseObject(jsonObject,0);
function parseObject(obj,depth){
var space="";
for(var i=0;i<depth;i++){
space+=" ";
}
console.log(space,"{");
for(var key in obj){
var type=typeof obj[key];
if(type=="object"){
if(obj[key] instanceof Array){
console.log(space,key,":","[");
for(var i=0;i<obj[key].length;i++){
parseObject(obj[key][i],depth+1);
}
var keyLength=key.length;
for(var i=0;i<keyLength;i++){
space+=" ";
}
console.log(space," ]");
}else{
console.log(space,key,":","Object");
parseObject(obj[key],depth+1);
}
}else{
console.log(space,key,":",obj[key]);
}
}
console.log(space,"}");
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.