text stringlengths 7 3.69M |
|---|
var myApp = angular.module('Blogze', ['ui.router']);
myApp.config([
'$stateProvider',
'$urlRouterProvider', '$locationProvider',
function($stateProvider, $urlRouterProvider, $locationProvider) {
// $locationProvider.html5Mode({
// enabled: true,
// requireBase: false
// });
$stateProvider.state('home', {
url: '/home',
templateUrl: '/views/posts.html',
controller: 'MainCtrl',
resolve: {
postPromise: ['posts', function(posts) {
return posts.getAll();
}]
}
})
.state('post', {
url: '/post/{id}',
templateUrl: '/views/post.html',
controller: 'PostsCtrl',
resolve: {
post: ['$stateParams', 'posts', function($stateParams, posts) {
console.log($stateParams.id);
return posts.get($stateParams.id);
}]
}
}).state('login', {
url: '/login',
templateUrl: '/views/login.html',
controller: 'AuthCtrl',
onEnter: ['$state', 'auth', function($state, auth) {
if (auth.isLoggedIn()) {
$state.go('home');
}
}]
})
.state('register', {
url: '/register',
templateUrl: '/views/register.html',
controller: 'AuthCtrl',
onEnter: ['$state', 'auth', function($state, auth) {
if (auth.isLoggedIn()) {
$state.go('home');
}
}]
});
$urlRouterProvider.otherwise('/home');
}
]); |
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
function fakecollision(x, y, rad) {
this.radius = rad
this.movable = false
this.x = x
this.y = y
};
fakecollision.prototype = {
};
module.exports = fakecollision; |
const lodash = require('lodash');
console.log(lodash.chunk([1,2,3,4,5,6,7,8,9,0], 5)); |
/* eslint-disable complexity */
'use strict';
const fs = require('fs');
const iniparser = require('iniparser');
const moment = require('moment-timezone');
const trim = require('lodash/trim');
const yaml = require('js-yaml');
const format = require('./format');
const dest = require('./dest');
const fileStat = require('./file-stat');
const parseAuthor = require('./parse-author');
function getDefaults() {
const homeDir = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
let osUserName;
if (homeDir && homeDir.split('/').pop()) {
osUserName = homeDir.split('/').pop();
} else {
osUserName = 'root';
}
const configFileLocal = `${homeDir}/.gitconfig.local`;
const configFile = `${homeDir}/.gitconfig`;
let user;
if (fileStat(configFileLocal)) {
user = iniparser.parseSync(configFileLocal).user;
}
if (!user && fileStat(configFile)) {
user = iniparser.parseSync(configFile).user;
}
user = user || {};
let authorName = format(user.name) || osUserName;
let authorEmail = user.email || '';
let pkg;
if (fileStat(dest('package.json'))) {
pkg = require(dest('package.json'));
}
let githubToken;
if (fileStat(dest('.githubtoken'))) {
githubToken = trim(fs.readFileSync(dest('.githubtoken'), 'utf8'));
}
let hostname;
if (fileStat(dest('CNAME'))) {
hostname = trim(fs.readFileSync(dest('CNAME'), 'utf8'));
}
let config;
if (fileStat(dest('_config.yml'))) {
try {
config = yaml.safeLoad(fs.readFileSync(dest('_config.yml'), 'utf8'));
} catch (e) {}
}
let authors;
if (fileStat(dest('_data/authors.yml'))) {
try {
authors = yaml.safeLoad(fs.readFileSync(dest('_data/authors.yml'), 'utf8'));
} catch (e) {}
}
let branch;
if (fileStat(dest('.travis.yml'))) {
try {
const travis = yaml.safeLoad(fs.readFileSync(dest('.travis.yml'), 'utf8'));
branch = travis.branches.only[0];
} catch (e) {}
}
let name;
if (config && config.title) {
name = config.title;
} else if (pkg && pkg.name) {
name = pkg.name;
}
let description;
if (config && config.description) {
description = config.description;
} else if (pkg && pkg.description) {
description = pkg.description;
}
let url;
if (config && config.url) {
url = config.url;
} else if (pkg && pkg.homepage) {
url = pkg.homepage;
}
let author;
let authorStr = '';
let authorTwitter = '';
if (authorName) {
authorStr += authorName;
}
if (authorEmail) {
authorStr += ` <${authorEmail}>`;
}
if (config && config.author && typeof config.author === 'string') {
authorName = config.author;
} else if (config && config.author && typeof config.author === 'object') {
author = config.author;
authorName = author.name;
authorEmail = author.email;
authorTwitter = author.twitter;
authorStr = `${authorName} <${authorEmail}>`;
}
if (authorName && authors && authors[authorName]) {
author = authors[authorName];
authorEmail = author.email;
authorTwitter = author.twitter;
authorStr = `${authorName} <${authorEmail}>`;
} else if (pkg && pkg.author && typeof pkg.author === 'string') {
author = parseAuthor(pkg.author);
authorName = author.authorName;
authorEmail = author.authorEmail;
authorStr = `${authorName} <${authorEmail}>`;
} else if (pkg && pkg.author && typeof pkg.author === 'object') {
author = pkg.author;
authorName = author.name;
authorEmail = author.email;
authorStr = `${authorName} <${authorEmail}>`;
}
const gitDirStats = fileStat(dest('.git'));
const repoPresent = gitDirStats && gitDirStats.isDirectory();
let gitConfig;
if (repoPresent) {
try {
gitConfig = iniparser.parseSync(dest('.git/config'));
} catch (e) {}
}
return {
name,
description,
url,
author: authorStr,
authorTwitter,
authorName,
authorEmail,
timezone: moment.tz.guess(),
pkg,
githubToken,
hostname,
config,
gitConfig,
branch,
repoPresent
};
}
module.exports = getDefaults;
|
'use strict';
angular.module('launch').factory('Leads', ['$resource',
function ($resource) {
return $resource('leads/:leadId', {
leadId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
]); |
// Given a string, find out if its characters can be rearranged to form
a palindrome.
function palindromeRearranging(str) {
/* with 0(n) complexity
var count_letter={};
var letter;
var count=0;
for (var i=0;i<str.length;i++){
letter=str[i];
count_letter[letter]=count_letter[letter]||0;
count_letter[letter]++;
}
for(var i in count_letter){
if(count_letter[i]&1) count++;
}
return count<2
*/
// to check how many odd count character
var odds=0;
// to check the count of each character
var count=0;
// for unique string
str1="";
// getting the unique string
for(var i=0;i<str.length;i++){
if(str1.indexOf(str[i])==-1) str1+=str[i];
}
// checking count for each character in str
for(var i=0;i<str1.length;i++){
for(var j=0;j<str.length;j++){
if(str1[i]==str[j]) count++;
}
// checking if count is odd or not and if odd increment odds
if(count&1) odds++;
// again making count 0 for another letter
count=0;
}
// if odds is less than 2 it will return true else false
return odds<2;
}
|
// import React, { useContext, useEffect, useState } from 'react';
// import axios from 'axios';
// import {
// CHANGE_FIELD,
// INITAILIZE_FORM,
// REGISTER_FAIL,
// REGISTER_SUCCESS,
// } from '../../contexts/auth';
// import { Auth } from '../../contexts/store';
// import Register from '../../components/auth/Register';
// import { withRouter } from 'react-router-dom';
// const url = window.location.href;
// const parse = url.split('/');
// const RegisterForm = ({ history }) => {
// const { AuthState, AuthDispatch } = useContext(Auth);
// const [error, setError] = useState(null);
// // 비동기
// const companyRegister = async () => {
// console.log(AuthState);
// try {
// const response = await axios.post(
// 'http://localhost:3000/api/auth/register/company',
// {
// username: AuthState.company.username,
// password: AuthState.company.password,
// passwordConfirm: AuthState.company.passwordConfirm,
// position: parse[parse.length - 1],
// companyName: AuthState.company.companyName,
// address: AuthState.company.address,
// phoneNumber: AuthState.company.phoneNumber,
// }
// );
// console.log(response);
// await AuthDispatch({
// type: REGISTER_SUCCESS,
// auth: response,
// });
// await console.log('회원가입성공');
// await history.push('/');
// } catch (error) {
// console.log(error);
// await AuthDispatch({
// type: REGISTER_FAIL,
// error,
// });
// await console.log(AuthState);
// await console.log('오류');
// }
// };
// const personRegister = async () => {
// try {
// const response = await axios.post(
// 'http://localhost:3000/api/auth/register/person',
// {
// username: AuthState.person.username,
// password: AuthState.person.password,
// passwordConfirm: AuthState.person.passwordConfirm,
// position: parse[parse.length - 1],
// address: AuthState.person.address,
// phoneNumber: AuthState.person.phoneNumber,
// }
// );
// await AuthDispatch({
// type: REGISTER_SUCCESS,
// auth: response,
// });
// await console.log('회원가입성공');
// } catch (error) {
// console.log(error);
// await AuthDispatch({
// type: REGISTER_FAIL,
// authError: error,
// });
// await console.log(AuthState.authError);
// await console.log('오류');
// }
// };
// const onChange = e => {
// const { value, name } = e.target;
// AuthDispatch({
// type: CHANGE_FIELD,
// form: parse[parse.length - 1],
// key: name,
// value,
// });
// };
// const onSubmit = e => {
// e.preventDefault();
// if (parse[parse.length - 1] === 'company') companyRegister();
// if (parse[parse.length - 1] === 'person') personRegister();
// };
// useEffect(() => {
// AuthDispatch({
// type: INITAILIZE_FORM,
// form: 'company',
// });
// }, [AuthDispatch]);
// return (
// <Register
// position={parse[parse.length - 1]}
// form={parse[parse.length - 1]}
// onChange={onChange}
// onSubmit={onSubmit}
// error={AuthState.authError}
// />
// );
// };
// export default withRouter(RegisterForm);
import React, { useContext, useEffect, useState } from 'react';
import axios from 'axios';
import {
CHANGE_FIELD,
INITAILIZE_FORM,
REGISTER_FAIL,
REGISTER_SUCCESS,
} from '../../contexts/auth';
import { Auth } from '../../contexts/store';
import Register from '../../components/auth/Register';
import { withRouter } from 'react-router-dom';
const RegisterForm = ({ history }) => {
const url = window.location.pathname;
const parse = url.split('/');
const { AuthState, AuthDispatch } = useContext(Auth);
const [error, setError] = useState(null);
// 비동기
const companyRegister = async () => {
try {
const response = await axios.post(
'http://localhost:3000/api/auth/register/company',
{
username: AuthState.company.username,
password: AuthState.company.password,
passwordConfirm: AuthState.company.passwordConfirm,
position: parse[parse.length - 1],
companyName: AuthState.company.companyName,
address: AuthState.company.address,
phoneNumber: AuthState.company.phoneNumber,
}
);
console.log(response);
await AuthDispatch({
type: REGISTER_SUCCESS,
auth: response,
});
await console.log('회원가입성공');
await history.push('/');
} catch (error) {
console.log(error);
await AuthDispatch({
type: REGISTER_FAIL,
error: error.response,
});
await setError(error.response.status);
}
};
const personRegister = async () => {
console.log(AuthState.person);
try {
const response = await axios.post(
'http://localhost:3000/api/auth/register/person',
{
username: AuthState.person.username,
password: AuthState.person.password,
passwordConfirm: AuthState.person.passwordConfirm,
position: parse[parse.length - 1],
address: AuthState.person.address,
phoneNumber: AuthState.person.phoneNumber,
}
);
console.log(response);
await AuthDispatch({
type: REGISTER_SUCCESS,
auth: response,
});
await console.log('회원가입성공');
await history.push('/');
} catch (error) {
console.log(error);
await AuthDispatch({
type: REGISTER_FAIL,
error: error.response,
});
await setError(error.response.status);
}
};
const onChange = e => {
const { value, name } = e.target;
AuthDispatch({
type: CHANGE_FIELD,
form: parse[parse.length - 1],
key: name,
value,
});
};
const onSubmit = async e => {
e.preventDefault();
if (parse[parse.length - 1] === 'company') companyRegister();
if (parse[parse.length - 1] === 'person') personRegister();
};
useEffect(() => {
AuthDispatch({
type: INITAILIZE_FORM,
form: parse[parse.length - 1],
});
}, [AuthDispatch]);
return (
<Register
position={parse[parse.length - 1]}
form={parse[parse.length - 1]}
onChange={onChange}
onSubmit={onSubmit}
error={error}
/>
);
};
export default withRouter(RegisterForm);
|
import React, { Component } from "react";
import {
AppRegistry,
View,
Text,
StyleSheet,
TextInput,
ScrollView
} from "react-native";
import { Container, Content, Card, CardItem, Body } from "native-base";
import { TouchableOpacity } from "react-native-gesture-handler";
import { Rating } from "react-native-elements";
var baseUrl = "http://groomingsolutions.somee.com/Api/";
export default class Comments extends Component {
static navigationOptions = {
title: "Users Review"
};
constructor(props) {
super(props);
this.state = {
Comments: [],
comment: ""
};
}
componentDidMount() {
const { params } = this.props.navigation.state;
let getId = params.itemID;
this.setState({
id: getId
});
fetch(baseUrl + `GetComments?id=${getId}`)
.then(response => response.json())
.then(responseJson => {
let { Comments } = responseJson;
this.setState({
Comments
});
})
.catch(error => {
console.error(error);
});
}
render() {
let { Comments } = this.state;
return (
<View style={{ flex: 1 }}>
<Container>
<Content>
{this.state.Comments.map(data => {
return (
<Card>
<CardItem>
<Body>
{data && data.User_name ? (
<Text style={{ fontSize: 20, fontWeight: "bold" }}>
{data.User_name}:
</Text>
) : (
<Text style={{ fontSize: 20, fontWeight: "bold" }}>
Annonymous
</Text>
)}
<Text style={styles.Text}>{data.Comment1}</Text>
</Body>
</CardItem>
</Card>
);
})}
</Content>
</Container>
</View>
);
}
}
const styles = StyleSheet.create({
bodyView: {
height: "100%"
// backgroundColor: "#cfd8dc"
},
Text: {
fontSize: 18,
// marginLeft: 10,
color: "#546e7a"
}
});
|
const Song = ({ currentSong, isPlaying }) => {
return (
<div className="song-container">
<img src={currentSong.cover} className={`music-image ${isPlaying? 'playing': ''}`} alt={`${currentSong.name} Cover art`} />
<h1>{currentSong.name}</h1>
<h3>{currentSong.artist}</h3>
</div>
);
};
export default Song;
|
const { default: axios } = require("axios")
const postMessage = async (message) => {
return axios.post('/messages' , message)
}
module.exports = {
postMessage
} |
exports.CodingChallenge = `
type CodingChallenge {
title: String!
description: String!
startingFunctionText: String!
returnValue: String!
functionName: String!
functionParams: String!
addedFunctionParams: String!
}
`;
|
import { EventHandler } from '../../core/event-handler.js';
/**
* Store, access and delete instances of the various ComponentSystems.
*/
class ComponentSystemRegistry extends EventHandler {
/**
* Gets the {@link AnimComponentSystem} from the registry.
*
* @type {import('./anim/system.js').AnimComponentSystem|undefined}
* @readonly
*/
anim;
/**
* Gets the {@link AnimationComponentSystem} from the registry.
*
* @type {import('./animation/system.js').AnimationComponentSystem|undefined}
* @readonly
*/
animation;
/**
* Gets the {@link AudioListenerComponentSystem} from the registry.
*
* @type {import('./audio-listener/system.js').AudioListenerComponentSystem|undefined}
* @readonly
*/
audiolistener;
/**
* Gets the {@link AudioSourceComponentSystem} from the registry.
*
* @type {import('./audio-source/system.js').AudioSourceComponentSystem|undefined}
* @readonly
* @ignore
*/
audiosource;
/**
* Gets the {@link ButtonComponentSystem} from the registry.
*
* @type {import('./button/system.js').ButtonComponentSystem|undefined}
* @readonly
*/
button;
/**
* Gets the {@link CameraComponentSystem} from the registry.
*
* @type {import('./camera/system.js').CameraComponentSystem|undefined}
* @readonly
*/
camera;
/**
* Gets the {@link CollisionComponentSystem} from the registry.
*
* @type {import('./collision/system.js').CollisionComponentSystem|undefined}
* @readonly
*/
collision;
/**
* Gets the {@link ElementComponentSystem} from the registry.
*
* @type {import('./element/system.js').ElementComponentSystem|undefined}
* @readonly
*/
element;
/**
* Gets the {@link JointComponentSystem} from the registry.
*
* @type {import('./joint/system.js').JointComponentSystem|undefined}
* @readonly
* @ignore
*/
joint;
/**
* Gets the {@link LayoutChildComponentSystem} from the registry.
*
* @type {import('./layout-child/system.js').LayoutChildComponentSystem|undefined}
* @readonly
*/
layoutchild;
/**
* Gets the {@link LayoutGroupComponentSystem} from the registry.
*
* @type {import('./layout-group/system.js').LayoutGroupComponentSystem|undefined}
* @readonly
*/
layoutgroup;
/**
* Gets the {@link LightComponentSystem} from the registry.
*
* @type {import('./light/system.js').LightComponentSystem|undefined}
* @readonly
*/
light;
/**
* Gets the {@link ModelComponentSystem} from the registry.
*
* @type {import('./model/system.js').ModelComponentSystem|undefined}
* @readonly
*/
model;
/**
* Gets the {@link ParticleSystemComponentSystem} from the registry.
*
* @type {import('./particle-system/system.js').ParticleSystemComponentSystem|undefined}
* @readonly
*/
particlesystem;
/**
* Gets the {@link RenderComponentSystem} from the registry.
*
* @type {import('./render/system.js').RenderComponentSystem|undefined}
* @readonly
*/
render;
/**
* Gets the {@link RigidBodyComponentSystem} from the registry.
*
* @type {import('./rigid-body/system.js').RigidBodyComponentSystem|undefined}
* @readonly
*/
rigidbody;
/**
* Gets the {@link ScreenComponentSystem} from the registry.
*
* @type {import('./screen/system.js').ScreenComponentSystem|undefined}
* @readonly
*/
screen;
/**
* Gets the {@link ScriptComponentSystem} from the registry.
*
* @type {import('./script/system.js').ScriptComponentSystem|undefined}
* @readonly
*/
script;
/**
* Gets the {@link ScrollbarComponentSystem} from the registry.
*
* @type {import('./scrollbar/system.js').ScrollbarComponentSystem|undefined}
* @readonly
*/
scrollbar;
/**
* Gets the {@link ScrollViewComponentSystem} from the registry.
*
* @type {import('./scroll-view/system.js').ScrollViewComponentSystem|undefined}
* @readonly
*/
scrollview;
/**
* Gets the {@link SoundComponentSystem} from the registry.
*
* @type {import('./sound/system.js').SoundComponentSystem|undefined}
* @readonly
*/
sound;
/**
* Gets the {@link SpriteComponentSystem} from the registry.
*
* @type {import('./sprite/system.js').SpriteComponentSystem|undefined}
* @readonly
*/
sprite;
/**
* Gets the {@link ZoneComponentSystem} from the registry.
*
* @type {import('./zone/system.js').ZoneComponentSystem|undefined}
* @readonly
* @ignore
*/
zone;
/**
* Create a new ComponentSystemRegistry instance.
*/
constructor() {
super();
// An array of pc.ComponentSystem objects
this.list = [];
}
/**
* Add a component system to the registry.
*
* @param {object} system - The {@link ComponentSystem} instance.
* @ignore
*/
add(system) {
const id = system.id;
if (this[id]) {
throw new Error(`ComponentSystem name '${id}' already registered or not allowed`);
}
this[id] = system;
// Update the component system array
this.list.push(system);
}
/**
* Remove a component system from the registry.
*
* @param {object} system - The {@link ComponentSystem} instance.
* @ignore
*/
remove(system) {
const id = system.id;
if (!this[id]) {
throw new Error(`No ComponentSystem named '${id}' registered`);
}
delete this[id];
// Update the component system array
const index = this.list.indexOf(this[id]);
if (index !== -1) {
this.list.splice(index, 1);
}
}
destroy() {
this.off();
for (let i = 0; i < this.list.length; i++) {
this.list[i].destroy();
}
}
}
export { ComponentSystemRegistry };
|
import React from 'react';
import Marker from './Marker'
import MarkerData from './MarkerData'
const Destination = () => {
return (
<React.Fragment>
<section className="destinations" style = {{ background: 'url(/images/destinations-background.png)' }} >
<div className="destination-cloud "></div>
<div className="container">
<div className="destinations-head">
<span className="heading-subtitle">Experience Awaits</span>
<h4 className="heading-text">
Choose your Dream Destination
</h4>
</div>
<div className="nepal-map">
<img src="./images/nepal.png" alt="" />
{
MarkerData.map((val, index) => {
return(
<Marker
key= {index}
top= {val.top}
left={val.left}
/>
)
})
}
</div>
<div className="why-choose">
<div className="ch-item">
<ion-icon name="ribbon-outline" role="img" className="md hydrated" aria-label="ribbon outline"></ion-icon>
<div className="ch-item-des">
<h4>Unlimited Pacakge</h4>
<p>Build a tailor made trip
in less time
</p>
</div>
</div>
<div className="ch-item">
<ion-icon name="flower-outline" role="img" className="md hydrated" aria-label="flower outline"></ion-icon>
<div className="ch-item-des">
<h4>Easy Booking</h4>
<p>Build a tailor made trip
in less time
</p>
</div>
</div>
<div className="ch-item">
<ion-icon name="finger-print-outline" role="img" className="md hydrated" aria-label="finger print outline"></ion-icon>
<div className="ch-item-des">
<h4>Service Booking</h4>
<p>Build a tailor made trip
in less time
</p>
</div>
</div>
</div>
</div>
</section>
</React.Fragment>
);
}
export default Destination; |
/*
* Copyright (C) 2021 Radix IoT LLC. All rights reserved.
*/
/**
* @ngdoc directive
* @name ngMango.directive:maPointEventDetector
* @restrict 'E'
* @scope
*
* @description Retrieves data point event detectors, or creates new ones. You can then use a separate input to modify the
* detector properties (e.g. high/low limits) and save the event detector.
*
* @param {object} point The data point to get/create the event detector for
* @param {string} detector-type Event detector type to query for or the type to create. e.g. LOW_LIMIT or HIGH_LIMIT.
* If the data point has multiple detectors of this type the first detector is returned.
* @param {string=} alarm-level The alarm level for the given detector type.
* If the data point has multiple detectors of the given detector type and alarm level the first detector is returned.
* If not provided and an event detector is created it will have an alarm level of WARNING.
* @param {expression} detector Assignable expression to output the retrieved detector.
* @param {expression=} on-detector Expression which is evaluated when the detector is retrieved.
* Available scope parameters are `$detector`.
* @param {object=} options Additional options which are passed to `maEventDetector.findPointDetector()`
*
* @usage
* <ma-point-event-detector point="dataPoint" detector-type="LOW_LIMIT" alarm-level="CRITICAL" detector="criticalLowDetector"></ma-point-event-detector>
* <input type="number" ng-model-options="{debounce: 1000}" ng-model="criticalLowDetector.limit" ng-change="criticalLowDetector.saveAndNotify();">
**/
class PointEventDetectorController {
static get $$ngIsClass() { return true; }
static get $inject () {
return ['maEventDetector'];
}
constructor(maEventDetector) {
this.maEventDetector = maEventDetector;
}
$onChanges(changes) {
if (changes.point) {
if (changes.point.isFirstChange() && !this.point) {
this.detector = null;
if (this.onDetector) {
this.onDetector({$detector: null});
}
}
if (this.point) {
this.findDetector();
}
}
}
findDetector() {
const options = Object.assign({
sourceId: this.point.id,
detectorType: this.detectorType
}, this.options);
if (this.alarmLevel) {
options.alarmLevel = this.alarmLevel;
}
this.maEventDetector.findPointDetector(options).then(detector => {
this.detector = detector;
if (this.onDetector) {
this.onDetector({$detector: detector});
}
});
}
}
export default {
bindings: {
point: '<',
detectorType: '@',
alarmLevel: '@?',
detector: '=',
onDetector: '&?',
options: '<?'
},
controller: PointEventDetectorController,
designerInfo: {
translation: 'ui.components.maPointEventDetector',
icon: 'warning',
attributes: {
alarmLevel: {options: ['NONE', 'INFORMATION', 'WARNING', 'URGENT', 'CRITICAL', 'LIFE_SAFETY']},
detectorType: {options: ['LOW_LIMIT', 'HIGH_LIMIT']}
}
}
};
|
import React, {PureComponent} from 'react';
import {
ActivityIndicator, Dimensions, FlatList, Image, ScrollView, StatusBar, Text, TouchableOpacity,
View
} from "react-native";
import {Default_Photos} from "../style/BaseContant";
import {
BackgroundColorLight, BaseStyles, BlackTextColor, MainBg, MainColor, ToolColor, White,
WhiteTextColor
} from "../style/BaseStyle";
import LinearGradient from "react-native-linear-gradient";
import NaviBarView from "../component/NaviBarView";
import httpUrl from "../http/HttpUrl";
import {width} from '../util/ScreenUtil';
import mainStyles from "../style/Css";
import {jumpPager} from "../util/Utils";
export default class ThemesPage extends PureComponent {
static navigationOptions = {
header: null,
};
constructor(props) {
super(props);
this.state = {
mHotList: [],
mThemeList: [],
MainColor: MainColor,
ToolColor: ToolColor,
isInitSuccess: true
};
}
async componentDidMount() {
this.index = this.props.navigation.state.params.data.index;
this.title = this.props.navigation.state.params.data.title;
this.getList();
}
render() {
this.index = this.props.navigation.state.params.data.index;
this.title = this.props.navigation.state.params.data.title;
const flag = (this.index === 0 || this.index === 1) ? true : false;
const show_result = flag ? this.getHotView() : this.getThemeView();
if (this.state.mHotList == null && this.state.mThemeList == null) {
return (
this.state.isInitSuccess ? (
<LinearGradient style={styles.loading_view} colors={[this.state.MainColor, WhiteTextColor]}>
<ActivityIndicator
animating={true}
color={this.state.MainColor}
size='large'/>
<Text style={[styles.loading_text, {color: this.state.MainColor}]}>loading</Text>
</LinearGradient>
) : (
<LinearGradient style={styles.loading_view} colors={[this.state.MainColor, WhiteTextColor]}>
<TouchableOpacity onPress={() => {
this.setState({isInitSuccess: true});
}}>
<Text style={[styles.reload_view, {
color: this.state.MainColor,
borderColor: this.state.MainColor,
}]}>reloading</Text>
</TouchableOpacity>
</LinearGradient>)
)
} else {
return (
<View style={[styles.container]}>
{/*状态栏*/}
<StatusBar
animated={true}
backgroundColor={this.state.ToolColor}
barStyle='light-content'/>
<NaviBarView backgroundColor={this.state.ToolColor}/>
<View style={[styles.toolbar, {backgroundColor: this.state.MainColor}]}>
<TouchableOpacity
style={{paddingStart: 15}}
onPress={() => {
this.props.navigation.goBack()
}}>
<Image
style={BaseStyles.baseIcon}
source={require('../images/icon_back.png')}/>
</TouchableOpacity>
<View style={styles.toolbar_middle}>
<Text style={styles.toolbar_middle_text}>{this.title}</Text>
</View>
</View>
<ScrollView style={{marginBottom: 5}}>
{show_result}
</ScrollView>
</View>
)
}
}
getHotView() {
return (
<View>
<FlatList
data={this.state.mHotList}
keyExtractor={(item, index) => index.toString()}
renderItem={({item}) => (this.renderHotItemView(item))}
showsVerticalScrollIndicator={false}
/>
</View>
)
};
getThemeView() {
return (
<View style={[styles.theme_view]}>
<FlatList
data={this.state.mThemeList}
keyExtractor={(item, index) => index.toString()}
renderItem={({item}) => (this.renderThemeItemView(item))}
showsVerticalScrollIndicator={false}
/>
</View>
)
}
renderHotItemView(item) {
return (
<View>
</View>
)
}
renderThemeItemView(item) {
const index = this.props.navigation.state.params.data.index;
return (
<TouchableOpacity
onPress={() => {
this.goTo(index, item.id);
}}
activeOpacity={0.8}
style={[styles.theme_item_view]}>
<View style={{flexDirection: 'row'}}>
<View style={{
flex: 1,
padding: 10
}}>
<Image
style={{
width: 50,
height: 50,
borderRadius: 45,
borderColor: BlackTextColor,
}}
source={{uri: item.thumbnail}}
mode={Image.resizeMode.contain}
/>
</View>
<View style={{flexDirection: 'column', flex: 5, padding: 10}}>
<Text>{item.name}</Text>
<Text>{item.description}</Text>
</View>
</View>
<View style={[mainStyles.line]}/>
</TouchableOpacity>
)
}
async getList() {
const index = this.props.navigation.state.params.data.index;
let mlist;
if (index === 0) {
mlist = await httpUrl.getHot({
query: {}
});
let hotlist = await mlist.json();
if (hotlist != null) {
this.setState({
mHotList: hotlist.recent,
isInitSuccess: true,
})
} else {
this.setState({
isInitSuccess: false,
})
}
} else if (index === 1) {
mlist = await httpUrl.getLatest({
query: {}
});
let latestlist = await mlist.json();
if (latestlist != null) {
this.setState({
mHotList: latestlist.stories,
isInitSuccess: true,
})
} else {
this.setState({
isInitSuccess: false,
})
}
} else if (index === 2) {
mlist = await httpUrl.getThemes({
query: {}
});
let themeslist = await mlist.json();
if (themeslist != null) {
this.setState({
mThemeList: themeslist.others,
isInitSuccess: true,
})
} else {
this.setState({
isInitSuccess: false,
})
}
} else if (index === 3) {
mlist = await httpUrl.getSections({
query: {}
});
let sectionslist = await mlist.json();
if (mlist != null) {
this.setState({
mThemeList: sectionslist.data,
isInitSuccess: true,
})
} else {
this.setState({
isInitSuccess: false,
})
}
}
console.log('mHotList:', this.state.mHotList);
console.log('mThemeList:', this.state.mThemeList);
}
goTo(index, id) {
if (index === 3) {
jumpPager(this.props.navigation.navigate, 'TimeAxis', id)
}
}
}
const styles = {
container: {
// backgroundColor: 'transparent',
position: 'relative',
flex: 1,
backgroundColor: White
},
toolbar: {
height: 56,
width: width,
alignItems: 'center',
flexDirection: 'row',
},
toolbar_left_img: {
width: 26,
height: 26,
alignSelf: 'center',
marginLeft: 20,
},
toolbar_middle: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
paddingEnd: 20
},
toolbar_middle_text: {
fontSize: 18,
fontWeight: '600',
color: White
},
toolbar_right_img: {
width: 26,
height: 26,
alignSelf: 'center',
marginRight: 20,
},
scrollview_container: {
flex: 1,
},
loading_view: {
flex: 1,
width: width,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: MainBg,
},
loading_text: {
fontSize: 18,
fontWeight: '500',
marginTop: 6,
backgroundColor: 'transparent',
},
reload_view: {
padding: 8,
textAlign: 'center',
fontSize: 20,
fontWeight: '500',
borderWidth: 3,
borderRadius: 6,
},
theme_view: {
width: width - 20,
alignItems: 'center',
justifyContent: 'center'
},
theme_item_view: {
width: width - 20,
justifyContent: 'center'
}
};
|
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {Breadcrumb, Icon} from 'antd';
import Link from '../page-link';
import './style.less';
const Item = Breadcrumb.Item;
export default class BreadcrumbComponent extends Component {
static propTypes = {
dataSource: PropTypes.array, // 数据源
};
static defaultProps = {
dataSource: [],
};
renderItems() {
const {dataSource} = this.props;
const iconStyle = {marginRight: 4};
if (dataSource && dataSource.length) {
return dataSource.map(({key, icon, text, path}) => {
if (path) {
return (
<Item key={key}>
<Link to={path}>
{icon ? <Icon type={icon} style={iconStyle}/> : null}
{text}
</Link>
</Item>
);
}
return (
<Item key={key}>
{icon ? <Icon type={icon} style={iconStyle}/> : null}
{text}
</Item>
);
})
}
return null;
}
render() {
const {theme} = this.props;
return (
<div styleName="breadcrumb" className={`system-breadcrumb-${theme}`}>
<Breadcrumb>
{this.renderItems()}
</Breadcrumb>
</div>
);
}
}
|
import React from "react"
import { Link } from "gatsby"
import Layout from "../components/layout"
function About() {
return (
<Layout>
<h1>About page I'm Alex Nielsen</h1>
<p>A web developer in Northern NJ</p>
<p>
<Link to="/contact">Contact me</Link>
</p>
</Layout>
)
}
export default About
|
import React from 'react';
import { FaStar, FaStarHalfAlt, FaRegStar} from "react-icons/fa";
function Rating(props) {
const {rating, numReviews} = props;
return (
<div className="rating">
{
rating >= 1 ? <span><i><FaStar /></i></span> : rating >= 0.5 ? <span><i><FaStarHalfAlt /></i></span> : <span><i><FaRegStar /></i></span>
}
{
rating >= 2 ? <span><i><FaStar /></i></span> : rating >= 1.5 ? <span><i><FaStarHalfAlt /></i></span> : <span><i><FaRegStar /></i></span>
}
{
rating >= 3 ? <span><i><FaStar /></i></span> : rating >= 2.5 ? <span><i><FaStarHalfAlt /></i></span> : <span><i><FaRegStar /></i></span>
}
{
rating >= 4 ? <span><i><FaStar /></i></span> : rating >= 3.5 ? <span><i><FaStarHalfAlt /></i></span> : <span><i><FaRegStar /></i></span>
}
{
rating >= 5 ? <span><i><FaStar /></i></span> : rating >= 4.5 ? <span><i><FaStarHalfAlt /></i></span> : <span><i><FaRegStar /></i></span>
}
<span>{`${numReviews} reviews`}</span>
</div>
)
}
export default Rating;
|
'use strict'
const log = require('../../../dd-trace/src/log')
class Sqs {
generateTags (params, operation, response) {
const tags = {}
if (!params || (!params.QueueName && !params.QueueUrl)) return tags
return Object.assign(tags, {
'resource.name': `${operation} ${params.QueueName || params.QueueUrl}`,
'aws.sqs.queue_name': params.QueueName || params.QueueUrl
})
}
responseExtract (params, operation, response, tracer) {
if (operation === 'receiveMessage') {
if (
(!params.MaxNumberOfMessages || params.MaxNumberOfMessages === 1) &&
response &&
response.Messages &&
response.Messages[0] &&
response.Messages[0].MessageAttributes &&
response.Messages[0].MessageAttributes._datadog &&
response.Messages[0].MessageAttributes._datadog.StringValue
) {
const textMap = response.Messages[0].MessageAttributes._datadog.StringValue
try {
return tracer.extract('text_map', JSON.parse(textMap))
} catch (err) {
log.error(err)
return undefined
}
}
}
}
requestInject (span, request, tracer) {
const operation = request.operation
if (operation === 'sendMessage') {
if (!request.params) {
request.params = {}
}
if (!request.params.MessageAttributes) {
request.params.MessageAttributes = {}
}
const ddInfo = {}
tracer.inject(span, 'text_map', ddInfo)
request.params.MessageAttributes._datadog = {
DataType: 'String',
StringValue: JSON.stringify(ddInfo)
}
}
}
}
module.exports = Sqs
|
import angular from 'angular';
let Constants = angular
.module('app.constants', [])
.constant('DEFAULT_STATE', 'app')
.constant('DEFAULT_STATE_NO_FTD', 'app.deposit')
.constant('AUTHENTICATION_STATE', 'authentication.login')
.constant('NOT_FOUND_STATE', 'misc.page-not-found');
export default Constants;
|
'use strict';
module.exports = function(Dosagemeasurement) {
};
|
const container = document.querySelector('.container')
const UNSPLASH_URL = 'https://source.unsplash.com/random/'
const rows = 10
const getRandomNumber = () => {
return Math.floor(Math.random() * 10) + 300
}
for (let i = 0; i < rows * 3; i++) {
const img = document.createElement('img')
img.src = `${UNSPLASH_URL}${getRandomNumber()}x${getRandomNumber()}`
container.appendChild(img);
}
|
import {
createUser,
saveUserChange,
changeUserName,
resetUserWeigths,
} from './utils';
import drawChart from './drawChart';
import { LOCALE } from './const';
let lang = 'RU';
window.onload = function work() {
const {
HELLO,
TITLE,
CHANGE_NAME,
RESET_WEIGHT,
SEND_WEIGHT,
WEIGHT_ADDED_ALERT,
WEIGHT_IS_CHANGED,
PROMPT_CREATE_USER,
PROMPT_CHANGE_NAME,
RESET_CONFIRM,
} = LOCALE[lang];
if (!localStorage['user']) {
createUser(...PROMPT_CREATE_USER);
}
const changeLangField = document.querySelector('#language');
changeLangField.innerHTML = '';
Object.keys(LOCALE).forEach(item => {
const btn = document.createElement('button');
btn.classList.add(
'btn',
'btn-sm',
item === lang ? 'btn-success' : 'btn-outline-success'
);
btn.innerText = item;
btn.style.cursor = 'pointer';
btn.onclick = event => {
lang = event.target.innerText;
work();
};
changeLangField.appendChild(btn);
});
const { userName, weigths } = JSON.parse(localStorage['user']);
const hello = document.querySelector('h3#hello');
hello.innerText = HELLO + userName + '!';
const title = document.querySelector('#title');
title.innerText = weigths.hasOwnProperty(new Date().toDateString())
? TITLE[1]
: TITLE[0];
const input = document.querySelector('input#weight');
input.addEventListener('keydown', event => {
if (event.keyCode === 13) sendWeigth();
});
const sendBtn = document.querySelector('button#send');
sendBtn.innerText = SEND_WEIGHT;
sendBtn.onclick = sendWeigth;
const changeNameBtn = document.querySelector('button#changeName');
changeNameBtn.innerText = CHANGE_NAME;
changeNameBtn.onclick = () => changeUserName(PROMPT_CHANGE_NAME);
const resetWeigthsBtn = document.querySelector('button#resetWeight');
resetWeigthsBtn.innerText = RESET_WEIGHT;
resetWeigthsBtn.onclick = () => resetUserWeigths(RESET_CONFIRM);
drawChart(weigths, lang);
function sendWeigth() {
const now = new Date().toDateString();
if (!weigths.hasOwnProperty(now)) {
alert(WEIGHT_ADDED_ALERT);
weigths[now] = input.value;
title.innerText = WEIGHT_IS_CHANGED;
saveUserChange(userName, weigths);
drawChart(weigths, lang);
}
input.value = '';
}
};
|
import React from "react";
import PropTypes from "prop-types";
import clsx from "clsx";
import { makeStyles } from "@material-ui/styles";
import { Typography, Link } from "@material-ui/core";
const useStyles = makeStyles((theme) => ({
root: {
padding: theme.spacing(4),
},
}));
let currentYear = new Date().getFullYear();
const Footer = (props) => {
const { className, ...rest } = props;
const classes = useStyles();
return (
<footer {...rest} className={clsx(classes.root, className)}>
<Typography variant="body1">
©{" "}
<Link component="a" href="https://airqo.net" target="_blank">
AirQo
</Link>
. {currentYear}
</Typography>
<Typography variant="caption">Air Quality Initiative</Typography>
</footer>
);
};
Footer.propTypes = {
className: PropTypes.string,
};
export default Footer;
|
import axios from "axios";
import * as SecureStore from "expo-secure-store";
import jwt_decode from "jwt-decode";
async function getValueStore(key) {
return await SecureStore.getItemAsync(key);
}
async function setValueStore(key, value) {
await SecureStore.setItemAsync(key, value);
}
export const Auth = {
signIn: async (email, password) => {
const { data } = await axios
.post("http://10.0.2.2/api/users/login/", {
email,
password,
})
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
if (
error.response.status == 401 &&
error.response.data.code &&
error.response.data.code === "not_valid_login"
) {
throw { loginFail: "아이디와 패스워드를 확인하세요." };
} else {
console.log("Error", error.response.status, error.response.data);
throw {
loginFail:
"서버에서 예상하지 못한 에러 발생하였습니다. 잠시후 재시도 해주세요.",
};
}
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log("Error", error.request);
throw {
loginFail: "서버에 문제가 있습니다. 잠시후 재시도 해주세요.",
};
} else {
// Something happened in setting up the request that triggered an Error
console.log("Error", error.message);
throw {
loginFail: "알수 없는 에러가 발생하였습니다.",
};
}
});
// console.log("data", data);
await setValueStore("refreshToken", data.refresh_token);
console.log("refreshToken save complete", data.refresh_token);
return data;
},
signUp: async (email, password1, password2) => {
const {
data: { access_token, refresh_token, user },
} = await axios
.post("http://10.0.2.2/api/users/signup/", {
email,
password1,
password2,
})
.catch((err) => {
console.log("Auth Error", err);
});
await setValueStore("refreshToken", refresh_token);
return data;
},
signOut: () => {
SecureStore.deleteItemAsync("refreshToken");
},
getTokenByRefreshToken: async (refreshToken) => {
const {
data: { access },
} = await axios
.post("http://10.0.2.2/api/users/token/refresh/", {
refresh: refreshToken,
})
// .then((t) => console.log(t))
.catch(function (error) {
console.log("Auth access Error", error);
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
if (
error.response.status == 401 &&
error.response.data.code &&
error.response.data.code === "token_not_valid"
) {
throw {
loginExpired: "로그인 기간 만료되었습니다. 다시 로그인해주세요.",
};
} else {
console.log(
"Auth Error",
error.response.status,
error.response.data
);
throw {
loginExpired: "로그인 기간 만료. 다시 로그인해주세요.",
};
}
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log("Auth Error", error.request);
throw {
loginExpired: "로그인 기간 만료. 다시 로그인해주세요.",
};
} else {
// Something happened in setting up the request that triggered an Error
console.log("Auth Error", error.message);
throw {
loginExpired: "로그인 기간 만료. 다시 로그인해주세요.",
};
}
});
console.log("Auth access", access);
return access;
},
getRefreshTokenAtStorage: async () => {
let refreshToken;
try {
refreshToken = await getValueStore("refreshToken");
} catch (e) {
console.log(e);
}
// token 없을경우
if (!refreshToken) {
console.log("Auth refreshToken Null");
return null;
}
// After restoring token, we may need to validate it
const { exp } = jwt_decode(refreshToken);
if (Date.now() >= exp * 1000) {
console.log("Auth refreshToken expired", Date.now(), exp * 1000);
return null;
}
return refreshToken;
},
getAuthorizationHeader: (token) => `Bearer ${token}`,
};
|
module.exports = function($interval) {
return {
restrict : 'E',
templateUrl : 'themes/fullsite/assets/js/directives/carousel/sdCarousel-template.html',
link : function(scope, element, attrs) {
var carouselItems = require('../../json/carouselItems.json');
var category = attrs.category;
var videos = [];
scope.isAutoScroll = false;
scope.carouselIndex = 0;
scope.autoscroll = initAttribute('autoscroll',attrs.autoscroll);
scope.arrows = initAttribute('arrows',attrs.arrows);
scope.bullets = initAttribute('bullets',attrs.bullets);
if(category == 'all'){
scope.items = angular.copy(carouselItems);
}else{
scope.items = _.where(carouselItems, { "mediaCategory" : category });
}
startWatchers();
init();
function init(){
startAutoScroll();
}
function startAutoScroll(){
if(scope.isAutoScroll == false && scope.autoscroll != 'false'){
var itemsLength = scope.items.length;
var scrollInterval = 5000;
if(!isNaN(parseFloat(scope.autoscroll)) && parseFloat(scope.autoscroll) > 2000){
scrollInterval = scope.autoscroll;
}
scope.autoScrollInterval = $interval(function(){
if(scope.carouselIndex < itemsLength-1){
scope.carouselIndex++;
}else{
scope.carouselIndex = 0;
}
},scrollInterval);
scope.isAutoScroll = true;
}
}
function stopAutoScroll(){
if(scope.isAutoScroll){
$interval.cancel(scope.autoScrollInterval);
}
scope.isAutoScroll = false;
}
function carouselScrollTo(index){
stopVideos();
startAutoScroll();
scope.carouselIndex = index;
}
function initAttribute(attr,value){
var variable;
if(attr in attrs){
variable = value;
}else{
variable = 'false';
}
return variable;
}
function startWatchers() {
scope.$watch("items", function(newV) {
if(angular.isDefined(newV)) {
videos = _.filter(scope.items, function(item) {
return item.mediaType == 'vid';
});
} else {
videos = [];
}
});
}
function playVideo(media, shouldPlay) {
media.videoControl.isPlaying = shouldPlay;
if(shouldPlay == true){
stopAutoScroll();
}else{
startAutoScroll();
}
}
function stopVideos() {
_.each(videos, function(video) {
video.videoControl.isPlaying = false;
});
}
function applySlideChangeImpact(action) {
stopVideos();
startAutoScroll();
if(action == 'previous'){
scope.carouselIndex--;
}else if(action == 'next'){
scope.carouselIndex++;
}
}
scope.playVideo = playVideo;
scope.applySlideChangeImpact = applySlideChangeImpact;
scope.carouselIndex = 0;
scope.carouselScrollTo = carouselScrollTo;
}
};
};
|
import React, { Component } from 'react';
import { View, Text, TextInput, Form } from 'react-native';
import { FormLabel, FormInput, FormValidationMessage, Button } from 'react-native-elements';
class SignInScreen extends Component {
render() {
return (
<View>
<FormLabel>Username</FormLabel>
<FormInput />
<FormLabel>Password</FormLabel>
<FormInput />
<Button
title='Submit'
backgroundColor='green'
borderRadius={5}
/>
</View>
)
}
}
export default SignInScreen;
|
function get_content() {
$.getScript(media_url+'js/aux/modals.js', function(){
$.getScript(media_url+'js/aux/journeys.js', function(){
$.getScript(media_url+'js/aux/date.js', function(){
$.getScript(media_url+'js/lib/jquery.keypad.min.js', function(){
$.getScript(media_url+'js/lib/jquery.keypad-es.js', function(){
$.post(base_url+'/partials/dashboard_digital_viewer', function(template, textStatus, xhr) {
$('#main').html(template);
loadRadio();
//loadGuard();
//startWakeup();
//startStatus();
});
});
});
});
});
});
}
var myradio=false;
//var guard=false;
//var firebase_url=false;
//var firebase_ref=false;
//var journeys_ref=false;
//var reservations_ref=false;
function show_radio_map() {
pulsador = window.open(base_url+'/radiomap/'+myradio.id, "RadioMap", "location=0,status=0,scrollbars=0,width=1024,height=680");
}
function loadRadio() {
$.getJSON(api_url+'radios/get?callback=?', {}, function(data){
if(data.status=='success'){
myradio = data.data;
//firebase_updating();
//checkhash();
startHistorical();
$('#radio_title').html(myradio.name);
if(myradio.digital){
$('#radio_map').fadeIn();
}
}
else super_error('Radio info failure');
});
}
// HISTORICAL
function startHistorical() {
$.getScript('http://code.jquery.com/ui/1.9.1/jquery-ui.min.js').done(function () {
$.getScript(media_url+'js/lib/jquery.ui.timepicker.js').done(function () {
$.getScript(media_url+'js/lib/jquery.ui.datepicker.es.js').done(function () {
$('<link/>').attr({'rel': "stylesheet", 'type': "text/css", 'href': media_url+"css/lib/jquery-ui-1.10.3.css"}).appendTo('head');
$('<link/>').attr({'rel': "stylesheet", 'type': "text/css", 'href': media_url+"css/lib/datetimepicker.css"}).appendTo('head');
$('<link/>').attr({'rel': "stylesheet", 'type': "text/css", 'href': media_url+"css/partials/datetimepicker.css"}).appendTo('head');
var center=$('<center></center>'); $('#submain').html(center);
var datepicker_wrapper=$('<div></div>').attr({'id':'datepicker_wrapper'}); center.append(datepicker_wrapper);
var datepicker_input=$('<input>').attr({'type':'hidden','id':'datepicker_input'}); center.append(datepicker_input);
var ahora=new Date();
datepicker_input.val(ahora.getFullYear()+'/'+(parseInt(ahora.getMonth())+1)+'/'+ahora.getDate());
$('#datepicker_wrapper').datepicker({ maxDate: "0", altField: "#datepicker_input", altFormat: "dd/mm/yy", onSelect: function(dateText) {
showDaily(dateText);
}});
var wrapper = $('<div></div>').attr({'id':'daily_list','class':'journeys_sm_list'});
$('#submain').append(wrapper);
showDaily(fecha_hoy_simple());
},true);
},true);
},true);
}
function showDaily(fecha) {
$('#daily_list').html('<div class="waiting"><i class="fa fa-cog fa-spin"></i></div>').css({'margin-top':'40px'});
var mydate=fecha.split("/");
$.getJSON(api_url+'radios/daily?callback=?', {id:myradio.id, day:mydate[0],month:mydate[1], year:mydate[2], offset:local_offset}, function(data){
if(data.status=='success'){
$('#daily_list').empty();
$.each(data.data, function(index, journey) {
draw_journey_sm(journey, $('#daily_list'));
});
}
else super_error('Historical failure');
});
}
function startStats() {
$.post(base_url+'/partials/stats_radio', function(template, textStatus, xhr) {
$('#submain').html(template);
loadStats();
});
}
function loadStats() {
$.getJSON(api_url+'radios/stats_foreign?callback=?', {id:myradio.id}, function(data){
if(data.status=='success'){
$('#stat_journeys').text(data.data.total_journeys);
$('#stat_completed').text(data.data.completed_journeys);
$('#stat_canceled').text(data.data.canceled_journeys);
$('#stat_credit_cards').text(parseInt(data.data.credit_card_percent)+'%');
$('#stat_enterprises').text(data.data.total_enterprises);
$('#stat_buttons').text(data.data.total_buttons);
$('#stat_licences').text(data.data.total_licences);
}
else{
if (data.response=='radio_analytics_not_found') launch_alert('<i class="fa fa-frown-o"></i> Aun sin datos','warning');
}
});
} |
import tw from 'tailwind-styled-components'
/** Div which contains Logo svg */
export const UserDropdownParent = tw.div`
h-full
relative
w-40
` |
import React from 'react';
import Container from '../button/container';
import Title from './title';
import Background from '../../images/bubbles.png';
const HowItWorks = props => (
<div style={{backgroundImage: "url(" + Background + ")", backgroundSize: 'cover', width: '100%', height: '750px'}}>
<Title className='row'/>
<Container className='row'/>
</div>
);
export default HowItWorks; |
import React, { Component } from 'react';
class CardTemplate extends Component {
render() {
return (
<div className="uk-grid uk-margin">
<div className="uk-width-1-3"></div>
<div className="uk-width-1-3">
<div className="uk-card uk-card-default uk-card-body">
{this.props.children}
</div>
</div>
</div>
)
}
}
export default CardTemplate;
|
$(document).ready(function () {
$('#expires').blur(function () {
let date = new Date($(this).val());
$('#commentsban-expires').val(date.getTime()/1000);
//console.log(date.getTime());
})
}) |
import eventsEngine from '../events/core/events_engine';
import { removeData, data as elementData } from '../core/element_data';
import Class from '../core/class';
import devices from '../core/devices';
import registerEvent from './core/event_registrator';
import { addNamespace, isTouchEvent, fireEvent } from './utils/index';
import pointerEvents from './pointer';
var HOVERSTART_NAMESPACE = 'dxHoverStart';
var HOVERSTART = 'dxhoverstart';
var POINTERENTER_NAMESPACED_EVENT_NAME = addNamespace(pointerEvents.enter, HOVERSTART_NAMESPACE);
var HOVEREND_NAMESPACE = 'dxHoverEnd';
var HOVEREND = 'dxhoverend';
var POINTERLEAVE_NAMESPACED_EVENT_NAME = addNamespace(pointerEvents.leave, HOVEREND_NAMESPACE);
var Hover = Class.inherit({
noBubble: true,
ctor: function ctor() {
this._handlerArrayKeyPath = this._eventNamespace + '_HandlerStore';
},
setup: function setup(element) {
elementData(element, this._handlerArrayKeyPath, {});
},
add: function add(element, handleObj) {
var that = this;
var handler = function handler(e) {
that._handler(e);
};
eventsEngine.on(element, this._originalEventName, handleObj.selector, handler);
elementData(element, this._handlerArrayKeyPath)[handleObj.guid] = handler;
},
_handler: function _handler(e) {
if (isTouchEvent(e) || devices.isSimulator()) {
return;
}
fireEvent({
type: this._eventName,
originalEvent: e,
delegateTarget: e.delegateTarget
});
},
remove: function remove(element, handleObj) {
var handler = elementData(element, this._handlerArrayKeyPath)[handleObj.guid];
eventsEngine.off(element, this._originalEventName, handleObj.selector, handler);
},
teardown: function teardown(element) {
removeData(element, this._handlerArrayKeyPath);
}
});
var HoverStart = Hover.inherit({
ctor: function ctor() {
this._eventNamespace = HOVERSTART_NAMESPACE;
this._eventName = HOVERSTART;
this._originalEventName = POINTERENTER_NAMESPACED_EVENT_NAME;
this.callBase();
},
_handler: function _handler(e) {
var pointers = e.pointers || [];
if (!pointers.length) {
this.callBase(e);
}
}
});
var HoverEnd = Hover.inherit({
ctor: function ctor() {
this._eventNamespace = HOVEREND_NAMESPACE;
this._eventName = HOVEREND;
this._originalEventName = POINTERLEAVE_NAMESPACED_EVENT_NAME;
this.callBase();
}
});
/**
* @name UI Events.dxhoverstart
* @type eventType
* @type_function_param1 event:event
* @module events/hover
*/
/**
* @name UI Events.dxhoverend
* @type eventType
* @type_function_param1 event:event
* @module events/hover
*/
registerEvent(HOVERSTART, new HoverStart());
registerEvent(HOVEREND, new HoverEnd());
export { HOVERSTART as start, HOVEREND as end }; |
//app.js
App({
//启动后执行
onLaunch: function () {
// 展示本地存储能力
var logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
// 登录
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
}
})
// 获取用户信息
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
// 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
wx.getUserInfo({
success: res => {
// 可以将 res 发送给后台解码出 unionId
this.globalData.userInfo = res.userInfo
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
if (this.userInfoReadyCallback) {
this.userInfoReadyCallback(res)
}
}
})
}
}
})
},
globalData: {
userInfo: null,
t: 0,
sn: [42, 41],
dz: 43,
fx: 1,
n: 0,
}
}) |
var teclado={};
// Con esta funcion dejamos definidos los eventos de teclado que usaremos para los disparos y mover nuestra nave.
function agregareventoteclado(){
agregarEvento(document,"keydown",function(e){
teclado[e.keyCode]=true;
});
agregarEvento(document,"keyup",function(e){
teclado[e.keyCode]=false;
});
function agregarEvento(elemento,nombreEvento,funcion){
if(elemento.addEventListener){
elemento.addEventListener(nombreEvento,funcion,false);
}
else if(elemento.attachEvent){
elemento.attachEvent(nombreEvento,funcion);
}
}
}
//------------------------------------------------------------------
//----------------- ANIMACIÓN NAVEGADOR SCROLL ----------------------
function funcionScroll() {
if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
document.getElementById("navdesarrollo").style.display = "none";
} else {
document.getElementById("navdesarrollo").style.display = "block";
}
}
|
import React, { useState } from "react";
import { SearchBar } from "react-native-elements";
import * as WebBrowser from "expo-web-browser";
function SearchBarComponent(props) {
let directionsTo = props.location.split(" ").map(elem => {
return elem.replace(",", "");
});
directionsTo = directionsTo.join("+");
const [input, setInput] = useState("");
let userInputToUrl = input.split(" ").map(elem => {
return elem.replace(",", "");
});
userInputToUrl = userInputToUrl.join("+");
const handleSearch = () => {
WebBrowser.openBrowserAsync(
`https://www.google.com/maps/search/?api=1&query=${userInputToUrl}+${directionsTo}`
);
setInput("");
};
return (
<SearchBar
placeholder="e.g pizza, beer, Lou Malnati's"
onChangeText={setInput}
value={input}
lightTheme={true}
round={true}
containerStyle={{ borderRadius: 21.5, height: 50 }}
inputContainerStyle={{ backgroundColor: "white" }}
platform='ios'
inputStyle={{ backgroundColor: "white" }}
onSubmitEditing={handleSearch}
/>
);
}
export default SearchBarComponent;
|
/**
* Created by hao.cheng on 2017/5/7.
*/
import React from 'react';
import img from '../style/imgs/404.png';
import img404 from '../style/imgs/404img.jpg'
const style = {
backgroundImage: 'url(' + img404 + ')',
backgroundRepeat: 'no-repeat',
backgroundSize: '100% 100%',
backgroundAttachment: 'fixed',
height: '100vh',
}
class NotFound extends React.Component {
state = {
animated: ''
};
enter = () => {
this.setState({ animated: 'hinge' })
};
render() {
return (
// <div className="center" style={{height: '100vh', background: '#ececec', overflow: 'hidden'}}>
// <img src={img} alt="404" className={`animated swing ${this.state.animated}`} onMouseEnter={this.enter} />
// </div>
<div style={style} >
{/* <img src={img404} /> */}
</div>
)
}
}
export default NotFound; |
// On créer un élément avec React
// @param1: nom du tag
// @param2: options
// @param3: enfant(s) text ou autre élément React
const title = React.createElement('h1', {}, 'Hello world');
// React envoie un objet javascript avec des propriétés
// par exemple props, type, ...
// checker ce que renvoie le console.log
console.log(title);
// C'est avec ReactDOM qu'on envoie notre élément crée avec React sur la vue
// @param1: nom élément
// @param2: noeud sur lequel appliqué le rendu
// Attention déconseillé de le mettre sur document.body c'est pour ça qu'on encapsule toujours dans une div ('#app' par exemple)
ReactDOM.render(title, document.querySelector('#app'));
// Ici on utilise du React pur mais en génral on utilise du JSX |
var connection = require("./connection.js");
// Object Relational Mapper (ORM)
// The ?? signs are for swapping out table or column names
// The ? signs are for swapping out other values
// These help avoid SQL injection
// https://en.wikipedia.org/wiki/SQL_injection
var orm = {
selectAll: function () {
var queryString = "SELECT * FROM `burgers_db`.`burgers`";
connection.query(queryString, function (err, result) {
if (err) throw err;
console.log(result);
});
},
insertOne: function (val1, val2) {
var queryString = "INSERT INTO burgers_db.burgers";
queryString += "(burger_name, devoured)";
queryString += "VALUES (" + val1 + "," + val2 + ")";
console.log(queryString);
connection.query(queryString, function (err, result) {
if (err) throw err;
console.log(result);
});
},
updateOne: function (burgerId) {
var queryString =
"UPDATE `burgers_db`.`burgers` SET `devoured` = '1' WHERE (`id` = ?)";
connection.query(queryString, [burgerId], function (err, result) {
if (err) throw err;
console.log(result);
}
);
}
};
module.exports = orm;
|
// pages/balance/rechargeDetail/index.js
const app = getApp();
const config = require("../../../utils/config.js");
Page({
/**
* 页面的初始数据
*/
data: {
height: null,
typeList: [
"全部",
"支出",
"收入"
],
currentType: 0,
balanceValue: 122.5,
dateTags: [
"当月",
"3个月",
"全部",
],
currentDateTag: 0,
dataSource: null,
allList: [
{
type: 0, // 类型 1 支出 0 收入
amount: 200, // 金额
name: "会员卡充值到账",
date: "2019-08-13",
time: "08:11:13",
},
{
type: 1, // 类型 1 支出 0 收入
amount: 13, // 金额
name: "消费支出",
date: "2019-08-12",
time: "11:11:13",
},
{
type: 1, // 类型 1 支出 0 收入
amount: 89, // 金额
name: "消费支出",
date: "2019-08-13",
time: "08:11:13",
},
{
type: 0, // 类型 1 支出 0 收入
amount: 500, // 金额
name: "会员卡充值到账",
date: "2019-08-13",
time: "08:11:13",
},
{
type: 1, // 类型 1 支出 0 收入
amount: 135, // 金额
name: "消费支出",
date: "2019-08-13",
time: "08:11:13",
},
{
type: 0, // 类型 1 支出 0 收入
amount: 200, // 金额
name: "会员卡充值到账",
date: "2019-08-13",
time: "08:11:13",
},
{
type: 1, // 类型 1 支出 0 收入
amount: 13, // 金额
name: "消费支出",
date: "2019-08-12",
time: "11:11:13",
},
{
type: 1, // 类型 1 支出 0 收入
amount: 89, // 金额
name: "消费支出",
date: "2019-08-13",
time: "08:11:13",
},
{
type: 0, // 类型 1 支出 0 收入
amount: 500, // 金额
name: "会员卡充值到账",
date: "2019-08-13",
time: "08:11:13",
},
{
type: 1, // 类型 1 支出 0 收入
amount: 135, // 金额
name: "消费支出",
date: "2019-08-13",
time: "08:11:13",
},
{
type: 0, // 类型 1 支出 0 收入
amount: 200, // 金额
name: "会员卡充值到账",
date: "2019-08-13",
time: "08:11:13",
},
{
type: 1, // 类型 1 支出 0 收入
amount: 13, // 金额
name: "消费支出",
date: "2019-08-12",
time: "11:11:13",
},
{
type: 1, // 类型 1 支出 0 收入
amount: 89, // 金额
name: "消费支出",
date: "2019-08-13",
time: "08:11:13",
},
{
type: 0, // 类型 1 支出 0 收入
amount: 500, // 金额
name: "会员卡充值到账",
date: "2019-08-13",
time: "08:11:13",
},
{
type: 1, // 类型 1 支出 0 收入
amount: 135, // 金额
name: "消费支出",
date: "2019-08-13",
time: "08:11:13",
},
{
type: 0, // 类型 1 支出 0 收入
amount: 200, // 金额
name: "会员卡充值到账",
date: "2019-08-13",
time: "08:11:13",
},
{
type: 1, // 类型 1 支出 0 收入
amount: 13, // 金额
name: "消费支出",
date: "2019-08-12",
time: "11:11:13",
},
{
type: 1, // 类型 1 支出 0 收入
amount: 89, // 金额
name: "消费支出",
date: "2019-08-13",
time: "08:11:13",
},
{
type: 0, // 类型 1 支出 0 收入
amount: 500, // 金额
name: "会员卡充值到账",
date: "2019-08-13",
time: "08:11:13",
},
{
type: 1, // 类型 1 支出 0 收入
amount: 135, // 金额
name: "消费支出",
date: "2019-08-13",
time: "08:11:13",
},
],
outList: [
{
type: 1, // 类型 1 支出 0 收入
amount: 13, // 金额
name: "消费支出",
date: "2019-08-12",
time: "11:11:13",
},
{
type: 1, // 类型 1 支出 0 收入
amount: 89, // 金额
name: "消费支出",
date: "2019-08-13",
time: "08:11:13",
},
{
type: 1, // 类型 1 支出 0 收入
amount: 500, // 金额
name: "消费支出",
date: "2019-08-13",
time: "08:11:13",
},
{
type: 1, // 类型 1 支出 0 收入
amount: 135, // 金额
name: "消费支出",
date: "2019-08-13",
time: "08:11:13",
},
],
inList: [
{
type: 0, // 类型 1 支出 0 收入
amount: 13, // 金额
name: "会员卡充值到账",
date: "2019-08-12",
time: "11:11:13",
},
{
type: 0, // 类型 1 支出 0 收入
amount: 89, // 金额
name: "会员卡充值到账",
date: "2019-08-13",
time: "08:11:13",
},
{
type: 0, // 类型 1 支出 0 收入
amount: 500, // 金额
name: "会员卡充值到账",
date: "2019-08-13",
time: "08:11:13",
},
{
type: 0, // 类型 1 支出 0 收入
amount: 135, // 金额
name: "会员卡充值到账",
date: "2019-08-13",
time: "08:11:13",
},
],
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.setData({
height: app.globalData.pageHeight
})
this.setDataSource(this.data.allList);
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
},
/**
* 设置数据源
*/
setDataSource: function (datasource) {
this.setData({
dataSource: datasource
})
},
/**
* 点击tab
*/
handleTabChange: function (e) {
this.setData({
currentType: e.detail.key
})
if (this.data.currentType == 0) {
this.setDataSource(this.data.allList);
} else if (this.data.currentType == 1) {
this.setDataSource(this.data.outList);
} else {
this.setDataSource(this.data.inList);
}
},
/**
* 点击时间
*/
tapDateTag: function(e) {
this.setData({
currentDateTag: e.currentTarget.dataset.index
})
},
}) |
import React, { useState } from 'react'
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import Form from './form';
import Menu from './class';
import UserDets from './Add';
import Edit from './edit';
import NewsLink from './linkingnewspage';
const MenuPage = ({}) => {
const [users,setUsers] = useState([])
return (
<div className='group-container'>
<Router>
<div className='nav'>
<ul>
<li><Link to='/'>Home</Link></li>
<li><Link to='/class'>News Feed</Link></li>
</ul>
</div>
<Switch>
<Route path={'/class'}>
< Menu/>
</Route>
<Route path={'/edit/:id'}>
<Edit />
{/* details e kae */}
{/* never mind dis one gape ke dirile a million pages befor ke dira the one ya add */}
</Route>
{/* i clled it here so, without the arrays or the props or mapping */}
<Route path={'/Add/:id'}>
<UserDets />
</Route>
<Route path={'/'}>
<Form users={users} setUsers={setUsers}/>
{/* this one yona k */}
</Route>
</Switch>
</Router>
</div>
)
}
export default MenuPage |
import React from 'react';
import {Tabs, Tab} from 'material-ui/Tabs';
import SwipeableViews from 'react-swipeable-views';
import Scroll from 'react-scroll';
import PhotosIndexContainer from '../photos/photos_index_container.js';
import SeascapeContainer from '../tabs/seascape_container.js';
import OtherContainer from '../tabs/other_container.js';
import WildlifeContainer from '../tabs/wildlife_container.js';
import PeopleContainer from '../tabs/people_container.js';
import DiscoverContainer from '../tabs/discover_container.js';
import CircularProgressSimple from '../widgets/loading.jsx';
const styles = {
headline: {
fontSize: 24,
paddingTop: 16,
marginBottom: 12,
fontWeight: 400,
},
tab: {
backgroundColor: 'white',
color: "gray",
fontSize: 14,
},
};
class TabsView extends React.Component {
constructor(props) {
super(props);
this.state = {
slideIndex: 0,
position: 0
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(value) {
this.setState({
slideIndex: value,
});
}
handleScroll() {
let executed = false;
if (!executed) {
let scroll = Scroll.animateScroll;
executed = true;
scroll.scrollTo(window.innerHeight - 295, {
duration: 2000,
delay: 100,
smooth: true
});
}
this.setState({position: 3});
}
componentDidMount() {
let loadingTimer = setTimeout(()=> this.setState({position: 1}), 2500);
let scrollTimer = setTimeout(()=> this.setState({position: 2}), 500);
}
switchTab(state) {
switch(state) {
case 0:
return <DiscoverContainer/>;
case 1:
return <SeascapeContainer/>;
case 2:
return <WildlifeContainer/>;
case 3:
return <PeopleContainer/>;
case 4:
return <OtherContainer/>;
case 5:
return <PhotosIndexContainer/>;
default:
return <DiscoverContainer/>;
}
}
render() {
if (this.state.position === 0 ) {
return (
<div className="circularProgress">
<CircularProgressSimple></CircularProgressSimple>
</div>
);
}
if (this.state.position === 2 ) {
this.handleScroll();
}
return (
<div>
<Tabs
onChange={this.handleChange}
value={this.state.slideIndex}
>
<Tab className="Discover" onActive={styles.active} label="Discover" value={0} style={styles.tab}/>
<Tab className="Seascape" label="Seascape" value={1} style={styles.tab} />
<Tab className="Wildlife" label="Wildlife" value={2} style={styles.tab} />
<Tab className="People" label="People" value={3} style={styles.tab} />
<Tab className="Others" label="Others" value={4} style={styles.tab}/>
<Tab className="AllUserUploads" label="All User Uploads" value={5} style={styles.tab} />
</Tabs>
<SwipeableViews
index={this.state.slideIndex}
onChangeIndex={this.handleChange}
>
<div className="tabsCssss">
<DiscoverContainer/>;
</div>
<div className="tabsCssss" >
{this.switchTab(this.state.slideIndex)}
</div>
<div className="tabsCssss" >
{this.switchTab(this.state.slideIndex)}
</div>
<div className="tabsCssss" >
{this.switchTab(this.state.slideIndex)}
</div>
<div className="tabsCssss" >
{this.switchTab(this.state.slideIndex)}
</div>
<div className="tabsCssss" >
{this.switchTab(this.state.slideIndex)}
</div>
</SwipeableViews>
</div>
);
}
}
export default TabsView;
|
module.exports = {
pluginOptions: {
i18n: {
locale: "pl",
fallbackLocale: "en",
localeDir: "locales",
enableInSFC: true
}
},
pwa: {
name: "Equipment Manager"
}
};
|
import React from 'react'
import god from '../../images/paintings/god.jpg'
import PaintingsComponent from "../../components/paintings_component";
const God = () => (
<PaintingsComponent image={god} title={'God'}>
<center>
<iframe width="90%" height="300" scrolling="no" frameBorder="no" allow="autoplay"
src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/274414593&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe>
</center>
</PaintingsComponent>
)
export default God
|
BenchForm = React.createClass({
createBench: function(event){
event.preventDefault();
var lat = event.target[0].value;
var lng = event.target[1].value;
var desc = event.target[2].value;
var seating = event.target[3].value;
ApiUtil.createBench({bench: {lat: lat, lng: lng, description: desc, seating: seating }});
this.props.history.pushState(null, "/")
},
render: function(){
return(
<form onSubmit={this.createBench}>Create a new Bench!<br/>
Latitude: <input type ="text" value={this.props.location.query.J} name="lat"></input><br/>
Longitude: <input type = "text" value={this.props.location.query.M} name="lng"></input><br/>
Description: <textarea name="description"></textarea><br/>
Seating:
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<input type ="submit"></input>
</form>
)}
}) |
import wxUtil from '../../utils/wxUtil'
import * as Api from '../api'
Page({
data: {
isLoaded: false,
basic: {},
educations: [],
works: [],
},
onLoad() {
this.loadAllInfo()
},
onShow() {
const app = getApp()
app.checkNotice('editedBasic', true, this.updateBasic)
app.checkNotice('editedEducation', true, this.updateEducation)
app.checkNotice('editedWork', true, this.updateWork)
},
onPullDownRefresh() {
this.loadAllInfo().then(() => {
wx.stopPullDownRefresh()
})
},
onShareAppMessage() {
const { basic } = this.data
return {
title: `${basic.real_name}的SEU校友名片`,
path: `/pages/detail/detail?id=${basic.openid}&isShare=1`,
}
},
handleBasicEdit() {
wxUtil.navigateTo('edit', { type: 'basic' })
},
handleShare() {
wxUtil.navigateTo('share', { type: 'basic' })
},
handleAbout() {
wxUtil.navigateTo('about', { type: 'basic' })
},
handleEducationAdd(e) {
const { num } = e.currentTarget.dataset
if (num) {
wxUtil.navigateTo('edit', {
type: 'education',
id: num,
})
return
}
wxUtil.navigateTo('edit', { type: 'education' })
},
handleWorkAdd(e) {
const { num } = e.currentTarget.dataset
if (num) {
wxUtil.navigateTo('edit', {
type: 'work',
id: num,
})
return
}
wxUtil.navigateTo('edit', { type: 'work' })
},
loadAllInfo() {
return Api.getAllInfo().then(data => {
const { base, personal, education, work } = data
this.setData({
isLoaded: true,
basic: { ...base[0], ...personal[0] },
educations: education,
works: work,
})
}, () => {})
},
updateBasic() {
Api.getBasicInfo().then(data => {
const { base, personal } = data
this.setData({
basic: { ...base[0], ...personal[0] },
})
}, () => {})
},
updateEducation() {
Api.getEducationInfo().then(data => {
this.setData({ educations: data })
}, () => {})
},
updateWork() {
Api.getWorkInfo().then(data => {
this.setData({ works: data })
}, () => {})
},
})
|
var React = require("react");
var Main = (props) => {
return (
<div>
<h1>Main Render</h1>
</div>
);
};
module.exports = Main; |
var srt = "Alex";
var toExchange = 'x';
var exchange = 'z'
function toExchangeFor (toExchange, exchange, srt) {
var result="";
for(var i = 0; i < srt.length; i++) {
//c = str.charAt(i)// pour garder la lettre
if (toExchange == srt.charAt(i)) {
result = result + exchange
} else {
result = result + srt.charAt(i)
}
}
return result
}
var toCall = toExchangeFor (toExchange, exchange, srt);
console.log(toCall);
|
import Axios from "axios";
export const postAction = () => async (dispatch, getState) => {
dispatch({ type: "POST_REQ_SEND" });
const token = localStorage.getItem("token");
if (token) Axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
try {
const { data } = await Axios.get(
"https://cors-anywhere.herokuapp.com/http://front-api-test.wsafar.com/posts"
);
dispatch({ type: "POST_REQ_SUCCESS", payload: data.result.items });
localStorage.setItem("items", JSON.stringify(getState().posts.items));
} catch (err) {
dispatch({ type: "POST_REQ_FAIL", payload: err });
}
};
|
var path = require('path');
var fs = require('fs');
//post
var formidable = require('formidable');
var dateFormat = require('dateformat');
module.exports = {
/**通过formdata上传图片
* 参数1,express请求
* 参数2,静态资源下的路径
* 参数3,回调函数,callback(err,fields,uploadPath),返回错误对象,表单字段和新地址
*/
uploadPhoto : function(req,dirName,callback){
//上传文件
// parse a file upload
var form = new formidable.IncomingForm();
form.uploadDir = path.join(__dirname,'../static',dirName);
//保留文件扩展名
form.keepExtensions = true;
form.encoding = 'utf-8';
form.onPart = function(part) {
if (part.filename != '') {
// let formidable handle all non-file parts
form.handlePart(part);
}
};
form.parse(req, function(err, fields, files) {
if(err) {
callback && callback(err,null,null);
return;
}
if(!files.userfile){
var errMsg = {
errCode : -10,
errMsg : '文件为空'
};
callback && callback(errMsg,null,null);
return;
}
var time = dateFormat(new Date(), "yyyymmddHHMMss");
var extName = path.extname(fields.imgName);
var newName = time + '_' + Math.floor(Math.random()*9999) + extName;
var oldPath = files.userfile.path;
var newPath = path.join(__dirname,'../static',dirName, newName);
//修改文件的名字
fs.renameSync(oldPath,newPath);
callback && callback(null, fields, path.join('/',dirName,newName).split('\\').join('/'));
});
},
uploadPhotoArr : function(req,dirName,callback){
//上传文件
// parse a file upload
var form = new formidable.IncomingForm();
form.uploadDir = path.join(__dirname,'../static',dirName);
//保留文件扩展名
form.keepExtensions = true;
form.encoding = 'utf-8';
form.onPart = function(part) {
if (part.filename != '') {
// let formidable handle all non-file parts
form.handlePart(part);
}
};
form.parse(req, function(err, fields, files) {
if(err) {
callback && callback(err,null,null);
throw err;
return;
}
var uploadPathArr = [];
// console.log(fields);
// console.log(files);
for(var key in files){ //for in 遍历一个一个修改文件名称
if(!files[key]){
var errMsg = {
errCode : -10,
errMsg : key +' 文件为空'
};
callback && callback(errMsg,null,null);
return;
}
var time = dateFormat(new Date(), "yyyymmddHHMMss");
var extName = '.png';
var newName = time + '_' + Math.floor(Math.random()*9999) + extName;
var oldPath = files[key].path;
var newPath = path.join(__dirname,'../static',dirName, newName);
//修改文件的名字
fs.renameSync(oldPath,newPath);
var finalPath = path.join('/',dirName,newName).split('\\').join('/');
uploadPathArr.push(finalPath);
}
callback && callback(null,fields,uploadPathArr);
});
}
}; |
const constant = {
title: "한글 초성 검색",
showMore: "더보기",
searchInputPlaceHolder: "Search...",
dataInputPlaceHolder: "데이터 추가하기 (Enter)",
};
export default constant;
|
const express = require("express");
const router = express.Router();
const meals = require("./../data/meals.json");
router.get("/:id", async (request, response) => {
console.log(meals);
try {
const mealId = parseInt(request.params.id);
if (isNaN(mealId)) {
response.status(400).json({ error: "Id must be integers." })
return;
}
if (mealId <= meals.length) {
const mealById = meals.filter((meal) => mealId == meal.id);
console.log(mealById);
response.json(mealById[0]);
} else {
//response.status(404).json({ error: "Id is not found!" })
response.send({});
}
} catch (error) {
response.status(500).send({ error: "Internal Server Error." });
}
})
router.get("/", async (request, response) => {
try {
const validQueryParams = ["maxPrice", "title", "createdAfter", "limit"]
const requestedParameters = Object.keys(request.query)
const isParamValid = param => validQueryParams.includes(param)
if (!requestedParameters.every(isParamValid)) {
response.status(400).send("The requested query does not exist")
return;
}
let filteredMeals = meals;
if ('maxPrice' in request.query) {
const maxPrice = parseFloat(request.query.maxPrice);
if (isNaN(maxPrice)) {
response.status(400).json({ error: "maxPrice must be integers." });
return;
}
filteredMeals = filteredMeals.filter(meal => meal.price < maxPrice);
}
if ('title' in request.query) {
const title = request.query.title;
filteredMeals = filteredMeals.filter(meal => meal.title.toLowerCase().includes((title).toLowerCase()));
}
if ('createdAfter' in request.query) {
const createdAfter = request.query.createdAfter;
const createdAfterDate = new Date(createdAfter);
if (!createdAfterDate.getDate()) {
response.status(400).json({ error: "Date is not valid." });
return;
}
filteredMeals = filteredMeals.filter(meal => new Date(meal.createdAt) > createdAfterDate);
}
if ('limit' in request.query) {
const limit = parseInt(request.query.limit);
if (isNaN(limit)) {
response.status(400).json({ error: "limit must be integers." });
return;
}
filteredMeals = filteredMeals.slice(0, limit);
}
response.send(filteredMeals);
} catch (error) {
response.status(500).send({ error: "Internal Server Error." });
}
})
module.exports = router;
|
// все просто! записываем в localStorage бибу)
localStorage.setItem('biba', 'biba')
// а тут получаем))
console.log(localStorage.getItem('biba')); |
import React from 'react';
import axios from 'axios';
import { Button, Form } from 'semantic-ui-react'
function UserForm() {
const [formState, setFormState] = React.useState({
name: '',
age: '',
salary: '',
hobby: '',
});
const changeHandler = (e) => {
console.log('e.target.name', e.target.name);
console.log('e.target.value', e.target.value);
setFormState((prevState) => ({
...prevState,
[e.target.name] : e.target.value
}))
}
const submitHandler = (e) => {
e.preventDefault();
console.log(formState);
// TODO: Update this to trigger straight to google sheets
const url = `https://sheet.best/api/sheets/${process.env.REACT_APP_GOOGLE_SHEET}`;
axios.post(url, formState)
.then((response) => {
console.log('Success posting', response);
})
.catch((error) => {
console.log('Error posting', error);
});
}
return (
<Form className="form" onSubmit={submitHandler}>
<Form.Field>
<label>Name</label>
<input
type="text"
placeholder='Enter your name'
name="name"
value={formState.name}
onChange={changeHandler} />
</Form.Field>
<Form.Field>
<label>Age</label>
<input
type="number"
placeholder='Enter your age'
name="age"
value={formState.age}
onChange={changeHandler} />
</Form.Field>
<Form.Field>
<label>Salary</label>
<input
type="number"
placeholder='Enter your salary'
name="salary"
value={formState.salary}
onChange={changeHandler} />
</Form.Field>
<Form.Field>
<label>Hobby</label>
<input
type="text"
placeholder='Enter your hobby'
name="hobby"
value={formState.hobby}
onChange={changeHandler} />
</Form.Field>
<Button color="blue" type='submit'>Submit</Button>
</Form>
)
}
export default UserForm;
|
// Libraries
import React from 'react';
import ReactDOM from 'react-dom';
import { ThemeProvider } from 'styled-components';
// Components | Utils
import UserContextProvider from './contexts/UserContext';
import App from './App';
// Assets
import './index.scss';
import { theme } from './globalStyles';
/* eslint-disable no-console */
console.log(
"%cHi, I'm Enes. Welcome to my project. You can find more at https://enesbaspinar.me. Oh by the way, feel free to look at my CV :)",
'background: #222; color: #bada55; padding: 4px;'
);
/* eslint-enable no-console */
ReactDOM.render(
<React.StrictMode>
<UserContextProvider>
<ThemeProvider theme={theme}>
<App />
</ThemeProvider>
</UserContextProvider>
</React.StrictMode>,
document.getElementById('root')
);
|
import { createAction } from "redux-actions";
export const CREATE_USER = "CREATE_USER";
export const createUser = createAction(CREATE_USER);
export const CREATE_USER_SUCCESS = "CREATE_USER_SUCCESS";
export const createUserSuccess = createAction(CREATE_USER_SUCCESS);
export const CREATE_USER_FAILED = "CREATE_USER_FAILED";
export const createUserFailed = createAction(CREATE_USER_FAILED);
export const CHECK_USER_AUTH = "CHECK_USER_AUTH";
export const checkUserAuth = createAction(CHECK_USER_AUTH);
export const SET_USER = "SET_USER";
export const setUser = createAction(SET_USER);
export const CLEAR_USER = "CLEAR_USER";
export const clearUser = createAction(CLEAR_USER);
export const DELETE_USER = "DELETE_USER";
export const deleteUser = createAction(DELETE_USER);
export const EDIT_PROFILE = "EDIT_PROFILE";
export const editProfile = createAction(EDIT_PROFILE);
export const UPDATE_USER_PROFILE = "UPDATE_USER_PROFILE";
export const updateUserProfile = createAction(UPDATE_USER_PROFILE);
const INITIAL_STATE = {
isLoading: false,
userCredential: null
};
const reducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case CREATE_USER: {
return {
...state,
isLoading: true
};
}
case CREATE_USER_SUCCESS: {
return {
...state,
isLoading: false
};
}
case CREATE_USER_FAILED: {
return {
...state
};
}
case CHECK_USER_AUTH: {
return {
...state
};
}
case SET_USER: {
const user = action.payload;
return {
...state,
isLoading: false,
userCredential: user
};
}
case CLEAR_USER: {
return {
...state,
userCredential: null
};
}
case DELETE_USER: {
return {
...state,
userCredential: null
};
}
case EDIT_PROFILE: {
return {
...state,
userCredential: null
};
}
case UPDATE_USER_PROFILE: {
return {
...state
};
}
default: {
return state;
}
}
};
export default reducer;
|
var x=8 % 2
var y=30 % 10
console.log(x)
console.log(y)
|
import test from 'tape'
import {h} from 'hastscript'
import {toHtml} from '../index.js'
test('`option` (closing)', (t) => {
t.deepEqual(
toHtml(h('option'), {omitOptionalTags: true}),
'<option>',
'should omit tag without parent'
)
t.deepEqual(
toHtml(h('select', h('option')), {omitOptionalTags: true}),
'<select><option></select>',
'should omit tag without following'
)
t.deepEqual(
toHtml(h('select', [h('option'), h('option')]), {omitOptionalTags: true}),
'<select><option><option></select>',
'should omit tag followed by `option`'
)
t.deepEqual(
toHtml(h('select', [h('option'), h('optgroup')]), {omitOptionalTags: true}),
'<select><option><optgroup></select>',
'should omit tag followed by `optgroup`'
)
t.deepEqual(
toHtml(h('select', [h('option'), h('p')]), {omitOptionalTags: true}),
'<select><option></option><p></select>',
'should not omit tag followed by others'
)
t.end()
})
|
import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import { Title, CategoriasButton, TextList, BackgroundApp } from './styled';
export default function Categorias() {
return (
<BackgroundApp>
<View>
<Title>Categorias</Title>
</View>
<CategoriasButton>
<TextList>Mercado</TextList>
</CategoriasButton>
<CategoriasButton>
<TextList>Celulares</TextList>
</CategoriasButton>
<CategoriasButton>
<TextList>Informática</TextList>
</CategoriasButton>
<CategoriasButton>
<TextList>Beleza e perfumaria</TextList>
</CategoriasButton>
<CategoriasButton>
<TextList>Tv, áudio e home theater</TextList>
</CategoriasButton>
<CategoriasButton>
<TextList>Eletrodoméstico e split</TextList>
</CategoriasButton>
<CategoriasButton>
<TextList>Eletroportáteis</TextList>
</CategoriasButton>
<CategoriasButton>
<TextList>Móveis e decoração</TextList>
</CategoriasButton>
<CategoriasButton>
<TextList>Brinquedos e bebês</TextList>
</CategoriasButton>
<CategoriasButton>
<TextList>Esporte e lazer</TextList>
</CategoriasButton>
<CategoriasButton>
<TextList>Livros</TextList>
</CategoriasButton>
<CategoriasButton>
<TextList>Papelaria</TextList>
</CategoriasButton>
<CategoriasButton>
<TextList>Petshop</TextList>
</CategoriasButton>
</BackgroundApp>
)
}
|
import models from "./../../models/index.js";
import { tools } from "./../../../tools/index.js";
import obj from "lodash";
export const resolvers = {
Query: {
getAllrecipes: async () => {
return await models.Recipes.find();
},
},
Mutation: {
addRecipe: async (_, { patient, doctor, treatment }) => {
const getPatient = await models.Users.findById({
_id: patient,
});
if (!obj.isEmpty(getPatient)) {
const getDoctor = await models.Users.findById({
_id: doctor,
});
if (!obj.isEmpty(getDoctor)) {
const newRecipes = await models.Recipes({
patient: getPatient._id,
doctor: getDoctor._id,
date: Date.now(),
treatment: treatment,
files: [],
});
if (await newRecipes.save()) {
await models.MedicalRecord.findOneAndUpdate(
{ patient: newRecipes.patient },
{ $push: { recipes: [newRecipes._id] } }
);
return newRecipes;
}
}
}
},
recipeAddFile: async (_, { file, ctx }) => {
const upload = await tools.fileHandler.uploadFile(file, ctx);
if (!obj.isEmpty(upload)) {
const newUpload = new models.Files({
type: upload.type,
filename: upload.filename,
mimeType: upload.mimetype,
path: upload.path,
});
if (await newUpload.save()) {
await models.Recipes.findOneAndUpdate(
{ _id: ctx.id },
{ $push: { files: [newUpload._id] } }
);
return newUpload;
}
}
},
},
Recipe: {
patient: async ({ patient }) => {
return await models.Users.findById(patient);
},
doctor: async ({ doctor }) => {
return await models.Users.findById(doctor);
},
files: async ({ files }) => {
return await models.Files.find({
_id: { $in: files },
});
},
},
};
|
for (let i = 0; i < 1; i++) {
console.log('Hello There!')
} |
/**
* Created by Adam on 2016-03-24.
*/
(function (){
"use strict";
angular.module('blog')
.controller('Home', Home);
function Home($scope, $http, $timeout, $routeParams, $route, $rootScope, $location){
var home = this;
home.restoreSession = function(){
console.log("restoring session.");
$http.get('api/user').success(function (data){
if(data.name){
console.log("session is restored!!");
$rootScope.authenticated = true;
$rootScope.username = data.principal.user.username;
$location.path('blog/' + $rootScope.username+ "/welcome");
$rootScope.editAllowed = true;
}else{
console.log("no session to restore");
$rootScope.authenticated = false;
$rootScope.editAllowed = false;
}
}).error(function(){
$rootScope.authenticated = false;
});
}
home.restoreSession();
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
if(next.params.username != undefined && $rootScope.authenticated != undefined && $rootScope.username != undefined){
console.log($rootScope.username + " " + next.params.username );
if($rootScope.authenticated){
if($rootScope.username == next.params.username ){
console.log("editAllowed became true!");
$rootScope.editAllowed = true;
}else{
console.log("editAllowed became false!");
$rootScope.editAllowed = false;
}
}
}
});
}
})();
|
var Util = require('../util');
var Base = require('../base');
/**
* a snap plugin for xscroll,wich support vertical and horizontal snap.
* @constructor
* @param {object} cfg
* @param {number} cfg.snapColIndex initial col index
* @param {number} cfg.snapRowIndex initial row index
* @param {number} cfg.snapDuration duration for snap animation
* @param {string} cfg.snapEasing easing for snap animation
* @param {number} cfg.snapOffsetLeft an offset from left boundry for snap wich default value is 0
* @param {number} cfg.snapOffsetTop an offset from top boundry for snap wich default value is 0
* @param {boolean} cfg.autoStep which step is based on scroll velocity
* @extends {Base}
*/
var Snap = function(cfg) {
Snap.superclass.constructor.call(this, cfg);
this.userConfig = Util.mix({
snapColIndex: 0,
snapRowIndex: 0,
snapDuration: 500,
snapEasing: "ease",
snapOffsetLeft: 0,
snapOffsetTop: 0,
autoStep: false //autostep
}, cfg);
}
Util.extend(Snap, Base, {
/**
* a pluginId
* @memberOf Snap
* @type {string}
*/
pluginId: "snap",
/**
* plugin initializer
* @memberOf Snap
* @override Base
* @return {Snap}
*/
pluginInitializer: function(xscroll) {
var self = this;
self.xscroll = xscroll.render();
self.snapColIndex = self.userConfig.snapColIndex;
self.snapRowIndex = self.userConfig.snapRowIndex;
prefix = self.userConfig.prefix;
self.render();
},
/**
* detroy the plugin
* @memberOf Snap
* @override Base
*/
pluginDestructor: function() {
var self = this;
var xscroll = self.xscroll;
xscroll.on("panend", xscroll._onpanend, xscroll);
xscroll.off("panend", self._snapAnimate, self);
delete self;
},
/**
* scroll to a col and row with animation
* @memberOf Snap
* @param {number} col col-index
* @param {number} row row-index
* @param {number} duration duration for animation ms
* @param {string} easing easing for animation
* @param {function} callback callback function after animation
* @return {Snap}
*/
snapTo: function(col, row, duration, easing, callback) {
this.snapToCol(col, duration, easing, callback);
this.snapToRow(row, duration, easing, callback);
return this;
},
/**
* scroll to a col with animation
* @memberOf Snap
* @param {number} col col-index
* @param {number} duration duration for animation ms
* @param {string} easing easing for animation
* @param {function} callback callback function after animation
* @return {Snap}
*/
snapToCol: function(col, duration, easing, callback) {
var self = this;
var userConfig = self.userConfig;
var duration = duration || userConfig.snapDuration;
var easing = easing || userConfig.snapEasing;
var snapWidth = userConfig.snapWidth;
var snapColsNum = userConfig.snapColsNum;
var snapOffsetLeft = userConfig.snapOffsetLeft;
col = col >= snapColsNum ? snapColsNum - 1 : col < 0 ? 0 : col;
self.snapColIndex = col;
var left = self.snapColIndex * snapWidth + snapOffsetLeft;
self.xscroll.scrollLeft(left, duration, easing, callback);
return self;
},
/**
* scroll to a row with animation
* @memberOf Snap
* @param {number} row row-index
* @param {number} duration duration for animation ms
* @param {string} easing easing for animation
* @param {function} callback callback function after animation
* @return {Snap}
*/
snapToRow: function(row, duration, easing, callback) {
var self = this;
var userConfig = self.userConfig;
var duration = duration || userConfig.snapDuration;
var easing = easing || userConfig.snapEasing;
var snapHeight = userConfig.snapHeight;
var snapRowsNum = userConfig.snapRowsNum;
var snapOffsetTop = userConfig.snapOffsetTop;
row = row >= snapRowsNum ? snapRowsNum - 1 : row < 0 ? 0 : row;
self.snapRowIndex = row;
var top = self.snapRowIndex * snapHeight + snapOffsetTop;
self.xscroll.scrollTop(top, duration, easing, callback);
return self;
},
/*
left => 2;
right => 4;
up => 8;
down => 16;
*/
_snapAnimate: function(e) {
var self = this;
var userConfig = self.userConfig;
var snapWidth = userConfig.snapWidth;
var snapHeight = userConfig.snapHeight;
self.xscroll.__topstart = null;
self.xscroll.__leftstart = null;
var cx = snapWidth / 2;
var cy = snapHeight / 2;
var direction = e.direction;
if (Math.abs(e.velocity) <= 0.2) {
var left = Math.abs(self.xscroll.getScrollLeft());
var top = Math.abs(self.xscroll.getScrollTop());
self.snapColIndex = Math.round(left / snapWidth);
self.snapRowIndex = Math.round(top / snapHeight);
self.snapTo(self.snapColIndex, self.snapRowIndex);
} else if (userConfig.autoStep) {
var transX = self.xscroll.computeScroll("x", e.velocityX);
var transY = self.xscroll.computeScroll("y", e.velocityY);
var snapColIndex = transX && transX.pos ? Math.round(transX.pos / snapWidth) : self.snapColIndex;
var snapRowIndex = transY && transY.pos ? Math.round(transY.pos / snapHeight) : self.snapRowIndex;
var duration = Math.ceil(transX && transX.duration, transY && transY.duration);
if (transX && transX.status == "inside") {
self.snapToCol(snapColIndex, duration, transX && transX.easing, function() {
self.xscroll.boundryCheckX();
});
} else if (transX) {
self.xscroll.scrollLeft(transX.pos, transX.duration, transX.easing, function() {
self.xscroll.boundryCheckX();
self.snapColIndex = Math.round(Math.abs(self.xscroll.getScrollLeft()) / snapWidth);
});
}
if (transY && transY.status == "inside") {
self.snapToRow(snapRowIndex, duration, transY && transY.easing, function() {
self.xscroll.boundryCheckY();
});
} else if (transY) {
self.xscroll.scrollTop(transY.pos, transY.duration, transY.easing, function() {
self.xscroll.boundryCheckY();
self.snapRowIndex = Math.round(Math.abs(self.xscroll.getScrollTop()) / snapHeight);
});
}
} else {
direction == 2 ? self.snapColIndex++ : direction == 4 ? self.snapColIndex-- : undefined;
direction == 8 ? self.snapRowIndex++ : direction == 16 ? self.snapRowIndex-- : undefined;
self.snapTo(self.snapColIndex, self.snapRowIndex);
}
},
/**
* render snap plugin
* @memberOf Snap
* @return {Snap}
*/
render: function() {
var self = this;
var xscroll = self.xscroll;
self.userConfig.snapWidth = self.userConfig.snapWidth || xscroll.width || 100;
self.userConfig.snapHeight = self.userConfig.snapHeight || xscroll.height || 100;
self.userConfig.snapColsNum = self.userConfig.snapColsNum || Math.max(Math.round(xscroll.containerWidth / xscroll.width), 1);
self.userConfig.snapRowsNum = self.userConfig.snapRowsNum || Math.max(Math.round(xscroll.containerHeight / xscroll.height), 1);
//remove default listener
xscroll.off("panend", xscroll._onpanend);
xscroll.on("panend", self._snapAnimate, self);
return self;
}
});
if (typeof module == 'object' && module.exports) {
module.exports = Snap;
} else if (window.XScroll && window.XScroll.Plugins) {
return XScroll.Plugins.Snap = Snap;
} |
import React, { useState, useContext } from "react";
import AccountCircleIcon from "@material-ui/icons/AccountCircle";
import { Link, NavLink } from "react-router-dom";
import { useHistory } from "react-router";
import { AuthContext } from "../../Context/AuthContext";
import "./Navbar.css";
export default function Navbar() {
const [flag, setFlag] = useState(false);
const { user } = useContext(AuthContext);
const history = useHistory();
function show() {
setFlag(!flag);
}
function hide() {
setFlag(false);
}
window.addEventListener("resize", function (event) {
if (window.innerWidth > 993) {
setFlag(false);
}
});
const handleLogOut = () => {
localStorage.removeItem("user");
history.push("/login");
window.location.reload();
};
return (
<div className="navbar">
<div className="navbar__login__separate__block">
<div className="signup" id="separate__signup">
<select className="dropdown" id="separate__dropdown">
<option>EUR</option>
<option>USD</option>
<option>GBP</option>
</select>
<AccountCircleIcon className="separate__icon" />
{user ? (
<Link
to="/logout"
style={{ textDecoration: `none`, color: "white" }}
>
<div className="no">
<h5 onClick={handleLogOut}>Logout</h5>
</div>
</Link>
) : (
<>
<Link
to="/login"
style={{ textDecoration: `none`, color: "white" }}
>
<div className="no">
<h5 onClick={hide}>Login</h5>
</div>
</Link>
<Link
to="/signup"
style={{ textDecoration: `none`, color: "white" }}
>
<h5 onClick={hide}>Sign Up</h5>
</Link>
</>
)}
</div>
</div>
<div className="mobile-menu-icon" id="#mobile-menu" onClick={show}>
<span></span>
<span></span>
<span></span>
</div>
<div className="navbar__block">
<div className="navbar__logo" onClick={hide}>
<Link to="/">
<img
className="logo__image"
src="https://www.quizando.com/assets/Quizando-Logo.png"
alt="logo"
/>
</Link>
</div>
<div className="navbar__right">
<ul className="nav__menu">
{[
{
link: "/quiz/fetch/live",
title: "Live",
},
{
link: "/quiz/fetch/classic",
title: "Classics",
},
{
link: "/quiz/fetch",
title: "Free Games",
},
].map((item, idx) => {
return (
<li>
<a key={idx} className="nav__links anchor" href={item.link}>
{item.title}
</a>
</li>
);
})}
</ul>
<div className="signup">
<select className="dropdown">
<option>EUR</option>
<option>USD</option>
<option>GBP</option>
</select>
<Link to="/profile">
<AccountCircleIcon className="signup__icon" />
</Link>
{user ? (
<h6 onClick={handleLogOut}>Logout</h6>
) : (
<>
<Link
to="/login"
style={{ textDecoration: `none`, color: "white" }}
>
<h6 onClick={hide}>Login</h6>
</Link>
<Link
to="/signup"
style={{ textDecoration: `none`, color: "white" }}
>
<h6 onClick={hide}>Sign Up</h6>
</Link>
</>
)}
</div>
</div>
</div>
<div
style={{ display: flag ? "flex" : "none" }}
className="vertical__navbar"
id="vertical__navbar_block"
>
{user ? (
""
) : (
<>
{" "}
<Link
to="/login"
style={{ textDecoration: `none`, color: "white" }}
>
<div className="vertical__login" onClick={hide}>
<img
alt=""
src="https://www.quizando.com/assets/nav_login_mobile.png"
/>
<h2>Login</h2>
</div>
</Link>
<Link
to="/signup"
style={{ textDecoration: `none`, color: "white" }}
>
<div className="vertical__createaccount" onClick={hide}>
<img
alt=""
src="https://www.quizando.com/assets/nav_reg_small.png"
/>
<h2>Create Account</h2>
</div>
</Link>
</>
)}
<div className="vertical__options">
<ul className="vertical__nav__menu">
<li className="menu__title">
<a href="#" style={{ color: "white" }}>
Quizzes
</a>
</li>
<li>
<img
alt=""
className="images__icons"
src="https://www.quizando.com/assets/live_quiz.png"
/>{" "}
<a href="#">Live Quizzes</a>
</li>
<li>
<img
alt=""
className="images__icons"
src="https://www.quizando.com/assets/classics_quiz.png"
/>
<a href="#">Classic Quizzes</a>
</li>
<li>
<img
alt=""
className="images__icons"
src="https://www.quizando.com/assets/notokens_quiz.png"
/>{" "}
<a href="#">Free Games</a>
</li>
<li>
<img
alt=""
src="https://www.quizando.com/assets/how_to_play.png"
/>{" "}
<a href="#">How to Play?</a>
</li>
<li>
<img alt="" src="https://www.quizando.com/assets/about.png" />{" "}
<a href="#">About</a>
</li>
<li>
<img alt="" src="https://www.quizando.com/assets/t_and_c.png" />{" "}
<a href="#">Terms & Conditions</a>
</li>
<li>
<img
alt=""
src="https://www.quizando.com/assets/contact_us.png"
/>{" "}
<a href="#">Contact us</a>
</li>
</ul>
</div>
</div>
</div>
);
}
|
import React from 'react';
import RadioInput from './RadioInput';
const SelectVehicle = ({
legend,
vehicles,
selectedPlanet,
selectedVehicle,
onChangeVehicle,
}) => {
const formatLabelText = (vehicle) => {
return `${vehicle.name} (${
selectedVehicle
? selectedVehicle.name === vehicle.name
? vehicle.total_no - 1
: vehicle.total_no
: vehicle.total_no
})`;
};
return (
<fieldset>
<legend className="col-form-label-lg">{legend}</legend>
{vehicles.map((vehicle) => (
<RadioInput
key={vehicle.name}
id={vehicle.name}
checked={
selectedVehicle ? selectedVehicle.name === vehicle.name : false
}
onChange={() => onChangeVehicle(vehicle)}
disabled={
vehicle.total_no === 0 ||
selectedPlanet.distance > vehicle.max_distance
}
labelText={formatLabelText(vehicle)}
/>
))}
</fieldset>
);
};
export default SelectVehicle;
|
console.log("hello console");
let cartIterate = document.querySelector(".cartIterate");
console.log(cartIterate);
let itemObj;
let cart = localStorage.getItem("cart");
if (cart == null) {
itemObj = [];
} else if (cart == "[]") {
cartIterate.innerHTML = "<h1 style=color:red; > No Item in Cart </h1>";
} else {
itemObj = JSON.parse(cart);
// console.log(itemObj.length);
let cartLength = document.querySelector(".cartLength");
// console.log(cartLength);
let cartitem = itemObj.length;
cartLength.innerHTML = cartitem;
iterateItem();
}
function iterateItem() {
// console.log(itemObj);
let html = "";
itemObj.forEach((element, index) => {
// console.log(element);
let vegiImg = element.vegiImg;
let vegiName = element.vegiName;
let vegiDelPrice = element.vegiDelPrice;
let vegiPrice = element.vegiPrice;
html += `<div class="box m-2 shadow p-3 mb-5 bg-body rounded">
<div class="img">
<img src=${vegiImg} style="width: 200px;" alt="">
</div>
<div class="info">
<h1>${vegiName}</h1>
<h2 class="price">Price: ₹ ${vegiPrice} per/Kg <span class="fs-5"> <del>₹${vegiDelPrice}</del></span> </h2>
<h2>Total: ₹<span class="total"> ${vegiPrice}</span> </h2>
<button class="btn btn-primary fs-3" id="${index}" onclick="deleteitem(this.id)">
Delete
</button>
</div>
</div>`;
cartIterate.innerHTML = html;
});
}
function deleteitem(index) {
console.log(index);
let itemObj;
let cart = localStorage.getItem("cart");
if (cart == null) {
itemObj = [];
} else {
itemObj = JSON.parse(cart);
console.log(itemObj);
}
itemObj.splice(index, 1);
localStorage.setItem("cart", JSON.stringify(itemObj));
console.log(itemObj);
iterateItem();
window.location.reload();
}
function costing() {
let itemObj;
let cart = localStorage.getItem("cart");
if (cart == null) {
itemObj = [];
} else {
itemObj = JSON.parse(cart);
}
let sum = 0;
let save = 0;
itemObj.forEach((element) => {
sum += element.vegiPrice;
save += element.vegiDelPrice;
});
let cost = document.getElementById("cost");
cost.innerHTML = sum;
let ship = parseInt(document.getElementById("ship").innerHTML);
console.log(ship);
let total = document.getElementById("total");
console.log(total);
total.innerHTML = sum + ship;
let saving = document.getElementById("saving");
saving.innerHTML = save - (sum + ship);
}
costing();
|
var readline = require('readline');
var utility = require('../Utility/utility.js');
var read = readline.createInterface({
input : process.stdin,
output : process.stdout
});
function quadratic()
{
read.question("Enter the value of a :", function(a){
read.question("Enter the value of b :", function(b){
read.question("Enter the value of c :", function(c){
utility.quadratic(a, b, c );
read.close();
})
})
})
}
quadratic(); |
import React from 'react';
var URLnetowrk = 'http://www.thevirtualpt.com:8080/pt_server/';
export default URLnetowrk; |
import Vue from 'vue';
import Router from 'vue-router';
import Profile from './views/Profile.vue';
import Login from './views/auth/Login.vue';
import Register from './views/auth/Register.vue';
import Notifications from './views/Notifications.vue';
import NotificationTemplates from './views/notifications/Templates.vue';
import NotificationStats from './views/notifications/Stats.vue';
import CreateNotification from './views/notifications/Create.vue';
import Page403 from './views/Page403.vue';
Vue.use(Router);
const router = new Router({
routes: [
{
path: '/',
name: 'Home',
component: NotificationStats,
},
{
path: '/login',
name: 'login',
component: Login,
meta: {
requiresAuth: false,
},
},
{
path: '/register',
name: 'register',
component: Register,
meta: {
requiresAuth: false,
},
},
{
path: '/profile',
name: 'profile',
component: Profile,
meta: {
requiresAuth: true,
},
},
{
path: '/403',
name: 'page403',
component: Page403,
},
{
path: '/notifications',
name: 'notifications',
component: Notifications,
children: [
{
path: 'stats',
name: 'notificationStats',
component: NotificationStats,
meta: {
requiresAuth: true,
requiresRead: true,
},
},
{
path: 'create',
name: 'createNotification',
component: CreateNotification,
meta: {
requiresAuth: true,
requiresRead: true,
},
},
{
path: 'templates',
name: 'notificationTemplates',
component: NotificationTemplates,
meta: {
requiresAuth: true,
requiresRead: true,
},
},
],
},
],
});
router.beforeEach((to, from, next) => {
if (to.name === 'page403' && from.name === null) {
next({
path: '/login',
});
}
const user = localStorage.getItem('USER') ? JSON.parse(localStorage.getItem('USER')) : '';
if (to.matched.some(record => record.meta.requiresAuth)) {
if (user) {
if (to.matched.some(record => record.meta.requiresRead)) {
if (user.rights && user.rights.indexOf('r') > -1
&& user.userType && user.userType.indexOf('dplusCRM') > -1) {
next();
} else {
next({
path: '/403',
});
}
} else if(to.matched.some(record => record.meta.requiresSpecialAdmin)) {
if (user.rights && user.rights.indexOf('r') > -1
&& user.userType && (user.userType.indexOf('specialAdmin') > -1 || user.userType.indexOf('dplusCRM') > -1)) {
next();
} else {
next({
path: '/403',
});
}
} else {
next();
}
} else {
next({
path: '/login',
});
}
} else {
next();
}
});
export default router;
|
export default {
'types': {
currentlyReading: {
id: "currentlyReading",
label: "Currently Reading",
},
wantToRead: {
id: "wantToRead",
label: "Want to Read",
},
read: {
id: "read",
label: "Reading",
},
}
} |
import React, { Component } from 'react'
import logo from './logo.svg'
import './App.css'
import { Dialog, Button, Intent, Popover } from '@blueprintjs/core'
class DialogTest extends React.Component {
state = {
isOpen: true
}
toggleDialog = () =>
this.setState({
isOpen: !this.state.isOpen
})
render() {
return (
<React.Fragment>
<Button text="Toggle Dialog" onClick={this.toggleDialog} />
<Dialog
icon="inbox"
isOpen={this.state.isOpen}
onClose={this.toggleDialog}
title="Dialog header"
>
<div className="pt-dialog-body">
<Popover>
<Button intent={Intent.PRIMARY}>Popover target</Button>
<div>
<h5>Popover title</h5>
<p>...</p>
<Button className="pt-popover-dismiss">Dismiss</Button>
</div>
</Popover>
</div>
<div className="pt-dialog-footer">
<div className="pt-dialog-footer-actions">
<Button text="Secondary" />
<Button
intent={Intent.PRIMARY}
onClick={this.toggleDialog}
text="Primary"
/>
</div>
</div>
</Dialog>
</React.Fragment>
)
}
}
class App extends Component {
render() {
return (
<div className="App">
<DialogTest />
</div>
)
}
}
export default App
|
'use strict';
(function (){
angular
.module("BookApp")
.controller("AdminController",AdminController);
function AdminController($scope,UserService){
$scope.selectedUserIndex = null;
$scope.updateUser = updateUser;
$scope.deleteUser = deleteUser;
$scope.selectUser = selectUser;
function init() {
getAllUsers();
}
init();
function getAllUsers(){
UserService.findAllUsers()
.then(
function(response){
$scope.users = response.data;
}
)
}
function updateUser(user){
UserService.updateUserById($scope.users[$scope.selectedUserIndex]._id, user)
.then(
function(response){
var updatedUser = response.data;
$scope.users[$scope.selectedUserIndex] = updatedUser;
$scope.selectedUserIndex = null;
$scope.newUser = {};
}
);
}
function deleteUser(index){
var username = $scope.users[index].username;
UserService.deleteUserById($scope.users[index]._id)
.then(
function(response){
console.log($scope.users);
$scope.users = response.data;
for( var i = 0; i < $scope.users.length ; i++ ){
//remove the deleted user from follower and following arrays of all users
removeFromFollowedList($scope.users[i],username);
}
});
}
function removeFromFollowedList (followedUser, deletedUsername) {
var followerArray = followedUser.followers;
var index = followerArray.indexOf(deletedUsername);
if(index > -1){
followerArray.splice(index,1);
}
var followingArray = followedUser.following;
index = followingArray.indexOf(deletedUsername);
if(index > -1){
followingArray.splice(index,1);
}
followedUser.followers = followerArray;
followedUser.following = followingArray;
UserService.
updateUserById(followedUser._id, followedUser)
.then(
function(doc) {
//do nothing
}
);
}
function selectUser(index){
$scope.selectedUserIndex = index;
$scope.newUser = {
//"_id" : $scope.users[index]._id,
"username" : $scope.users[index].username,
"password" : $scope.users[index].password,
"email" : $scope.users[index].email,
"role" : $scope.users[index].role
};
}
}
})(); |
define(['knockout', 'jquery'], function (ko, $) {
var messageBoxViewModel = {
Icon: ko.observable(''),
Message: ko.observable(''),
Type: ko.observable('hidden'),
ShowSuccess: function(message) {
this.Type("alert-success");
this.Icon("glyphicon-ok");
this.Message(message);
},
ShowError: function(message) {
this.Type("alert-danger");
this.Icon("glyphicon-remove");
this.Message(message);
},
ShowErrors: function(message, objFromServer) {
this.Type("alert-danger");
this.Icon("glyphicon-remove");
if (objFromServer != null && objFromServer.responseJSON.ValidationErrors != null) {
message = "<p>" + message + "</p><ul>";
ko.utils.arrayForEach(objFromServer.responseJSON.ValidationErrors, function(objError) {
message += ("<li>" + (objError.Row ? "[" + objError.Row + "] " : "") + objError.Property + " : " + objError.ErrorMessage + "</li>");
});
message += "</ul>";
} else if (objFromServer != null && objFromServer.responseJSON.ErrorMessage != null) {
message = message + " : " + objFromServer.responseJSON.ErrorMessage;
}
this.Message(message);
},
Hide: function() {
this.Type("hidden");
}
};
if ($("#messageBox").length) {
ko.applyBindings(messageBoxViewModel, $("#messageBox")[0]);
}
return messageBoxViewModel;
}); |
tunings = {
"2": [
{"notes": ['e','a'], "name": "Standard"},
{"notes": ['d','a'], "name": "Drop D"},
{"notes": ['eb','ab'], "name": "1/2 Step Down"},
{"notes": ['db','ab'], "name": "1/2 Step Drop Db"}
],
"3": [
{"notes": ['e','a','d'], "name": "Standard"},
{"notes": ['d','a','d'], "name": "Drop D"},
{"notes": ['eb','ab','db'], "name": "1/2 Step Down"},
{"notes": ['db','ab','db'], "name": "1/2 Step Drop Db"}
],
"4": [
{"notes": ['e','a','d','g'], "name": "Standard"},
{"notes": ['d','a','d','g'], "name": "Drop D"},
{"notes": ['eb','ab','db','gb'], "name": "1/2 Step Down"},
{"notes": ['db','ab','db','gb'], "name": "1/2 Step Drop Db"},
{"notes": ['c','g','d','a'], "name": "Cello/Viola"},
{"notes": ['g','d','a','e'], "name": "Mandolin/Violin"},
{"notes": ['g','c','e','a'], "name": "Ukulele"}
],
"5": [
{"notes": ['e','a','d','g','b'], "name": "5 String Standard"},
{"notes": ['d','a','d','g','b'], "name": "5 String Drop D"},
{"notes": ['eb','ab','db','gb','bb'], "name": "1/2 Step Down"},
{"notes": ['db','ab','db','gb','bb'], "name": "1/2 Step Drop Db"},
{"notes": ['b','e','a','d','g'], "name": "5 String Bass"},
{"notes": ['g','d','g','b','d'], "name": "5 String Banjo"},
{"notes": ['f','c','g','d','a'], "name": "5 String Cello Low"},
{"notes": ['c','g','d','a','e'], "name": "5 String Cello High"}
],
"6": [
{"notes": ['e','a','d','g','b','e'], "name": "Standard"},
{"notes": ['d','a','d','g','b','e'], "name": "Drop D"},
{"notes": ['eb','ab','db','gb','bb','eb'], "name": "1/2 Step Down"},
{"notes": ['db','ab','db','gb','bb','eb'], "name": "1/2 Step Drop Db"},
{"notes": ['b','e','a','d','f#','b'], "name": "Baritone"},
{"notes": ['a','e','a','d','f#','b'], "name": "Baritone Drop A"},
{"notes": ['f#','b','e','a','d','g'], "name": "6 String Bass Low"},
{"notes": ['b','e','a','d','g','c'], "name": "6 String Bass High"},
{"notes": ['f','c','g','d','a','e'], "name": "6 String Cello"}
],
"7": [
{"notes": ['b','e','a','d','g','b','e'], "name": "7 String Standard"},
{"notes": ['a','e','a','d','g','b','e'], "name": "7 String Drop A"},
{"notes": ['bb','eb','ab','db','gb','bb','eb'], "name": "1/2 Step Down"},
{"notes": ['ab','eb','ab','db','gb','bb','eb'], "name": "1/2 Step Drop Ab"},
{"notes": ['f#','b','e','a','d','f#','b'], "name": "7 String Baritone"},
{"notes": ['e','a','e','a','d','f#','b'], "name": "7 String Baritone Drop E"},
{"notes": ['e','a','d','g','b','e','a'], "name": "7 String High"}
],
"8": [
{"notes": ['f#','b','e','a','d','g','b','e'], "name": "8 String Standard"},
{"notes": ['e','b','e','a','d','g','b','e'], "name": "8 String Drop E"},
{"notes": ['f','bb','eb','ab','db','gb','bb','eb'], "name": "1/2 Step Down"},
{"notes": ['eb','bb','eb','ab','db','gb','bb','eb'], "name": "1/2 Step Drop Eb"},
{"notes": ['b','e','a','d','g','b','e','a'], "name": "8 String High"}
],
"9": [
{"notes": ['c#','f#','b','e','a','d','g','b','e'], "name": "9 String Standard"},
{"notes": ['b','e','b','e','a','d','g','b','e'], "name": "9 String Drop B"},
{"notes": ['c','f','bb','eb','ab','db','gb','bb','eb'], "name": "1/2 Step Down"},
{"notes": ['bb','f','bb','eb','ab','db','gb','bb','eb'], "name": "1/2 Step Drop Bb"}
],
"10": [
{"notes": ['g#','c#','f#','b','e','a','d','g','b','e'], "name": "10 String Standard"},
{"notes": ['f#','b','e','b','e','a','d','g','b','e'], "name": "10 String Drop F#"},
{"notes": ['g','c','f','bb','eb','ab','db','gb','bb','eb'], "name": "1/2 Step Down"},
{"notes": ['f','c','f','bb','eb','ab','db','gb','bb','eb'], "name": "1/2 Step Drop F"}
]
};
|
import setupHtmlToAmp from 'html-to-amp';
const htmlToAmp = setupHtmlToAmp();
const html = `
<p>beep booop</p>
// if width and/or height is missing of an image the width & height will be
// read from the image (since width & height is required in AMP)
<img src="http://example.com/image.jpg" />
// youtube, twitter, instagram, facebook, vine & custom embeds are
// (through html-to-article-json) supported
<blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr"><a href="https://t.co/kt1c5RWajI">https://t.co/kt1c5RWajI</a>’s <a href="https://twitter.com/david_bjorklund">@david_bjorklund</a> published 2 node modules to convert HTML snippets to <a href="https://twitter.com/AMPhtml">@amphtml</a><a href="https://t.co/yB5KMDijh6">https://t.co/yB5KMDijh6</a></p>— Malte Ubl (@cramforce) <a href="https://twitter.com/cramforce/status/697485294531145730">February 10, 2016</a></blockquote> <script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
`;
// can be used with callbacks
htmlToAmp(html, (err, amp) => {
if (err) {
throw err;
}
// do something with it
});
// when second argument is ommited a promise is returned
htmlToAmp(html).then(amp => {
// do something with it
});
|
const fs = require('fs');
const request = require("supertest");
const app = require("../src/backend/app");
const knex = require("../src/backend/database");
const testConcerts = require('./test_concerts');
const performanceDate = new Date().toISOString().replace('T', ' ').split('.')[0].replace('Z', '');
beforeAll(async done => {
process.env.NODE_ENV = "test";
await knex.migrate.latest();
await knex('concerts').truncate()
done()
});
beforeEach(async done => {
await knex.seed.run()
done()
});
afterEach(async done => {
await knex('concerts').truncate()
done()
});
describe(".env file", () => {
test("exists", () => {
let envFile = './.env';
expect(fs.existsSync(envFile)).toBeTruthy();
});
});
describe("GET /api/concerts", () => {
test("returns all concerts", async () => {
const response = await request(app).get("/api/concerts");
expect(response.statusCode).toBe(200);
expect(response.body).toMatchObject(testConcerts);
expect(Array.isArray(response.body)).toBeTruthy();
});
});
describe("GET /api/concerts?maxPrice=500", () => {
test("returns only concerts below 500", async () => {
const response = await request(app).get("/api/concerts?maxPrice=500");
expect(response.statusCode).toBe(200);
expect(response.body).toMatchObject([testConcerts[0]]);
expect(Array.isArray(response.body)).toBeTruthy();
});
});
describe("GET /api/concerts?band=metallica", () => {
test("returns concerts that only match the band name", async () => {
const response = await request(app).get("/api/concerts?maxPrice=500");
expect(response.statusCode).toBe(200);
expect(response.body).toMatchObject([testConcerts[0]]);
expect(Array.isArray(response.body)).toBeTruthy();
});
});
describe("GET /api/concerts?title=yonce%20in%20", () => {
test("returns concerts only that match title", async () => {
const response = await request(app).get("/api/concerts?title=yonce%20in%20");
expect(response.statusCode).toBe(200);
console.log(response.body);
expect(response.body).toMatchObject([testConcerts[1]]);
expect(Array.isArray(response.body)).toBeTruthy();
});
});
describe("GET /api/concerts?createdAfter=2000", () => {
test("returns concerts after 2020", async () => {
const response = await request(app).get("/api/concerts?createdAfter=2000");
expect(response.statusCode).toBe(200);
expect(response.body).toMatchObject(testConcerts.slice(0, 2));
expect(Array.isArray(response.body)).toBeTruthy();
});
});
describe("GET /api/concerts/<id>", () => {
test("returns the concert at ID specified in params", async () => {
const concertId = 2;
const expectedConcert = testConcerts.filter(
concert => concert.id === concertId)[0];
const response = await request(app).get(`/api/concerts/${concertId}`);
expect(response.statusCode).toBe(200);
expect(response.body).toMatchObject(expectedConcert);
expect(Array.isArray(response.body)).toBeFalsy();
});
});
describe("GET /api/concerts/<id>", () => {
test("returns 400 when concerts nonexistent ID requested", async () => {
const concertId = "blah";
const response = await request(app).get(`/api/concerts/${concertId}`);
expect(response.statusCode).toBe(404);
});
});
describe("POST /api/concerts", () => {
test("creates valid concert in database", async () => {
const band = 'Blackpink';
const concert = {
title: `${band} at Roskilde Festival`,
band: band,
venue: 'Roskilde Festival',
performance_date: performanceDate,
price: 1500,
};
const response = await request(app)
.post(`/api/concerts`)
.send(concert);
const createdConcert = await knex('concerts')
.where({ band: band });
expect(response.statusCode).toBe(201);
expect(createdConcert[0]).toMatchObject(concert);
});
});
describe("POST /api/concerts", () => {
test("returns 400 when body invalid", async () => {
const response = await request(app)
.post(`/api/concerts`)
.send(
{
title: "Invalid",
}
);
expect(response.statusCode).toBe(400);
});
});
describe("PUT /api/concerts/<id>", () => {
test("updates record when request is valid", async () => {
const band = 'Blackpink';
const newVenue = 'Store Vega';
const response = await request(app)
.post(`/api/concerts`)
.send(
{
title: `${band} at Roskilde Festival`,
band: band,
venue: 'Roskilde Festival',
performance_date: performanceDate,
price: 1500,
}
).then(createdConcert => {
const createdConcertId = createdConcert.body.id;
return request(app)
.put(`/api/concerts/${createdConcertId}`)
.send({ venue: newVenue });
});
expect(response.statusCode).toBe(201);
expect(response.body.venue).toBe(newVenue);
});
});
describe("PUT /api/concerts/<id>", () => {
test("does something", async () => {
const response = await request(app)
.post(`/api/concerts`)
.send(
{
title: 'Blackpink at Roskilde Festival',
band: 'Blackpink',
venue: 'Roskilde Festival',
performance_date: performanceDate,
price: 1500,
}
).then(createdConcert => {
const createdConcertId = createdConcert.body.id;
return request(app)
.put(`/api/concerts/${createdConcertId}`)
.send({ nonexistent: 'blah' });
});
expect(response.statusCode).toBe(400);
});
});
describe("DELETE /api/concerts/<id>", () => {
test("deletes record in database if it exists", async () => {
const band = 'Blackpink';
const concert = {
title: `${band} at Roskilde Festival`,
band: band,
venue: 'Roskilde Festival',
performance_date: performanceDate,
price: 1500,
};
const response = await request(app)
.post(`/api/concerts`)
.send(concert);
const createdId = response.body.id;
const deleteResponse = await request(app)
.delete(`/api/concerts/${createdId}`);
expect (deleteResponse.statusCode).toBe(204);
expect((await knex("concerts").where({ id: createdId })).length).toBe(0);
});
}); |
import React from 'react'
import Divider from 'material-ui/Divider'
import Paper from 'material-ui/Paper'
// components
import Table from '../../components/table/Table'
// styles
import baseStyles from '../../base/base.scss'
const SideBarContainer = () => {
return (
<Paper className={baseStyles.container} zDepth={2}>
<p>
<h2>Table</h2>
<p>
<small>
This table can replaced all the tables on the admin sites
</small>
</p>
<Divider />
<Table />
</p>
</Paper>
)
}
export default SideBarContainer
|
import React, { Component } from 'react';
import './student-form.scss';
export default class StudentForm extends Component {
state = {
id: null,
firstName: '',
lastName: '',
dofb: '',
grade: '',
isEditMode: false
}
updateState({id, firstName, lastName, dofb, grade}) {
if (this.state.id !== id) {
this.setState({
id,
firstName,
lastName,
dofb,
grade
})
}
return this.state;
}
onSubmit = (ev) => {
ev.preventDefault();
if (this.state.firstName.trim() === '' ||
this.state.lastName.trim() === '' ||
this.state.dofb.trim() === '') {
return true;
}
if (!this.state.isEditMode) {
this.props.onAddStudent(this.state);
} else {
this.props.onUpdateStudent(this.state);
}
this.setState({
id: null,
firstName: '',
lastName: '',
dofb: '',
grade: '',
})
}
formChangeHandler = (ev) => {
const prop = ev.target.name;
const val = ev.target.value;
this.setState({[prop]: val});
}
componentDidUpdate(prevProps) {
if (prevProps.selectedStudent !== this.props.selectedStudent) {
this.setState({
id: this.props.selectedStudent.id,
firstName: this.props.selectedStudent.firstName,
lastName: this.props.selectedStudent.lastName,
dofb: this.props.selectedStudent.dofb,
grade: this.props.selectedStudent.grade,
isEditMode: true
})
}
}
render() {
const { firstName, lastName, dofb, grade } = this.state;
return (
<form onSubmit={this.onSubmit}>
<div className="row">
<div className="col-6">
<div className="form-group">
<label htmlFor="fname">Имя</label>
<input type="text"
className="form-control"
id="fname"
name="firstName"
onChange={this.formChangeHandler}
value={firstName} />
</div>
</div>
<div className="col-6">
<div className="form-group">
<label htmlFor="lname">Фамилия</label>
<input type="text"
className="form-control"
id="lname"
name="lastName"
value={lastName}
onChange={this.formChangeHandler} />
</div>
</div>
</div>
<div className="row">
<div className="col-6">
<div className="form-group">
<label htmlFor="dofb">Дата рождения</label>
<input type="text"
className="form-control"
id="dofb"
name="dofb"
value={dofb}
onChange={this.formChangeHandler} />
</div>
</div>
<div className="col-6">
<div className="form-group">
<label htmlFor="grade">Успеваемость</label>
<select className="form-control"
id="grade"
name="grade"
value={ grade }
onChange={this.formChangeHandler}>
<option>Выбрать</option>
<option value="1">Неудовлетворительно</option>
<option value="2">Удовлетворительно</option>
<option value="3">Хорошо</option>
<option value="4">Отлично</option>
</select>
</div>
</div>
</div>
<div className="row">
<div className="col-12 btn-row">
<button type="submit" className="btn btn-lg btn-primary">Сохранить</button>
</div>
</div>
</form>
)
}
}
|
export default {
name: 'BookCard',
props: {
book: {type: Object}, // component book
},
data () {
return {
selectQuantity : false, // shows a modal to choose the number of books to add
quantity : 1, // variable that collects the number of books to add
prices : [], // stores all available book prices
chosenPrice : '' // the price chosen from the user
}
},
// when component is created gets all the available book prices from a given string
created: function () {
this.getsAllPrices()
},
methods: {
// event emitted to the parent to add a book to the cart
addBookToCart () {
this.selectQuantity = false
// eslint-disable-next-line no-useless-escape
// let regex = /\$((?:\d|\,)*\.?\d+)/g
this.$emit('bookToCart', this.book, this.quantity, this.chosenPrice)
this.quantity = 1
},
// activates selectQuantity property to display the quantity selection modal
quantitySelection () {
this.selectQuantity = true
},
// close the quantity selection modal
quantitySelected () {
this.selectQuantity = false
},
// sets the chosen quantity from the user to send it to the parent
setQuantity () {
this.quantity = this.$refs['book-quantity-select'].value
},
// increase quantity to send it to the parent
increaseQuantity () {
this.quantity += 1
},
// reduce quantity to send it to the parent
reduceQuantity () {
this.quantity = this.quantity < 2 ? 1 : this.quantity - 1
},
// gets the prices from the text and separes it when comes some books versions
getsAllPrices () {
this.prices = this.book.price.split("\n")
this.chosenPrice = this.prices[0]
},
// gets the price chosen by the user
selectPrice (price) {
this.chosenPrice = price
}
}
} |
/* The input will be a single string.
Find all special words starting with #. Word is invalid if it has anything other than letters. Print the words you found without the tag each on a new line.
1. Solve it your way first!
2. Create new array variable and .split(" ") into an array.
3. Create another new array, the value is the result of a .filter() method. The array you'll filter is the array of strings.
4. The condition for the filter should be if the indexOf("#"") is equal to zero. This means it starts with a #. Also check to make sure the length is more than 1. Don't want just a hashtag with no tag.
5. Open up a "for of" loop and console log each word from the filtered array.
*/
|
/*!
* siphash.js - siphash for bcoin
* Copyright (c) 2017, Christopher Jeffrey (MIT License).
*/
'use strict';
module.exports = require('./js/siphash');
|
/* USAGE */
/*
// Doesn't handle errors
get5minuteCandleSticks(1499990400000, 1516460405000, 'BTCUSDT').then((candlesticks) => {
console.log(candlesticks)
})
*/
import binance from 'node-binance-api'
// binance.options({
// 'APIKEY': process.env.BINANCEAPIKEY,
// 'APISECRET': process.env.BINANCEAPISECRET,
// 'test': true
// })
// returns an array of candlesticks
export const get5minuteCandleSticks = (startTime, endTime, symbol) => {
return new Promise((resolve, reject) => {
let timestampDifference = Math.abs(endTime - startTime)
// 2500 minutes
const INCREMENT = 150000000
let noOfRequiredRequests = Math.ceil(timestampDifference / INCREMENT)
let currentTime = startTime
let candlesticks = []
let callbacksDone = 0
for (let i = 1; i <= noOfRequiredRequests; i++) {
binance.candlesticks(symbol, '5m', (error, ticks, symbol) => {
// time, open, high, low, close, volume, closeTime, assetVolume, trades, buyBaseVolume, buyAssetVolume, ignored
if (!error) {
candlesticks = candlesticks.concat(ticks)
callbacksDone++
if (callbacksDone === noOfRequiredRequests) {
candlesticks = candlesticks.sort((a, b) => {
return a[0] - b[0]
})
resolve(candlesticks)
}
}
},
{
limit: 500,
startTime: currentTime,
endTime: currentTime + INCREMENT
})
currentTime = currentTime + INCREMENT
}
})
}
|
import styled from 'styled-components';
export default styled.button`
background-color: white;
border-radius: 4px;
border: 2px solid #ef4136;
margin-top: 10px;
padding: 10px 5px;
color: #ef4136;
width: 100%;
font-weight: bold;
` |
const { DataSource } = require('apollo-datasource');
const { Responses } = require('../utils/responses');
class Library extends DataSource {
initialize(config) {
this.db = config.context.db;
}
async findById(id) {
const result = await this.db.Library.findByPk(id);
return result;
}
async create(name) {
const result = await this.db.Library.create({
name,
});
return {
...Responses.success(),
library: result,
};
}
}
module.exports = {
Library,
};
|
import React from 'react';
import {SingleDayComponent} from "./SingleDayComponent";
import './styles/FiveDayComponent.css'
export const FiveDayComponent = ({fiveDayData}) => {
return (
<div className="five-day">
{fiveDayData.map((day, index) => {
return <SingleDayComponent
key={day.dayName}
data={day}
today = {index === 0? true: false}
/>
})}
</div>
)
} |
angular.module('dataCoffee').controller('editCategoria', editCategoria);
editCategoria.$inject = ['$scope', '$http', '$routeParams', '$rootScope', '$location'];
function editCategoria($scope, $http, $routeParams, $rootScope, $location) {
$scope.reset = function (){
$scope.name = '';
}
$scope.salvar = function() {
$scope.data = JSON.stringify({ id: $routeParams.obj, categoria : $scope.name });
$http({ method: 'POST', url: $rootScope.url.edit.categoria,
data: $scope.data,
headers: {'Content-Type': 'application/json; charset=utf-8'}
});
alertify.success("Atualizado com sucesso!");
$location.path('categoria/list');
}
$http({ method: 'GET', url: $rootScope.url.categoria + '?id=' + $routeParams.obj, headers: {'Content-Type': 'application/json; charset=utf-8'}
}).then(function success(response) {
$scope.categoria = response.data;
$scope.name = $scope.categoria.categoria;
}, function error(response) {
console.log(response.statusText);
});
} |
window.onload = function(){
createAutocomplete();
}
function createAutocomplete(){
var input = document.querySelector('.container > .wrapper > input'),
svg = document.querySelector(".container > .wrapper > .icon-select");
svg .style.display = "none";
svg.addEventListener("click", clear);
input.addEventListener("keyup",search, false);
}
function search(e){
var ul = document.querySelector('.container > .options > ul'),
svg = document.querySelector(".container > .wrapper > .icon-select");
svg.style.display = "block";
ul.style.height = "120px";
while (ul.firstChild) {
ul.removeChild(ul.firstChild);
}
for(var i = 0; i < country.length; i++){
if(country[i].includes(e.target.value)){
var li = document.createElement("li");
li.innerHTML = country[i];
li.addEventListener("click", chooseCity.bind(null, li));
ul.appendChild(li);
}
}
}
function chooseCity(element){
var ul = document.querySelector('.container > .options > ul'),
input = document.querySelector(".container > .wrapper > input"),
value = element.innerHTML;
ul.style.height = "0px";
input.value = value;
}
function clear(){
var input = document.querySelector(".container > .wrapper > input"),
ul = document.querySelector('.container > .options > ul');
ul.style.height = "0px";
input.value = '';
} |
// load q promise library
var q = require("q");
module.exports = function(db, mongoose) {
// load review schema
var ReviewSchema = require("./review.schema.server.js")(mongoose);
// create book model from schema
var ReviewModel = mongoose.model('ReviewModel', ReviewSchema);
var api = {
createReview: createReview,
findReviewsForUser: findReviewsForUser,
findReviewsForBook: findReviewsForBook,
deleteReviewById: deleteReviewById,
updateReviewById: updateReviewById
};
return api;
function createReview(review) {
var deferred = q.defer();
ReviewModel.create(review, function (err, doc) {
if (err) {
// reject promise if error
console.log("err: "+err);
deferred.reject(err);
} else {
// resolve promise
deferred.resolve(doc);
}
});
// return a promise
return deferred.promise;
}
function findReviewsForUser(userId) {
var deferred = q.defer();
ReviewModel.find(
{userId: userId},
function (err, doc) {
if (err) {
// reject promise if error
console.log("err: "+err);
deferred.reject(err);
} else {
// resolve promise
deferred.resolve(doc);
}
});
return deferred.promise;
}
function findReviewsForBook(bookId) {
var deferred = q.defer();
ReviewModel.find(
{googleBooksId: bookId},
null,
{sort: {dateAdded: -1}},
function (err, doc) {
if (err) {
// reject promise if error
console.log("err: "+err);
deferred.reject(err);
} else {
// resolve promise
deferred.resolve(doc);
}
});
return deferred.promise;
}
function deleteReviewById(reviewId) {
var deferred = q.defer();
// remove user with mongoose user model's remove()
ReviewModel.remove(
{_id: reviewId},
function(err, stats) {
if (err) {
// reject promise if error
deferred.reject(err);
} else {
// resolve promise
//deferred.resolve(findAllUsers());
deferred.resolve();
}
});
return deferred.promise;
}
function updateReviewById(reviewId, changedReview) {
var deferred = q.defer();
var newReview = {
googleBooksId: changedReview.googleBooksId,
username: changedReview.username,
comment: changedReview.comment,
dateAdded: changedReview.dateAdded
};
ReviewModel.update (
{_id: reviewId},
{$set: newReview},
function (err, stats) {
if(err) {
console.log("err: "+err);
deferred.reject(err);
}
else {
ReviewModel.findOne(
{_id: reviewId},
function (err, review) {
if(err) {
console.log("err: "+err);
deferred.reject(err);
}
else {
deferred.resolve(review);
}
});
}
});
return deferred.promise;
}
}; |
import {
hasFlag,
countries
} from '../index'
describe('exports/core', () => {
it('should export ES6', () => {
hasFlag.should.be.a('function')
countries.includes('RU').should.equal(true)
})
it('should export CommonJS', () => {
const Library = require('../index.commonjs')
Library.hasFlag.should.be.a('function')
Library.countries.includes('RU').should.equal(true)
})
}) |
const api = {
key: "c405b7757602550ec70ff322cd5812dc",
baseurl: "https://api.openweathermap.org/data/2.5/",
};
const searchBox = document.querySelector(".form-control");
const body = document.querySelector("body");
const forecast = document.querySelector(".forecast");
const footer = document.querySelector("footer");
let now = new Date();
searchBox.addEventListener("keypress", setQuery);
function setQuery(event) {
if (event.keyCode == 13) {
getData(searchBox.value);
searchBox.value = "";
}
}
function getData(query) {
fetch(`${api.baseurl}weather?q=${query}&units=metric&appid=${api.key}`)
.then((location) => location.json())
.then(getResult);
}
function getResult(location) {
let lon = location.coord.lon;
let lat = location.coord.lat;
let city = document.querySelector(".location .city");
city.innerHTML = `${location.name}, ${location.sys.country}`;
fetch(
`${api.baseurl}onecall?lat=${lat}&lon=${lon}&exclude=minutely,hourly&units=metric&APPID=${api.key}`
)
.then((location) => location.json())
.then(displayCurrentWeather);
}
function displayCurrentWeather(location) {
console.log(location);
if (location.current.weather[0].main == "Rain") {
body.classList.add("weather_rain");
} else {
body.classList.remove("weather_rain");
}
if (location.current.weather[0].main == "Clouds") {
body.classList.add("weather_clouds");
} else {
body.classList.remove("weather_clouds");
}
if (location.current.weather[0].main == "Clear") {
body.classList.add("weather_clear");
} else {
body.classList.remove("weather_clear");
}
if (location.current.weather[0].main == "Thunderstorm") {
body.classList.add("weather_thunderstorm");
} else {
body.classList.remove("weather_thunderstorm");
}
let dateTime = document.querySelector(".date-time");
dateTime.innerText = dateBuilder(now);
let bigTemp = document.querySelector(".big-temp");
bigTemp.innerHTML = `${Math.round(location.current.temp)}<span>°C</span>`;
let weatherDesc = document.querySelector(".weather");
weatherDesc.innerText = `${location.current.weather[0].main}`;
let feelsLike = document.querySelector(".feels-like-temp");
feelsLike.innerHTML = `Feels like <span class="feels-degrees">${Math.round(
location.current.feels_like
)}°C</span>`;
footer.innerHTML = `BKirilov Weather <span>©</span> 2020`;
displayForecast(location.daily);
}
function displayForecast(location) {
location.splice(5, 3);
forecast.innerHTML = "";
for (let i = 0; i < location.length; i++) {
createForecast(location[i], i + 1);
}
}
function createForecast(day, to_add) {
let days = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
let n = now.getDay() + to_add;
let name = n <= 6 ? days[n] : days[n - 7];
const item = document.createElement("div");
item.classList.add("day");
item.innerHTML = `<div class="name">${name}</div>
<div class="temp">${Math.round(day.temp.min)}° / ${Math.round(
day.temp.max
)}°</div>
<div class="weather-forecast">${day.weather[0].main}</div>`;
forecast.appendChild(item);
}
function dateBuilder(d) {
let months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
let days = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
let day = days[d.getDay()];
let date = d.getDate();
let month = months[d.getMonth()];
let year = d.getFullYear();
return `${day} ${date} ${month} ${year}`;
}
|
//Basic server setup that includes sessions and massive
//run npm install --save express body-parser express-session dotenv cors massive
const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
require('dotenv').config();
const cors = require('cors');// potentially not necessary
const massive = require('massive');
//Import High-Level Middleware that I created
const checkForSession = require('./middlewares/zample-checkForSession');
//Import Controllers I created that are used in Endpoints
const auth_controller = require('./controllers/zample-auth_controller')
const product_controller = require('./controllers/zample-product_controller');
const cart_controller = require('./controllers/zample-cart_controller');
// Instantiate express
const app = express();
// Instantiate massive MAKE SURE .env file has CONNECTION_STRING set to CORRECT Heroku postgress db uri
massive(process.env.CONNECTION_STRING).then( dbInstance => {
app.set('db',dbInstance);
//run quick test - create a table, add a record, then get test_table - then comment these out.
db.dbInstance.create_test_table().then( results => console.log(results) ).catch( err => console.log(err) );
db.dbInstance.add_test_item().then( results => console.log(results) ).catch( err => console.log(err) );
db.dbInstance.get_test().then( results => console.log(results) ).catch( err => console.log(err) );
db.dbInstance.put_test().then( results => console.log(results) ).catch( err => console.log(err) );
});//end of massive invoke
//Instantiate high-level middleware
app.use( bodyParser.json() );
app.use( session({
secret: process.env.SESSION_SECRET, //Check the .env file to make sure SESSION_SECRET is what you think
resave: false, //if they don't modify the session, don't save it
saveUninitialized: true //even if they don't initialize their store session with adding data, still want to keep the session in case they do add something.
}) );
app.use( checkForSession );
//Endpoints
app.get( '/api/product', zample-product_controller.read );
app.post( '/api/login', zample-auth_controller.login );
app.post( '/api/register', zample-auth_controller.register );
app.post( '/api/signout', zample-auth_controller.signout );
app.get( '/api/user', zample-auth_controller.getUser );
//Start server listening
const port = process.env.PORT || 3005
app.listen( port, () => { console.log(`Server listening on port ${port}.`); } ); |
const Sequelize = require("sequelize");
const DbConnection = require('./db-connection');
const dbHost = process.env.DB_HOST;
const dbPort = process.env.DB_PORT;
const dbName = process.env.DB_NAME;
const dbUser = process.env.DB_USER;
const dbPass = process.env.DB_PASSWORD;
const _connectDB = () => {
return new Sequelize(dbName, dbUser, dbPass, {
host: dbHost,
dialect: "mysql",
port: dbPort
});
}
const connect = () => {
return new Promise((resolve, reject) => {
const sequelize = _connectDB();
sequelize
.authenticate()
.then(() => {
console.dir("Authentication successfully.");
resolve(new DbConnection(sequelize));
})
.catch(err => {
reject(new Error(err));
});
});
};
let connection = null;
const getConnection = () => {
return new Promise((resolve, reject) => {
if (!connection) {
console.log("No connection defined. Connect to DB");
connect()
.then(dbConnection => {
connection = dbConnection;
console.dir("Connection has been established successfully.");
resolve(connection);
})
.catch(err => {
console.error("Unable to connect to the database:", err);
reject(err);
});
} else {
console.log("Connection defined. Reuse existing connection");
resolve(connection);
}
});
};
module.exports = { getConnection };
|
import React from "react";
import {
BrowserRouter as Router,
Route,
Link,
Redirect,
withRouter
} from "react-router-dom";
const fakeAuth = {
isLogin: false,
authenticate(fn) {
this.isLogin = true;
setTimeout(fn, 100)// fake async
},
signout(fn) {
this.isLogin = false;
setTimeout(fn, 100)
}
}
function AuthExample() {
return (
<Router>
<div>
<AuthLogin></AuthLogin>
<ul>
<li><Link to="/entrance1">通用入口</Link></li>
<li><Link to="/entrance2" >需要登陆才能进入的入口</Link></li>
</ul>
<Route path="/entrance1" component={CommonEntrance}></Route>
<CaseRoute path="/entrance2" component={VipEntrance}></CaseRoute>
<Route path="/login" component={Login}></Route>
</div>
</Router>
)
}
const AuthLogin = withRouter( ({history}) =>
fakeAuth.isLogin ? (
<p>Welcome!
<button onClick={() => {
fakeAuth.signout(() => history.push("/"))
}}>Sign out</button>
</p>
) : <p>暂未登陆</p>
)
function CommonEntrance() {
return (
<p>通用入口</p>
)
}
function VipEntrance() {
return (
<p>会员功能</p>
)
}
function TouristEntrance() {
return (
<p>游客功能</p>
)
}
function CaseRoute({component: Component, ...rest}) {
return <Route {...rest} render={props => {
if(fakeAuth.isLogin){
return <Component></Component>
}else{
return <Redirect to={{
pathname: '/login',
state: {from: props.match.url}
}}></Redirect>
}
}}>
</Route>
}
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
isLogin: false
}
}
login = () => {
fakeAuth.authenticate(() => {
this.setState(
{isLogin: true}
)
})
}
render() {
let isLogin = this.state.isLogin
if(isLogin){
return <Redirect to={this.props.location.state.from}></Redirect>
}
return <p>你需要先登陆! <button onClick={this.login}> log in</button></p>
}
}
export default AuthExample |
"use strict";
var requireShared = require.main.exports.requireShared;
const modPath = require("path"),
modUrl = require("url");
const modUtils = requireShared("utils");
exports.init = function (config)
{
require.main.exports.registerService("res", new Service(config));
};
function Service(config)
{
//var m_resourceRoot = modPath.join(require.main.exports.serverHome(), "res");
var m_resourceMap = { };
this.setResourceMap = function (map)
{
m_resourceMap = map;
};
this.handleRequest = function (request, response, userContext, shares, callback)
{
var urlObj = modUrl.parse(request.url, true);
var res = urlObj.pathname.substr(7);
for (var prefix in m_resourceMap)
{
if (res.startsWith(prefix + "/"))
{
var targetFile = modPath.normalize(m_resourceMap[prefix] + res.substr(res.indexOf("/")));
if (targetFile.startsWith(m_resourceMap[prefix]))
{
modUtils.getFile(response, targetFile);
}
else
{
response.writeHeadLogged(403, "Forbidden");
response.end();
}
callback();
return;
}
}
response.writeHeadLogged(404, "Not found");
response.end();
callback();
};
}
|
import React from 'react';
import { Text, Image, TouchableOpacity, View, StyleSheet, } from 'react-native';
import { colors, fonts, globalStyles } from '../styles/gobalStyles'
//accpets a climber object that contains name, pic, totalPoints, and totalFeet
export function ClimberWidget( { climber }) {
const activeClimber = climber;
if(activeClimber){
return (
<View style={globalStyles.widget}>
<TouchableOpacity style={styles.container}>
<Image style={styles.img} source={climber.picUri ? {uri: climber.picUri} : require('../assets/climbs.png')}/>
<View style={styles.name}>
<Text style={globalStyles.h2}>{climber.name}</Text>
<View style={styles.info}>
<Text style={styles.text}>{climber.totalPoints} Total Points</Text>
<Text style={styles.text}>{climber.totalHeight}' Climbed</Text>
</View>
</View>
</TouchableOpacity>
</View>
);
}else{
return(
<View style={globalStyles.widget}>
<TouchableOpacity style={styles.container}>
<Image style={styles.img} source={require('../assets/climbs.png')}/>
<View style={styles.name}>
<Text style={globalStyles.h2}>No Climber Selected</Text>
</View>
</TouchableOpacity>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
},
img: {
width: 70,
height: 70,
borderRadius: 35,
margin: 3,
},
name: {
flex: 1,
margin: 5,
},
info: {
flexDirection: 'row',
},
text:{
marginTop: 3,
marginRight: 15,
color: colors.white,
fontFamily: fonts.bodyFont
}
}); |
/**
* Draws a line based on a single action.
*/
export default (ctx, action) => {
// Start line
ctx.beginPath();
ctx.lineCap = action.brushType;
ctx.lineWidth = action.brushSize;
ctx.strokeStyle = action.color;
// Plot every movement of the line
for (let i = 1; i < action.path.length; i++) {
ctx.moveTo(action.path[i - 1].x, action.path[i - 1].y);
ctx.lineTo(action.path[i].x, action.path[i].y);
}
// Draw the line
ctx.stroke();
}
|
const express = require("express");
const router = express.Router();
const {
addOrderController,
allOrderController,
getUserOrders,
updateStatus,
pendingOrderController,
updateFeedbackController,
updateRefundController,
} = require("../controllers/order");
const { authenticated } = require("../middlewares/authenticate");
//!!delete order will be added later
//@route -- POST api/order/add-order
//@desc -- adding an order
//@access -- public
router.post("/add-order", authenticated, addOrderController);
//@route -- POST api/order/all-orders
//@desc -- view all orders
//@access -- public
router.get("/all-orders", allOrderController);
router.get("/pending-orders", pendingOrderController);
router.get("/user-orders", authenticated, getUserOrders);
router.post("/update-status/:status/:id", updateStatus);
router.post("/update-feedback/:id", updateFeedbackController);
router.post("/update-refund/:id", updateRefundController);
module.exports = router;
|
const superagent = require("superagent"); //发送网络请求获取DOM
const cheerio = require("cheerio"); //能够像Jquery一样方便获取DOM节点
const nodemailer = require("nodemailer"); //发送邮件的node插件
const ejs = require("ejs"); //ejs模版引擎
const fs = require("fs"); //文件读写
const path = require("path"); //路径配置
const schedule = require("node-schedule"); //定时器任务库
//配置项
// Git https://github.com/Vincedream/NodeMail 可作参考
//纪念日
let startDay = "2018/5/12";
//当地拼音,需要在下面的墨迹天气url确认
const local = "hunan/changsha";
//发送者邮箱厂家
let EmianService = "qq";
//发送者邮箱账户SMTP授权码
let EamilAuth = {
user: "1397467062@qq.com",
pass: "tvaqhdugsjlihebf"
};
//发送者昵称与邮箱地址
let EmailFrom = '"酱酱的爱" <1397467062@qq.com>';
//接收者邮箱地
let EmailTo = "1624105525@qq.com";
//邮件主题
let EmailSubject = "一封暖暖的小邮件";
//每日发送时间
let EmailHour = 06;
let EmialMinminute= 30;
// 爬取数据的url
const OneUrl = "http://wufazhuce.com/";
const WeatherUrl = "https://tianqi.moji.com/weather/china/" + local;
// 获取ONE内容
function getOneData(){
let p = new Promise(function(resolve,reject){
superagent.get(OneUrl).end(function(err, res) {
if (err) {
reject(err);
}
let $ = cheerio.load(res.text);
let selectItem = $("#carousel-one .carousel-inner .item");
let todayOne = selectItem[0];
let todayOneData = {
imgUrl: $(todayOne)
.find(".fp-one-imagen")
.attr("src"),
type: $(todayOne)
.find(".fp-one-imagen-footer")
.text()
.replace(/(^\s*)|(\s*$)/g, ""),
text: $(todayOne)
.find(".fp-one-cita")
.text()
.replace(/(^\s*)|(\s*$)/g, "")
};
resolve(todayOneData)
});
})
return p
}
// 获取天气提醒
function getWeatherTips(){
let p = new Promise(function(resolve,reject){
superagent.get(WeatherUrl).end(function(err, res) {
if (err) {
reject(err);
}
let threeDaysData = [];
let weatherTip = "";
let $ = cheerio.load(res.text);
$(".wea_tips").each(function(i, elem) {
weatherTip = $(elem)
.find("em")
.text();
});
resolve(weatherTip)
});
})
return p
}
// 获取天气预报
function getWeatherData(){
let p = new Promise(function(resolve,reject){
superagent.get(WeatherUrl).end(function(err, res) {
if (err) {
reject(err);
}
let threeDaysData = [];
let weatherTip = "";
let $ = cheerio.load(res.text);
$(".forecast .days").each(function(i, elem) {
const SingleDay = $(elem).find("li");
threeDaysData.push({
Day: $(SingleDay[0])
.text()
.replace(/(^\s*)|(\s*$)/g, ""),
WeatherImgUrl: $(SingleDay[1])
.find("img")
.attr("src"),
WeatherText: $(SingleDay[1])
.text()
.replace(/(^\s*)|(\s*$)/g, ""),
Temperature: $(SingleDay[2])
.text()
.replace(/(^\s*)|(\s*$)/g, ""),
WindDirection: $(SingleDay[3])
.find("em")
.text()
.replace(/(^\s*)|(\s*$)/g, ""),
WindLevel: $(SingleDay[3])
.find("b")
.text()
.replace(/(^\s*)|(\s*$)/g, ""),
Pollution: $(SingleDay[4])
.text()
.replace(/(^\s*)|(\s*$)/g, ""),
PollutionLevel: $(SingleDay[4])
.find("strong")
.attr("class")
});
});
resolve(threeDaysData)
});
});
return p
}
// 发动邮件
function sendMail(HtmlData) {
const template = ejs.compile(
fs.readFileSync(path.resolve(__dirname, "email.ejs"), "utf8")
);
const html = template(HtmlData);
let transporter = nodemailer.createTransport({
service: EmianService,
port: 465,
secureConnection: true,
auth: EamilAuth
});
let mailOptions = {
from: EmailFrom,
to: EmailTo,
subject: EmailSubject,
html: html
};
transporter.sendMail(mailOptions, (error, info={}) => {
if (error) {
console.log(error);
sendMail(HtmlData); //再次发送
}
console.log("邮件发送成功", info.messageId);
console.log("静等下一次发送");
});
}
// 聚合
function getAllDataAndSendMail(){
let HtmlData = {};
// how long with
let today = new Date();
console.log(today)
let initDay = new Date(startDay);
let lastDay = Math.floor((today - initDay) / 1000 / 60 / 60 / 24);
let todaystr =
today.getFullYear() +
" / " +
(today.getMonth() + 1) +
" / " +
today.getDate();
HtmlData["lastDay"] = lastDay;
HtmlData["todaystr"] = todaystr;
Promise.all([getOneData(),getWeatherTips(),getWeatherData()]).then(
function(data){
HtmlData["todayOneData"] = data[0];
HtmlData["weatherTip"] = data[1];
HtmlData["threeDaysData"] = data[2];
sendMail(HtmlData)
}
).catch(function(err){
getAllDataAndSendMail() //再次获取
console.log('获取数据失败: ',err);
})
}
let rule = new schedule.RecurrenceRule();
rule.dayOfWeek = [0, new schedule.Range(1, 6)];
rule.hour = EmailHour;
rule.minute = EmialMinminute;
console.log('NodeMail: 开始等待目标时刻...')
let j = schedule.scheduleJob(rule, function() {
console.log("执行任务");
getAllDataAndSendMail();
});
|
let clicked = null;
// let comments = [];
comments = localStorage.getItem('comments') ? JSON.parse(localStorage.getItem('comments')) : [];
setComment();
function toggleMenu() {
console.log(document.getElementById("primaryNav").classList);
document.getElementById("primaryNav").classList.toggle("hide");
};
const addNewComment = document.getElementById('openComments');
const newCommentModal = document.getElementById('newComment');
const deleteCommentModal = document.getElementById('deleteComment');
let commentTitle = document.getElementById('commentTitle');
console.log(comments);
//Display the comments
function setComment() {
if (comments.length > 0) {
let commentList = document.querySelector('#commentList');
commentList.innerHTML = '';
comments.forEach( comment => {
commentList.innerHTML += `<li>${comment.title}</li>`;
}
);
}
}
function saveComment() {
if (commentTitle.value) {
commentTitle.classList.remove('error');
let commentText = document.querySelector("#commentTitle").value;
comments.push({
comment: Date.now(),
title: commentTitle.value,
});
localStorage.setItem('comments', JSON.stringify(comments));
setComment();
// closeComment();
} else {
commentTitle.classList.add('error');
}
}
function deleteComment() { //probably pass on comments from sveComment()
comments = comments.filter(e => e.comment !== clicked);
localStorage.setItem('comments', JSON.stringify(comments));
comments = [];
setComment();
}
function initButtons() {
document.getElementById('saveButton').addEventListener('click', saveComment);
document.getElementById('deleteButton').addEventListener('click', deleteComment);
}
initButtons();
// load(); |
import styled from "styled-components";
import Footer from "../Footer/Footer";
import Header from "../Header/Header";
import Container from "../shared/Container";
import { FaCheck } from "react-icons/fa"
import UserContext from "../../contexts/UserContext";
import HabitsContext from "../../contexts/HabitsContext";
import { useContext, useEffect } from "react";
import { getTodayHabits, markHabitAsDone, markHabitAsUndone } from "../../services/trackit";
import { useState } from "react/cjs/react.development";
import dayjs from "dayjs";
export default function Today() {
const { loggedUser } = useContext(UserContext);
const { habitCompletionProgress, setHabitCompletionProgress } = useContext(HabitsContext);
const [todayHabits, setTodayHabits] = useState([]);
useEffect(() => {
updateTodayHabits();
}, []);
useEffect(() => {
if (todayHabits.length > 0) {
updateHabitCompletionProgress();
}
}, [todayHabits]);
function updateTodayHabits() {
getTodayHabits(loggedUser.token)
.then((resp) => {
setTodayHabits(resp.data);
});
}
function updateHabitCompletionProgress() {
const todayHabitsDone = todayHabits.filter(habit => habit.done);
setHabitCompletionProgress((todayHabitsDone.length / todayHabits.length * 100).toFixed(0));
}
function getToday() {
require("dayjs/locale/pt-br");
const today = dayjs().locale('pt-br');
return today;
}
function clickHabit(habit, index) {
const tmpTodayHabits = [...todayHabits];
if (!habit.done) {
markHabitAsDone(loggedUser.token, habit.id)
.then(() => updateTodayHabits())
.catch(() => updateTodayHabits());
tmpTodayHabits[index].done = true;
setTodayHabits(tmpTodayHabits);
} else {
markHabitAsUndone(loggedUser.token, habit.id)
.then(() => updateTodayHabits())
.catch(() => updateTodayHabits());
tmpTodayHabits[index].done = false;
setTodayHabits(tmpTodayHabits);
}
}
return (
<>
<Header />
<Container>
<h1>{getToday().locale('pt-br').format("dddd[, ]DD/MM")}</h1>
<h2>{habitCompletionProgress ? `${habitCompletionProgress}% dos hábitos concluídos` : "Nenhum hábito concluído ainda"}</h2>
<ul>
{todayHabits.length > 0 ? todayHabits.map((habit, index) => (
<TodayHabit key={habit.id}
isDone={habit.done}>
<Description>
<h1>{habit.name}</h1>
<p>{"Sequência atual: "}
<CurrentSequence isDone={habit.done}>
{habit.currentSequence} dias
</CurrentSequence></p>
<p>{"Seu recorde: "}
<HighestSequence
brokeRecorde={habit.currentSequence >= habit.highestSequence
&& habit.currentSequence > 0 ? true : false}>
{habit.highestSequence}
</HighestSequence> dias</p>
</Description>
<CheckButton
isDone={habit.done}
onClick={() => clickHabit(habit, index)}>
<FaCheck />
</CheckButton>
</TodayHabit>
)) : "Nenhum hábito pra hoje!"
}
</ul>
</Container>
<Footer />
</>
);
}
const TodayHabit = styled.li`
background: #FFFFFF;
border-radius: 5px;
width: 100%;
height: 94px;
margin-bottom: 10px;
padding: 13px 15px;
display: flex;
justify-content: space-between;
h1 {
font-size: 20px;
color: #666666;
margin-bottom: 7px;
}
h2 {
margin: 0;
}
p {
font-size: 13px;
margin: 0;
}
`
const Description = styled.div`
`
const CurrentSequence = styled.span`
color: ${props => props.isDone ? "#8FC549" : "inherit"};
`
const HighestSequence = styled.span`
color: ${props => props.brokeRecorde ? "#8FC549" : "inherit"};
`
const CheckButton = styled.button`
width: 69px;
height: 69px;
border: none;
border-radius: 5px;
background-color: ${props => props.isDone ? "#8FC549" : "#EBEBEB"};
font-size: 35px;
color: #FFFFFF;
display: flex;
align-items: center;
justify-content: center;
` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.