text
stringlengths 7
3.69M
|
|---|
import React from 'react';
import '../styles/App.css';
import '../styles/experience.css';
import ReactDOM from 'react-dom';
import {SAS} from './sas.js';
import {TownOf} from './toch.js';
export class Experience extends React.Component {
renderSAS() {
ReactDOM.unmountComponentAtNode(document.getElementById('d-section'));
ReactDOM.render(<SAS/>, document.getElementById('d-section'));
}
renderTownOf() {
ReactDOM.unmountComponentAtNode(document.getElementById('d-section'));
ReactDOM.render(<TownOf/>, document.getElementById('d-section'));
}
render() {
return (
<React.Fragment>
<h2 id="h-experience">Select a tile to learn more about my experience </h2>
<div id="tile-holder">
<div id="d-tile-ex" onClick={this.renderSAS}>
<p id="ex-tile">Software Development Intern</p>
<p>SAS Institute </p>
<p>Cary, NC</p>
<p> Summer 2019-Present</p>
</div>
<div id="d-tile-ex-toch" onClick={this.renderTownOf}>
<p id="ex-tile">Technology Solutions Intern</p>
<p>Town of Chapel Hill</p>
<p >Chapel Hill, NC</p>
<p> Summer 2018</p>
</div>
</div>
</React.Fragment>
);
}
}
|
/**
* LINKURIOUS CONFIDENTIAL
* Copyright Linkurious SAS 2012 - 2018
*
* - Created on 2014-11-26.
*/
'use strict';
// Codes and/or names should identify any status unically
// Codes are inspired from http codes:
// - 1** : Processing / information
// - 2** : Ok
// - 4** : backend external error
// - 5** : backend related error
// services
const LKE = require('../index');
const Config = LKE.getConfig();
const STATUSES = {
Linkurious: [
{
code: 100,
name: 'starting',
message: 'Starting Linkurious in ' + Config.mode + ' mode...'
},
{
code: 200,
name: 'initialized',
message: 'Linkurious ready to go :)'
},
{
code: 400,
name: 'error',
message: 'Some components of Linkurious are not working properly.'
},
{
code: 500,
name: 'unknown_error',
message: 'Linkurious encountered an unexpected error.'
}
],
SqlDB: [
{
code: 100,
name: 'starting',
message: 'Starting SQL database'
},
{
code: 101,
name: 'up',
message: 'The SQL database is up.'
},
{
code: 200,
name: 'synced',
message: 'The SQL database is synced.'
},
{
code: 401,
name: 'down',
message: 'Could not connect to the SQL database.'
},
{
code: 402,
name: 'sync_error',
message: 'We could not write to the SQL database, please check its status and configuration'
}
],
DataService: [
{
code: 100,
name: 'starting',
message: 'Starting data service.'
},
{
code: 200,
name: 'up',
message: 'Data-sources ready.'
},
{
code: 201,
name: 'indexing',
message: 'A data-source is currently indexing.'
},
{
code: 401,
name: 'down',
message: 'Could not connect to any data-source.'
}
],
WebServer: [
{
code: 100,
name: 'starting',
message: 'Starting Web Server'
},
{
code: 200,
name: 'ready',
message: 'The Web Server ready.'
},
{
code: 400,
name: 'error',
message: 'The Web Server could not start.'
},
{
code: 401,
name: 'port_busy',
message: 'The Web Server could not start: the port is busy.'
},
{
code: 403,
name: 'port_restricted',
message:
'The Web Server could not start: root access is required to listen to ports under 1024'
}
]
};
module.exports = STATUSES;
|
const isFetchingAverageSelector = state => state.reputation.isFetchingAverage;
const isFetchingUsersCalificationsSelector = state => state.reputation.isFetchingUsersCalifications;
const averageSelector = state => state.reputation.average;
const calificationsSelector = state => state.reputation.califications;
export const Selectors = {
isFetchingAverageSelector,
isFetchingUsersCalificationsSelector,
averageSelector,
calificationsSelector
};
|
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { Strip, StripGeometry, StripHelper, UvPreset } from '../../build/three-strip.js'
import { Pane } from '//cdn.skypack.dev/tweakpane@3.0.5?min'
const renderer = new THREE.WebGLRenderer();
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, 2, .1, 100);
const controls = new OrbitControls(camera, renderer.domElement);
scene.background = new THREE.Color('white');
controls.target.set(0, 2, 0);
camera.position.set(0, 2, 3);
controls.enableDamping = true;
scene.add(new THREE.GridHelper());
// ----
// params
// ----
const uvFns = {
0: UvPreset.strip[0],
1: UvPreset.strip[1],
2: UvPreset.strip[2],
3: UvPreset.strip[3],
4: UvPreset.dash[0],
5: UvPreset.dash[1],
6: UvPreset.dash[2],
7: UvPreset.dash[3],
};
const params = {
twist: 0,
taper: 0,
nSeg: 50,
useDash: true,
dashArray: '5,1,2',
dashOffset: 0,
uvFnsIdx: 0,
};
// ----
// Curve
// ----
const curve = new THREE.LineCurve3(
new THREE.Vector3(0, 0, 0),
new THREE.Vector3(0, 4, 0)
);
// ----
// Mesh
// ----
const { geom, strip } = make(params);
const map = new THREE.TextureLoader().load('../img/a.jpg');
const mat = new THREE.MeshBasicMaterial({ side: THREE.DoubleSide, map });
const mesh = new THREE.Mesh(geom, mat);
scene.add(mesh);
// ----
// StripHelper
// ----
const helper = new StripHelper(strip, params.nSeg, .2);
helper.material.depthTest = false;
scene.add(helper);
// ----
// Strip and StripGeometry
// ----
function make(params) {
const strip = new Strip(
curve,
(i, I) => 1 - i / I * params.taper,
(i, I) => i / I * params.twist + Math.PI / 2
);
const par1 = params.useDash
? [
params.nSeg,
params.dashArray.split(',').map(Number.parseFloat),
params.dashOffset
]
: params.nSeg
;
const geom = new StripGeometry(strip, par1, uvFns[params.uvFnsIdx]);
return { strip, geom };
}
// ----
// GUI
// ----
const pane = new Pane({ title: 'three-strip' });
pane.addInput(params, 'twist', { min: -Math.PI * 2, max: Math.PI * 2 });
pane.addInput(params, 'taper', { min: 0, max: 1 });
pane.addInput(params, 'uvFnsIdx', {
title: 'uvFn',
options: {
'UvPreset.strip[0]': 0,
'UvPreset.strip[1]': 1,
'UvPreset.strip[2]': 2,
'UvPreset.strip[3]': 3,
'UvPreset.dash[0]': 4,
'UvPreset.dash[1]': 5,
'UvPreset.dash[2]': 6,
'UvPreset.dash[3]': 7,
}
});
pane.addInput(params, 'nSeg', { min: 1, max: 100, step: 10 });
pane.addInput(params, 'useDash');
const dashArrayInput = pane.addInput(params, 'dashArray');
const dashOffsetInput = pane.addInput(params, 'dashOffset', { min: -10, max: 10, step: 1 });
pane.on('change', (e) => {
const { geom, strip } = make(params);
mesh.geometry.dispose();
mesh.geometry = geom;
helper.strip = strip;
helper.segments = params.nSeg;
helper.update();
dashArrayInput.hidden = !params.useDash;
dashOffsetInput.hidden = !params.useDash;
});
// ----
// render
// ----
const clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
renderer.render(scene, camera);
controls.update();
});
// ----
// view
// ----
function resize(w, h, dpr = devicePixelRatio) {
renderer.setPixelRatio(dpr);
renderer.setSize(w, h, false);
camera.aspect = w / h;
camera.updateProjectionMatrix();
}
addEventListener('resize', () => resize(innerWidth, innerHeight));
dispatchEvent(new Event('resize'));
document.body.prepend(renderer.domElement);
|
var express = require('express');
var bodyParser = require ('body-parser');
var path = require('path');
var app = express();
// allow cross-origin requests
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// REGISTER OUR ROUTES
// public-facing application route
app.use(express.static(path.resolve(__dirname, '../build')));
app.use('/', require('./public/main'));
// all of our API routes will prefixed with /api
// app.use('/api', require('./api/todos'));
module.exports = app;
|
/**
* RullerJS is an utility for listening to changes in ruller services
*
* It will take the "input" parameters and send to a ruller URL and
* the resulting "output" from ruller will be notified by method "onOutput".
*
* If the client application changes the input (setInput) it will resend the
* request and, only if the output is different from previous notification,
* will notify the changes using "onOutput"
*
* It can monitor ruller for changes by pooling the endpoint automatically too using "startPooling()"
*/
class RullerJS {
constructor(rullerURL, input, cacheMillis, onChange, onErr) {
if (!rullerURL) {
throw "rullerURL is required"
}
if (!onChange) {
throw "onOutput is required"
}
this.rullerURL = rullerURL
this.onChange = onChange
this.onErr = onErr
this.input = input
this.previousData = null
this.cacheMillis = cacheMillis
this.rullerWSURL = null
this.backoffMinMillis = null
this.backoffMaxMillis = null
this.maxRetryIntervalMillis = null
this.retryCount = 0
this.retryWaitTime = null
this.currentTimer = null
if(cacheMillis == 0) {
localStorage.removeItem("rullerjs:lastData")
}
this.poll(false);
}
startMonitoring(rullerWSURL, backoffMinMillis, backoffMaxMillis, maxRetryIntervalMillis) {
if(!backoffMinMillis) {
backoffMinMillis = 2000
}
if(!backoffMaxMillis) {
backoffMaxMillis = 20000
}
this.rullerWSURL = rullerWSURL
this.backoffMinMillis = backoffMinMillis
this.backoffMaxMillis = backoffMaxMillis
this.maxRetryIntervalMillis = maxRetryIntervalMillis
this.schedule(null, true)
}
stopMonitoring() {
if(this.currentTimer!=null) {
clearTimeout(this.currentTimer)
this.currentTimer = null
}
this.rullerWSURL = null
this.backoffMinMillis = null
this.backoffMaxMillis = null
this.maxRetryIntervalMillis = null
if(this.ws!=null) {
this.ws.close()
this.ws = null
}
}
poll(applySchedule) {
if(applySchedule) {
this.currentTimer = null
}
fetch(this.rullerURL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(this.input)
}).then((response) => {
if(response.status!=200) {
this.schedule("Error fetching " + this.rullerURL + ". status=" + response.status, applySchedule)
return
}
response.json()
.then((data) => {
// console.log("RullerJS: got response: " + data)
let ndata = JSON.stringify(data)
if(this.cacheMillis>0) {
localStorage.setItem("rullerjs:lastData", JSON.stringify({time:new Date().getTime(), data: data}))
}
if(this.previousData == null || (JSON.stringify(this.previousData) != ndata)) {
console.log("RullerJS flags: " + ndata);
this.onChange(data)
this.previousData = data
}
this.schedule(null, applySchedule)
}).catch((err) => {
this.schedule(err, applySchedule)
});
}).catch((err) => {
this.schedule("Error fetching " + this.rullerURL + ". err=" + err, applySchedule)
})
}
setInput(input) {
this.input = input
this.poll(false)
}
schedule(lastErr, applySchedule) {
if(lastErr) {
console.log("RullerJS: " + lastErr)
if(this.onErr) {
this.onErr(lastErr)
}
this.notifyIfValidCache()
}
//LOCALSTORAGE CACHE
if(!applySchedule) {
return
}
if(this.rullerWSURL == null) {
return
}
if(this.currentTimer) {
console.log("RullerJS: skipping overlapped schedule")
return
}
if(lastErr) {
this.retryCount++
} else {
if(this.retryCount>0) {
console.log("RullerJS: connection restored")
}
this.retryCount = 0
this.retryWaitTime = null
}
//RETRY FROM FAILURE
//define first retry random backoff to avoid too much pressure on server when
//it restarts so that not all clients would connect back at the same time
if(this.retryCount > 0) {
if(this.retryCount == 1) {
// console.log("Random backoff retry delay")
this.retryWaitTime = getRandomIntInclusive(this.backoffMinMillis, this.backoffMaxMillis)
} else if(this.retryCount == 2) {
// console.log("retryCount==2")
this.retryWaitTime = this.backoffMinMillis
} else {
// console.log("retryCount>2")
this.retryWaitTime = Math.min(this.retryWaitTime * 2, this.maxRetryIntervalMillis)
}
console.log("RullerJS: Retrying in " + this.retryWaitTime + "ms")
if(this.retryWaitTime>=1000) {
this.currentTimer = setTimeout(() => this.poll(true), this.retryWaitTime)
}
return
}
//MONITOR WS CLOSED
if(this.rullerWSURL != null) {
var ws = new WebSocket(this.rullerWSURL);
ws.onopen = () => {
// console.log("RullerJS: connected to " + this.rullerWSURL)
};
ws.onclose = (err) => {
this.schedule("websocket closed. err=" + err, true)
};
ws.onerror = (err) => {
this.schedule("websocket err=" + err, true)
ws.close()
};
this.ws = ws
}
}
notifyIfValidCache() {
if(this.cacheMillis==0) {
return
}
let cachedData = localStorage.getItem("rullerjs:lastData")
if(cachedData==null) {
return
}
let lcache = null
try {
lcache = JSON.parse(cachedData)
} catch (err) {
console.log("RullerJS: error parsing localstorage cache data. err=" + err)
return
}
if(lcache.data==null || lcache.time==null) {
return
}
let elapsedCache = (new Date().getTime()-lcache.time)
if(!(elapsedCache <= this.cacheMillis)) {
console.log("RullerJS: cache expired")
localStorage.removeItem("rullerjs:lastData")
lcache.data = null
}
if(this.previousData == null || (JSON.stringify(this.previousData) != JSON.stringify(lcache.data))) {
console.log("RullerJS flags (cached): " + lcache.data);
this.onChange(lcache.data)
this.previousData = lcache.data
}
}
}
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
|
const userController = require('./userController');
const bookController = require('./bookController');
const genreController = require('./genreController');
const authorController = require('./authorController');
const ownerController = require('./ownerController');
const borrowController = require('./borrowController');
const searchController = require('./searchController');
module.exports = {
userController,
bookController,
genreController,
authorController,
ownerController,
borrowController,
searchController
};
|
import Spotify from './spotify';
import Auth from './auth';
export { Spotify, Auth }
|
const showName = function () {
console.log(this)
}
const person = {
name: 'Julio Silva',
talk: function () {
console.log(`Hola! Mi nombre es ${this.name}`)
},
walk: () => {
console.log('Julio esta caminando')
console.log(this)
}
}
|
import React, {Component} from "react";
import {Link} from "react-router-dom";
import Menu from './menu.component';
import axios from 'axios';
class Listar extends Component {
state = {usuarios: []};
async componentDidMount() {
const config = {
headers: {
Authorization: 'Bearer ' + localStorage.getItem('token')
}
}
await axios.get('listado.php', config).then(
res => {
if (res.data.message === 'success') {
this.setState({
usuarios: res.data.user
})
}
}
).catch(
err => {
console.log(err);
}
);
}
render() {
return(
<div className="container-fluid">
<div className="row">
<Menu loadList={this.loadList}/>
<div className="menu-right menu-panel col-9">
<div className="text-right">
<Link to={'/register'} type="button" className="btn btn-primary">Nuevo usuario</Link>
</div>
<h3>Usuarios</h3>
<table className="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Nombre</th>
<th scope="col">Apellido</th>
<th scope="col">Correo</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
{
this.state.usuarios.map( usuario => (
<tr key={usuario.id}>
<th scope="row">{usuario.id}</th>
<td>{usuario.firstName}</td>
<td>{usuario.lastName}</td>
<td>{usuario.email}</td>
<td>
<Link to={'/register/'+usuario.id} type="button" className="btn btn-light">
<svg width="1em" height="1em" viewBox="0 0 16 16" className="bi bi-pencil-fill" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fillRule="evenodd" d="M12.854.146a.5.5 0 0 0-.707 0L10.5 1.793 14.207 5.5l1.647-1.646a.5.5 0 0 0 0-.708l-3-3zm.646 6.061L9.793 2.5 3.293 9H3.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.207l6.5-6.5zm-7.468 7.468A.5.5 0 0 1 6 13.5V13h-.5a.5.5 0 0 1-.5-.5V12h-.5a.5.5 0 0 1-.5-.5V11h-.5a.5.5 0 0 1-.5-.5V10h-.5a.499.499 0 0 1-.175-.032l-.179.178a.5.5 0 0 0-.11.168l-2 5a.5.5 0 0 0 .65.65l5-2a.5.5 0 0 0 .168-.11l.178-.178z"/>
</svg>
</Link>
</td>
<td><Link to={'/register'} type="button" className="btn btn-light">
<svg width="1em" height="1em" viewBox="0 0 16 16" className="bi bi-trash" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0V6z"/>
<path fillRule="evenodd" d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1v1zM4.118 4L4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4H4.118zM2.5 3V2h11v1h-11z"/>
</svg>
</Link>
</td>
</tr>
))
}
</tbody>
</table>
</div>
</div>
</div>
);
}
}
export default Listar;
|
//// MOGODB
/*
* MEAN APP uses Mongoose ODM.
* Connect to app mogod database using mogoose.connect();
*/
// Mongodb connection URI
var DB_URI = "mongodb://localhost/mean";
module.exports = function(mongoose) {
mongoose.connect(DB_URI);
}
|
import showdown from 'showdown'
import layoutFragment from "../_fragments/layout/layout.fragment.js";
export default data => {
const converter = new showdown.Converter({
simpleLineBreaks: true
})
return layoutFragment(
data,
{
title: data.storyboard.title
+ ' | STORYBOARDS | '
+ data.title,
content: `<div class="container">
<h1 class="main">
${ data.storyboard.title }</h1>
${ data.storyboard.description
? '<p>' + data.storyboard.description + '</p>'
: '' }
<ul class="list-unstyled">
<li class="d-inline-block mt-2 mr-2">
<a class="btn btn-warning rounded-pill px-4"
href="/storyboards/${ data.storyboard.id }/1">
<b>Commencer la lecture !
<span class="badge badge-pill badge-light mt-1">
1</span></b></a>
</a>
${
data.storyboard.pages.slice(1)
.map((page, index) =>
` <li class="d-inline-block mt-2">
<a class="btn btn-light rounded-pill"
href="/storyboards/${
data.storyboard.id }/${ index + 2 }">
${ index + 2 }
</a>
</li>`)
.join('\n')
}
</ul>
${ data.storyboard.content
? '<div>'
+ converter.makeHtml(data.storyboard.content)
+ '</div>'
: '' }
<h3>
Retour
<a href="/storyboards">
STORYBOARDS</a>
/
<a href="/">
HUB (accueil)</a>
</h3>
</div>`
})
}
|
'use strict';
const request = require('request');
const path = require("path");
const fs = require("fs");
const player = require('play-sound')();
const SERVER = {
HOST: '138.68.2.51',
PORT: '1234'
};
const AUDIO_DIR = path.resolve("./audio");
const SERVER_FULL = 'http://' + SERVER.HOST + ':' + SERVER.PORT;
let body = [];
// File Playing Function
function playFile(fileName) {
const filePath = AUDIO_DIR + "/" + fileName;
if(!fs.existsSync(filePath)) {
console.log("File does not exist: " + filePath);
return false;
}
// Via http://thisdavej.com/node-js-playing-sounds-to-provide-notifications/
player.play(filePath, { timeout: 5000 }, function(err){
if (err) throw err
});
}
// Make Server Request Every 5 Seconds
setInterval(function(){
request
.get(SERVER_FULL)
.on('data', function(chunk) {
body.push(chunk);
})
.on('end', function() {
body = Buffer.concat(body).toString();
console.log('Received response of: ' + body);
playFile(body);
body = [];
// at this point, `body` has the entire request body stored in it as a string
})
.on('error', function () {
console.log('No trigger from server. Retrying in 5 seconds.');
});
}, 5000);
|
import React from 'react';
import PropTypes from 'prop-types';
import {
Card,
CardText,
CardBody,
CardTitle,
Button,
CardHeader,
CardFooter
} from 'reactstrap';
import 'rc-slider/assets/index.css';
import Slider,{ Range }from 'rc-slider';
import Error from '../UI/Error';
class CardProduit extends React.Component {
static propTypes = {
error: PropTypes.array,
loading: PropTypes.bool.isRequired,
produit: PropTypes.shape().isRequired,
onFormSubmit: PropTypes.func.isRequired,
recipeId:PropTypes.string,
success:PropTypes.string,
}
static defaultProps = {
error: null,
success:null,
}
state = {
quantite:0,
prix:0
}
constructor(props) {
super(props);
this.onSliderChange = this.onSliderChange.bind(this);
//this.achatProduit = this.achatProduit.bind(this);
}
onSliderChange = (value) => {
this.setState({quantite:value,prix:Math.round(this.props.produit.prix*value*100,2)/100})
}
render() {
const { loading, error, success ,recipeId,produit} = this.props;
const {prix,quantite}=this.state;
// Show Listing
return (
<Card >
<CardHeader >{produit.nom}</CardHeader>
{!recipeId?
<CardBody >
<CardText>Prix : {produit.prix}€/kg </CardText>
<CardText>Quantité : {produit.quantite} kg disponible </CardText>
</CardBody>
:
(produit.quantite>0.1?
<CardBody >
<CardTitle>{produit.prix}€/kg {produit.quantite} kg disponible</CardTitle>
<CardText>Prix : {prix} € </CardText>
<CardText>Quantité achetée : {quantite} kg</CardText>
<Slider style={{marginBottom:20}}
min={0}
max={produit.quantite}
defaultValue={0}
step={0.1}
onChange={this.onSliderChange}
trackStyle={{ backgroundColor: 'blue', height: 10 }}
handleStyle={{
borderColor: 'blue',
height: 28,
width: 28,
marginLeft: -14,
marginTop: -9,
backgroundColor: 'black',
}}
withBars={true}
railStyle={{ backgroundColor: 'grey', height: 10 }}
/>
</CardBody>:
<CardBody >
<CardTitle>Produit Indisponible </CardTitle>
</CardBody>
)
}
<CardFooter>
{!recipeId?
<Button color="primary"
onClick={(evt) =>{this.props.supprimerProduit(evt,this.props.produit._id)}}
disabled={loading}
className="btn btn-primary">
{loading ? 'Loading' : 'Supprimer'}
</Button>:
(produit.quantite>0.1?<Button color="primary"
onClick={() =>{this.props.achatProduit({idAcheteur:'',quantite:this.state.quantite,prix: this.state.prix,idVendeur:this.props.produit.idUser,idProduit:this.props.produit._id})}}
disabled={loading}
className="btn btn-primary">
{loading ? 'Loading' : 'Acheter'}
</Button>:'')
}
</CardFooter>
</Card>
);
}
}
export default CardProduit;
|
//BACK-END
//ticketPrices object
var ticketPrices = {"avengers":6, "deadpool":8, "solo":8, "last-jedi":6, "matinee":0, "evening":3, "children":0, "students":2, "adults":4, "seniors":1};
//ticket constructor
function Ticket(movie, age, time) {
this.movie = movie
this.age = age
this.time = time
}
//findPrice prototype
Ticket.prototype.findPrice = function() {
var values = Object.values(this);
var price = 0
values.forEach(function(value) {
price += ticketPrices[value];
})
return price;
}
//displayResult prototype
Ticket.prototype.displayResult = function (price) {
$("div#posterResult").append(
"<img src='img/" + this.movie +
".jpg' alt='" + this.movie +
"' height=400px>"
);
$("div#priceResult").text("$" + price);
}
//resetFields function
function resetFields() {
$("div#posterResult").empty();
$("div#priceResult").text("");
}
//FRONT-END
$(document).ready(function() {
$("form#new-ticket").submit(function(event) {
event.preventDefault();
resetFields();
var movieInput = $("select#movie-title").val();
var ageInput = $("select#age").val();
var timeInput = $("select#time").val();
var ticketInstance = new Ticket(movieInput, ageInput, timeInput);
var instancePrice = ticketInstance.findPrice();
ticketInstance.displayResult(instancePrice);
});
});
|
import React, {Component} from 'react';
import ArticleIndividual from './ArticleIndividual';
import Article from './Article';
class ArticleDetails extends Component {
constructor(props){
super(props)
this.url = props.url;
this.state = {
articles: []
}
}
componentDidMount(){
fetch(this.url)
.then((res) => res.json())
.then((data) => {
this.setState({articles: data})
console.log(this.state.articles);
})
}
render() {
if (this.state.articles.length > 1){
const articles = this.state.articles.map(article => {
return <Article article={article}/>
})
return articles
}
console.log('rendering ad', this.state);
return (
<ArticleIndividual data={this.state.articles}/>
)
}
}
export default ArticleDetails;
|
// ==UserScript==
// @name Advanced button
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Go to advanced settings!
// @author You
// @match https://vimeo.com/library-search?*
// @icon https://www.google.com/s2/favicons?sz=64&domain=vimeo.com
// @grant none
// ==/UserScript==
(function () {
window.addEventListener("load", (event) => {
setTimeout(repeatAction, 15000);
});
function css(element, style) {
for (const property in style) {
element.style[property] = style[property];
}
}
function repeatAction() {
const listScroll = document.getElementsByClassName('eLdKCj')
addButton()
listScroll[0].addEventListener("scroll", (event) => {
addButton()
})
}
function addButton() {
var resultList = document.querySelectorAll('.bslsMW');
var aList = document.querySelectorAll('.hjzzyJ')
for (let i = 1; i < resultList.length; i++) {
const btn = document.createElement("button");
css(btn, {
'position': "absolute",
'right': "0px",
"top": "13px",
"border-radius": " 0.375rem",
"text-decoration": "none",
"height": "2.5rem",
"min-width": "2.5rem",
"padding": "0px 1.3125rem",
"background-color": "rgb(0, 173, 239)",
color: "rgb(255, 255, 255)",
"border": "none"
});
btn.innerHTML = "➦";
btn.addEventListener("click", function () {
const url = aList[i - 1].href.split("/").pop()
window.location.href = `https://vimeo.com/manage/${url}/advanced`;
});
resultList[i].appendChild(btn);
}
}
})();
|
import {InputField,InputFieldAlt} from "../components/InputFields.js";
import {IconButton} from "../components/iconButton.js";
export class SiteForm{
constructor(){
this.formContainer = document.createElement("div");
this.formContainer.classList.add("site-form");
}
createFormHeader(contents){
let headerContainer = document.createElement("div");
headerContainer.classList.add("site-form-header");
contents.forEach(content=>headerContainer.appendChild(content));
return headerContainer;
}
createFormBody(firstRowContents,secondRowContents){
let formBody = document.createElement("div");
formBody.classList.add("site-form-body");
let firstRowContainer = document.createElement("div");
let secondRowContainer = document.createElement("div");
firstRowContents.forEach(content=>firstRowContainer.appendChild(content));
secondRowContents.forEach(content=>secondRowContainer.appendChild(content));
formBody.appendChild(firstRowContainer);
formBody.appendChild(secondRowContainer);
return formBody;
}
createFormFooter(footerContents){
let formFooter = document.createElement("div");
formFooter.classList.add("site-form-footer");
footerContents.forEach(content=>formFooter.appendChild(content));
return formFooter;
}
createSiteForm(){
let formTitle = document.createElement("h2");
formTitle.innerHTML = "BOOK YOUR FLIGHTS";
let altField = new InputFieldAlt("Domestic","International",{color:"white","backgroundColor":"maroon"});
let formHeader = this.createFormHeader([formTitle,altField.createElement()]);
let firstRowContents = [
{label:"FROM",placeholder:"Eg. Melbourne, Australia"},
{label:"TO",placeholder:"Eg. New York, United States"}
].map(rec=>(new InputField(rec.label,rec.placeholder)).createElement());
let secondRowContents = [
{label:"DEPARTURE",placeholder:"MM/DD/YYYY"},
{label:"RETURN",placeholder:"MM/DD/YYYY"},
{label:"ADULTS",placeholder:"2"}
].map(rec=>(new InputField(rec.label,rec.placeholder)).createElement());
let formBody = this.createFormBody(firstRowContents,secondRowContents);
let searchFlightsButtonEle = (new IconButton("SEARCH FLIGHTS","",{backgroundColor:"maroon",color:"white",border:"none"})).createElement();
let advancedSearchLink = document.createElement("a");
advancedSearchLink.style.color = "maroon";
advancedSearchLink.style.textDecoration = "underline";
advancedSearchLink.style.fontFamily ="italic";
advancedSearchLink.innerHTML = "Advanced Search"
advancedSearchLink.style.cursor ="pointer";
let formFooter = this.createFormFooter([searchFlightsButtonEle,advancedSearchLink]);
this.formContainer.appendChild(formHeader);
this.formContainer.appendChild(formBody);
this.formContainer.appendChild(formFooter);
return this.formContainer;
}
}
|
/* present data in server */
var serverData = {
'left' : new Array(),
'right' : new Array()
};
const DATAMEMBERS = 5;
const random_uId = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
const random_name = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
function DataObj () {
this['uId'] = '';
this['name'] = '';
}
function randomData (type, base) {
let valueLength = 0;
let value = '';
let randomNumber;
switch (type)
{
case 'id':
valueLength = 10;
for (let idIndex=0; idIndex<valueLength; idIndex++)
{
randomNumber = Math.floor(Math.random()*random_uId.length);
value += random_uId.slice(randomNumber, randomNumber+1);
}
if (!checkUidUnique(value, base))
{
value = randomData('id', base);
}
break;
case 'name':
valueLength = Math.ceil(Math.random()*10);
for (let idIndex=0; idIndex<valueLength; idIndex++)
{
randomNumber = Math.floor(Math.random()*random_name.length);
value += random_name.slice(randomNumber, randomNumber+1);
}
break;
}
return value;
}
function checkUidUnique (uId, base)
{
for (let baseIndex=0; baseIndex<base.length; baseIndex++)
{
if (base[baseIndex].uId == uId)
{ // if duplicate uId, random again
return false;
}
}
return true;
}
const ServerAPI = (() => {
const initData = (type) => {
serverData[type] = [];
// random data instead of 'fetch' data
let dataTemp;
for (let i=0; i<DATAMEMBERS; i++)
{
dataTemp = new DataObj();
dataTemp['uId'] = randomData('id', serverData[type]);
dataTemp['name'] = randomData('name');
serverData[type].push(dataTemp);
}
return serverData[type];
};
const getData = (type) => {
return ('all' == type)? serverData : (serverData[type])? serverData[type] : [];
};
const addData = (type, obj) => {
obj['uId'] = randomData('id', serverData[type]);
serverData[type].push(obj);
return serverData[type];
};
const changeData = (moveFrom, moveTo, obj) => {
let data = [];
for (let i=0; i<serverData[moveFrom].length; i++)
{
if (obj['uId'] == serverData[moveFrom][i].uId)
{
data = serverData[moveFrom].splice(i, 1);
for (let baseIndex=0; baseIndex<serverData[moveTo].length; baseIndex++)
{
if (serverData[moveTo][baseIndex].uId == data['value'])
{ // if duplicate uId, random again
data['value'] = this.randomData('id', serverData[moveTo]);
break;
}
}
serverData[moveTo] = serverData[moveTo].concat(data);
break;
}
}
return serverData[moveFrom];
};
const removeData = (type, obj) => {
for (let i=0; i<serverData[type].length; i++)
{
if (obj['uId'] == serverData[type][i].uId)
{
serverData[type].splice(i, 1);
break;
}
}
return serverData[type];
};
return {
'initData' : initData,
'getData' : getData,
'addData' : addData,
'changeData' : changeData,
'removeData' : removeData
};
})();
export default ServerAPI;
|
/**
* @module Data
*/
/*
* Test de l'Objet Data
* --------------------
* Gestion des données diverses
*/
window.Data = {
// Dispatche les données +data+ dans l'objet +obj+
// Corrige certaines valeurs spéciales.
dispatch:function(obj, data)
{
var prop, val ;
for(prop in data)
{
if(false == data.hasOwnProperty(prop)) continue
val = data[prop]
// Traitement spécial en fonction de la propriété
switch(prop)
{
case 'id': val = parseInt(val, 10); break;
default:
// Traitement spécial en fonction du typeof de la valeur
switch( this.exact_typeof( val ) )
{
// Quand la valeur est un string
case 'string':
val = this.exact_val_of_string(val)
break
case 'object':
break
}
}
obj[prop] = val
}
},
// Retourne le « type exact » de la valeur +valeur+
// array, integer, float (marge d'erreur si aucune décimale), 'nan', 'infinity', 'null', etc.
exact_typeof:function( valeur )
{
switch(typeof valeur){
case 'function' : return 'function'
case 'object' :
if(valeur === null) return 'null'
if(valeur instanceof RegExp) return 'regexp'
if('function' == typeof valeur.slice) return 'array'
else return 'object'
case 'number' :
var tos = valeur.toString()
if(tos == "NaN") return "nan"
if(tos == "Infinity") return "infinity"
if(tos.indexOf('.')>-1) return 'float'
else return 'integer'
default: return typeof valeur // 'string', 'boolean'
}
},
// Transforme des valeurs string spéciales
exact_val_of_string:function(val)
{
switch(val)
{
case 'null' : return null
case 'false' : return false
case 'true' : return true
default: return val
}
}
}
|
var structMxOps =
[
[ "type", "structMxOps.html#a7426508d3737f8021c01df861f58a997", null ],
[ "name", "structMxOps.html#add03949683c170dc70e02f24f201356d", null ],
[ "is_local", "structMxOps.html#a15a6d1b3b3a214b6e23a36e4b82e1353", null ],
[ "ac_find", "structMxOps.html#a0c32dbbc5b81c53527d3bc4d223501c1", null ],
[ "ac_add", "structMxOps.html#acaaf1dbbfc2a6011bdbd0b30df1b923c", null ],
[ "mbox_open", "structMxOps.html#afeb0e3670299347367a17472a56a238d", null ],
[ "mbox_open_append", "structMxOps.html#a25bfad683d37065e6229b6b423208b3a", null ],
[ "mbox_check", "structMxOps.html#a1724c9c0a6fdded37dc85c6e02892e45", null ],
[ "mbox_check_stats", "structMxOps.html#a1ac2fb69ffba9d75c97fba86b113f130", null ],
[ "mbox_sync", "structMxOps.html#a6222971b7c4455ec5db897da762cd388", null ],
[ "mbox_close", "structMxOps.html#acb1e9584ccbd356be24fbd8630f236d3", null ],
[ "msg_open", "structMxOps.html#ab004e20c441741ce2b4d5cee457bb51b", null ],
[ "msg_open_new", "structMxOps.html#a1c2349306e40a8f9838d57bd34cdce54", null ],
[ "msg_commit", "structMxOps.html#ab59dadf81aec5575a1c690caa4822e37", null ],
[ "msg_close", "structMxOps.html#ad53e3df1ff124eea52bc0488915e9ae4", null ],
[ "msg_padding_size", "structMxOps.html#a784ae2e2b98208080a641974ce4df834", null ],
[ "msg_save_hcache", "structMxOps.html#a4c0ce9432905dfb3f6849c97ae504f84", null ],
[ "tags_edit", "structMxOps.html#a0e3f825e2d93106795c85d5df78874ea", null ],
[ "tags_commit", "structMxOps.html#a9e996b21c0a4d701020aa632ecc5ae82", null ],
[ "path_probe", "structMxOps.html#a625a6ea0abfdb6620542e26acc499177", null ],
[ "path_canon", "structMxOps.html#ad7d938f02ba15c08d45128bc2ca00e28", null ],
[ "path_pretty", "structMxOps.html#a3a85067a3d76652ec0014ce520c565db", null ],
[ "path_parent", "structMxOps.html#a0816dd26eb79c12783e9ac9e7b67ecd9", null ],
[ "path_is_empty", "structMxOps.html#a6ef058630b8418ae080d17762c26a75d", null ]
];
|
var express = require('express');
var router = require('router')
var app = express();
var http = require("http");
var path = require('path');
var config = require('config');
var log = require('libs/log');
var logger = require('morgan');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var jwt = require('jsonwebtoken');
var User = require('models/user').User;
var passport = require('passport');
var localStrategy = require('passport-local');
var jwtStrategy = require('passport-jwt');
var extractJwt = require('passport-jwt');
app.use(passport.initialize());
//app.set('port',config.get('port'));
app.engine('ejs', require('ejs-locals')); //файлы ejs надо обрабатывать с помощью 'ejs-local'
app.set('views', path.join(__dirname, 'templates')); //настройки для системы шаблонизации
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json()); //you can find data by req.body...
app.use(cookieParser());
app.get('/', function(req, res, next){
res.render("index", {
// body: '<b>Hiii<b>'
});
});
app.get('/signin', function(req, res, next){
res.render("signin", {
});
});
app.get('/signup', function(req, res, next){
res.render("signup", {
});
});
app.use(express.static(path.join(__dirname, 'public')));
//*****************ERRORS************
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
//******************************************
var server = http.createServer(app);
server.listen(config.get('port'),function(){
log.info('Express server listening on port ' + config.get('port'));
});
var io = require('socket.io')(server);
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' }); //передаёт
socket.on('my other event', function (data) { //слушает
console.log(data);
});
socket.on('message', function (text, cb) { //слушает
socket.broadcast.emit('message', text);
cb(text);
});
});
/*
var user = new User({
username: "Test38",
password: "secret"
});
user.save(function (err, user, affected) {
if (err) throw err;
User.findOne({username: "Test30"}, function(err, tester){
console.log(tester);
})
});
*/
//--------JWT-----------
app.post('/', function(req, res) {
var user = {name: 'Kate'};
var token = jwt.sign({ user }, "my_key");
res.json({
token: token
});
console.log(token);
var l = jwt.decode(token); //декодируем
console.log(l);
});
function somefunc(){
var name = document.getElementById("login").value;
var password = document.getElementById("password").value;
alert(name + " " +password);
}
/*
//middleware
app.use(function (req,res,next) {
if(req.url =='/'){
res.end("Hi");
} else {
next();
}
});
app.use(function (req,res,next) {
if(req.url =='/test'){
res.end("Hiiiiiii");
} else {
next();
}
});
app.use(function (req,res,next) {
if(req.url =='/error'){
next ( new Error('aaaaaa'));
} else {
next();
}
});
app.use(function(req, res){
res.send(404, "Page not found");
});
*/
/*
// view engine setup
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
*/
|
//jshint esversion:6
//global objects!
// console.log(); //global in JS
//
// setTimeout(); //call delay
// clearTimeout();
//
// setInterval();// call delay recursively
// clearInterval();
//
//
// //In browser, call global functions via window objects
// window.console.log();
// //window can be omitted
//
// //Node don't have window function, but we have glocal object instead
// global.setTimeout();
//
// let message="";
// console.log(global.message);//which give undefined
//we should decline building variables in global scope otherwise it might be overwrite by otherwise
//define it into module, very like the package in JAVA
//use Module and store the variable in const to prevent overwrite
const log = require('./logger');
// console.log(logger);
log('message');
|
function myHeader(employee_id, name)
{
if(employee_id != 0){
$(".main_top").append('<div class="pic"><a href="Home.jsp"><img alt="Beehyv" src="http://www.beehyv.com/images/logo.jpg"/></a></div>');
$(".main_top").append('<div id="reg"> <a href="Logout" style="color:Azure">Logout</a></div>');
$(".main_top").append('<div class="myProfile"><a href="myProfile.jsp?employee_id='+employee_id+'" style="color:Azure">My Account</a></div>');
$(".main_top").append('<div class="myPosts"><a href="MyPosts.jsp?employee_id='+employee_id +'" style="color:Azure;">MyPosts</a></div> ');
$(".main_top").append('<div id="id">'+name+'</div>');
}
else
{
$(".main_top").append('<div class="pic"><a href="Home.jsp"><img alt="Beehyv" src="http://www.beehyv.com/images/logo.jpg"/></a></div>');
$(".main_top").append('<div id="id"><a href="Login.html" style="color:Azure;">Login</a></div>');
$(".main_top").append('<div id="reg"> <a href="Register.jsp" style="color:Azure;">Register</a></div>');
}
}
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, browserHistory/*, IndexRoute*/ } from 'react-router';
// I'm making temporary routes just so I can see stuff when I'm building it. I know we won't really need a route for the Product build page. We also talked about both the Sign (in and up) and Success messages being modals. AND i didn't mess with needing IDs, which I know you'll have to add. But, for tonight, I'll have routes so I can see what on earth I'm building.
import Home from './components/Home';
// import Sign from './components/Sign';
// import ProductBuild from './components/ProductBuild';
import Products from './components/Products';
// import ProductSelected from './components/ProductSelected';
import Cart from './components/Cart';
import Login from './components/Login';
// import Success from './components/Success';
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={Home}/>
<Route path="/products" component={Products} />
<Route path="/cart" component={Cart} />
<Route path="/login" component={Login} />
</Router>,
document.getElementById('root')
);
/* <Route path="/sign" component={Sign} />
<Route path="/productbuild" component={ProductBuild} />
<Route path="/productselected" component={ProductSelected} />
*/
|
/**
* 登陆成功后
* @author zegu
*/
function afterLogin(data) {
showSound("../music/clickOn.mp3");
$(".login").css({
"left": "-200%"
});
$(".gameStar").css({
"left": "0"
});
player.userInfo = data.userInfo;
let danGrad = chessBit[parseInt(data.userInfo.score / 1000) % 6]
$('.play2 .userRank span').eq(1).html(danGrad.bit)
$(".play2 .userName span").eq(1).html(data.userInfo.username);
$('.play2 .userStep span').eq(1).html(player.steps)
}
function gameStart() {
showSound("../music/clickOn.mp3");
$(".gameStar").css({
"left": "-200%"
});
$(".pieces").css({
"z-index": "1"
});
$(".page1").css({
"left": "0"
}); //蒙版图像显示
}
/**
* 点击棋盘后
* @author zegu lubing
*/
//点击棋盘
$(".mid").on('click', '#board', function() {
// alert('emmm')
var x = event.offsetX; //获得鼠标点击对象内部的x,y轴坐标
var y = event.offsetY;
if (x >= 585 || y >= 665 || y < 20 || x < 5) { //点击边界外的坐标忽略
return false;
}
let {
r_x,
r_y
} = getRelative(x, y);
let {
a_x,
a_y
} = getAbsolute(r_x, r_y);
board.click.r_x = r_x;
board.click.r_y = r_y;
board.click.a_x = a_x;
board.click.a_y = a_y;
movePieces();
})
|
let numero1, numero2, resultado;
console.log(numero1);
function suma(){
numero1=parseInt(document.getElementById('numero1').value);
numero2=parseInt(document.getElementById('numero2').value);
resultado=numero1+numero2
alert("las suma de los numero es " + resultado);
if(resultado % 2== 0){
alert("el numero es par");
}else{
alert("el numero es impar");
}
document.location.reload();
}
|
import React, { useState, useEffect } from "react";
import "../styles/QuoteContainer.css";
function QuoteContainer() {
const [content, setContent] = useState("Loading...");
const [author, setAuthor] = useState("");
async function fetchQuote() {
try {
const response = await fetch(
`https://quotesondesign.com/wp-json/wp/v2/posts/?orderby=rand&_=${Date.now()}`
);
const [quote] = await response.json();
setContent(quote?.content?.rendered);
setAuthor(quote?.title?.rendered);
} catch (error) {
alert(error.message);
}
}
useEffect(() => {
fetchQuote();
}, []);
return (
<div className="quote">
<div className="quotecontent">
<div className="text" dangerouslySetInnerHTML={{ __html: content }} />
</div>
<div className="author">— {author}</div>
<div className="button">
<h5 className="newquote" onClick={fetchQuote}>
New Quote?
</h5>
</div>
</div>
);
}
export default QuoteContainer;
|
const express = require("express")
const router = express.Router()
const Categories = require('../db/models/Categories')
router.get('/', (req, res) => {
Categories.find({})
.then(cat => {
res.json(cat)
})
})
router.post('/', (req, res) => {
Categories.create(req.body)
.then(cat => {
res.json(cat)
})
})
router.put('/', (req, res) => {
Categories.findOne({name: req.params.name}, req.body)
.then(cat => {
res.json(cat)
})
})
router.delete('/', (req, res) => {
Categories.delete({name: req.params.name})
.then(cat => {
res.json(cat)
})
})
module.exports = router
|
FvB.Renderer = (function () {
// Sprite Render Constants
//
FvB.setConsts({
SCREENWIDTH: 640,
SCREENHEIGHT: 400,
R_X_ALIGN_CENTER: 1,
R_Y_ALIGN_CENTER: 2,
R_X_ALIGN_LEFT : 4,
R_Y_ALIGN_TOP: 8,
R_X_ALIGN_RIGHT: 16,
R_Y_ALIGN_BOTTOM: 32,
// Combinations
R_ALIGN_CENTER: 1 | 2,
R_ALIGN_TOP_LEFT: 4|8
});
var width = FvB.SCREENWIDTH,
height = FvB.SCREENHEIGHT,
canvas = null,
ctx = null,
RATIO = null,
scale = 1,
currentWidth= null,
currentHeight= null;
function resize() {
currentHeight = window.innerHeight;
// resize the width in proportion
// to the new height
currentWidth = currentHeight * RATIO;
// set the new canvas style width & height plus the fader overlay
// note: our canvas is still 320x480 but
// we're essentially scaling it with CSS
var faderOverlay = document.getElementById('fader-overlay'),
titleScreen = document.getElementById('intro-screen');
canvas.style.width = titleScreen.style.width = faderOverlay.style.width = currentWidth + 'px';
canvas.style.height = titleScreen.style.height =faderOverlay.style.height = currentHeight + 'px';
// the amount by which the css resized canvas
// is different to the actual (480x320) size.
scale = currentWidth / width;
// position of canvas in relation to
// the screen
}
function init() {
canvas = document.getElementsByTagName('canvas')[0];
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext('2d');
RATIO = width / height;
// these will change when the screen is resize
currentWidth = width;
currentHeight = height;
resize();
window.addEventListener('resize', FvB.Renderer.resize, false);
}
function getContext() {
return ctx;
}
function clearScreen(bgColor) {
if (bgColor == null)
bgColor = "#000000";
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function renderEntity(entity) {
var sprite = FvB.Sprites.getSprite(entity.sprite),
offset = entity.flip ? entity.dir : 0;
ctx.save();
ctx.translate(Math.floor(entity.x), Math.floor(entity.y));
var img = FvB.Sprites.getTexture(entity.sprite);
ctx.drawImage(img,
sprite.xOffset, sprite.yOffset + (offset * sprite.height),
sprite.width, sprite.height,
-sprite.width / 2, -sprite.height,
sprite.width, sprite.height);
//ctx.beginPath();
//ctx.strokeStyle = "red";
//ctx.rect(entity.hitBox.x1, entity.hitBox.y1, entity.hitBox.x2 - entity.hitBox.x1, entity.hitBox.y2 - entity.hitBox.y1);
//ctx.stroke();
ctx.restore();
}
// Render sprite on the canvas
// The default flags are R_X_ALIGN_LEFT | R_Y_ALIGN_TOP
function renderSprite(id, x, y, renderFlags) {
renderFlags = renderFlags || FvB.R_ALIGN_TOP_LEFT;
var sprite = FvB.Sprites.getSprite(id),
renderX, renderY;
if ((renderFlags & FvB.R_X_ALIGN_RIGHT) == FvB.R_X_ALIGN_RIGHT) {
renderX = x - sprite.width;
} else if ((renderFlags & FvB.R_X_ALIGN_CENTER) == FvB.R_X_ALIGN_CENTER) {
renderX = x - sprite.width/2;
} else {
renderX = x;
}
if ((renderFlags & FvB.R_Y_ALIGN_BOTTOM) == FvB.R_Y_ALIGN_BOTTOM) {
renderY = y - sprite.height;
} else if ((renderFlags & FvB.R_Y_ALIGN_CENTER) == FvB.R_Y_ALIGN_CENTER) {
renderY = y - sprite.height / 2;
} else {
renderY = y;
}
ctx.save();
ctx.translate(renderX, renderY);
ctx.drawImage(FvB.Sprites.getTexture(id),
sprite.xOffset, sprite.yOffset,
sprite.width, sprite.height,
0, 0,
sprite.width, sprite.height);
ctx.restore();
}
function renderPrimitive(e) {
// Only line supported at the moment
ctx.save();
if (e.objClass == FvB.ob_Line) {
ctx.beginPath();
ctx.moveTo(e.temp2.x1, e.temp2.y1);
ctx.lineTo(e.temp2.x2, e.temp2.y2);
ctx.strokeStyle = e.temp2.color;
ctx.lineWidth = 2;
ctx.stroke();
}
ctx.restore();
}
return {
init: init,
resize: resize,
getContext: getContext,
clearScreen: clearScreen,
renderEntity: renderEntity,
renderSprite: renderSprite,
renderPrimitive: renderPrimitive
};
})();
|
const ALL_SCOPES = [
'admin',
'banned',
'database',
'database:shikivideos',
'database:shikivideos_create',
'database:articles',
'default',
'user',
'user:modify'
];
const SCOPES_COMPARATOR = {
MORE: 1,
LESS: -1,
EQUAL: 0,
INCOMPARABLE: {}
};
class Scope {
constructor(scope) {
if (ALL_SCOPES.includes(scope))
this.scope = scope;
else this.scope = 'default';
}
static compare(left_scope, right_scope) {
if (ALL_SCOPES.includes(left_scope) && ALL_SCOPES.includes(right_scope)) {
if (left_scope === right_scope) {
return SCOPES_COMPARATOR.EQUAL;
} else if (left_scope.includes(right_scope)) {
return SCOPES_COMPARATOR.LESS;
} else if (right_scope.includes(left_scope) || left_scope === 'default') {
return SCOPES_COMPARATOR.MORE
} else
return SCOPES_COMPARATOR.INCOMPARABLE;
} else throw new Error(`Invalid scopes to compare: ${left_scope} and ${right_scope}`);
}
static normilize(scopes) {
let scopes_set = new Set(`${scopes}`.split(';'));
let normilized = new Set([]);
// TODO: remove scopes with fewer permissions
scopes_set.forEach(scope => {
let scope_obj = new Scope(scope);
normilized.add(scope_obj.toString());
});
if (normilized.length === 0)
normilized.add('default');
return Array.from(normilized);
}
/**
* Compares a Scopes instance with another string scope
* @param {string} scope
* @returns {number} -1 if passed argument has more permissions, 0 if equal, 1 otherwise
* @throws {Error}
*/
compareWith(scope) {
const scope_obj = typeof scope === typeof Scope ? scope : new Scope(scope);
return Scope.compare(this.scope, scope_obj.scope);
}
isAllowedFor(scope) {
const cmp = this.compareWith(scope);
return cmp === SCOPES_COMPARATOR.EQUAL || cmp === SCOPES_COMPARATOR.MORE;
}
toString() {
return `${this.scope}`;
}
}
module.exports = {
Scope: Scope,
AVAILABLE_SCOPE: ALL_SCOPES,
SCOPES_COMPARATOR: SCOPES_COMPARATOR
};
|
import React, { useEffect, useState } from "react";
import { listenData } from "../firebase/database";
export const Monsters = () => {
const [monsters, setMonsters] = useState({});
//
useEffect(() => {
// readData();
listenData("monsters", (monsters) => {
setMonsters(monsters);
});
}, []);
return <div></div>;
};
|
$(document).ready(function () {
$(document).on('click', 'a[href^="#"]', function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: $('a[name=' + $.attr(this, 'href').replace('#', '') + ']').offset().top -100
}, 500);
});
});
|
var mongoose = require('mongoose');
var FeedbackSchema = mongoose.Schema({
username: {type: String, require: true},
password: {type: String, require: true},
name: {type: String, require: true},
subname: {type: String, require: true},
age: {type: String, require: true},
gender: {type: String, require: true},
address: {type: String, require: true},
province: {type: String, require: true},
state: {type: String, require: true},
zipcode: {type: String, require: true}
})
var FeedbackModel = mongoose.model('profiles', FeedbackSchema);
module.exports = FeedbackModel;
|
const forms = require('forms')
const formFunctions = require('../../functions/forms/file');
const settings = require("../../models/settings")
const levels = require("../../models/levels")
const pagging = require("../../functions/pagging")
const globalModel = require("../../models/globalModel")
const languageModel = require("../../models/languages")
const fileManager = require("../../models/fileManager")
const permission = require("../../models/levelPermissions")
const categoryModel = require("../../models/categories")
const commonFunctions = require("../../functions/commonFunctions")
const castncrewModel = require("../../models/castncrew")
const uniqid = require("uniqid")
const movieModel = require("../../models/movies")
const notifications = require("../../models/notifications")
const dateTime = require('node-datetime')
const getSymbolFromCurrency = require('currency-symbol-map')
exports.index = async (req, res) => {
let LimitNum = 10;
let page = 1
if (req.params.page == '') {
page = 1;
} else {
//parse int Convert String to number
page = parseInt(req.params.page) ? parseInt(req.params.page) : 1;
}
const categories = []
await categoryModel.findAll(req, { type: "movie" }).then(result => {
result.forEach(function (doc, index) {
if (doc.subcategory_id == 0 && doc.subsubcategory_id == 0) {
const docObject = doc
//2nd level
let sub = []
result.forEach(function (subcat, index) {
if (subcat.subcategory_id == doc.category_id) {
let subsub = []
result.forEach(function (subsubcat, index) {
if (subsubcat.subsubcategory_id == subcat.category_id) {
subsub.push(subsubcat)
}
});
if (subsub.length > 0) {
subcat["subsubcategories"] = subsub;
}
sub.push(subcat)
}
});
if (sub.length > 0) {
docObject["subcategories"] = sub;
}
categories.push(docObject);
}
})
})
const query = { ...req.query }
let conditionalWhere = ""
let condition = []
if (query.title) {
condition.push(query.title.toLowerCase())
conditionalWhere += " AND LOWER(movies.title) LIKE CONCAT('%', ?, '%')"
}
if (query.displayname) {
condition.push(query.displayname.toLowerCase())
conditionalWhere += " AND LOWER(userdetails.displayname) LIKE CONCAT('%', ?, '%')"
}
if (query.email) {
condition.push(query.email.toLowerCase())
conditionalWhere += " AND LOWER(users.email) LIKE CONCAT('%', ?, '%')"
}
if (query.category_id) {
condition.push(query.category_id)
conditionalWhere += " AND movies.category_id = ?"
}
if (query.subcategory_id) {
condition.push(query.subcategory_id)
conditionalWhere += " AND movies.subcategory_id = ?"
}
if (query.subsubcategory_id) {
condition.push(query.subsubcategory_id)
conditionalWhere += " AND movies.subsubcategory_id = ?"
}
if (typeof query.paidfee != "undefined" && query.paidfee.length) {
if(query.paidfee == 0){
conditionalWhere += " AND movies.price = 0"
}else{
conditionalWhere += " AND movies.price > 0"
}
}
if (typeof query.rentfee != "undefined" && query.rentfee.length) {
if(query.rentfee == 0){
conditionalWhere += " AND movies.rent_price = 0"
}else{
conditionalWhere += " AND movies.rent_price > 0"
}
}
if (query.category) {
condition.push(query.category)
conditionalWhere += " AND movies.category = ?"
}
if (typeof query.adult != "undefined" && query.adult.length) {
condition.push(query.adult)
conditionalWhere += " AND movies.adult = ?"
}
if (typeof query.approve != "undefined" && query.approve.length) {
condition.push(query.approve)
conditionalWhere += " AND movies.approve = ?"
}
if (typeof query.is_locked != "undefined" && query.is_locked.length) {
condition.push(query.is_locked)
conditionalWhere += " AND movies.is_locked = ?"
}
if (typeof query.featured != "undefined" && query.featured.length) {
condition.push(query.featured)
conditionalWhere += " AND movies.is_featured = ?"
}
if (typeof query.sponsored != "undefined" && query.sponsored.length) {
condition.push(query.sponsored)
conditionalWhere += " AND movies.is_sponsored = ?"
}
if (typeof query.hot != "undefined" && query.hot.length) {
condition.push(query.hot)
conditionalWhere += " AND movies.is_hot = ?"
}
conditionalWhere += " AND movies.custom_url != '' "
conditionalWhere += " AND users.user_id IS NOT NULL "
let results = []
let totalCount = 0
let sql = "SELECT COUNT(*) as totalCount FROM movies LEFT JOIN users on users.user_id = movies.owner_id LEFT JOIN userdetails ON users.user_id = userdetails.user_id WHERE 1 = 1 AND (custom_url IS NOT NULL) " + conditionalWhere
await globalModel.custom(req, sql, condition).then(result => {
totalCount = result[0].totalCount
})
if (totalCount > 0) {
condition.push(LimitNum)
condition.push((page - 1) * LimitNum)
conditionalWhere += " ORDER BY movies.movie_id DESC limit ? offset ?"
let sqlQuery = "SELECT movies.*,userdetails.username,userdetails.displayname FROM movies LEFT JOIN users on users.user_id = movies.owner_id LEFT JOIN userdetails ON users.user_id = userdetails.user_id WHERE 1 = 1 AND (custom_url IS NOT NULL) " + conditionalWhere
await globalModel.custom(req, sqlQuery, condition).then(result => {
results = result
})
}
const paggingData = pagging.create(req, totalCount, page, '', LimitNum)
const url = req.originalUrl.replace(process.env.ADMIN_SLUG, '');
res.render('admin/movies/index', { categories: categories, loggedin_id: (req.user ? req.user.user_id : ""), loggedinLevel_id: (req.user ? req.user.level_id : ""), totalCount: totalCount, query: query, nav: url, results: results, title: "Manage Movies", paggingData: paggingData });
}
exports.approve = async (req, res) => {
const id = req.params.id
if (!id || !req.user) {
res.send({ error: 1 })
return
}
await globalModel.custom(req, "SELECT * from movies where movie_id = ?", id).then(async result => {
if (result && result.length) {
let item = result[0]
await globalModel.update(req, { approve: !item.approve }, "movies", "movie_id", id).then(result => {
if (item.owner_id != req.user.user_id && !item.approve) {
notifications.insert(req, { owner_id: item.owner_id, type: "movies_admin_approved", subject_type: "users", subject_id: item.owner_id, object_type: "movies", object_id: item.movie_id, insert: true }).then(result => {
}).catch(err => {
})
} else if (item.owner_id != req.user.user_id && item.approve) {
notifications.insert(req, { owner_id: item.owner_id, type: "movies_admin_disapproved", subject_type: "users", subject_id: item.owner_id, object_type: "movies", object_id: item.movie_id, insert: true }).then(result => {
}).catch(err => {
})
}
res.send({ status: !item.approve })
})
} else {
res.send({ error: 1 })
}
})
}
exports.slidershow = async (req, res) => {
const id = req.params.id
if (!id || !req.user) {
res.send({ error: 1 })
return
}
await globalModel.custom(req, "SELECT * from movies where movie_id = ?", id).then(async result => {
if (result && result.length) {
let item = result[0]
await globalModel.update(req, { show_slider: !item.show_slider }, "movies", "movie_id", id).then(result => {
res.send({ status: !item.show_slider })
})
} else {
res.send({ error: 1 })
}
})
}
exports.featured = async (req, res) => {
const id = req.params.id
if (!id || !req.user) {
res.send({ error: 1 })
return
}
await globalModel.custom(req, "SELECT * from movies where movie_id = ?", id).then(async result => {
if (result && result.length) {
let item = result[0]
await globalModel.update(req, { is_featured: !item.is_featured }, "movies", "movie_id", id).then(result => {
if (item.owner_id != req.user.user_id && !item.is_featured) {
notifications.insert(req, { owner_id: item.owner_id, type: "movies_featured", subject_type: "users", subject_id: item.owner_id, object_type: "movies", object_id: item.movie_id, insert: true }).then(result => {
}).catch(err => {
})
}
res.send({ status: !item.is_featured })
})
} else {
res.send({ error: 1 })
}
})
}
exports.sponsored = async (req, res) => {
const id = req.params.id
if (!id || !req.user) {
res.send({ error: 1 })
return
}
await globalModel.custom(req, "SELECT * from movies where movie_id = ?", id).then(async result => {
if (result && result.length) {
let item = result[0]
await globalModel.update(req, { is_sponsored: !item.is_sponsored }, "movies", "movie_id", id).then(result => {
if (item.owner_id != req.user.user_id && !item.is_sponsored) {
notifications.insert(req, { owner_id: item.owner_id, type: "movies_sponsored", subject_type: "users", subject_id: item.owner_id, object_type: "movies", object_id: item.movie_id, insert: true }).then(result => {
}).catch(err => {
})
}
res.send({ status: !item.is_sponsored })
})
} else {
res.send({ error: 1 })
}
})
}
exports.hot = async (req, res) => {
const id = req.params.id
if (!id || !req.user) {
res.send({ error: 1 })
return
}
await globalModel.custom(req, "SELECT * from movies where movie_id = ?", id).then(async result => {
if (result && result.length) {
let item = result[0]
await globalModel.update(req, { is_hot: !item.is_hot }, "movies", "movie_id", id).then(result => {
if (item.owner_id != req.user.user_id && !item.is_hot) {
notifications.insert(req, { owner_id: item.owner_id, type: "movies_hot", subject_type: "users", subject_id: item.owner_id, object_type: "movies", object_id: item.movie_id, insert: true }).then(result => {
}).catch(err => {
})
}
res.send({ status: !item.is_hot })
})
} else {
res.send({ error: 1 })
}
})
}
exports.delete = async (req, res) => {
const id = req.params.id
let backURL = req.header('Referer') || process.env.ADMIN_SLUG + "/movies";
if (!id || !req.user) {
res.redirect(backURL)
return
}
await movieModel.delete(id, req).then(result => {
res.redirect(backURL)
return
})
}
exports.castncrew = async (req, res) => {
//get all artists
let artists = []
await castncrewModel.findAll(req, { type: "movie" }).then(results => {
artists = results
})
let imageSuffix = ""
if (req.appSettings.upload_system == "s3") {
imageSuffix = "https://" + req.appSettings.s3_bucket + ".s3.amazonaws.com";
}else if (req.appSettings.upload_system == "wisabi") {
imageSuffix = "https://s3.wasabisys.com/"+req.appSettings.s3_bucket ;
}
const url = req.originalUrl.replace(process.env.ADMIN_SLUG, '');
res.render("admin/movies/cast-crew", { imageSuffix: imageSuffix, results: artists, title: "Manage Cast & Crew Members", nav: url })
}
exports.createCastncrew = async (req, res) => {
const cast_crew_id = req.params.id
let existingCastnCrew = {}
//if exists means req from edit page
if (req.imageError) {
res.send({ "errors": { 'file': "Error Uploading file." } })
return
}
if (cast_crew_id) {
await castncrewModel.findById(cast_crew_id, req, res).then(result => {
existingCastnCrew = result
}).catch(error => {
});
} else {
if (!req.fileName && req.checkImage) {
res.send({ "errors": { 'file': "Please select file." } })
return
}
}
const url = req.originalUrl.replace(process.env.ADMIN_SLUG, '');
var fields = forms.fields;
var validators = forms.validators;
var widgets = forms.widgets;
const cssClasses = {
label: [""],
field: ["form-group"],
classes: ["form-control"]
};
let imageSuffix = ""
if (req.appSettings.upload_system == "s3" && existingCastnCrew.image) {
imageSuffix = "https://" + req.appSettings.s3_bucket + ".s3.amazonaws.com";
}else if (req.appSettings.upload_system == "wisabi" && existingCastnCrew.image) {
imageSuffix = "https://s3.wasabisys.com/"+req.appSettings.s3_bucket ;
}
var reg_form = forms.create({
name: fields.string({
label: "Name",
required: true,
cssClasses: { "field": ["form-group"] },
widget: widgets.text({ "classes": ["form-control"] }),
value: existingCastnCrew.name
}),
biography: fields.string({
label: "Biography",
cssClasses: { "field": ["form-group"] },
widget: widgets.textarea({ "classes": ["form-control"] }),
value: existingCastnCrew.biography
}),
birthdate: fields.string({
label: "Birth Date",
cssClasses: { "field": ["form-group"] },
widget: widgets.text({ "classes": ["form-control"] }),
value: existingCastnCrew.birthdate
}),
gender: fields.string({
label: "Artist Gender",
cssClasses: { "field": ["form-group"] },
widget: widgets.text({ "classes": ["form-control"] }),
value: existingCastnCrew.gender
}),
deathdate: fields.string({
label: "Death Date",
cssClasses: { "field": ["form-group"] },
widget: widgets.text({ "classes": ["form-control"] }),
value: existingCastnCrew.deathdate
}),
birthplace: fields.string({
label: "Birth Place",
cssClasses: { "field": ["form-group"] },
widget: widgets.text({ "classes": ["form-control"] }),
value: existingCastnCrew.birthplace
}),
file: fields.string({
label: "Upload Photo",
cssClasses: { "field": ["form-group"] },
widget: formFunctions.file({ name: "file", value: existingCastnCrew.image ? imageSuffix + existingCastnCrew.image : "" }),
})
}, { validatePastFirstError: true });
reg_form.handle(req, {
success: function (form) {
delete form.data["file"]
if (req.fileName) {
form.data["image"] = "/upload/images/movies/cast-crew/" + req.fileName
}
if (existingCastnCrew.image && req.fileName) {
commonFunctions.deleteImage(req, res, existingCastnCrew.image, "cast-crew/movie")
}
if (!cast_crew_id) {
form.data['custom_url'] = uniqid.process('cc')
globalModel.create(req, form.data, 'cast_crew_members').then(result => {
})
} else
globalModel.update(req, form.data, 'cast_crew_members', 'cast_crew_member_id', cast_crew_id)
res.send({ success: 1, message: "Operation performed successfully.", url: process.env.ADMIN_SLUG + "/movies/cast-crew" })
},
error: function (form) {
const errors = formFunctions.formValidations(form);
res.send({ errors: errors });
},
other: function (form) {
res.render('admin/movies/cast-crew/create', { nav: url, reg_form: reg_form, title: (!cast_crew_id ? "Add" : "Edit") + " Cast & Crew Member" });
}
});
}
exports.deleteCastncrew = async (req, res) => {
const id = req.params.id
let existingCastnCrew = {}
if (id) {
await castncrewModel.findById(id, req, res).then(result => {
existingCastnCrew = result
}).catch(error => {
});
}
if (existingCastnCrew.image) {
commonFunctions.deleteImage(req, res, existingCastnCrew.image, "")
}
globalModel.delete(req, "cast_crew_members", "cast_crew_member_id", id).then(result => {
globalModel.delete(req, "cast_crew", "cast_crew_member_id", id).then(result => {
})
res.redirect(process.env.ADMIN_SLUG + "/movies/cast-crew/")
})
}
exports.getGalleries = async(req,res,next) => {
let LimitNum = 10;
let page = 1
if (req.params.page == '') {
page = 1;
} else {
//parse int Convert String to number
page = parseInt(req.params.page) ? parseInt(req.params.page) : 1;
}
let cast_crew_id = req.params.cast_crew_id
let artists = {}
await globalModel.custom(req, "SELECT * FROM cast_crew_members where cast_crew_member_id = ?", [cast_crew_id]).then(result => {
if(result && result[0])
artists = result[0]
})
if(!cast_crew_id || Object.keys(artists) < 1){
next()
return
}
const query = { ...req.query }
let conditionalWhere = ""
let condition = []
condition.push(cast_crew_id)
conditionalWhere += " where resource_id = ? AND resource_type = 'cast_crew'"
let results = []
let totalCount = 0
let sql = "SELECT COUNT(*) as totalCount FROM photos " + conditionalWhere
console.log(sql);
await globalModel.custom(req, sql, condition).then(result => {
totalCount = result[0].totalCount
})
if (totalCount > 0) {
condition.push(LimitNum)
condition.push((page - 1) * LimitNum)
conditionalWhere += " ORDER BY photos.photo_id DESC limit ? offset ?"
let sqlQuery = "SELECT photos.* FROM photos " + conditionalWhere
await globalModel.custom(req, sqlQuery, condition).then(result => {
results = result
})
}
const paggingData = pagging.create(req, totalCount, page, '', LimitNum,cast_crew_id+"/")
const url = req.originalUrl.replace(process.env.ADMIN_SLUG, '');
res.render('admin/movies/cast-crew/gallery', { loggedin_id: (req.user ? req.user.user_id : ""),artists:artists, totalCount: totalCount, query: query, nav: url, results: results, title: "Manage "+artists.name+" Gallery Photos", paggingData: paggingData });
}
exports.createGallery = async(req,res) => {
const cast_crew_id = req.params.cast_crew_id
const photo_id = req.params.id
let castnCrew = {}
await globalModel.custom(req, "SELECT * FROM cast_crew_members where cast_crew_member_id = ?", [cast_crew_id]).then(result => {
if(result && result[0])
castnCrew = result[0]
})
let existingPhoto = {}
//if exists means req from edit page
if (req.imageError) {
res.send({ "errors": { 'file': "Error Uploading file." } })
return
}
if (photo_id) {
await globalModel.custom(req, "SELECT * FROM photos where photo_id = ?", [photo_id]).then(result => {
if(result && result[0])
existingPhoto = result[0]
})
} else {
if (!req.fileName && req.checkImage) {
res.send({ "errors": { 'file': "Please select file." } })
return
}
}
const url = req.originalUrl.replace(process.env.ADMIN_SLUG, '');
var fields = forms.fields;
var validators = forms.validators;
var widgets = forms.widgets;
const cssClasses = {
label: [""],
field: ["form-group"],
classes: ["form-control"]
};
let imageSuffix = ""
if (req.appSettings.upload_system == "s3" && existingPhoto.image) {
imageSuffix = "https://" + req.appSettings.s3_bucket + ".s3.amazonaws.com";
}else if (req.appSettings.upload_system == "wisabi" && existingPhoto.image) {
imageSuffix = "https://s3.wasabisys.com/"+req.appSettings.s3_bucket ;
}
var reg_form = forms.create({
name: fields.string({
label: "Title",
required: false,
cssClasses: { "field": ["form-group"] },
widget: widgets.text({ "classes": ["form-control"] }),
value: existingPhoto.name
}),
// description: fields.string({
// label: "Description",
// cssClasses: { "field": ["form-group"] },
// widget: widgets.textarea({ "classes": ["form-control"] }),
// value: existingPhoto.description
// }),
file: fields.string({
label: "Upload Photo",
cssClasses: { "field": ["form-group"] },
widget: formFunctions.file({ name: "file", value: existingPhoto.image ? imageSuffix + existingPhoto.image : "" }),
})
}, { validatePastFirstError: true });
reg_form.handle(req, {
success: function (form) {
delete form.data["file"]
if (req.fileName) {
form.data["image"] = "/upload/images/cast-crew/gallery/" + req.fileName
}
form.data["resource_id"] = castnCrew.cast_crew_member_id
form.data.resource_type = "cast_crew"
if (existingPhoto.image && req.fileName) {
commonFunctions.deleteImage(req, res, existingPhoto.image, "artist/cast-crew/photo")
}
if (!photo_id) {
globalModel.create(req, form.data, 'photos').then(result => {})
} else
globalModel.update(req, form.data, 'photos', 'photo_id', photo_id)
res.send({ success: 1, message: "Operation performed successfully.", url: process.env.ADMIN_SLUG + "/movies/cast-crew/gallery/"+castnCrew.cast_crew_member_id })
},
error: function (form) {
const errors = formFunctions.formValidations(form);
res.send({ errors: errors });
},
other: function (form) {
res.render('admin/movies/cast-crew/createphoto', { nav: url, reg_form: reg_form, title: (!cast_crew_id ? "Add " : "Edit ") + castnCrew.name +" Photos" });
}
});
}
exports.deleteGallery = async(req,res) => {
const id = req.params.id
let backURL = req.header('Referer') || process.env.ADMIN_SLUG + "/movies";
if (!id || !req.user) {
res.redirect(backURL)
return
}
await globalModel.custom(req,"DELETE FROM photos WHERE photo_id = ?",[id]).then(result => {
res.redirect(backURL)
return
})
}
exports.soldMovies = async (req,res) => {
let LimitNum = 10;
let page = 1
if (req.params.page == '') {
page = 1;
} else {
//parse int Convert String to number
page = parseInt(req.params.page) ? parseInt(req.params.page) : 1;
}
const query = { ...req.query }
let conditionalWhere = ""
let condition = []
if (query.title) {
condition.push(query.title.toLowerCase())
conditionalWhere += " AND LOWER(movies.title) LIKE CONCAT('%', ?, '%')"
}
if (query.displayname) {
condition.push(query.displayname.toLowerCase())
conditionalWhere += " AND LOWER(userdetails.displayname) LIKE CONCAT('%', ?, '%')"
}
if (query.email) {
condition.push(query.email.toLowerCase())
conditionalWhere += " AND LOWER(users.email) LIKE CONCAT('%', ?, '%')"
}
conditionalWhere += " AND users.user_id IS NOT NULL "
let results = []
let totalCount = 0
let sql = "SELECT COUNT(*) as totalCount FROM transactions INNER JOIN movies on movies.movie_id = transactions.id LEFT JOIN users on users.user_id = transactions.owner_id INNER JOIN userdetails ON users.user_id = userdetails.user_id WHERE 1 = 1 AND users.active = '1' AND users.approve = '1' AND (transactions.state = 'approved' || transactions.state = 'completed' || transactions.state = 'active') AND ( transactions.type IN ('rent_series_purchase','purchase_series_purchase','rent_movie_purchase','purchase_movie_purchase') ) " + conditionalWhere
await globalModel.custom(req, sql, condition).then(result => {
totalCount = result[0].totalCount
})
if (totalCount > 0) {
condition.push(LimitNum)
condition.push((page - 1) * LimitNum)
conditionalWhere += " ORDER BY transactions.transaction_id DESC limit ? offset ?"
let sqlQuery = "SELECT transactions.*,userdetails.username,userdetails.displayname,movies.title as movieTitle,movies.custom_url as movie_url,transactions.price as amount FROM transactions INNER JOIN movies on movies.movie_id = transactions.id INNER JOIN users on users.user_id = transactions.owner_id INNER JOIN userdetails ON users.user_id = userdetails.user_id WHERE 1 = 1 AND users.active = '1' AND users.approve = '1' AND (transactions.state = 'approved' || transactions.state = 'completed' || transactions.state = 'active') AND transactions.type IN ('rent_series_purchase','purchase_series_purchase','rent_movie_purchase','purchase_movie_purchase') " + conditionalWhere
await globalModel.custom(req, sqlQuery, condition).then(result => {
results = result
})
}
const paggingData = pagging.create(req, totalCount, page, '', LimitNum)
const url = req.originalUrl.replace(process.env.ADMIN_SLUG, '');
res.render('admin/movies/sold-movies', {getSymbolFromCurrency:getSymbolFromCurrency, loggedin_id: (req.user ? req.user.user_id : ""), loggedinLevel_id: (req.user ? req.user.level_id : ""), totalCount: totalCount, query: query, nav: url, results: results, title: "Manage Sold Movies & Series", paggingData: paggingData });
}
exports.deleteSoldMovies = async(req,res) => {
const id = req.params.id
let backURL = req.header('Referer') || process.env.ADMIN_SLUG + "/movies";
if (!id || !req.user) {
res.redirect(backURL)
return
}
await globalModel.custom(req,"DELETE FROM transactions WHERE transaction_id = ?",[id]).then(result => {
res.redirect(backURL)
return
})
}
exports.changeOrder = async (req, res) => {
const id = req.body.id
const nextid = req.body.nextid
let order = req.body.articleorder
order = order.split(',')
if (id || nextid) {
let categoryData = {}
await globalModel.custom(req, "SELECT * from categories WHERE category_id = ?", [id]).then(result => {
categoryData = JSON.parse(JSON.stringify(result));
categoryData = categoryData[0]
})
let categoryType = "", categoryTypeId = ""
if (categoryData.subcategory_id != 0) {
categoryType = 'subcategory_id'
categoryTypeId = categoryData.subcategory_id
} else if (categoryData.subsubcategory_id != 0) {
categoryType = 'subsubcategory_id'
categoryTypeId = categoryData.subsubcategory_id
} else
categoryType = 'category_id';
let categories = []
if (categoryTypeId) {
await globalModel.custom(req, "SELECT category_id FROM categories WHERE show_movies = 1 AND " + categoryType + " = ?", [categoryTypeId]).then(results => {
Object.keys(results).forEach(function (key) {
let result = JSON.parse(JSON.stringify(results[key]))
categories.push(result.category_id.toString())
})
})
} else {
await globalModel.custom(req, "SELECT category_id FROM categories WHERE show_movies = 1 AND subcategory_id = 0 AND subsubcategory_id = 0").then(results => {
Object.keys(results).forEach(function (key) {
let result = JSON.parse(JSON.stringify(results[key]))
categories.push(result.category_id.toString())
})
})
}
const newOrder = order.filter(Set.prototype.has, new Set(categories))
let orderIndex = newOrder.length + 1
newOrder.forEach(cat => {
orderIndex = orderIndex - 1;
globalModel.custom(req, "UPDATE categories SET `order` = " + orderIndex + " WHERE category_id = " + cat).then(result => {
})
})
}
res.send(req.body)
}
exports.deleteCategories = async (req, res) => {
let category_id = req.params.category_id
let categoryData = {}
await globalModel.custom(req, "SELECT * from categories WHERE category_id = ?", [category_id]).then(result => {
categoryData = JSON.parse(JSON.stringify(result));
categoryData = categoryData[0]
if (categoryData.subsubcategory_id == 0) {
if (categoryData.subcategory_id != 0) {
//select all subsubcategory_id
globalModel.custom(req, "SELECT * from categories WHERE subsubcategory_id = ?", [categoryData.category_id]).then(result => {
result.forEach(cat => {
if (cat.image) {
commonFunctions.deleteImage(req, res, cat.image, "movies/category")
}
globalModel.custom(req, "UPDATE movies SET subsubcategory_id = 0 WHERE subsubcategory_id = ?", [cat.category_id])
})
globalModel.custom(req, "DELETE from categories WHERE subsubcategory_id = ?", [categoryData.category_id]);
})
} else {
//select all subcategory_id
globalModel.custom(req, "SELECT * from categories WHERE subcategory_id = ?", [categoryData.category_id]).then(result => {
result.forEach(cat => {
globalModel.custom(req, "SELECT * from categories WHERE subsubcategory_id = ?", [cat.category_id]).then(result => {
result.forEach(cat => {
if (cat.image) {
commonFunctions.deleteImage(req, res, cat.image, "movies/category")
}
globalModel.custom(req, "UPDATE movies SET subsubcategory_id = 0 WHERE subsubcategory_id = ?", [cat.category_id])
})
globalModel.custom(req, "DELETE from categories WHERE subsubcategory_id = ?", [cat.category_id]);
})
if (cat.image) {
commonFunctions.deleteImage(req, res, cat.image, "movies/category")
}
globalModel.custom(req, "UPDATE movies SET subcategory_id = 0 WHERE subcategory_id = ?", [cat.category_id])
})
globalModel.custom(req, "DELETE from categories WHERE subcategory_id = ?", [categoryData.category_id]);
})
}
}
})
if (categoryData.image) {
commonFunctions.deleteImage(req, res, categoryData.image, "movies/category")
}
await globalModel.delete(req, "categories", "category_id", category_id).then(result => {
res.redirect(process.env.ADMIN_SLUG + "/movies/categories")
})
}
exports.categories = async (req, res) => {
const url = req.originalUrl.replace(process.env.ADMIN_SLUG, '');
//get all categories
const categories = []
await categoryModel.findAll(req, { type: "movie" }).then(result => {
result.forEach(function (doc, index) {
if (doc.subcategory_id == 0 && doc.subsubcategory_id == 0) {
const docObject = doc
//2nd level
let sub = []
result.forEach(function (subcat, index) {
if (subcat.subcategory_id == doc.category_id) {
let subsub = []
result.forEach(function (subsubcat, index) {
if (subsubcat.subsubcategory_id == subcat.category_id) {
subsub.push(subsubcat)
}
});
if (subsub.length > 0) {
subcat["subsubcategories"] = subsub;
}
sub.push(subcat)
}
});
if (sub.length > 0) {
docObject["subcategories"] = sub;
}
categories.push(docObject);
}
})
})
let imageSuffix = ""
if (req.appSettings.upload_system == "s3") {
imageSuffix = "https://" + req.appSettings.s3_bucket + ".s3.amazonaws.com";
}else if (req.appSettings.upload_system == "wisabi") {
imageSuffix = "https://s3.wasabisys.com/"+req.appSettings.s3_bucket ;
}
res.render('admin/movies/categories', { imageSuffix: imageSuffix, nav: url, title: "Manage Movies & Series Categories", categories: categories });
}
exports.addCategories = async (req, res) => {
let category_id = req.params.category_id
let categoryData = {}
const url = req.originalUrl.replace(process.env.ADMIN_SLUG, '');
if (category_id) {
await categoryModel.findById(category_id, req, res).then(result => {
if (result) {
categoryData = result
} else {
res.redirect(process.env.ADMIN_SLUG + "/error")
}
})
}
let imageSuffix = ""
if (req.appSettings.upload_system == "s3") {
imageSuffix = "https://" + req.appSettings.s3_bucket + ".s3.amazonaws.com";
}else if (req.appSettings.upload_system == "wisabi") {
imageSuffix = "https://s3.wasabisys.com/"+req.appSettings.s3_bucket ;
}
if (Object.keys(req.body).length === 0 && category_id) {
res.render("admin/movies/editCategories", { imageSuffix: imageSuffix, category_id: category_id, categoryData: categoryData, nav: url, title: "Edit Movie Category" })
return
}
if (req.imageError) {
res.send({ 'imageError': true })
return
}
categoryData['title'] = req.body.category_name;
categoryData['slug'] = req.body.slug
let cat_id = req.body.parent
if (category_id && categoryData.image && req.fileName) {
//remove image
commonFunctions.deleteImage(req, res, categoryData.image, "movies/category")
}
if (req.fileName) {
categoryData["image"] = "/upload/images/categories/movies/" + req.fileName
}
let slugExists = false
await categoryModel.findAll(req, { slug: req.body.slug, type: "movie", category_id: category_id }).then(result => {
if (result && result.length > 0) {
slugExists = true
}
})
if (slugExists) {
res.send({ 'slugError': true })
return
}
let parentId = 0, seprator = "", tableSeprator = "", data = ""
if (!category_id) {
if (cat_id != -1) {
let catData = {}
await categoryModel.findById(cat_id, req, res).then(result => {
catData = result
})
if (catData.subcategory_id == 0) {
categoryData['subcategory_id'] = cat_id;
seprator = ' ';
tableSeprator = '- ';
parentId = cat_id;
await categoryModel.orderNext(req, res, { 'subcat_id': cat_id }).then(result => {
categoryData['order'] = result ? result : 1
})
} else {
categoryData['subsubcategory_id'] = cat_id;
seprator = '3';
tableSeprator = '-- ';
await categoryModel.orderNext(req, res, { 'subsubcat_id': cat_id }).then(result => {
categoryData['order'] = result ? result : 1
})
parentId = cat_id;
}
} else {
parentId = 0;
seprator = '';
await categoryModel.orderNext(req, res, { 'category_id': true }).then(result => {
categoryData['order'] = result ? result : 1
})
tableSeprator = '';
}
categoryData["show_movies"] = 1;
}
//create category
let categoryId = ""
if (!category_id) {
await globalModel.create(req, categoryData, "categories").then(category => {
categoryId = category.insertId;
})
if (req.fileName) {
data = '<img style="height: 50px;width:50px;margin-bottom: 10px;" src="' + categoryData["image"] + '" />';
} else {
data = "---";
}
let editCat = '<a class="btn btn-primary btn-xs" href="' + process.env.ADMIN_SLUG + '/movies/categories/add/' + categoryId + '">Edit</a>';
let deleteCat = ' <a class="btn btn-danger btn-xs" onclick="preDeleteFn(this)" data-id="' + categoryId + '" data-toggle="modal" data-target="#modal-danger">Delete</a>'
let tableData = '<tr id="categoryid-' + categoryId + '"><td>' + data + '</td><td>' + tableSeprator + req.body.category_name + '<div class="hidden" style="display:none" id="inline_' + categoryId + '"><div class="parent">' + parentId + '</div></div></td><td>' + req.body.slug + '</td><td>' + editCat + deleteCat + '</td></tr>';
res.send({ 'seprator': seprator, 'tableData': tableData, 'id': categoryId, 'name': req.body.category_name, 'slugError': false })
} else {
await globalModel.update(req, categoryData, "categories", "category_id", category_id).then(category => {
res.send({ success: true })
})
}
}
exports.levels = async (req, res) => {
let level_id = req.params.level_id
let memberLevels = {}
let flag = ""
let type = "user"
await levels.findAll(req, req.query).then(result => {
if (result) {
result.forEach(res => {
if ((!level_id && res.flag == "default")) {
level_id = res.level_id
}
if (res.level_id == level_id || (!level_id && res.flag == "default")) {
flag = res.flag
type = res.type
}
memberLevels[res.level_id] = res.title
});
}
})
const cacheContent = await permission.getKeyValue(req, level_id)
//get uploaded file by admin
const files = { "": "" }
await fileManager.findAll(req, { "column": "path", "like": "image" }).then(result => {
result.forEach(res => {
let url = res.path.split(/(\\|\/)/g).pop()
files[res.path] = res.orgName
});
})
const url = req.originalUrl.replace(process.env.ADMIN_SLUG, '');
var fields = forms.fields;
var validators = forms.validators;
var widgets = forms.widgets;
const cssClasses = {
label: [""],
field: ["form-group"],
classes: ["form-control"]
};
const deleteOptions = {}
const viewOptions = {}
const editOptions = {}
if (type == "admin" || type == "moderator") {
deleteOptions["2"] = "Yes, allow to delete other users movies."
viewOptions["2"] = "Yes, allow to view private and locked movies of users."
editOptions["2"] = "Yes, allow to edit everyones movies."
}
viewOptions["0"] = "No, do not allow to view movies."
viewOptions["1"] = "Yes, allow to view movies."
deleteOptions["1"] = "Yes, allow to delete own movies."
deleteOptions["0"] = "No, do not allow to delete movies."
editOptions["1"] = "Yes, allow to edit own movies."
editOptions["0"] = "No, do not edit movies."
let formFields = {
level_id: fields.string({
label: "Member Role",
choices: memberLevels,
required: true,
widget: widgets.select({ "classes": ["select"] }),
cssClasses: { "field": ["form-group"] },
value: level_id
}),
}
if (flag != "public") {
let formFieldsPublic ={
create: fields.string({
choices: {"1" : "Yes, allow to upload movies","0" : "No, do not allow to upload movies"},
widget: widgets.select({ "classes": ["select"] }),
label:"Allow member to upload movies",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value:cacheContent["movie.create"] ? cacheContent["movie.create"].toString() : 1
})
}
formFields = {...formFields,...formFieldsPublic}
}
let formFieldsView = {
view: fields.string({
choices: viewOptions,
widget: widgets.select({ "classes": ["select"] }),
label: "Can Member view uploaded movies?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: cacheContent["movie.view"] ? cacheContent["movie.view"].toString() : 1
}),
}
formFields = { ...formFields, ...formFieldsView }
if (flag != "public") {
let formFields1 = {
edit: fields.string({
choices: editOptions,
widget: widgets.select({ "classes": ["select"] }),
label: "Can Member edit uploaded movies?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: cacheContent["movie.edit"] ? cacheContent["movie.edit"].toString() : 1
}),
delete: fields.string({
choices: deleteOptions,
widget: widgets.select({ "classes": ["select"] }),
label: "Can Member delete uploaded movies?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: cacheContent["movie.delete"] ? cacheContent["movie.delete"].toString() : 1
}),
quota: fields.string({
label: "No. Of movies member can upload to selected level? Enter 0 for unlimited",
validators: [validators.integer('Enter integer value only.')],
cssClasses: { "field": ["form-group"] },
widget: widgets.text({ "classes": ["form-control"] }),
value: cacheContent["movie.quota"] ? cacheContent["movie.quota"].toString() : 0
}),
storage: fields.string({
label: "Movies Storage Limit",
choices: { "1048576": "1 MB", "5242880": "5 MB", "26214400": "25 MB", "52428800": "50 MB", "104857600": "100 MB", "524288000": "50 MB", "1073741824": "1 GB", "2147483648": "2 GB", "5368709120": "5 GB", "10737418240": "10 GB", "0": "Unlimited" },
required: true,
widget: widgets.select({ "classes": ["select"] }),
cssClasses: { "field": ["form-group"] },
value: cacheContent["movie.storage"] ? cacheContent["movie.storage"].toString() : 0
}),
embedcode: fields.string({
choices: { "1": "Yes", "0": "No" },
widget: widgets.select({ "classes": ["select"] }),
label: "Do you want to allow Embed Code?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: cacheContent["movie.embedcode"] ? cacheContent["movie.embedcode"].toString() : 0
}),
sponsored: fields.string({
choices: { "1": "Yes", "0": "No" },
widget: widgets.select({ "classes": ["select"] }),
label: "Do you want to auto mark Movies as Sponsored?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: cacheContent["movie.sponsored"] ? cacheContent["movie.sponsored"].toString() : 1
}),
featured: fields.string({
choices: { "1": "Yes", "0": "No" },
widget: widgets.select({ "classes": ["select"] }),
label: "Do you want to auto mark Movies as Featured?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: cacheContent["movie.featured"] ? cacheContent["movie.featured"].toString() : 1
}),
hot: fields.string({
choices: { "1": "Yes", "0": "No" },
widget: widgets.select({ "classes": ["select"] }),
label: "Do you want to auto mark Movies as Hot?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: cacheContent["movie.hot"] ? cacheContent["movie.hot"].toString() : 1
}),
auto_approve: fields.string({
choices: { "1": "Yes", "0": "No" },
widget: widgets.select({ "classes": ["select"] }),
label: "Do you want to auto approve movies?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: cacheContent["movie.auto_approve"] ? cacheContent["movie.auto_approve"].toString() : 1
}),
// donation: fields.string({
// choices: { "1": "Yes", "0": "No" },
// widget: widgets.select({ "classes": ["select"] }),
// label: "Do you want to enable donation on uploaded movies?",
// fieldsetClasses: "form_fieldset",
// cssClasses: { "field": ["form-group"] },
// value: cacheContent["movie.donation"] ? cacheContent["movie.donation"].toString() : 1
// }),
sell_movies: fields.string({
choices: { "1": "Yes", "0": "No" },
widget: widgets.select({ "classes": ["select"] }),
label: "Do you want to allow member to sell uploaded movies?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: cacheContent["movie.sell_movies"] ? cacheContent["movie.sell_movies"].toString() : 1
}),
sell_rent_movies: fields.string({
choices: { "1": "Yes", "0": "No" },
widget: widgets.select({ "classes": ["select"] }),
label: "Do you want to allow members to sell movies on rent?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: cacheContent["movie.sell_rent_movies"] ? cacheContent["movie.sell_rent_movies"].toString() : 1
}),
}
formFields = { ...formFields, ...formFields1 }
}
var reg_form = forms.create(formFields, { validatePastFirstError: true });
reg_form.handle(req, {
success: function (form) {
permission.insertUpdate(req, res, form.data, level_id, "movie").then(result => {
res.send({ success: 1, message: "Operation performed successfully.", url: process.env.ADMIN_SLUG + "/movies/levels/" + level_id })
})
},
error: function (form) {
const errors = formFunctions.formValidations(form);
res.send({ errors: errors });
},
other: function (form) {
res.render('admin/movies/levels', { nav: url, reg_form: reg_form, title: "Movies Member Role Settings" });
}
});
}
exports.settings = async (req, res) => {
const url = req.originalUrl.replace(process.env.ADMIN_SLUG, '');
var fields = forms.fields;
var validators = forms.validators;
var widgets = forms.widgets;
var cssClasses = {
field: ["form-group"],
classes: ["form-control"]
};
//get uploaded file by admin
const files = { "": "" }
await fileManager.findAll(req, { "column": "path", "like": "image" }).then(result => {
result.forEach(res => {
let url = res.path.split(/(\\|\/)/g).pop()
files[res.path] = res.orgName
});
})
let allLaguages = await languageModel.spokenLanguages()
let languages = {}
allLaguages.forEach(language => {
languages[language.code] = language.name
})
var reg_form = forms.create({
enable_movie: fields.string({
choices: { "1": "Yes", "0": "No" },
widget: widgets.select({ "classes": ["select"] }),
label: "Do you want to enable movies & series?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "enable_movie", '0').toString()
}),
movie_tmdb_api_key: fields.string({
label: "TMDB API Key",
cssClasses: { "field": ["form-group"] },
widget: widgets.text({ "classes": ["form-control"] }),
value: req.loguserallowed ? "****" : settings.getSetting(req, "movie_tmdb_api_key", '')
}),
movie_tmdb_language: fields.string({
label: "TMDB Language",
choices: languages,
required: false,
widget: widgets.select({ "classes": ["select"] }),
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "movie_tmdb_language", "en").toString()
}),
movie_tmdb_language_label: fields.string({
widget: widgets.label({ content: 'In what language should content be fetched from TMDB.' }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
movie_tmdb_owner: fields.string({
widget: widgets.text({ "classes": ["form-control"] }),
label: "Enter Owner ID which you want to associate for impoted movies/series?",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "movie_tmdb_owner", '1').toString()
}),
movie_tmdb_adult: fields.string({
choices: { "1": "Yes", "0": "No" },
widget: widgets.select({ "classes": ["select"] }),
label: "Allow Adult Content to fetched from TMDB?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "movie_tmdb_adult", '0').toString()
}),
multiple_movies_series: fields.string({
widget: formFunctions.makeClickable({ content: '[0] to learn how to import movies/series in bulk.', replace: [{ 0: '<a href="javascript:;" data-toggle="modal" data-target="#modal-tmdb">Click here</a>' }] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
movie_upload_movies_type: fields.string({
label: "Select videos conversion types from below upload types",
choices: { "360": "360p", "480": "480p",'720':"720p","1080":"1080p","2048":"2048p","4096":"4096p" },
cssClasses: { "field": ["form-group"] },
widget: widgets.multipleCheckbox({ "classes": ["form-control-checkbox"] }),
value: settings.getSetting(req, "movie_upload_movies_type", '').split(",")
}),
movie_upload_movies_type_label: fields.string({
widget: widgets.label({ content: 'Choose from above setting in which format you want to upload movies & series videos on your website. If you enable higher resolution movies than your server must be that much capable to convert those resolution movies.' }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
movie_conversion_type: fields.string({
label: "Convert movies & series video speed",
choices: { "ultrafast": "Ultrafast", "superfast": "Superfast",'veryfast':"Veryfast",'faster':"Faster",'fast':"Fast",'medium':"Medium",'slow':"Slow",'slower':"Slower",'veryslow':"Veryslow" },
widget: widgets.select({ "classes": ["select"] }),
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "movie_conversion_type", 'ultrafast')
}),
movie_conversion_type_label: fields.string({
widget: widgets.label({ content: 'Using a slower preset gives you better compression, or quality per filesize, whereas faster presets give you worse compression and higher filesize.' }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
movie_upload_limit: fields.string({
label: "Maximum Upload Limit of video in movies & series. Enter value in MB (Enter 0 for unlimited.)",
validators: [validators.integer('Enter integer value only.')],
cssClasses: { "field": ["form-group"] },
widget: widgets.text({ "classes": ["form-control"] }),
value: settings.getSetting(req, "movie_upload_limit", '0')
}),
// movie_advanced_grid: fields.string({
// choices: { "1": "Yes", "0": "No" },
// widget: widgets.select({ "classes": ["select"] }),
// label: "Show movies/series advanced grid on browse pages",
// fieldsetClasses: "form_fieldset",
// cssClasses: { "field": ["form-group"] },
// value: settings.getSetting(req, "movie_advanced_grid", '0').toString()
// }),
movie_favourite: fields.string({
choices: { "1": "Yes", "0": "No" },
widget: widgets.select({ "classes": ["select"] }),
label: "Enable Favourite feature on movies & series?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "movie_favourite", '1').toString()
}),
// movie_donation: fields.string({
// choices: { "1": "Yes", "0": "No" },
// widget: widgets.select({ "classes": ["select"] }),
// label: "Enable donation feature on movies & series?",
// fieldsetClasses: "form_fieldset",
// cssClasses: { "field": ["form-group"] },
// value: settings.getSetting(req, "movie_donation", '1').toString()
// }),
// movie_donation_label: fields.string({
// widget: widgets.label({ content: 'Enabling this feature user can request for donation on uploaded movies' }),
// cssClasses: { "field": ["form-group", "form-description"] },
// }),
movie_sell: fields.string({
choices: { "1": "Yes", "0": "No" },
widget: widgets.select({ "classes": ["select"] }),
label: "Allow user to sell movies & series?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "movie_sell", '1').toString()
}),
movie_commission_type: fields.string({
choices: { "1": "Fixed Price", "2": "Percentage" },
widget: widgets.select({ "classes": ["select"] }),
label: "Commission Type of sell movies & series?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "movie_commission_type", '1').toString()
}),
movie_commission_value: fields.string({
label: "Get Commission from sell movies & series (put 0 if you not want comission.)",
cssClasses: { "field": ["form-group"] },
widget: widgets.text({ "classes": ["form-control"] }),
value: settings.getSetting(req, "movie_commission_value", '')
}),
movie_rent: fields.string({
choices: { "1": "Yes", "0": "No" },
widget: widgets.select({ "classes": ["select"] }),
label: "Allow user to rent movies & series?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "movie_rent", '1').toString()
}),
movie_commission_rent_type: fields.string({
choices: { "1": "Fixed Price", "2": "Percentage" },
widget: widgets.select({ "classes": ["select"] }),
label: "Commission Type of rent movies & series?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "movie_commission_rent_type", '1').toString()
}),
movie_commission_rent_value: fields.string({
label: "Get Commission from rent movies & series (put 0 if you not want comission.)",
cssClasses: { "field": ["form-group"] },
widget: widgets.text({ "classes": ["form-control"] }),
value: settings.getSetting(req, "movie_commission_rent_value", '')
}),
movie_watchlater: fields.string({
choices: { "1": "Yes", "0": "No" },
widget: widgets.select({ "classes": ["select"] }),
label: "Enable Watch Later Feature on movies & series?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "movie_watchlater", '1').toString()
}),
movie_like: fields.string({
choices: { "1": "Yes", "0": "No" },
widget: widgets.select({ "classes": ["select"] }),
label: "Enable like feature on movies & series?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "movie_like", '1').toString()
}),
movie_dislike: fields.string({
choices: { "1": "Yes", "0": "No" },
widget: widgets.select({ "classes": ["select"] }),
label: "Enable dislike feature on movies & series?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "movie_dislike", '1').toString()
}),
movie_comment: fields.string({
choices: { "1": "Yes", "0": "No" },
widget: widgets.select({ "classes": ["select"] }),
label: "Enable comment feature on movies & series?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "movie_comment", '1').toString()
}),
movie_comment_like: fields.string({
choices: { "1": "Yes", "0": "No" },
widget: widgets.select({ "classes": ["select"] }),
label: "Enable like feature on movies & series comment?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "movie_comment_like", '1').toString()
}),
movie_comment_dislike: fields.string({
choices: { "1": "Yes", "0": "No" },
widget: widgets.select({ "classes": ["select"] }),
label: "Enable dislike feature on movies & series comment?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "movie_comment_dislike", '1').toString()
}),
movie_rating: fields.string({
choices: { "1": "Yes", "0": "No" },
widget: widgets.select({ "classes": ["select"] }),
label: "Enable rating feature on movies & series?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "movie_rating", '1').toString()
}),
movie_featured: fields.string({
choices: { "1": "Yes", "0": "No" },
widget: widgets.select({ "classes": ["select"] }),
label: "Enable featured label on movies & series?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "movie_featured", '1').toString()
}),
movie_sponsored: fields.string({
choices: { "1": "Yes", "0": "No" },
widget: widgets.select({ "classes": ["select"] }),
label: "Enable sponsored label on movies & series?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "movie_sponsored", '1').toString()
}),
movie_hot: fields.string({
choices: { "1": "Yes", "0": "No" },
widget: widgets.select({ "classes": ["select"] }),
label: "Enable hot label on movies & series?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "movie_hot", '1').toString()
}),
movie_adult: fields.string({
choices: { "1": "Yes", "0": "No" },
widget: widgets.select({ "classes": ["select"] }),
label: "Enable adult marking on movies & series?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "movie_adult", '1').toString()
}),
movie_default_photo: fields.string({
label: "Default Photo on movies & series",
choices: files,
required: false,
widget: widgets.select({ "classes": ["select"] }),
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "movie_default_photo", "").toString()
}),
episode_default_photo: fields.string({
label: "Default Photo on Episode",
choices: files,
required: false,
widget: widgets.select({ "classes": ["select"] }),
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "episode_default_photo", "").toString()
}),
seasons_default_photo: fields.string({
label: "Default Photo on Seasons",
choices: files,
required: false,
widget: widgets.select({ "classes": ["select"] }),
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "seasons_default_photo", "").toString()
}),
movie_category_default_photo: fields.string({
label: "Default Photo on movies & series Category",
choices: files,
required: false,
widget: widgets.select({ "classes": ["select"] }),
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "movie_category_default_photo", "").toString()
}),
cast_crew_default_photo: fields.string({
label: "Default Photo on Cast & Crew Members",
choices: files,
required: false,
widget: widgets.select({ "classes": ["select"] }),
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "cast_crew_default_photo", "").toString()
}),
movie_cnt_label: fields.string({
widget: formFunctions.makeClickable({ content: '<h2 style="text-align: center;margin: 40px;text-decoration: underline;">Movie Cast & Crew Members Settings</h2>', replace: [] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
cast_crew_member: fields.string({
choices: { "1": "Enabled", "0": "Disabled" },
widget: widgets.select({ "classes": ["select"] }),
label: "Enable Cast & Crew functionality in movies & series?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "cast_crew_member", '1').toString()
}),
cast_crew_member_label: fields.string({
widget: widgets.label({ content: 'If you enable this feature then user are able to select Cast & Crew in the movies & series.' }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
cast_crew_member_rating: fields.string({
choices: { "1": "Enabled", "0": "Disabled" },
widget: widgets.select({ "classes": ["select"] }),
label: "Enable rating functionality in Cast & Crew?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "cast_crew_member_rating", '1').toString()
}),
cast_crew_member_favourite: fields.string({
choices: { "1": "Enabled", "0": "Disabled" },
widget: widgets.select({ "classes": ["select"] }),
label: "Enable favourite feature on Cast & Crew?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "cast_crew_member_favourite", '1').toString()
}),
cast_crew_member_like: fields.string({
choices: { "1": "Enabled", "0": "Disabled" },
widget: widgets.select({ "classes": ["select"] }),
label: "Enable like feature on Cast & Crew?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "cast_crew_member_like", '1').toString()
}),
cast_crew_member_dislike: fields.string({
choices: { "1": "Enabled", "0": "Disabled" },
widget: widgets.select({ "classes": ["select"] }),
label: "Enable dislike feature on Cast & Crew?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "cast_crew_member_dislike", '1').toString()
}),
cast_crew_member_comment: fields.string({
choices: { "1": "Enabled", "0": "Disabled" },
widget: widgets.select({ "classes": ["select"] }),
label: "Enable comment feature on Cast & Crew?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "cast_crew_member_comment", '1').toString()
}),
cast_crew_member_comment_like: fields.string({
choices: { "1": "Enabled", "0": "Disabled" },
widget: widgets.select({ "classes": ["select"] }),
label: "Enable like feature on comment in Cast & Crew?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "cast_crew_member_comment_like", '1').toString()
}),
cast_crew_member_comment_dislike: fields.string({
choices: { "1": "Enabled", "0": "Disabled" },
widget: widgets.select({ "classes": ["select"] }),
label: "Enable dislike feature on comment Cast & Crew?",
fieldsetClasses: "form_fieldset",
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req, "cast_crew_member_comment_dislike", '1').toString()
}),
}, { validatePastFirstError: true });
reg_form.handle(req, {
success: function (form) {
if(form.data['movie_commission_type'] == "1"){
if(parseFloat(form.data['movie_commission_value']) < 0){
res.send({ "errors": { 'movie_commission_value': "Please enter valid value." } })
return
}
}else if(form.data['movie_commission_type'] == "2"){
if(parseFloat(form.data['movie_commission_value']) > 99.99 || parseFloat(form.data['movie_commission_value']) < 0){
//error
res.send({ "errors": { 'movie_commission_value': "Please enter valid value." } })
return
}
}
if(form.data['movie_commission_rent_type'] == "1"){
if(parseFloat(form.data['movie_commission_rent_value']) < 0){
res.send({ "errors": { 'movie_commission_rent_value': "Please enter valid value." } })
return
}
}else if(form.data['movie_commission_rent_type'] == "2"){
if(parseFloat(form.data['movie_commission_rent_value']) > 99.99 || parseFloat(form.data['movie_commission_rent_value']) < 0){
//error
res.send({ "errors": { 'movie_commission_rent_value': "Please enter valid value." } })
return
}
}
delete form.data["movie_upload_label"]
delete form.data["movie_tmdb_language_label"]
delete form.data["multiple_movies_series"]
delete form.data["movie_ffmpeg_path_label"]
delete form.data["movie_donation_label"]
delete form.data["cast_crew_member_label"]
delete form.data["artist_cnt_label"]
form.data['movie_commission_value'] = parseFloat(form.data['movie_commission_value'])
settings.setSettings(req, form.data)
res.send({ success: 1, message: "Setting Saved Successfully." })
},
error: function (form) {
const errors = formFunctions.formValidations(form);
res.send({ errors: errors });
},
other: function (form) {
res.render('admin/movies/settings', { nav: url, reg_form: reg_form, title: "Movies & Series Settings" });
}
});
}
|
const isObject = (value) => {
return !!value &&
typeof value === 'object' &&
typeof value.getMonth !== 'function' &&
!Array.isArray(value)
}
const merge = (...sources) => {
const [target, ...rest] = sources
for (const object of rest) {
for (const key in object) {
const targetValue = target[key]
const sourceValue = object[key]
const isMergable = isObject(targetValue) && isObject(sourceValue)
target[key] = isMergable ? merge({}, targetValue, sourceValue) : sourceValue
}
}
return target
}
const sortByKey = (unsortedObject) => {
const sortedObject = {}
Object.keys(unsortedObject).sort().forEach((key) => {
sortedObject[key] = unsortedObject[key]
})
return sortedObject
}
module.exports = {
isObject,
merge,
sortByKey
}
|
import { RSAA, getJSON } from 'redux-api-middleware';
export const START_PROFILE_NAME = '@@profile/START_PROFILE_NAME';
export const PROFILE_NAME = '@@profile/PROFILE_NAME';
export const ERROR_PROFILE_NAME = '@@profile/ERROR_PROFILE_NAME';
export const START_PROFILE_LOADING = '@@profile/START_PROFILE_LOADING';
export const SUCCESS_PROFILE_LOADING = '@@profile/SUCCESS_PROFILE_LOADING';
export const ERROR_PROFILE_LOADING = '@@profile/ERROR_PROFILE_LOADING';
export const setName = (name) => ({
[RSAA]: {
endpoint: "http://localhost:3000/profile",
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name,
}),
types: [
START_PROFILE_NAME,
{
type: PROFILE_NAME,
payload: (action, state, res) => getJSON(res).then(data => data),
},
ERROR_PROFILE_NAME,
]
}
});
export const loadProfile = () => ({
[RSAA]: {
endpoint: "http://localhost:3000/profile",
method: 'GET',
headers: { 'Content-Type': 'application/json' },
types: [
START_PROFILE_LOADING,
{
type: SUCCESS_PROFILE_LOADING,
payload: (action, state, res) => getJSON(res).then(data => data),
},
ERROR_PROFILE_LOADING,
]
}
});
|
import { types } from '../constants';
import { todoApi } from '../apis';
import { mapTeams, mapTeam } from '../services/mappers';
const getTeamsStart = () => {
return { type: types.GET_TEAMS_START };
};
const getTeamsSuccess = response => {
return { type: types.GET_TEAMS_SUCCESS, payload: mapTeams(response.data) };
};
export const getTeams = authToken => async dispatch => {
dispatch(getTeamsStart());
todoApi.setJwt(authToken);
const response = await todoApi.get('/teams');
dispatch(getTeamsSuccess(response));
};
export const createTeam = (params, authToken) => async dispatch => {
todoApi.setJwt(authToken);
const response = await todoApi.post('/teams', params);
dispatch({ type: types.CREATE_TEAM, payload: mapTeam(response.data) });
};
export const updateTeam = (params, id, authToken) => async dispatch => {
todoApi.setJwt(authToken);
await todoApi.put(`/teams/${id}`, params);
dispatch({ type: types.UPDATE_TEAM, payload: { params, id } });
};
|
import React from 'react';
import { Form, Field } from 'react-final-form';
import Styles from './FormStyles';
import { mapPlayers } from '../initialState';
const required = value => (value ? undefined : 'Required');
const mustBeNumber = value => (isNaN(value) ? 'Must be a number' : undefined);
const minValue = min => value =>
isNaN(value) || value >= min ? undefined : `Should be greater than ${min}`;
const usernameAlreadyTaken = (value) => {
const usernames = [];
mapPlayers.forEach((v) => {
usernames.push(v.name);
});
return usernames.includes(value) ? 'Username already taken!' : undefined;
};
const composeValidators = (...validators) => value =>
validators.reduce((error, validator) => error || validator(value), undefined);
const SignInForm = ({ onSubmit }) => (
<Styles data-styled-components="true">
<Form
onSubmit={onSubmit}
initialValues={{ }}
validate={(values) => {
const errors = {};
// if (!values.Username) {
// errors.Username = 'Required';
// }
if (!values.Password) {
errors.Password = 'Required';
}
// if (!values.favoriteColor) {
// errors.favoriteColor = 'Required';
// }
/*
if (!values.age) {
errors.age = 'Required';
} else if (isNaN(values.age)) {
errors.age = "Must be a number";
} else if (values.age < 18) {
errors.age = "No kids allowed";
}
*/
return errors;
}}
render={({ handleSubmit, form, submitting, pristine, values }) => (
<form onSubmit={handleSubmit}>
<Field
name="Username"
validate={composeValidators(required, usernameAlreadyTaken)}
>
{({ input, meta }) => (
<div>
<label>Username</label>
<input {...input} type="text" placeholder="Username" />
{meta.error && meta.touched && <span>{meta.error}</span>}
</div>
)}
</Field>
<Field name="Password">
{({ input, meta }) => (
<div>
<label>Password</label>
<input {...input} type="password" placeholder="Password" />
{meta.error && meta.touched && <span>{meta.error}</span>}
</div>
)}
</Field>
<div>
<label>Favorite Color</label>
<Field name="favoriteColor" component="select">
<option />
<option value="#ff0000">❤️ Red</option>
<option value="#00ff00">💚 Green</option>
<option value="#0000ff">💙 Blue</option>
</Field>
</div>
<div className="buttons">
<button
type="submit"
disabled={submitting || pristine}
>
Submit
</button>
<button
type="button"
onClick={form.reset}
disabled={submitting || pristine}
>
Reset
</button>
</div>
{/* <pre>{JSON.stringify(values, 0, 2)}</pre> */}
</form>
)}
/>
</Styles>
);
export default SignInForm;
|
import React from "react";
import axios from "./axios";
import { Link } from "react-router-dom";
export default class Register extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.handleInput = this.handleInput.bind(this);
this.submitRegistration = this.submitRegistration.bind(this);
}
handleInput(e) {
this[e.target.name] = e.target.value;
}
submitRegistration(e) {
e.preventDefault();
axios
.post("/register.json", {
first: this.first,
last: this.last,
email: this.email,
password: this.password
})
.then(resp => {
if (resp.data.success) {
location.replace("/");
} else {
console.log("registration not successful");
this.setState({
error: true
});
}
})
.catch(err => {
console.log("Error in axios.post('/register') ", err);
});
}
render() {
return (
<div>
<form
className="form flex column"
method="post"
onSubmit={this.submitRegistration}
>
<input
type="text"
name="first"
placeholder="First name"
onChange={this.handleInput}
/>
<input
type="text"
name="last"
placeholder="Last name"
onChange={this.handleInput}
/>
<input
type="email"
name="email"
placeholder="Email address"
onChange={this.handleInput}
/>
<input
type="password"
name="password"
placeholder="Password"
onChange={this.handleInput}
/>
<button>Register</button>
<button className="instead">
<Link
to="/login"
className="instead"
onClick={this.props.welcomeToggle}
>
Login instead
</Link>
</button>
</form>
{this.state.error && (
<div className="error">
Registration did not work. Please try again
</div>
)}
</div>
);
}
}
|
var transportIn = require('rh-transformer').transportIn;
var transportOut = require('rh-transformer').transportOut;
(function (angular) {
angular.module('rhasesAngularJSCommons.services')
.service('transformService', function () {
if (!transportIn || !transportOut ){
throw new Error('Error requiring transporter. Undefined function.')
}
return {
transportIn: transportIn,
transportOut: transportOut
};
});
})(angular);
|
require('dotenv').config()
var express = require('express');
var router = express.Router();
var axios = require('axios');
/* GET home page. */
router.get('/', function (req, res, next) {
res.render('index', { title: 'WeatherApp' });
});
router.post('/data', (req, res, next) => {
var city = req.body.city;
var unit = req.body.units;
console.log(typeof unit);
var url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${process.env.API_KEY}`;
if (unit === '1') {
url = url + `&units=metric`;
}
else {
url = url
}
axios.get(url)
.then((response) => {
res.send(response.data.main);
})
.catch((err) => {
if (err.request) {
res.status(404).send('Something went wrong with Request!');
}
else if (err.response) {
console.log(err.response);
res.status(404).send('Something went wrong with response!');
}
else {
res.status(404).send(err.message)
}
})
})
module.exports = router;
|
import { makeStyles } from "@material-ui/core";
export const useStyles = makeStyles((theme) => ({
state: {
fontSize: 16,
},
collegeName: {
fontSize: '17px',
fontWeight: '450'
},
cardRoot: {
minWidth: 275,
margin: '10px 20px 15px 0',
width: '100%',
},
cardContentRoot: {
backgroundColor: '#fffefc',
},
navigateIcon: {
},
navigateGPS: {
padding: '0'
},
icon: {
marginRight:'15px',
color: '#000000',
opacity: .8,
height: '18px',
alignSelf: 'center',
}
}));
|
function averagePrice(arr) {
var totalBitcoin = 0,
totalMoney = 0;
arr.forEach(function (curr) {
totalMoney += curr[0];
totalBitcoin += curr[0] / curr[1];
});
return totalMoney / totalBitcoin;
}
if (require.main === module) {
function assert(truthy) {
if (!truthy) {
throw new Error('fail');
}
}
assert(averagePrice([[200, 245]]), 245);
assert(averagePrice([[200, 245], [200, 255]]), 250);
assert(averagePrice([[200, 200], [400, 200]]), 200);
assert(averagePrice([[100, 200], [500, 200]]), 240);
}
|
import React from 'react';
import {
Button,
Modal,
} from "reactstrap";
class EmailVerifyDialog extends React.Component {
render() {
return(
<Modal
className="modal-dialog-centered modal-danger"
contentClassName="bg-gradient-danger"
isOpen={this.state.notificationModal}
toggle={() => this.toggleModal("notificationModal")}
>
<div className="modal-header">
<h6 className="modal-title" id="modal-title-notification">
Your attention is required
</h6>
<button
aria-label="Close"
className="close"
data-dismiss="modal"
type="button"
onClick={() => this.toggleModal("notificationModal")}
>
<span aria-hidden={true}>×</span>
</button>
</div>
<div className="modal-body">
<div className="py-3 text-center">
<i className="ni ni-bell-55 ni-3x" />
<h4 className="heading mt-4">You should read this!</h4>
<p>
A small river named Duden flows by their place and supplies
it with the necessary regelialia.
</p>
</div>
</div>
<div className="modal-footer">
<Button className="btn-white" color="default" type="button">
Ok, Got it
</Button>
<Button
className="text-white ml-auto"
color="link"
data-dismiss="modal"
type="button"
onClick={() => this.toggleModal("notificationModal")}
>
Close
</Button>
</div>
</Modal>
)
}
}
export default EmailVerifyDialog;
|
import React, {Component} from 'react'
export default class About extends Component {
render() {
return (
<div>
<section className="colorlib-skills" data-section="work">
<div className="colorlib-narrow-content">
<div className="row">
<div className="col-md-6 col-md-offset-3 col-md-pull-3 animate-box"
data-animate-effect="fadeInLeft">
<span className="heading-meta">My Work</span>
<h2 className="colorlib-heading animate-box">Recent Work</h2>
</div>
</div>
<div className="row">
<div className="col-md-8 animate-box" data-animate-effect="fadeInLeft">
<p>Currently, I am very happy with my work as a full-stack developer at PTN Company.</p>
<p>Now, I am happy with DotNet technology stack an try to study more it.</p>
</div>
<div className="col-md-6 animate-box" data-animate-effect="fadeInLeft">
<div className="progress-wrap">
<h3>Java</h3>
<div className="progress">
<div className="progress-bar color-1" role="progressbar" aria-valuenow="75"
aria-valuemin="0" aria-valuemax="100" style={{width: '50%'}}>
<span></span>
</div>
</div>
</div>
</div>
<div className="col-md-6 animate-box" data-animate-effect="fadeInRight">
<div className="progress-wrap">
<h3>DotNet</h3>
<div className="progress">
<div className="progress-bar color-2" role="progressbar" aria-valuenow="60"
aria-valuemin="0" aria-valuemax="100" style={{width: '50%'}}>
<span></span>
</div>
</div>
</div>
</div>
<div className="col-md-6 animate-box" data-animate-effect="fadeInLeft">
<div className="progress-wrap">
<h3>HTML</h3>
<div className="progress">
<div className="progress-bar color-3" role="progressbar" aria-valuenow="75"
aria-valuemin="0" aria-valuemax="100" style={{width: '50%'}}>
<span></span>
</div>
</div>
</div>
</div>
<div className="col-md-6 animate-box" data-animate-effect="fadeInRight">
<div className="progress-wrap">
<h3>CSS</h3>
<div className="progress">
<div className="progress-bar color-4" role="progressbar" aria-valuenow="90"
aria-valuemin="0" aria-valuemax="100" style={{width: '50%'}}>
<span></span>
</div>
</div>
</div>
</div>
<div className="col-md-6 animate-box" data-animate-effect="fadeInLeft">
<div className="progress-wrap">
<h3>Angular</h3>
<div className="progress">
<div className="progress-bar color-5" role="progressbar" aria-valuenow="70"
aria-valuemin="0" aria-valuemax="100" style={{width: '50%'}}>
<span></span>
</div>
</div>
</div>
</div>
<div className="row" style={{marginBottom: '15px'}}>
<div className="col-md-12 animate-box" data-animate-effect="fadeInLeft">
<div className="hire">
<h2>I working in cute team name <strong>OpenOffice</strong></h2>
</div>
</div>
</div>
<div className="row">
<div className="col-md-6 animate-box" data-animate-effect="fadeInLeft">
<div className="project" style={{backgroundImage: 'url(images/duy.jpg)'}}>
<div className="desc">
<div className="con">
<h3><a href="work.html">Duy Vo</a></h3>
<span>Role: Lead</span>
<span>Skill: FullSkill</span>
</div>
</div>
</div>
</div>
<div className="col-md-6 animate-box" data-animate-effect="fadeInRight">
<div className="project" style={{backgroundImage: 'url(images/tan.jpg)'}}>
<div className="desc">
<div className="con">
<h3><a href="work.html">Tan Tran</a></h3>
<span>Role: Sub Lead</span>
<span>Skill: half full skill</span>
</div>
</div>
</div>
</div>
<div className="col-md-6 animate-box" data-animate-effect="fadeInRight">
<div className="project" style={{backgroundImage: 'url(images/nguyen.jpg)'}}>
<div className="desc">
<div className="con">
<h3><a href="work.html">Nguyen Tran</a></h3>
<span>Role: BA</span>
</div>
</div>
</div>
</div>
<div className="col-md-6 animate-box" data-animate-effect="fadeInRight">
<div className="project" style={{backgroundImage: 'url(images/an.jpg)'}}>
<div className="desc">
<div className="con">
<h3><a href="work.html">An Nguyen</a></h3>
<span>Role: Sub Lead</span>
<span>Skill: super skill</span>
</div>
</div>
</div>
</div>
<div className="col-md-6 animate-box" data-animate-effect="fadeInRight">
<div className="project" style={{backgroundImage: 'url(images/huy.jpg)'}}>
<div className="desc">
<div className="con">
<h3><a href="work.html">Huy Truong</a></h3>
<span>Role: Junior developer</span>
<span>Skill: Angular, DotNet</span>
</div>
</div>
</div>
</div>
<div className="col-md-6 animate-box" data-animate-effect="fadeInRight">
<div className="project" style={{backgroundImage: 'url(images/trinh.jpg)'}}>
<div className="desc">
<div className="con">
<h3><a href="work.html">Trinh Tran</a></h3>
<span>Role: QA Lead</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
)
}
}
|
import React, { Component } from 'react';
import WeeklyActItem from './WeeklyActItem';
const content = [
{
week:0,
title:'제목1',
date:'2019-03-15',
text:'활동내용',
file: [
{
fileName : '파일이름',
filePath : '파일경로',
fileSize : '파일사이즈',
fileTime : '파일시간'
}
],
comment: [
{
name : '서지혜',
content :'Aaaaa'
},
{
name : '서지혜',
content :'Aaaaa'
}
]
},
{
week:1,
title:'제목2',
date:'2019-03-16',
text:'활동내용2',
file: [
{
fileName : '파일이름',
filePath : '파일경로',
fileSize : '파일사이즈',
fileTime : '파일시간'
}
],
comment: [
{
name : '서지혜',
content :'Aaaaa',
},
{
name : '서지혜',
content :'Aaaaa',
}
]
},
{
week:2,
title:'제목3',
date:'2019-03-17',
text:'활동내용3',
file: [
{
fileName : '파일이름',
filePath : '파일경로',
fileSize : '파일사이즈',
fileTime : '파일시간'
}
],
comment: [
{
name : '서지혜',
content :'Aaaaa',
},
{
name : '서지혜',
content :'Aaaaa',
}
]
}
];
class WeeklyActivities extends Component {
render() {
const weeklist = content.map(content=><WeeklyActItem key = {content.week} week = {content.week} title = {content.title} date = {content.date} text = {content.text}
file ={content.file} comment = {content.comment}/>);
return (
<div>
{weeklist}
</div>
);
}
}
export default WeeklyActivities;
|
'use strict'
const Telegram = require('telegram-node-bot')
const TelegramBaseController = Telegram.TelegramBaseController
const TextCommand = Telegram.TextCommand
const tg = new Telegram.Telegram('428506352:AAEvuu8-bJhdBAQ55HLPXuY0WU71TzM6FLY')
class MainController extends TelegramBaseController {
get routes () {
return {
'saveCommand': 'saveHandler'
}
}
saveHandler ($) {
/*
* $ is reference for incoming message
*/
$.sendMessage('saved')
}
handle ($) {
$.sendMessage('unknown command')
}
}
var mainController = new MainController()
tg.router
.when(new TextCommand('/save', 'saveCommand'), mainController)
.otherwise(mainController)
|
// Ağırlıklı oylama
let hesaplaBtn = document.getElementById("hesapla");
hesaplaBtn.onclick = function () {
let value = document.getElementById("deger").value;
// kural;
let islem = 1 / (value * value);
// panel'e ulaşmak
let panel = document.getElementById("panel");
// h4 etiketi oluşturuldu
let etiket = document.createElement("h4");
etiket.classList = "text-center text-danger";
etiket.textContent = islem;
panel.appendChild(etiket);
};
|
servicesModule.factory('AreaSrvc', function($http) {
return {
getAll: function(){
return $http.get('broker/area-list');
},
getOne: function(id){
return $http.get('broker/area/'+id);
},
update: function(area){
return $http.post('broker/area-save', area)
},
deleteOne: function(id)
{
return $http.delete('broker/area/'+id);
}
}
})
|
import DivWrapper from './divWrapper';
export default DivWrapper;
|
import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as courseActions from '../../actions/courseActions';
import CourseList from './CourseList';
import {browserHistory} from 'react-router';
//******* 5 major pieces to a react Container Component *******
class CoursesPage extends React.Component {
// 1: constructor - will initialState
// - call bind functions
constructor(props, context) {
super(props, context);
//do binding of funcitons in constructor to increase preformance. if you did bind in the
//render function, a new function would be created on each render.
this.redirectToAddCoursePage = this.redirectToAddCoursePage.bind(this);
}
// 2: child functions - which are called by render to pass values from user to state
courseRow(course, index) {
return <div key={index}>{course.title}</div>;
}
redirectToAddCoursePage() {
browserHistory.push('/course');
}
// 3: render function - usually call a child(ren) component(s)
render() {
const {courses} = this.props;
return (
<div>
<h1>Courses</h1>
<input
type="submit"
value="Add Course"
className="btn btn-primary"
onClick={this.redirectToAddCoursePage} />
<CourseList courses={courses}/>
</div>
);
}
}
// 4: PropTypes - validate our prop types, so values come in as expected
CoursesPage.propTypes = {
courses: PropTypes.array.isRequired,
actions: PropTypes.object.isRequired
};
// 5: Redux, Connect, and related functions - dispatch actions to the store
function mapStateToProps(state, ownProps) {
return {
courses: state.courses
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(courseActions, dispatch)
};
}
//function mapDispatchToProps(){} second param of connect, without define your own connect will set a dispatch property of props for you
export default connect(mapStateToProps, mapDispatchToProps)(CoursesPage);
|
import { config } from './index.config';
import { runBlock } from './index.run';
import { DataService } from './services/data.service';
import { ApiService } from './services/api.service';
import { MainController } from './views/main.controller';
import { OverviewDirective } from './views/overview.directive';
import { OverviewCardDirective } from './views/overview.card.directive';
import { BaseUrlInterceptor } from './services/baseurl';
angular.module('app', [
'ngAnimate',
'ngNumeraljs',
])
.config(config)
.run(runBlock)
.factory('BaseUrlInterceptor', BaseUrlInterceptor)
.service('DataService', DataService)
.service('ApiService', ApiService)
.controller('MainController', MainController)
.directive('hbOverviewCard', OverviewCardDirective)
.directive('hbOverview', OverviewDirective);
|
import axios from "axios";
import { GET_TOP_RATED_TV_SHOWS } from "../types";
export const getTopRatedTvShows = () => dispatch => {
axios.get("/.netlify/functions/getTopRatedTvShows").then(res =>
dispatch({
type: GET_TOP_RATED_TV_SHOWS,
payload: res.data
})
);
};
|
import React from 'react';
import './Editor.scss';
import EditorContainer from 'containers/EditorContainer';
const Editor = () => {
return (
<div className="EditorTemplate">
<div className="EditorSection">
<EditorContainer />
</div>
</div>
);
};
export default Editor;
|
import fetch from '@/utils/fetch'
export const loginAxios=(data)=>(
fetch.post('/user/login',data)
)
export const registerAxios=(data)=>(
fetch.post('/user/register',data)
)
export const resetPasswordAxios=(data)=>(
fetch.post('/user/resetPassword',data)
)
// 获取个人信息
export const getUserInfoAxios=(data)=>(
fetch.get('/user/userInfo',data)
)
export const updateUserInfoAxios=(data)=>(
fetch.post('/user/update',data)
)
// 签到
export const signAxios=(data)=>(
fetch.post('/user/sign',data)
)
|
/* begin copyright text
*
* Copyright © 2016 PTC Inc., Its Subsidiary Companies, and /or its Partners. All Rights Reserved.
*
* end copyright text
*/
/* jshint node: true */
/* jshint strict: global */
'use strict';
var request = require('request');
function RequestHelper(properties) {
this.baseRequest = request.defaults(RequestHelper.buildDefaultOptions(properties));
}
RequestHelper.prototype.request = function(options, callback) {
this.baseRequest(options, callback);
};
RequestHelper.buildDefaultOptions = function(properties) {
var defaultOptions = {};
if (properties && typeof properties === 'object') {
defaultOptions.proxy = properties["request_proxy"];
}
return defaultOptions;
};
module.exports = RequestHelper;
|
alert("content.js")
|
const { exec, sql, transaction } = require('../db/mysqls')
const xss = require('xss')
const { genPassword } = require('../utils/cryp')
const { secretKey } = require('../utils/index')
const jwt = require('jsonwebtoken')
async function adminLogin(username, password) {
username = username
// 生成加密密码
password = genPassword(password)
let logintime = new Date()
let promiste = {
username: username,
password: password
}
return exec(
sql
.table('admin')
.where(promiste)
.select()
)
.then(data => {
if (data.length > 0) {
let userInfo = data[0]
let tokenObj = {
//携带参数
id: userInfo.id,
username: userInfo.uasername
}
let tokenKey = secretKey //加密内容
let token = jwt.sign(tokenObj, tokenKey, {
expiresIn: 3600 * 3 // token时长
})
token = 'Bearer ' + token
let parameter = {
token: token
}
exec(
sql
.table('amdin')
.data({ logintime: logintime })
.where({ id: userInfo.id })
.update()
)
return Promise.resolve(parameter)
// return true
} else {
return false
}
})
.catch(err => {
console.log(err)
})
}
async function uaersInfo(req) {
let id = req.user.id
return exec(
sql
.table('admin')
.where({ id: id })
.field('username,avatar')
.select()
).then(data => {
return data[0]
})
}
async function usersList(req) {
let pageSize = req.query.pageSize ? req.query.pageSize : 20
let pageNum = req.query.pageNum ? req.query.pageNum : 1
let data = {}
let pagePromiste = await exec(
sql
.table('users')
.field('id,username,qq,nickname,head_portrait,account,logintime,is_vip')
.page(pageNum, pageSize)
.select()
)
let totalPromiste = await exec(
sql
.table('users')
.where()
.select()
)
data.list = pagePromiste
data.total = totalPromiste.length
return Promise.resolve(data)
}
module.exports = {
adminLogin,
uaersInfo,
usersList
}
|
$('.deleteButton').on('click', function () {
$('#resultDelete').html('');
var id = $(this).attr('data-id');
var name = $(this).attr('data-name');
var type = $(this).attr('data-type');
if(type == "Equipe"){
var messege = "Você tem certeza que deseja excluir essa Equipe? A equipe pode conter Membros e Projetos Ativos";
var url = urlAPP()+'teams/'+id;
}
if(type == "Projeto"){
var messege = "Você tem certeza que deseja excluir esse Projeto? Pode existe Equipes ativas trabalhando nesse Projeto";
var url = urlAPP()+'projects/'+id;
}
$('#deleteConfirmButton').attr('data-id',id);
$('#deleteConfirmButton').attr('data-type',type);
$('#deleteConfirmButton').attr('data-name',name);
$('#labelNameType').text('Excluir '+type);
$('#idElement').val(id);
$('#itemName').text(name);
$('#bodyMessege').text(messege);
$('#modalDeleteConfirm').modal();
});
$('#deleteConfirmButton').on('click', function () {
var id = $(this).attr('data-id');
var name = $(this).attr('data-name');
var type = $(this).attr('data-type');
if(type == "Equipe"){
var messege = "Equipe "+name+" excluída com sucesso.";
var url = urlAPP()+'teams/'+id;
}
if(type == "Projeto"){
var messege = "Projeto "+name+" excluído com sucesso";
var url = urlAPP()+'projects/'+id;
}
$.ajax({
url: url,
data: { "_token": "{{ csrf_token() }}" },
type: 'DELETE',
success: function(result) {
console.log(messege);
if(result.status == 'ok'){
$('#resultDelete').html('<div class="alert alert-success">'+
'<div align="center"><i class="fa fa-check-circle"></i> '+ result.message +
'</div></div>');
$('#rowElement'+id).hide('slow');
$(this).remove();
}else{
}
}
});
});
|
//action types
export const FETCH_GENERAL_DATA= 'FETCH_GENERAL_DATA'
export const FETCH_GENERAL_DATA_SUCCESS= 'FETCH_GENERAL_DATA_SUCCESS'
export const FETCH_TECHNICAL_DATA= 'TECHNICAL_GENERAL_DATA'
export const FETCH_TECHNICAL_DATA_SUCCESS= 'TECHNICAL_GENERAL_DATA_SUCCESS'
export const FETCH_SPORTS_DATA= 'SPORTS_GENERAL_DATA'
export const FETCH_SPORTS_DATA_SUCCESS= 'SPORTS_GENERAL_DATA_SUCCESS'
export const FETCHING_FAILED= 'FETCHING_FAILED'
|
module.exports = function ItemImageFunc(sequelize, DataTypes) {
const ItemImage = sequelize.define('ItemImage', {
itemId: { type: DataTypes.BIGINT(8).ZEROFILL, allowNull: false, primaryKey: true },
imageId: { type: DataTypes.BIGINT(8).ZEROFILL, allowNull: false, primaryKey: true },
}, {
timestamps: true,
freezeTableName: true,
});
return ItemImage;
};
|
(function($){
/**
URL Parsing Function v2.2
by DJDavid98 - created for EQReverb.com ("site").
2013 (c) DJDavid98
You may not copy or redistribute this script in parts or in whole
without permission from the original author.
@requires jQuery
Short documentation:
$.parseURL(string str)
Accepts one parameter - a string - containing a valid URL.
**/
$.parseURL = function(str) {
var check = {
whole: /^((http|https):\/\/)?((.*\.)?.*\..*|localhost|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/.*/,
protocol: /^(http|https):\/\//,
absolute: /^\/\/((.*\.)?.*\..*|localhost|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\//,
ip: /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/,
relative: /^(#|(\.?\.)?[\/](?!\/).*(\..*|\/)?)?.*$/,
params: /\?([A-Za-z0-1._-]*=[A-Za-z0-1._-]*(\&)?)+/g,
},
r = {
protocol: undefined,
hostname: undefined,
hash: undefined,
href: {
original: undefined,
noparams: undefined,
nohashparams: undefined,
nohash: undefined,
},
origin: undefined,
parentDomain: undefined,
parameters: {},
paramString: '',
pathname: {
nohash: undefined,
withhash: undefined,
},
port: undefined,
}, wl;
if (arguments.length === 0 && typeof window.location.href !== 'undefined') wl = window.location;
else { wl = document.createElement('a'); wl.href = str }
r.protocol = wl.protocol;
r.port = wl.port;
r.origin = wl.origin;
r.hostname = wl.hostname;
r.hash = wl.hash;
r.href.original = wl.href;
r.pathname.nohash = wl.pathname;
r.href.nohash = r.origin+r.pathname.nohash;
r.href.nohashparams = r.origin+r.pathname.nohash;
r.pathname.withhash = wl.pathname+r.hash;
if (wl.search.length !== 0){
r.paramString = wl.search;
var urlparams = r.paramString.substring(1).split("&");
for (var i=0,l=urlparams.length; i<l; i++){
var item = urlparams[i].split('=');
r.parameters[item[0]] = item[1];
}
r.href.noparams = r.href.original.replace(check.params,'');
r.href.nohash = r.origin+r.pathname.nohash+r.paramString;
}
else r.href.noparams = r.href.original;
return r;
};
/**
Page Slider v1.2
by DJDavid98 - created for EQReverb.com ("site").
2013 (c) DJDavid98
You may not copy or redistribute this script in parts or in whole
without permission from the original author.
@requires jQuery
@requires parseURL
**/
$.pageSlider = function(todo,callback){
if (typeof callback !== 'function') callback = undefined;
if (typeof todo === 'undefined') todo = '';
if (todo === 'update' || arguments.length === 0){
$('.pageSlider li.current').removeClass('current');
var $toUnActive = [
$('.pageSlider a.current:not([href="'+$.parseURL().pathname.withhash+'"])'),
$('.pageSlider a.current:not([href="'+$.parseURL().pathname.withhash.replace(window.location.pathname,'')+'"])')
];
if (typeof $toUnActive[0][0] !== 'undefined') $toUnActive[0].removeClass('current');
else if (typeof $toUnActive[1][0] !== 'undefined') $toUnActive[1].removeClass('current');
var $toBeActive = [
$('.pageSlider a[href="'+$.parseURL().pathname.withhash+'"]'),
$('.pageSlider a[href="'+$.parseURL().pathname.withhash.replace(window.location.pathname,'')+'"]')
];
if (typeof $toBeActive[0][0] !== 'undefined') $toBeActive[0].addClass('current');
else if (typeof $toBeActive[1][0] !== 'undefined') $toBeActive[1].addClass('current');
$('.pageSlider a[href]').each(function(){
if (this.pathname == $.parseURL().pathname.withhash || this.pathname == $.parseURL().pathname.nohash){
if (!$(this).hasClass('current')) $(this).addClass('current')
}
else if ($(this).hasClass('current')) $(this).removeClass('current');
});
var updated = 0;
$('.pageSlider').each(function(){
var $this = $(this);
var $slideBtn = $this.find('a.slide-button');
var $navs = $this.find('a[href]');
var navsSize = $navs.size();
var percent = 100/navsSize;
var actNavIndx;
if ($(this).hasClass('auto-size')){
if (this.nodeName.toLowerCase() === 'ul' && $(this).hasClass('auto-size')){
$navs.parent().css('width',percent+'%');
$this.find('a.current').parent().addClass('current');
actNavIndx = $this.find('a.current').parent().index();
}
else {
$navs.css('width',percent+'%');
actNavIndx = $this.find('a.current').index();
}
}
if (typeof $slideBtn[0] !== 'undefined') {
if (actNavIndx < 0) return false;
$slideBtn.css('width',percent+'%');
if (todo === 'update') $slideBtn.css('left',((actNavIndx)*percent)+'%');
else $slideBtn.animate({left:((actNavIndx)*percent)+'%'},500,callback);
}
updated++;
});
return updated+" sliders updated";
}
};
$(window).on('hashchange',function(){ $.pageSlider() });
$(document).ready(function(){
$.pageSlider();
$('header .pageSlider a').on('click',function(){
var url = $(this).attr('href');
if ($.ajaxPage.exists(url)) $.ajaxPage.load(url);
return false;
});
});
/**
Ajax page loading
by DJDavid98 - created for EQReverb.com ("site").
2013 (c) DJDavid98
You may not copy or redistribute this script in parts or in whole
without permission from the original author.
@requires jQuery
**/
var requestMade = false;
$.ajaxPage = {
exists: function(page,params){
if (typeof page === "undefined") return false;
var retUrn, parsed = $.parseURL(page);
if (typeof parsed === 'object'){
var page = parsed.pathname.nohash;
$.ajax({
type: "GET",
url: (page),
async: false,
}).done(function(data){
if (typeof data !== 'undefined' && data !== '') retUrn = true;
else retUrn = false;
});
}
else retUrn = false;
return retUrn;
},
load: function(page,selector,callback){
if (selector === true){ var noPushSate = true; selector = undefined }
if (typeof selector === 'undefined') var selector = '.grid-container.content';
var parsed = $.parseURL(page);
if (typeof parsed === 'object'){
$(selector).animate({left:-$(selector).outerWidth()+10}, 500, "easeInCubic", function(){
$.ajax({
type: "GET",
url: (parsed.pathname.nohash),
}).done(function(data){
if (typeof data !== 'undefined' && data !== ''){
var html = $(data).find('.grid-container.content').html();
$(selector).html(html);
$(selector)
.css('left',$(selector).outerWidth())
.animate({left:0}, 500);
if (noPushSate !== true) window.history.pushState({},'',page);
if (requestMade === false) requestMade = true;
$.pageSlider();
}
});
});
}
},
};
$(window).on('popstate',function(){ if (requestMade === true) $.ajaxPage.load(window.location.href,true); else requestMade = true });
/** <Speakker Related Code> **/
(function($){
var moveBy = 62;
$(window).resize(function(){
$('body').height($(window).height());
/* $('body.player-open div.site-wrapper').height($(window).height()-moveBy); */
$('.skMiddleBlock').outerWidth($('.speakker').width()-($('.skLeftBlock').outerWidth()+$('.skRightBlock').outerWidth()));
var thatWidth = $('.speakker').width()-($('.skMainControl').outerWidth()+$('.skVolumeControl').outerWidth()+$('.skModuleControl').outerWidth());
$('.skActControl,.skScrubbler').outerWidth(thatWidth);
$('.skAct').outerWidth(thatWidth-($('.skTime').outerWidth()+5)).css({paddingLeft:($('.skTime').outerWidth()+5)/2,marginRight:(-($('.skTime').outerWidth()+5))/2});
});
$(window).resize();
$(document).ready(function() {
window.player = projekktor('.projekktor');
$('.skVolumeControl').insertBefore('.skActControl');
setTimeout(function(){
$('.speakker > .ppbuffering').prependTo('.skActControl');
$('.skArtistlist').on('hover mouseenter mouseleave',function(){
if ($(this).find('.scrollbar-pane:visible').size() > 0){
$(this).find('.scrollbar-pane ul li').each(function(){$(this).appendTo('.skArtistlist')});
$(this).find('div[class^="scrollbar-handle-"]').remove();
$(this).find('.scrollbar-pane').hide();
}
else return true;
});
$(window).resize();
$('body .skModuleControl .skOpener').on('click',function(e){
e.preventDefault();
if ($('body').hasClass('player-open')){
moveBy = 280;
togglePlayer(true);
}
return false;
});
$('body .skModuleControl .skCloser').on('click',function(e){
e.preventDefault();
if ($('body').hasClass('player-open')){
moveBy = 62;
togglePlayer(true);
}
return false;
});
},100);
});
var togglePlayer = function(skToggle){
var settings = [
(skToggle === true ? 600 : 300),
(skToggle === true ? "swing" : "easeOutCubic"),
];
var windHeight = $(window).height();
if ($('body').hasClass('player-open') && skToggle !== true){
$('div.site-wrapper').stop().animate({bottom:0/*, height:$('div.site-wrapper').height()+moveBy*/}, 1000, "easeOutBounce");
$('div.player-wrapper').stop().animate({bottom:-moveBy}, 1000, "easeOutBounce");
}
else {
$('div.site-wrapper').stop().animate({bottom: moveBy/*, height:windHeight-moveBy */}, settings[0], settings[1]);
$('div.player-wrapper').stop().animate({bottom:0}, settings[0], settings[1]);
}
if (skToggle !== true) $('body').toggleClass('player-open');
};
//key('ctrl+q', togglePlayer); (Old way to toggle player bar)
$(document).on('keydown',function(e){
if ($('*:focus').size() === 0 && e.keyCode == 81) togglePlayer();
});
$('a.link').on('click',togglePlayer);
$('.site-wrapper').on('mousedown',function(){
if ($('body').hasClass('player-open')) togglePlayer();
})
$('body').on('click','.albumart .overlay',function(){
if (typeof window.player !== 'undefined') window.player.setPlay();
togglePlayer();
setTimeout(togglePlayer,2000);
});
window.togglePlayer = function(){
togglePlayer();
};
})(jQuery);
/** </Speakker Related Code> **/
})(jQuery);
|
const templateUrl = require('~fsm/playpause.partial.svg');
var playpause = function() {
return { restrict: 'A', templateUrl};
};
exports.playpause = playpause;
|
var searchData=
[
['8_20bits_20masks',['8 bits masks',['../group_____bits___masks.html',1,'']]]
];
|
import React from "react";
import { storiesOf } from "@storybook/react";
import { action } from "@storybook/addon-actions";
import { withKnobs, boolean, text } from "@storybook/addon-knobs";
import { Button, Column, Modal, Row } from "../../src/index";
const stories = storiesOf("Modal", module);
stories.addDecorator(withKnobs);
stories.addWithInfo("Default", () => {
let visibility = boolean("visibility", false);
let maxWidth = text("maxWidth", "2000px");
return (
<div>
<Modal
visible={visibility}
onClose={() => {
visibility = false;
}}
maxWidth={maxWidth}
>
<Row>
<Column>
<h1>
<span role="img" aria-label="Party Popper">
🎉
</span>{" "}
Here's the modal
</h1>
<p>For all your exciting stuff...</p>
</Column>
</Row>
</Modal>
</div>
);
});
|
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import { Link } from "react-router-dom";
const ContactButton = makeStyles((theme) => ({
root: {
backgroundColor: "#FFD791",
borderColor: '#FFD791',
boxShadow: 'none',
color: '#3D5559',
fontFamily: 'Lexend, sans-serif',
'&:hover': {
backgroundColor: '#3D5559',
boxShadow: 'none',
color: '#FFFFFF',
},
'&:active': {
boxShadow: 'none',
backgroundColor: '#FFD791',
},
'&:focus': {
boxShadow: '0 0 0 0.2rem rgba(116,160,166, 0.5)',
},
},
}));
const AboutButton = makeStyles((theme) => ({
root: {
border: "1px solid #3D5559",
boxShadow: 'none',
color: '#3D5559',
fontFamily: 'Lexend, sans-serif',
'&:hover': {
boxShadow: 'none',
backgroundColor: 'rgba(61,85,89, 0.2)',
border: "1px solid rgb(62,86,89)",
},
'&:active': {
boxShadow: 'none',
},
'&:focus': {
boxShadow: '0 0 0 0.2rem rgb(116,160,166)',
},
},
}));
function SectionThreeLastCalltoAction() {
const ContactButtonclasses = ContactButton();
const AboutButtonclasses = AboutButton();
return (
<div className="SectionThreeLastCalltoAction">
<div className="SThree-LCTA-Fitter">
<div className="SThree-LCTA-CallToAction">
<h1>Let´s build beautiful, meaningful things together.</h1>
</div>
<div className="SThree-LCTA-CallToActionButtons">
<div className="row SThree-LCTA-row justify-content-md-center">
<div className="col-12 col-md-6">
<Button variant="contained" size="large" color="primary" className={ContactButtonclasses.root}>
<a href="mailto:manuel.nenninger@web.de?subject=Mail from Your Site">Contact me</a>
</Button>
</div>
<div className="col-12 col-md-6">
<Button variant="outlined" size="large" color="primary" className={AboutButtonclasses.root}>
<Link to="/about">About Me</Link>
</Button>
</div>
</div>
</div>
</div>
</div>
);
}
export default SectionThreeLastCalltoAction;
|
// using an adjacency list for undirected graphs
class Graph {
constructor() {
this.adjacencyList = {}
}
addVertex(vertex) {
// error handling
if (!this.adjacencyList[vertex]) {
this.adjacencyList[vertex] = [];
}
}
addEdge(vertex1, vertex2) {
// error handling
if (!(this.adjacencyList[vertex1].includes(vertex2))) {
this.adjacencyList[vertex1].push(vertex2);
}
if (!(this.adjacencyList[vertex2].includes(vertex1))) {
this.adjacencyList[vertex2].push(vertex1);
}
}
removeEdge(vertex1, vertex2) {
// no error handling
// remove vertex2 from vertex1's array
let removedV2 = this.adjacencyList[vertex1].filter(el => el !== vertex2);
this.adjacencyList[vertex1] = removedV2;
let removedV1 = this.adjacencyList[vertex2].filter(el => el !== vertex1);
this.adjacencyList[vertex2] = removedV1;
}
removeVertex(vertex) {
for (let connection of this.adjacencyList[vertex]) {
this.removeEdge(vertex, connection)
}
delete this.adjacencyList[vertex];
}
depthFirstRecursive(start) {
// no error handling
let visited = {};
let results = [];
// helper function won't recognize this
let adjacencyList = this.adjacencyList;
(function dfs(vertex) {
// base case
if (!vertex) return;
// recursion
visited[vertex] = true;
results.push(vertex);
for (let neighbor of adjacencyList[vertex]) {
if (!visited[neighbor]) {
dfs(neighbor);
}
}
})(start);
return results;
}
depthFirstIterative(start) {
let visited = {};
let results = [];
let stack = [start];
let currVertex;
while (stack.length) {
currVertex = stack.pop();
visited[currVertex] = true;
results.push(currVertex);
this.adjacencyList[currVertex].forEach(neighbor => {
if (!visited[neighbor]) {
stack.push(neighbor);
}
})
}
return results;
}
breadthFirst(start) {
let visited = {};
let results = [];
let queue = [start];
let currVertex;
while (queue.length) {
currVertex = queue.shift();
visited[currVertex] = true;
results.push(currVertex);
this.adjacencyList[currVertex].forEach(neighbor => {
if (!visited[neighbor]) {
queue.push(neighbor);
}
})
}
return results;
}
}
let graph = new Graph;
graph.addVertex("first");
graph.addVertex("second");
graph.addVertex("third");
// console.log(graph);
graph.addEdge("first", "third");
graph.addEdge("first", "second");
graph.addEdge("second", "first");
console.log(graph);
// {
// first: [ 'third', 'second' ],
// second: [ 'first' ],
// third: [ 'first' ]
// }
// graph.removeEdge("first", "third");
// console.log(graph);
// {
// first: [ 'second' ],
// second: [ 'first' ],
// third: []
// }
// graph.removeVertex("second");
// console.log(graph);
// {
// first: [ 'third' ],
// third: [ 'first' ]
// }
console.log(graph.depthFirstRecursive("first")); // ["first", "third", "second"]
console.log(graph.depthFirstIterative("first")); // ["first", "second", "third"]
console.log(graph.breadthFirst("first")); // ["first", "third", "second"]
|
var BrithCertificate = artifacts.require("./BirthCertificate.sol");
module.exports = function(deployer) {
deployer.deploy(BrithCertificate);
};
|
define("input", ["expose"], function(expose){
var _listener,
_mouse = {isDown:false, selected:false},
_touches = {},
_source;
function startInput(listener, source){
_listener = listener;
_source = source;
source.addEventListener("mousedown", onMouseDown, false);
source.addEventListener("mousemove", onMouseMove, false);
window.addEventListener("mouseup", onMouseUp, false);
source.addEventListener("touchstart", onTouchStart, false);
source.addEventListener("touchmove", onTouchMove, false);
source.addEventListener("touchend", onTouchEnd, false);
_mouse.isDown = false;
_mouse.selected = false;
}
function stopInput(listener, source){
source.removeEventListener("mousedown", onMouseDown);
source.removeEventListener("mousemove", onMouseMove);
window.removeEventListener("mouseup", onMouseUp);
source.removeEventListener("touchstart", onTouchStart);
source.removeEventListener("touchmove", onTouchMove);
source.removeEventListener("touchend", onTouchEnd);
}
function onMouseDown(e){
var point = transformPoint(unOffsetPoint(e.pageX, e.pageY, e.target), _source.width/_source.clientWidth, 0);
var blob = _listener.findBlobAt(point.x, point.y);
if(blob){
_mouse.selected = blob;
blob.startPath(point.x, point.y);
_mouse.isDown = true;
}
e.stopPropagation();
e.preventDefault();
return false;
};
function onMouseMove(e){
var point = transformPoint(unOffsetPoint(e.pageX, e.pageY, e.target), _source.width/_source.clientWidth, 0);
if(_mouse.isDown){
_mouse.selected.movePath(point.x, point.y);
}
e.stopPropagation();
e.preventDefault();
return false;
};
function onMouseUp(e){
_mouse.isDown = false;
e.stopPropagation();
e.preventDefault();
return false;
};
function onTouchStart(e){
for(var i=0; i<e.changedTouches.length; i++){
var touch = e.changedTouches[i];
var point = transformPoint(unOffsetPoint(touch.pageX, touch.pageY, touch.target), _source.width/_source.clientWidth, 0);
var blob = _listener.findBlobAt(point.x, point.y);
if(blob){
_touches["t"+touch.identifier] = blob;
blob.startPath(point.x, point.y);
}
}
e.stopPropagation();
e.preventDefault();
return false;
};
function onTouchMove(e){
for(var i=0; i<e.changedTouches.length; i++){
var touch = e.changedTouches[i];
var point = transformPoint(unOffsetPoint(touch.pageX, touch.pageY, touch.target), _source.width/_source.clientWidth, 0);
if(("t"+touch.identifier) in _touches){
_touches["t"+touch.identifier].movePath(point.x, point.y);
}
}
e.stopPropagation();
e.preventDefault();
return false;
};
function onTouchEnd(e){
for(var i=0; i<e.changedTouches.length; i++){
var touch = e.changedTouches[i];
if(("t"+touch.identifier) in _touches){
delete _touches["t"+touch.identifier];
}
}
e.stopPropagation();
e.preventDefault();
return false;
};
function transformPoint(point, scale, rotation){
return {x: point.x*scale,
y: point.y*scale};
}
function unOffsetPoint(x, y, elm){
if(elm.offsetParent){
var u = unOffsetPoint(x, y, elm.offsetParent);
return {x:u.x - elm.offsetLeft,
y:u.y - elm.offsetTop};
}else{
return {x:x - elm.offsetLeft,
y:y - elm.offsetTop};
}
}
function unOffsetTouches(touches){
for(var i=0; i<touches.length; i++){
var pos = unOffsetPoint(touches[i].pageX, touches[i].pageY, touches[i].target);
touches[i].localX = pos.x;
touches[i].localY = pos.y;
}
};
return expose(startInput,
stopInput);
});
|
import decode from 'jwt-decode';
export default class AuthService {
constructor(domain) {
this.domain = domain || 'http://localhost:8080'
this.fetch = this.fetch.bind(this)
this.login = this.login.bind(this)
this.getProfile = this.getProfile.bind(this)
}
login(username, password) {
// Get a token
return this.fetch(`${this.domain}/api/authenticate`, {
method: 'POST',
body: JSON.stringify({
username,
password
})
}).then(res => {
this.setToken(res.id_token);
return Promise.resolve(this._getUserData());
}).catch(err =>{
return Promise.reject("Usuario o contraseña invalido");
})
}
loggedIn() {
// Checks if there is a saved token and it's still valid
const token = this.getToken()
return !!token && !this.isTokenExpired(token) // handwaiving here
}
isTokenExpired(token) {
try {
const decoded = decode(token);
if (decoded.exp < Date.now() / 1000) {
return true;
}
else
return false;
}
catch (err) {
return false;
}
}
setToken(idToken) {
// Saves user token to sessionStorage
console.log(idToken);
sessionStorage.setItem('id_token', idToken)
}
getToken() {
// Retrieves the user token from sessionStorage
return sessionStorage.getItem('id_token')
}
logout() {
// Clear user token and profile data from sessionStorage
sessionStorage.removeItem('id_token');
}
getProfile() {
return JSON.parse(sessionStorage.getItem("user"));
}
fetch(url, options) {
// performs api calls sending the required authentication headers
const headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
if (this.loggedIn()) {
headers['Authorization'] = 'Bearer ' + this.getToken()
}
return fetch(url, {
headers,
...options
})
.then(this._checkStatus)
.then(response => response.json())
}
_checkStatus(response) {
// raises an error in case response status is not a success
if (response.status >= 200 && response.status < 300) {
return response
} else {
var error = new Error(response.statusText)
error.response = response
throw error
}
}
_getUserData() {
return this.fetch(`${this.domain}/api/account`, {
method: 'GET',
}).then(res => {
if (!res.authorities.includes('ROLE_ADMIN') && !res.authorities.includes('ROLE_ADM_DPTO')) {
this.logout();
return Promise.reject("No es un usuario Admin");
}
sessionStorage.setItem("user", JSON.stringify(res));
return Promise.resolve(res);
});
}
}
|
// text.js
hAzzle.define('text', function() {
var getText = function(elem) {
var node,
ret = '',
i = 0,
nodeType = elem.nodeType;
if (!nodeType) {
// If no nodeType, this is expected to be an array
while ((node = elem[i++])) {
// Do not traverse comment nodes
ret += getText(node);
}
} else if (nodeType === 1 ||
nodeType === 9 ||
nodeType === 11) {
if (typeof elem.textContent === 'string') {
return elem.textContent;
}
// Traverse its children
for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
ret += getText(elem);
}
} else if (nodeType === 3 ||
nodeType === 4) { // Text or CDataSection
return elem.nodeValue;
}
return ret;
};
return {
getText: getText
};
});
|
import express from 'express';
import Movie from '../models/movie';
import RoleMiddleware from '../middlewares/role.middleware';
const router = express.Router();
// GET: /
router.get('/', RoleMiddleware(['superadmin', 'admin', 'basic']), async (req, res) => {
const movies = await Movie
.find()
.populate('actors', 'name')
.populate('directors', 'name')
.populate('studios', 'name')
.populate('genres', 'name')
.exec();
return res.status(200).json({ data: movies });
});
// POST: /
router.post('/', RoleMiddleware(['superadmin', 'admin']), async (req, res) => {
const {
name,
actors,
synopsis,
directors,
studios,
genres,
} = req.body;
// TODO: Add validations
const newMovie = new Movie({
name,
synopsis,
actors,
directors,
studios,
genres,
});
await newMovie.save();
return res.status(201).json();
});
export default router;
|
//Prikaz svih farmaceuta
$(document).ready(function () {
var changePrice = $(".changePrice");
changePrice.hide();
var changePriceMed = $(".changePriceMed");
changePriceMed.hide();
$.ajax({
type: "GET",
url: "http://localhost:8081/counselings/getCounselingsPharmacy",
dataType: "json",
beforeSend: function (xhr) {
if (localStorage.token) {
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token);
}
},
success: function (data) {
console.log("SUCCESS", data);
for (i = 0; i < data.length; i++) {
var row = "<tr>";
row += "<td>" + data[i]['pharmacist']['id'] + "</td>";
row += "<td>" + data[i]['pharmacist']['firstName'] + "</td>";
row += "<td>" + data[i]['pharmacist']['lastName'] + "</td>";
row += "<td>" + data[i]['beginofappointment']+ "</td>";
row += "<td>" + data[i]['endofappointment'] + "</td>";
row += "<td>" + data[i]['price'] + "</td>";
var btnChange = "<button class='btnChangePh' id = " + data[i]['id'] + "> Izmeni cenu </button>";
row += "<td>" + btnChange + "</td>";
$('#tablePharmacistsAdminPharmacy').append(row);
}
},
error: function (jqXHR) {
if(jqXHR.status === 403)
{
window.location.href="error.html";
}
if(jqXHR.status === 401)
{
window.location.href="error.html";
}
}
});
});
//Prikaz svih dermatologa
$(document).ready(function () {
$.ajax({
type: "GET",
url: "http://localhost:8081/appointments/getAppointmentsPharmacy",
dataType: "json",
beforeSend: function (xhr) {
if (localStorage.token) {
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token);
}
},
success: function (data) {
console.log("SUCCESS", data);
for (i = 0; i < data.length; i++) {
var row = "<tr>";
row += "<td>" + data[i]['dermatologist']['id'] + "</td>";
row += "<td>" + data[i]['dermatologist']['firstName'] + "</td>";
row += "<td>" + data[i]['dermatologist']['lastName'] + "</td>";
row += "<td>" + data[i]['beginofappointment']+ "</td>";
row += "<td>" + data[i]['endofappointment'] + "</td>";
row += "<td>" + data[i]['price'] + "</td>";
var btnChange = "<button class='btnChangeDerm' id = " + data[i]['id'] + "> Izmeni cenu </button>";
row += "<td>" + btnChange + "</td>";
$('#tableDermatologistsAdminPharmacy').append(row);
}
},
error: function (jqXHR) {
if(jqXHR.status === 403)
{
window.location.href="error.html";
}
if(jqXHR.status === 401)
{
window.location.href="error.html";
}
}
});
});
$(document).ready(function () {
$.ajax({
type: "GET",
url: "http://localhost:8081/medications/adminmedications",
dataType: "json",
beforeSend: function (xhr) {
if (localStorage.token) {
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token);
}
},
success: function (data) {
console.log("SUCCESS", data);
for (i = 0; i < data.length; i++) {
var row = "<tr>";
row += "<td>" + data[i]['code'] + "</td>";
row += "<td>" + data[i]['name'] + "</td>";
row += "<td>" + data[i]['beginPriceValidity'] + "</td>";
row += "<td>" + data[i]['endPriceValidity']+ "</td>";
row += "<td>" + data[i]['price'] + "</td>";
var btnChange = "<button class='btnChangeMed' id = " + data[i]['id'] + "> Izmeni cenu </button>";
row += "<td>" + btnChange + "</td>";
$('#tableMedicationAdminPharmacy').append(row);
}
},
error: function (jqXHR) {
if(jqXHR.status === 403)
{
window.location.href="error.html";
}
if(jqXHR.status === 401)
{
window.location.href="error.html";
}
}
});
});
//Promena cene savetovanja
$(document).on('click', '.btnChangePh', function () {
var changePrice = $(".changePrice");
changePrice.show();
var medicationShowAdminPharmacy = $(".medicationShowAdminPharmacy");
var dermatologistsShowAdminPharmacy = $(".dermatologistsShowAdminPharmacy");
var pharmacistsShowAdminPharmacy = $(".pharmacistsShowAdminPharmacy");
medicationShowAdminPharmacy.hide();
dermatologistsShowAdminPharmacy.hide();
pharmacistsShowAdminPharmacy.hide();
id = this.id;
});
$(document).on('click', '#btnSubmitPrice', function () {
var changePrice = $("#changePrice").val();
var myJSON = JSON.stringify({"id" : id, "price" : changePrice});
if(changePrice > 0 && changePrice !== null) {
$.ajax({
type: "POST",
url: "http://localhost:8081/counselings/changeCounselingPrice",
dataType: "json",
contentType: "application/json",
data: myJSON,
beforeSend: function (xhr) {
if (localStorage.token) {
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token);
}
},
success: function (data) {
console.log("SUCCESS: ", data);
$(".changePrice").val("");
window.location.href = "adminPharmacyPrices.html";
},
error: function (jqXHR) {
if (jqXHR.status === 403) {
window.location.href = "error.html";
}
if (jqXHR.status === 401) {
window.location.href = "error.html";
}
}
});
}
});
//Promena cene pregleda
$(document).on('click', '.btnChangeDerm', function () {
var changePrice = $(".changePrice");
changePrice.show();
var medicationShowAdminPharmacy = $(".medicationShowAdminPharmacy");
var dermatologistsShowAdminPharmacy = $(".dermatologistsShowAdminPharmacy");
var pharmacistsShowAdminPharmacy = $(".pharmacistsShowAdminPharmacy");
medicationShowAdminPharmacy.hide();
dermatologistsShowAdminPharmacy.hide();
pharmacistsShowAdminPharmacy.hide();
id = this.id;
});
$(document).on('click', '#btnSubmitPrice', function () {
var changePrice = $("#changePrice").val();
var myJSON = JSON.stringify({"id" : id, "price" : changePrice});
if(changePrice > 0 && changePrice !== null) {
$.ajax({
type: "POST",
url: "http://localhost:8081/appointments/changeAppointmentPrice",
dataType: "json",
contentType: "application/json",
data: myJSON,
beforeSend: function (xhr) {
if (localStorage.token) {
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token);
}
},
success: function (data) {
console.log("SUCCESS: ", data);
$(".changePrice").val("");
window.location.href = "adminPharmacyPrices.html";
},
error: function (jqXHR) {
if (jqXHR.status === 403) {
window.location.href = "error.html";
}
if (jqXHR.status === 401) {
window.location.href = "error.html";
}
}
});
}
});
//Promena cene savetovanja
$(document).on('click', '.btnChangeMed', function () {
var changePriceMed = $(".changePriceMed");
changePriceMed.show();
var changePrice = $(".changePrice");
var medicationShowAdminPharmacy = $(".medicationShowAdminPharmacy");
var dermatologistsShowAdminPharmacy = $(".dermatologistsShowAdminPharmacy");
var pharmacistsShowAdminPharmacy = $(".pharmacistsShowAdminPharmacy");
changePrice.hide();
medicationShowAdminPharmacy.hide();
dermatologistsShowAdminPharmacy.hide();
pharmacistsShowAdminPharmacy.hide();
id = this.id;
});
$(document).on('click', '#btnSubmitPriceMed', function () {
var changePrice = $("#changePriceMed").val();
var dateEndPrice = $("#dateEndPrice").val();
var myJSON = JSON.stringify({"id" : id, "price" : changePrice, "end" : dateEndPrice});
dateEndPrice = Date.parse(dateEndPrice);
if(changePrice > 0 && changePrice !== null && dateEndPrice !== null && dateEndPrice > Date.now()) {
$.ajax({
type: "POST",
url: "http://localhost:8081/medications/changeMedicationPrice",
dataType: "json",
contentType: "application/json",
data: myJSON,
beforeSend: function (xhr) {
if (localStorage.token) {
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token);
}
},
success: function (data) {
console.log("SUCCESS: ", data);
$("#changePriceMed").val("");
$("#dateEndPrice").val("");
window.location.href = "adminPharmacyPrices.html";
},
error: function (jqXHR) {
if (jqXHR.status === 403) {
window.location.href = "error.html";
}
if (jqXHR.status === 401) {
window.location.href = "error.html";
}
}
});
}
});
|
import React from "react";
export default () => {
return <div className="m:12">margin example</div>;
};
|
import Vue from 'vue'
import Vuetify from 'vuetify/lib'
Vue.use(Vuetify)
export default new Vuetify({
theme: {
themes: {
light: {
primary: '#204051',
secondary: '#3b6978',
third: '#3b6978',
fourth: '#cae8d5'
}
}
}
})
|
(function () {
var checkIsIE = function () {
var userAgent = window.navigator.userAgent; //取得浏览器的userAgent字符串
var isOpera = userAgent.indexOf("Opera") > -1; //判断是否Opera浏览器
var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera; //判断是否IE浏览器
if(isIE){
var version=userAgent.match(/MSIE\s\d+/);
var vNumber=version[0].split(" ")[1];
if(vNumber<10){
var fls = flashChecker();
if (fls.f){
if(fls.v < 23){
warnInfo("非常抱歉,您当前安装的flash版本较低,为了不影响后期操作的正常进行,请您升级最新版本");
}
}else{
warnInfo("非常抱歉,您当前安装的flash版本较低,为了不影响后期操作的正常进行,请您升级最新版本");
}
}
}
//检测是否安装flash
function flashChecker() {
var hasFlash = 0; //是否安装了flash
var flashVersion = 0; //flash版本
var swf;
try{
swf = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
}
catch(e){
}
if (swf) {
hasFlash = 1;
VSwf = swf.GetVariable("$version");
flashVersion = parseInt(VSwf.split(" ")[1].split(",")[0]);
}
return { f: hasFlash, v: flashVersion };
}
//弹出提示框
function warnInfo (content) {
var con = '<div style="padding:0 0 20px;">'+content+'</div>';
layer.alert(con, {
title:"提示",
//area: ["318px","216px"],
btn:["下载"],
yes : function(index){
var btn = $('.layui-layer-btn');
btn.find('.layui-layer-btn0').attr({
href: '../../installPackage/flashplayer23ax_ca_install.exe'
});
layer.close(index);
}
});
}
};
checkIsIE();
return {};
})();
|
'use strict';
var assert = require('chai').assert,
isUtils = require('../is-utils');
describe('isUtils', function () {
describe('.isObject()', function () {
var isObject = isUtils.isObject;
it('return true for plain object', function () {
assert.isTrue(isObject({}));
});
it('return true for regexp', function () {
assert.isTrue(isObject(/alice/));
});
it('return true for date', function () {
assert.isTrue(isObject(new Date()));
});
it('return true for object created by constructor', function () {
var Constructor = function () {},
object = new Constructor();
assert.isTrue(isObject(object));
});
it('return false for null', function () {
assert.isFalse(isUtils.isObject(null));
});
it('return false for function', function () {
var doSomething = function () {};
assert.isFalse(isObject(doSomething));
});
});
describe('.isPlainObject()', function () {
var isPlainObject = isUtils.isPlainObject;
it('return true for plain object', function () {
assert.isTrue(isPlainObject({}));
});
it('return false for regexp', function () {
assert.isFalse(isPlainObject(/alice/));
});
it('return false for date', function () {
assert.isFalse(isPlainObject(new Date()));
});
it('return false for object created by constructor', function () {
var Box = function (contents) {
this.contents = contents;
};
var box = new Box("Schrödinger's cat");
assert.isFalse(isPlainObject(box));
});
it('return false for function', function () {
var doStuff = function () {};
assert.isFalse(isPlainObject(doStuff));
});
});
describe('.isFunction()', function () {
var isFunction = isUtils.isFunction;
it('return true for function', function () {
var doSomething = function () {};
assert.isTrue(isFunction(doSomething));
});
it('return false for object', function () {
assert.isFalse(isFunction({}));
});
});
describe('.isUndefined()', function () {
var isUndefined = isUtils.isUndefined;
it('return true for undefined', function () {
var notDefined = void 0;
assert.isTrue(isUndefined(notDefined));
});
it('return false for null', function () {
assert.isFalse(isUndefined(null));
});
});
describe('isDefined()', function () {
var isDefined = isUtils.isDefined;
it('return true for defined value', function () {
var value = "i'm defined!";
assert.isTrue(isDefined(value));
});
it('return true for null', function () {
assert.isTrue(isDefined(null));
});
});
describe('.isPresent()', function () {
var isPresent = isUtils.isPresent;
it('return false for null', function () {
assert.isFalse(isPresent(null));
});
it('return false for undefined', function () {
var notDefined = void 0;
assert.isFalse(isPresent(notDefined));
});
});
});
|
import {
SET_INPUT,
CANCEL_POST,
TOGGLE_CREATE_POST_LOADING,
EDIT_POST_INSERT_DATA,
RESET_CREATE_POST_FORM_DATA,
} from "../actions/types";
const initialState = {
isLoading: false,
isPublished: false,
};
const reducer = function (state = initialState, action) {
const { type, payload } = action;
switch (type) {
case TOGGLE_CREATE_POST_LOADING:
return {
...state,
isLoading: action.payload,
};
case SET_INPUT:
return {
...state,
isPublished: false,
[payload.name]: payload.value,
};
case CANCEL_POST:
return {
...initialState,
};
case EDIT_POST_INSERT_DATA:
return {
...state,
...payload,
};
case RESET_CREATE_POST_FORM_DATA:
return {
...initialState,
isPublished: true,
};
default:
return state;
}
};
export default reducer;
|
import React, { PropTypes } from 'react';
import posts from '../posts';
const SinglePost = ({ params }) => {
const post = posts.filter(p => p.id === +params.postId)[0];
return (
<div>
<h1>{`Post ${post.id} - ${post.title}`}</h1>
<p>{post.body}</p>
</div>
);
}
SinglePost.propTypes = {
params: PropTypes.object.isRequired
};
export default SinglePost
|
import { connect } from 'react-redux';
import SignupEmailScreen from '../components/SignupEmailScreen';
import { signupSaveEmail, navigatePush } from '../actions';
const mapStateToProps = (state) => {
return {
email: state.authState.newEmail
};
};
const mapDispatchToProps = (dispatch) => {
return {
onEnterEmail: (email) => {
dispatch(signupSaveEmail(email));
},
onSubmitPress: () => {
dispatch(navigatePush('SignupPassword'));
}
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(SignupEmailScreen);
|
import { css } from '@emotion/core'
import { experience } from './breakpoints'
import { grey } from './colors'
export const h1 = css`
font-size: 40pt;
font-weight: 700;
line-height: 1.1;
color: ${grey};
margin: 0 0 40px;
@media (max-width: ${experience}) {
font-size: 30pt;
}
`
export const linkWithNoStyles = css`
box-shadow: none;
&:hover {
background: none;
}
`
|
import SurpportDesk from './SurpportDesk'
export default SurpportDesk;
|
import React from 'react';
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
//import $ from 'jquery';
React.initializeTouchEvents(true);
/* --- Profile Page ---*/
var Profile = React.createClass({
getInitialState: function(){
return{
ifLoggedIn: false,
showedPage: "mainPage",
level2Page: [],
}
},
profileBarHandler:function(sender){
if(sender == "settings"){
console.log("To Settings");
}
else if(sender == "login"){
if(this.state.ifLoggedIn){
console.log("Goto user detail page.");
}
else{
this.setState({
level2Page: (<div id="level2PageContainer"><LoginPage handler={this.level2ViewHandler}/></div>),
showedPage: "loginPage",
});
}
}
},
tableViewHandler:function(sender){
if((sender == "payments") || (sender == "shipping") || (sender == "review")){
var active = 0;
switch(sender){
case "payments" :
active = 0;
break;
case "shipping" :
active = 1;
break;
case "review" :
active = 2;
break;
default :
active = 0;
break;
}
this.setState({
level2Page: (<div id="level2PageContainer"><WaitingPayment activeSwitch={0} handler={this.level2ViewHandler}/></div>),
showedPage: "myOrdersPage",
});
}
else if(sender == "orders"){
this.setState({
level2Page: (<div id="level2PageContainer"><MyOrders activeSwitch={0} handler={this.level2ViewHandler}/></div>),
showedPage: "myOrdersPage",
});
}
else if(sender == "favourites"){
this.setState({
level2Page: (<div id="level2PageContainer"><MyFavourites handler={this.level2ViewHandler}/></div>),
showedPage: "myFavouritessPage",
});
}
},
level2ViewHandler: function(action, data){
if(action == "closeLevel2"){
if(data){
}
this.setState({
level2Page: [],
showedPage: "mainPage",
});
}
},
render: function() {
return (
<div id="container">
<div id="mainPageContainer">
<ProfileBar loginStatus={this.state.ifLoggedIn} profileData={sampleData} handler={this.profileBarHandler}/>
<ProfileTableView handler={this.tableViewHandler} />
</div>
<ReactCSSTransitionGroup transitionName="level2PageTransition">
{this.state.level2Page}
</ReactCSSTransitionGroup>
</div>
);
}
});
//Render
export function startRender(){
React.render(
<Profile />,
document.getElementById('trProfile')
);
}
/* --- Main Page ---*/
var ProfileBar = React.createClass({
handleClick: function(sender){
this.props.handler(sender);
},
render: function() {
var sender = null;
return (
<div className="profileBar">
<div className="settings" onClick={this.handleClick.bind(this, sender="settings")}></div>
<div className="profileImage" onClick={this.handleClick.bind(this, sender="login")}>
<img src={this.props.profileData.profileImageUrl}/>
</div>
<div className="profileName">
<span>{this.props.loginStatus?this.props.profileData.profileName:"点击头像登录"}</span>
</div>
<div className="balanceCouponsContainer">
<div className="remianBalance">
<div className="balance">
<span>{"¥" + this.props.profileData.remainBalance.toFixed(2)}</span>
</div>
<div className="title">
<span>账户余额</span>
</div>
</div>
<div className="separator"></div>
<div className="remianCoupons">
<div className="coupons">
<span>{this.props.profileData.remainCoupons}</span>
</div>
<div className="title">
<span>优惠劵</span>
</div>
</div>
</div>
</div>
);
}
});
var ProfileTableView = React.createClass({
handleClick: function(sender){
this.props.handler(sender);
},
render: function() {
var sender = null;
return (
<div className="profileTableView">
<div className="statusButtons">
<div className="payments" onClick={this.handleClick.bind(this, sender="payments")}>
<div className="icon"></div>
<div className="title"><span></span>待付款</div>
</div>
<div className="separator"></div>
<div className="shipping" onClick={this.handleClick.bind(this, sender="shipping")}>
<div className="icon"></div>
<div className="title"><span></span>待收货</div>
</div>
<div className="separator"></div>
<div className="review" onClick={this.handleClick.bind(this, sender="review")}>
<div className="icon"></div>
<div className="title"><span></span>待评价</div>
</div>
</div>
<div className="cells">
<div className="orders cell" onClick={this.handleClick.bind(this, sender="orders")}>
<div className="icon"></div>
<div className="title"><span>全部订单</span></div>
<div className="arrow"></div>
</div>
<div className="separator"></div>
<div className="favourites cell" onClick={this.handleClick.bind(this, sender="favourites")}>
<div className="icon"></div>
<div className="title"><span>我的关注</span></div>
<div className="arrow"></div>
<div className="separator2"></div>
</div>
<div className="management cell" onClick={this.handleClick.bind(this, sender="management")}>
<div className="icon"></div>
<div className="title"><span>管理中心</span></div>
<div className="arrow"></div>
<div className="separator2"></div>
</div>
<div className="userdata cell" onClick={this.handleClick.bind(this, sender="userdata")}>
<div className="icon"></div>
<div className="title"><span>用户信息</span></div>
<div className="arrow"></div>
</div>
<div className="separator"></div>
<div className="transferMoney cell" onClick={this.handleClick.bind(this, sender="transferMoney")}>
<div className="icon"></div>
<div className="title"><span>会员充值</span></div>
<div className="arrow"></div>
<div className="separator2"></div>
</div>
<div className="orderDetails cell" onClick={this.handleClick.bind(this, sender="orderDetails")}>
<div className="icon"></div>
<div className="title"><span>账单明细</span></div>
<div className="arrow"></div>
</div>
<div className="separator"></div>
<div className="faq cell" onClick={this.handleClick.bind(this, sender="faq")}>
<div className="icon"></div>
<div className="title"><span>常见问题</span></div>
<div className="arrow"></div>
<div className="separator2"></div>
</div>
<div className="customService cell" onClick={this.handleClick.bind(this, sender="customService")}>
<div className="icon"></div>
<div className="title"><span>联系客服</span></div>
<div className="arrow"></div>
</div>
<div className="separator"></div>
</div>
</div>
);
}
});
/* --- My Orders Page ---*/
var MyOrders = React.createClass({
getInitialState: function(){
return{
activeSwitch: this.props.activeSwitch,
ordersArray: sampleData.orders,
}
},
handleSwitch: function(number){
this.setState({
activeSwitch: number,
});
},
handleClick: function(sender){
if(sender == "backButton"){
this.props.handler("closeLevel2", null);
}
else if(sender == "buyAgain"){
console.log("buyAgain");
}
},
render: function() {
var sender = null;
var orders = [];
for(var i=0; i<this.state.ordersArray.length; i++){
orders.push(<OrderItem orderItem={this.state.ordersArray[i]} key={i} handleClick={this.handleClick}/>);
}
return (
<div id="myOrders">
<div className="titleBar">
<div className="backButton" onClick={this.handleClick.bind(this, sender="backButton")}></div>
<div className="titleText"><span>我的订单</span></div>
<div className="editButton"><span>编辑</span></div>
</div>
<div className="switch">
<div className="holder">
<div className={"allOrders "+((this.state.activeSwitch==0)?"active":"inactive")} onClick={this.handleSwitch.bind(this, 0)}>
<div className="text"><span>全部订单</span></div>
<div className="indicator"></div>
</div>
<div className={"pendingPayment "+((this.state.activeSwitch==1)?"active":"inactive")} onClick={this.handleSwitch.bind(this, 1)}>
<div className="text"><span>待收款</span></div>
<div className="indicator"></div>
</div>
<div className={"pendingShipment "+((this.state.activeSwitch==2)?"active":"inactive")} onClick={this.handleSwitch.bind(this, 2)}>
<div className="text"><span>待发货</span></div>
<div className="indicator"></div>
</div>
</div>
</div>
<div className="ordersContainer">
{orders}
</div>
</div>
);
}
});
var OrderItem = React.createClass({
handleClick: function(sender){
if(sender == "buyAgain"){
this.props.handleClick("buyAgain");
}
},
render: function() {
var sender = null;
var orderItem = this.props.orderItem;
var products = [];
for(var i=0; i<orderItem.orderContent.length; i++){
products.push(<ProductImage imageUrl={orderItem.orderContent[i]}/>);
}
return (
<div className="orderItem">
<div className="orderStatus">
<div className="orderNumber"><span>{"订单号: " + orderItem.orderNumber}</span></div>
<div className="status"><span>{orderItem.orderStatus}</span></div>
</div>
<div className="orderContentWarper">
<div className="orderContent" style={{width : (orderItem.orderContent.length*100 + "px")}}>
{products}
</div>
</div>
<div className="orderPriceAndDateContainer">
<div className="orderPriceAndDate">
<div className="orderPrice">
<div className="label"><span>{"订单金额(含运费: " + orderItem.shippingFee + "): "}</span></div>
<div className="price"><span>{"¥" + (orderItem.shippingFee + orderItem.orderPrice).toFixed(2)}</span></div>
</div>
<div className="orderDate">
<span>{"下单日期: " + orderItem.orderDate}</span>
</div>
</div>
</div>
<div className="orderAgain" onClick={this.handleClick.bind(this, sender="buyAgain")}>
<div className="text"><span>再次购买</span></div>
</div>
</div>
);
}
});
var ProductImage = React.createClass({
render: function() {
return (
<div className="productImage">
<img src={this.props.imageUrl} />
</div>
);
}
});
/* --- My Favourite Page ---*/
var MyFavourites = React.createClass({
getInitialState: function(){
return{
activeSwitch: 0,
favouriteProductsArray: sampleData.favourites,
}
},
handleSwitch: function(number){
this.setState({
activeSwitch: number,
});
},
handleClick: function(sender){
if(sender == "backButton"){
this.props.handler("closeLevel2", null);
}
else if(sender == "addToCart"){
console.log("addToCart");
}
},
render: function() {
var sender = null;
var favouriteProducts = [];
for(var i=0; i<this.state.favouriteProductsArray.length; i++){
favouriteProducts.push(<FavouritesItem favouriteItem={this.state.favouriteProductsArray[i]} key={i} handleClick={this.handleClick}/>);
}
return (
<div id="myFavourites">
<div className="titleBar">
<div className="backButton" onClick={this.handleClick.bind(this, sender="backButton")}></div>
<div className="titleText"><span>我的关注</span></div>
<div className="editButton"><span>编辑</span></div>
</div>
<div className="switch">
<div className="holder">
<div className={"products "+((this.state.activeSwitch==0)?"active":"inactive")} onClick={this.handleSwitch.bind(this, 0)}>
<div className="text"><span>关注商品</span></div>
<div className="indicator"></div>
</div>
<div className={"brands "+((this.state.activeSwitch==1)?"active":"inactive")} onClick={this.handleSwitch.bind(this, 1)}>
<div className="text"><span>关注品牌</span></div>
<div className="indicator"></div>
</div>
</div>
</div>
<div className="favouritesContainer">
{favouriteProducts}
</div>
</div>
);
}
});
var FavouritesItem = React.createClass({
handleClick: function(sender){
if(sender == "addToCart"){
this.props.handleClick("addToCart");
}
},
render: function() {
var sender = null;
var favouriteItem = this.props.favouriteItem;
return (
<div className="favouriteItem">
<div className="description">
<div className="productImage">
<img src={favouriteItem.productImage} />
</div>
<div className="productName">
<span>{favouriteItem.productName}</span>
</div>
<div className="productPrice">
<span>{"¥" + favouriteItem.productPrice.toFixed(2)}</span>
</div>
</div>
<div className="favouritedTime">
<span>{"收藏时间: " + favouriteItem.favouritedTime}</span>
</div>
<div className="addToCart" onClick={this.handleClick.bind(this, sender="addToCart")}>
<div className="text"><span>加入购物车</span></div>
</div>
</div>
);
}
});
/* --- Waiting Payment Page ---*/
var WaitingPayment = React.createClass({
getInitialState: function(){
return{
activeSwitch: 0,
ordersArray: sampleData.waitingPayment,
}
},
handleSwitch: function(number){
this.setState({
activeSwitch: number,
});
},
handleClick: function(sender){
if(sender == "backButton"){
this.props.handler("closeLevel2", null);
}
else if(sender == "payNow"){
console.log("PayNow");
}
},
render: function() {
var sender = null;
var orders = [];
for(var i=0; i<this.state.ordersArray.length; i++){
orders.push(<WaitingPaymentItem orderItem={this.state.ordersArray[i]} key={i} handleClick={this.handleClick}/>);
}
return (
<div id="waitingPayment">
<div className="titleBar">
<div className="backButton" onClick={this.handleClick.bind(this, sender="backButton")}></div>
<div className="titleText"><span>我的订单</span></div>
<div className="editButton"><span>编辑</span></div>
</div>
<div className="switch">
<div className="holder" ref="holder">
<div className={"pendingPayment "+((this.state.activeSwitch==0)?"active":"inactive")} onClick={this.handleSwitch.bind(this, 0)}>
<div className="text"><span>待付款</span></div>
<div className="indicator"></div>
</div>
<div className={"pendingShipment "+((this.state.activeSwitch==1)?"active":"inactive")} onClick={this.handleSwitch.bind(this, 1)}>
<div className="text"><span>待发货</span></div>
<div className="indicator"></div>
</div>
<div className={"prepareForShipment "+((this.state.activeSwitch==2)?"active":"inactive")} onClick={this.handleSwitch.bind(this, 2)}>
<div className="text"><span>待收货</span></div>
<div className="indicator"></div>
</div>
</div>
</div>
<div className="ordersContainer">
{orders}
</div>
</div>
);
}
});
var WaitingPaymentItem = React.createClass({
handleClick: function(sender){
if(sender == "payNow"){
this.props.handleClick("payNow");
}
},
render: function() {
var sender = null;
var orderItem = this.props.orderItem;
return (
<div className="orderItem">
<div className="orderStatus">
<div className="orderNumber"><span>{"订单号: " + orderItem.orderNumber}</span></div>
<div className="status"><span>{orderItem.orderStatus}</span></div>
</div>
<div className="orderContent">
<div className="productImage">
<img src={orderItem.orderContent.productImage} />
</div>
<div className="productName">
<span>{orderItem.orderContent.productName}</span>
</div>
</div>
<div className="orderPriceAndDateContainer">
<div className="orderPriceAndDate">
<div className="orderPrice">
<div className="label"><span>{"订单金额(含运费: " + orderItem.shippingFee + "): "}</span></div>
<div className="price"><span>{"¥" + (orderItem.shippingFee + orderItem.orderPrice).toFixed(2)}</span></div>
</div>
<div className="orderDate">
<span>{"下单日期: " + orderItem.orderDate}</span>
</div>
</div>
</div>
<div className="payNow" onClick={this.handleClick.bind(this, sender="payNow")}>
<div className="text"><span>立即付款</span></div>
</div>
</div>
);
}
});
/* --- Login Page ---*/
var LoginPage = React.createClass({
getInitialState: function(){
return{
autoLogin: false,
nextLevelPage: [],
}
},
handleClick: function(sender){
if(sender == "backButton"){
this.props.handler("closeLevel2", null);
}
else if(sender == "autoLogin"){
this.setState({
autoLogin: !this.state.autoLogin,
});
}
else if(sender == "register"){
this.setState({
nextLevelPage: (<div id="nextLevelPageContainer"><RegisterPage handler={this.nextLevelViewHandler}/></div>),
});
}
},
handleSubmit: function(){
var username = React.findDOMNode(this.refs.username).value.trim();
var password = React.findDOMNode(this.refs.password).value.trim();
//Use Ajax login here
console.log("Login with username: " + username + ", and password: " + password + "; Auto Login: " + this.state.autoLogin);
//If success
var receivedData = {
status: true,
data: null, //There should be a token in data.
}
this.props.handler("closeLevel2", receivedData);
//If unsuccess
},
nextLevelViewHandler: function(action, data){
if(action == "closeLevel"){
if(data){
}
this.setState({
nextLevelPage: [],
});
}
},
render: function() {
var sender = null;
return (
<div id="loginPage">
<div className="titleBar">
<div className="backButton" onClick={this.handleClick.bind(this, sender="backButton")}></div>
<div className="titleText"><span>登录</span></div>
</div>
<div className="loginField">
<div className="inputField">
<input className="username" type="text" placeholder="请输入用户名" ref="username" />
<input className="password" type="password" placeholder="请输入密码" ref="password" />
</div>
<div className="autoLogin">
<div className={"checkBox "+(this.state.autoLogin?"checked":"")} onClick={this.handleClick.bind(this, "autoLogin")}></div>
<div className="label"><span>七天内免登录</span></div>
</div>
<div className="submitBox" onClick={this.handleSubmit}><span>登录</span></div>
</div>
<div className="otherOptions">
<div className="signup" onClick={this.handleClick.bind(this, "register")}><span>免费注册</span></div>
<div className="forgetPassword"><span>找回密码</span></div>
</div>
<ReactCSSTransitionGroup transitionName="nextLevelPageTransition">
{this.state.nextLevelPage}
</ReactCSSTransitionGroup>
</div>
);
}
});
/* --- Register Page ---*/
var RegisterPage = React.createClass({
getInitialState: function(){
return{
userData: null,
}
},
handleClick: function(sender){
if(sender == "backButton"){
this.props.handler("closeLevel");
}
},
handleSubmit: function(){
var data = {
username : React.findDOMNode(this.refs.username).value.trim(),
password : React.findDOMNode(this.refs.password).value.trim(),
re_password : React.findDOMNode(this.refs.re_password).value.trim(),
email : React.findDOMNode(this.refs.email).value.trim(),
mobilePhone : React.findDOMNode(this.refs.mobilePhone).value.trim(),
gov_id : React.findDOMNode(this.refs.gov_id).value.trim(),
}
this.setState({
userData: data,
});
//Use Ajax register here
console.log(data);
//If success
var receivedData = {
status: true,
data: null, //There should be a token in data.
}
this.props.handler("closeLevel");
//If unsuccess
},
render: function() {
var sender = null;
return (
<div id="registerPage">
<div className="titleBar">
<div className="backButton" onClick={this.handleClick.bind(this, sender="backButton")}></div>
<div className="titleText"><span>注册</span></div>
</div>
<div className="registerField">
<div className="inputField">
<div className="userTypeDropDown">
<span>请选择会员类型</span>
</div>
<input className="username" type="text" placeholder="请输入会员名称" ref="username" />
<input className="password" type="password" placeholder="请输入登录密码" ref="password" />
<input className="re_password" type="password" placeholder="请再次输入登录密码" ref="re_password" />
<div className="locationDropDown">
<span>所属地区</span>
</div>
<input className="email" type="email" placeholder="请输入您的邮箱" ref="email" />
<input className="mobilePhone" type="text" placeholder="请输入您的手机号码" ref="mobilePhone" />
<input className="gov_id" type="text" placeholder="请输入您的身份证号码" ref="gov_id" />
</div>
<div className="policy">
<span>注册即视为同意<a href="#">河南驼人集团的《服务条款》</a></span>
</div>
<div className="submitBox" onClick={this.handleSubmit}><span>注册</span></div>
</div>
</div>
);
}
});
var sampleData = {
profileName: "A Shop User",
profileImageUrl: "./assets/sampleUserAvatar.jpg",
remainBalance: 500.00,
remainCoupons: 10,
orders: [
{
orderNumber: "SN1212121212121211511",
orderStatus: "已完成",
orderPrice: 150.00,
shippingFee: 0,
orderDate: "2015-07-29",
orderContent: [
"./assets/sampleOrder.png",
"./assets/sampleOrder2.png",
"./assets/sampleOrder.png",
"./assets/sampleOrder2.png",
"./assets/sampleOrder.png",
"./assets/sampleOrder2.png"
],
},
{
orderNumber: "SN1212121212121211511",
orderStatus: "Completed",
orderPrice: 400.00,
shippingFee: 0,
orderDate: "2015-08-03",
orderContent: [
"./assets/sampleOrder.png",
"./assets/sampleOrder2.png"
],
}
],
favourites: [
{
productName: "电子输注泵 1.03.04.118T 电子泵一托+275ml",
productImage: "./assets/sampleProduct2@2x.png",
productPrice: 228.00,
favouritedTime: "2015-08-01",
},
{
productName: "一次性使用静脉留置针 1.04.01.466T Y式18G",
productImage: "./assets/sampleProduct2@2x.png",
productPrice: 12.00,
favouritedTime: "2015-08-02",
}
],
waitingPayment: [
{
orderNumber: "SN1212121212121211511",
orderStatus: "等待付款",
orderPrice: 50.00,
shippingFee: 0,
orderDate: "2015-07-29",
orderContent: {
productName: "电子输注泵 1.03.04.118T 电子泵一托+275ml",
productImage: "./assets/sampleProduct2@2x.png",
},
}
]
}
|
const express = require("express");
const connectDB = require("./config/db");
const app = express();
const PORT = process.env.PORT || 5000;
// Connect Database
connectDB();
// Initialize Middleware
app.use(express.json({ extended: false }));
app.get("/", (req, res) => {
res.send("App is up and running!");
});
// User Routes
app.use("/api/users", require("./routes/api/users/users"));
app.use("/api/profile", require("./routes/api/users/profile"));
app.use("/api/auth", require("./routes/api/users/auth"));
// Host Routes
app.use("/api/hosts", require("./routes/api/hosts/hosts"));
app.use("/api/field", require("./routes/api/hosts/fields"));
app.use("/api/hostAuth", require("./routes/api/hosts/auth"));
app.use("/api/hostProfile", require("./routes/api/hosts/profile"));
app.listen(PORT, () => {
console.log(`Server up and running on port ${PORT}`);
});
|
import snippetStore from '../../stores/snippet';
import HorizontalScroll from 'react-scroll-horizontal';
import React from 'react';
import Rundown from '../layouts/rundown';
import styled from 'styled-components';
const Box = styled.div`
flex-direction: column;
box-sizing: border-box;
height: 100%;
width: 100%;
`;
const Title = styled.h2`
flex-grow: 1;
font-size: 40px;
font-weight: bold;
margin: 0;
padding: 80px 32px 40px 32px;
`;
const Wrapper = styled.div`
flex-grow: 1;
height: 75%;
`;
const Story = styled.span`
font-weight: normal;
`;
export default class Project extends React.Component {
constructor () {
super();
this.state = {
rundowns: snippetStore.getAll()
};
}
componentWillMount () {
snippetStore.on('change', () => {
this.setState({
rundowns: snippetStore.getAll()
});
});
}
render () {
const { rundowns } = this.state;
const title = 'Next Generation Methods';
const rundownComponents = rundowns.map((snippets, index) => {
return <Rundown key={index} week={index + 1} snippets={snippets} />;
});
return (
<Box>
<Title>{title} <Story>Story</Story></Title>
<Wrapper>
<HorizontalScroll>
{ rundownComponents }
</HorizontalScroll>
</Wrapper>
</Box>
);
}
}
|
export default {
set() {
this.textInput = document.getElementById('text');
this.count = document.getElementById('count');
this.countForm = document.getElementById('countForm');
}
}
|
var {MessageDistributor} = require("./messagedistributor");
exports.getMessageDistributor = function(namespace, options) {
return module.singleton("MessageDistributor" + namespace, function() {
return new MessageDistributor(namespace, options);
});
};
exports.isPlatformSupported = MessageDistributor.isPlatformSupported;
exports.GCMMessage = require("./gcm/message").Message;
exports.APNSMessage = require("./apns/message").Message;
|
import React, { Component } from 'react';
import { Button, Icon, Empty, Tag } from 'antd';
import FlowModal from '../../FlowModal';
import './EmptyHome.scss';
export class EmptyHome extends Component {
state = {
visible: false
};
componentWillMount() {
this.addKeybindListener();
}
handleKeyPress = (event) => {
event.preventDefault();
if(event.key === 'f') {
this.showModal();
} else if (event.ctrlKey && event.key === 's') {
this.showModal();
}
};
showModal = () => {
document.removeEventListener('keydown', this.handleKeyPress);
this.setState({ visible: !this.state.visible });
};
addKeybindListener = () => {
document.addEventListener('keydown', this.handleKeyPress);
}
render() {
return (
<div>
<FlowModal visible={this.state.visible} type="create" addKeybindListener={this.addKeybindListener}/>
<Empty
image={<Icon type="coffee" style={{fontSize: 64, color: "#ccc"}}/>}
description={
<span style={{ color: '#bbb', marginBottom: '3em' }}>
No active flows. Add one here!
<span>
<br />
<Icon type="bulb" /> <strong>Tip:</strong> use <Tag>⌘ + s</Tag> or simply <Tag>f</Tag> to save a flow
</span>
</span>
}
>
<Button icon="thunderbolt" size="large" type="primary" onClick={this.showModal} style={{ boxShadow: '0 2px 4px 0 rgba(62,80,104,0.32)'}}>
Add Flow!
</Button>
</Empty>
</div>
);
}
}
export default EmptyHome;
|
class BankAccount {
constructor(accountNumber, accountHolder, accountBalance) {
this.accountNumber = accountNumber;
this.accountHolder = accountHolder;
this.accountBalance = accountBalance;
}
getBalance() {
console.log("Available balance: Rs. " + this.accountBalance);
}
}
class Savings extends BankAccount {
constructor(accountNumber, accountHolder, accountBalance) {
super(accountNumber, accountHolder, accountBalance);
}
withdraw(amount) {
if(this.accountBalance - amount >= 0) {
console.log("Withdrawal of Rs. " + amount + "successfull. ");
this.accountBalance=this.accountBalance-amount;
} else {
console.log("Withdrawal of Rs. " + amount + "failed: Not enough Balance");
}
}
}
class Current extends BankAccount {
constructor(accountNumber, accountHolder, accountBalance, odLimit) {
super(accountNumber, accountHolder, accountBalance);
this.odLimit = odLimit;
}
withdraw(amount) {
if(this.accountBalance - amount >= -(this.odLimit)) {
console.log("Withdrawal of Rs. " + amount + "successfull. ");
this.accountBalance=this.accountBalance-amount;
} else {
console.log("Withdrawal of Rs. " + amount + "failed: Not enough Balance");
}
}
}
var currentAccount = new Current(12, "AB", 10000, 1000);
console.log("Operation of Current account: ");
currentAccount.getBalance();
currentAccount.withdraw(10000);
currentAccount.getBalance();
currentAccount.withdraw(500);
currentAccount.getBalance();
currentAccount.withdraw(1000);
currentAccount.getBalance();
var savingAccount = new Savings(13, "CD", 12000);
console.log("Operation of Current account: ");
savingAccount.getBalance();
savingAccount.withdraw(12000);
savingAccount.getBalance();
savingAccount.withdraw(1);
savingAccount.getBalance();
|
class QuickSort {
constructor() {
this.speed = 1000 - speed_slider.value
this.cancel = false;
}
async sort(low, high){
// perform quick sort
if(low >= high || this.cancel){
update_heights();
return;
}
let index = await this.partition(low, high);
this.sort(low, index - 1);
this.sort(index + 1, high);
}
async partition(low, high){
// seperate into two seperate lists
let pivot = item_heights[high]
let pivot_index = low;
for(let i = low; i < high; i++){
if(this.cancel){
return
}
if (item_heights[i] < pivot){
let temp = item_heights[i];
item_heights[i] = item_heights[pivot_index];
item_heights[pivot_index] = temp;
pivot_index++;
}
this.highlight(low, high, i, pivot_index);
update_heights();
await sleep(this.speed);
this.unhighlight(low, high, i, pivot_index)
}
let temp = item_heights[high];
item_heights[high] = item_heights[pivot_index];
item_heights[pivot_index] = temp;
return pivot_index;
}
highlight(low, high, i, index){
// highlight selected portions
for(let j = low; j < high; j++){
inner_items[j].style.background = colors.FOCUSED;
}
inner_items[i].style.background = colors.SELECTED;
inner_items[index].style.background = colors.SELECTED2;
}
unhighlight(low, high, i, index){
// unhighlight selected portions
let inner_items = document.getElementsByClassName("inner_item");
for(let j = low; j < high; j++){
inner_items[j].style.background = colors.NORMAL;
}
inner_items[i].style.background = colors.NORMAL;
inner_items[index].style.background = colors.NORMAL;
}
}
|
module.exports = {
"copyright": "©",
"trademark": "™",
"pound": "£",
"euro": "€",
"interpunct": "·"
};
|
import React from 'react';
import styles from './style.module.css';
import downArrowIcon from '../../assets/icons/downArrow.png';
export default function Dropdown({ text, children }) {
const [isExpended, setExpend] = React.useState(true);
const handleClick = () => {
setExpend(!isExpended);
};
return (
<div>
<button type="button" className={styles.button} onClick={handleClick}>
<p className={styles.title}>{text}</p>
<img className={styles.icon} alt="icon" src={downArrowIcon} />
</button>
{isExpended && children}
</div>
);
}
|
import React from 'react'
import { Route } from 'react-router-dom'
import "bootstrap/dist/css/bootstrap.min.css"
import HookForm from './componentes/Home/Home';
import Nav from './componentes/Navbar/Navbar';
import Form from './componentes/Login/FormLogin';
import Register from './componentes/Register/Index';
import About from './componentes/About/About';
function App() {
return (
<>
<Nav />
<Route exact path='/' render={() => <HookForm />} />
<Route path='/login' render={() => <Form />} />
<Route path='/register' render={() => <Register />} />
<Route path='/about' render={() => <About />} />
</>
);
}
export default App;
|
import React, { Component } from "react";
import SignIn from "./components/SignIn/SignIn.jsx";
import SignUp from "./components/SignUp/SignUp.jsx";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
signup: true,
};
}
changeState = () => {
var temp = this.state.signup ? false : true;
this.setState({
signup: temp,
});
};
render() {
if (this.state.signup) return <SignUp func={this.changeState} />;
else return <SignIn func={this.changeState} />;
}
}
|
function welcome() {
console.log("welcome to this function.");
}
function getLost()
{
console.log("get Lost from here");
}
function getchoice(choice)
{
choice();
}
getchoice(welcome);
getchoice(getLost);
|
var http = require("http");
var manejador = function(sol, resp){
console.log("recibimos una nueva peticion");
resp.end("hola Mundo");
}
var servidor = http.createServer(manejador);
servidor.listen(8000);
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class SpriteRendererConfig extends SupCore.Data.Base.ComponentConfig {
constructor(pub) { super(pub, SpriteRendererConfig.schema); }
static create() {
const emptyConfig = {
formatVersion: SpriteRendererConfig.currentFormatVersion,
spriteAssetId: null, animationId: null,
horizontalFlip: false, verticalFlip: false,
castShadow: false, receiveShadow: false,
color: "ffffff",
overrideOpacity: false, opacity: null,
materialType: "basic", shaderAssetId: null
};
return emptyConfig;
}
static migrate(pub) {
if (pub.formatVersion === SpriteRendererConfig.currentFormatVersion)
return false;
if (pub.formatVersion == null) {
pub.formatVersion = 1;
// NOTE: Settings introduced in Superpowers 0.8
if (pub.overrideOpacity == null)
pub.overrideOpacity = false;
if (pub.color == null)
pub.color = "ffffff";
if (pub.horizontalFlip == null)
pub.horizontalFlip = false;
if (pub.verticalFlip == null)
pub.verticalFlip = false;
// NOTE: Settings introduced in Superpowers 0.7
if (pub.castShadow == null)
pub.castShadow = false;
if (pub.receiveShadow == null)
pub.receiveShadow = false;
if (pub.materialType == null)
pub.materialType = "basic";
// NOTE: Legacy stuff from Superpowers 0.4
if (typeof pub.spriteAssetId === "number")
pub.spriteAssetId = pub.spriteAssetId.toString();
if (typeof pub.animationId === "number")
pub.animationId = pub.animationId.toString();
}
return true;
}
restore() {
if (this.pub.spriteAssetId != null)
this.emit("addDependencies", [this.pub.spriteAssetId]);
if (this.pub.shaderAssetId != null)
this.emit("addDependencies", [this.pub.shaderAssetId]);
}
destroy() {
if (this.pub.spriteAssetId != null)
this.emit("removeDependencies", [this.pub.spriteAssetId]);
if (this.pub.shaderAssetId != null)
this.emit("removeDependencies", [this.pub.shaderAssetId]);
}
setProperty(path, value, callback) {
let oldDepId;
if (path === "spriteAssetId")
oldDepId = this.pub.spriteAssetId;
if (path === "shaderAssetId")
oldDepId = this.pub.shaderAssetId;
super.setProperty(path, value, (err, actualValue) => {
if (err != null) {
callback(err);
return;
}
if (path === "spriteAssetId" || path === "shaderAssetId") {
if (oldDepId != null)
this.emit("removeDependencies", [oldDepId]);
if (actualValue != null)
this.emit("addDependencies", [actualValue]);
}
if (path === "overrideOpacity")
this.pub.opacity = null;
callback(null, actualValue);
});
}
}
SpriteRendererConfig.schema = {
formatVersion: { type: "integer" },
spriteAssetId: { type: "string?", min: 0, mutable: true },
animationId: { type: "string?", min: 0, mutable: true },
horizontalFlip: { type: "boolean", mutable: true },
verticalFlip: { type: "boolean", mutable: true },
castShadow: { type: "boolean", mutable: true },
receiveShadow: { type: "boolean", mutable: true },
color: { type: "string?", length: 6, mutable: true },
overrideOpacity: { type: "boolean", mutable: true },
opacity: { type: "number?", min: 0, max: 1, mutable: true },
materialType: { type: "enum", items: ["basic", "phong", "shader"], mutable: true },
shaderAssetId: { type: "string?", min: 0, mutable: true }
};
SpriteRendererConfig.currentFormatVersion = 1;
exports.default = SpriteRendererConfig;
|
var examinationId = -1;
$(document).ready(function () {
var examination = $(".examination")
examination.show();
var writeReport = $(".writeReport")
writeReport.hide();
var prescriptMedication = $(".prescriptMedication")
prescriptMedication.hide();
var scheduleNewAppointment = $(".scheduleNewAppointment")
scheduleNewAppointment.hide();
var medInPharmacy = $(".medInPharmacy");
medInPharmacy.hide();
var medNotInPharmacy = $(".medNotInPharmacy");
medNotInPharmacy.hide();
var alternativeMedication = $(".alternativeMedication");
alternativeMedication.hide();
var howToScheduleAppointment = $(".howToScheduleAppointment")
howToScheduleAppointment.hide();
var existingAppointments = $(".existingAppointments")
existingAppointments.hide();
var createAppointment = $(".createAppointment")
createAppointment.hide();
$.ajax({
type: "GET",
url: "http://localhost:8081/examinations/getAppointmentId",
dataType: "json",
beforeSend: function(xhr) {
if (localStorage.token) {
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token);
}
},
success: function (data) {
examinationId = data['id'];
console.log(examinationId);
},
error: function () {
window.location.href="error.html";
}
});
});
$(document).on('click', '#btnReport', function () {
var examination = $(".examination")
examination.hide();
var writeReport = $(".writeReport")
writeReport.show();
var prescriptMedication = $(".prescriptMedication")
prescriptMedication.hide();
var scheduleNewAppointment = $(".scheduleNewAppointment")
scheduleNewAppointment.hide();
var medInPharmacy = $(".medInPharmacy");
medInPharmacy.hide();
var medNotInPharmacy = $(".medNotInPharmacy");
medNotInPharmacy.hide();
var alternativeMedication = $(".alternativeMedication");
alternativeMedication.hide();
var howToScheduleAppointment = $(".howToScheduleAppointment")
howToScheduleAppointment.hide();
var existingAppointments = $(".existingAppointments")
existingAppointments.hide();
var createAppointment = $(".createAppointment")
createAppointment.hide();
$(document).on('click', '#btnSubmitReport', function () {
var report = $("#chReport").val();
var myJSON = JSON.stringify({"id":examinationId, "report":report});
$.ajax({
type: "POST",
url: "http://localhost:8081/examinations/writeReport",
dataType: "json",
contentType: "application/json",
data: myJSON,
beforeSend: function(xhr) {
if (localStorage.token) {
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token);
}
},
success: function (data) {
var writeReport = $(".writeReport")
writeReport.hide();
var examination = $(".examination")
examination.show();
alert("Izmene su sacuvane");
},
error: function (data) {
window.location.href="error.html";
}
});
});
});
$(document).on('click', '#btnPrescript', function () {
var examination = $(".examination");
examination.hide();
var writeReport = $(".writeReport");
writeReport.hide();
var prescriptMedication = $(".prescriptMedication");
prescriptMedication.show();
var scheduleNewAppointment = $(".scheduleNewAppointment");
scheduleNewAppointment.hide();
var medInPharmacy = $(".medInPharmacy");
medInPharmacy.hide();
var medNotInPharmacy = $(".medNotInPharmacy");
medNotInPharmacy.hide();
var alternativeMedication = $(".alternativeMedication");
alternativeMedication.hide();
var howToScheduleAppointment = $(".howToScheduleAppointment")
howToScheduleAppointment.hide();
var existingAppointments = $(".existingAppointments")
existingAppointments.hide();
var createAppointment = $(".createAppointment")
createAppointment.hide();
$("#idDropDown").empty();
var myJSON = JSON.stringify({"id":examinationId});
$.ajax({
type: "POST",
url: "http://localhost:8081/examinations/getMedicationsForPrescription",
dataType: "json",
contentType: "application/json",
data: myJSON,
beforeSend: function(xhr) {
if (localStorage.token) {
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token);
}
},
success: function (data) {
console.log('Success', data);
$("#idDropDown").append("<option> </option>");
for (i = 0; i < data.length; i++) {
/*var row = "<tr>";
row += "<td>" + data[i]['name'] + "</td>";
var btn = "<button class='btnButton' id = " + data[i]['name'] + ">Proveri</button>";
row += "<td>" + btn + "</td>";
$('#tableMeds').append(row);*/
var name = data[i]['name'];
$("#idDropDown").append("<option value='"+name+"'>"+name+"</option>");
}
},
error: function (data) {
console.log('Error', data);
}
});
});
var imeIzabranogLeka;
$(document).on('change', '#idDropDown', function () {
//console.log('Something');
var name = $("#idDropDown :selected").val();
var myJSON = JSON.stringify({"id":examinationId, "name":name});
imeIzabranogLeka = name;
/*console.log(name, examinationId);
var examination = $(".examination");
examination.hide();
var writeReport = $(".writeReport");
writeReport.hide();
var prescriptMedication = $(".prescriptMedication");
prescriptMedication.hide();
var scheduleNewAppointment = $(".scheduleNewAppointment");
scheduleNewAppointment.hide();*/
var medInPharmacy = $(".medInPharmacy");
medInPharmacy.hide();
var medNotInPharmacy = $(".medNotInPharmacy");
medNotInPharmacy.hide();
$.ajax({
type: "POST",
url: "http://localhost:8081/examinations/checkIfMedicationIsAvailable",
dataType: "json",
contentType: "application/json",
data: myJSON,
beforeSend: function(xhr) {
if (localStorage.token) {
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token);
}
},
success: function (data) {
console.log('Success', data);
var d = data['value'];
console.log('d',d);
if(d === true){
medInPharmacy.show();
/*var row = "<tr>";
row += "<td>Lek je dostupan u apoteci.</td>";
var btn = "<button class='btnSubmitPrescription' id = " + name + ">Potvrdi</button>";
row += "<td>" + btn + "</td>";
$('#tableMedInPharmacy').append(row);*/
}
else {
medNotInPharmacy.show();
}
},
error: function (data) {
console.log('Error', data);
}
});
});
$(document).on('click', '#btnPrescriptMedication', function () {
//console.log('Something');
var duration = $("#chTherapyDuration").val();
var myJSON = JSON.stringify({"id":examinationId, "name":imeIzabranogLeka,"duration":duration});
$.ajax({
type: "POST",
url: "http://localhost:8081/examinations/savePrescription",
dataType: "json",
contentType: "application/json",
data: myJSON,
beforeSend: function(xhr) {
if (localStorage.token) {
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token);
}
},
success: function (data) {
console.log('Success', data);
var medInPharmacy = $(".medInPharmacy");
medInPharmacy.hide();
var prescriptMedication = $(".prescriptMedication");
prescriptMedication.hide();
var examination = $(".examination");
examination.show();
alert('Lek je prepisan');
},
error: function (data) {
console.log('Error', data);
}
});
});
$(document).on('click', '#btnCanclePrescription', function () {
console.log('opopo');
var examination = $(".examination");
examination.show();
var writeReport = $(".writeReport");
writeReport.hide();
var prescriptMedication = $(".prescriptMedication");
prescriptMedication.hide();
var scheduleNewAppointment = $(".scheduleNewAppointment");
scheduleNewAppointment.hide();
var medInPharmacy = $(".medInPharmacy");
medInPharmacy.hide();
var medNotInPharmacy = $(".medNotInPharmacy");
medNotInPharmacy.hide();
var alternativeMedication = $(".alternativeMedication");
alternativeMedication.hide();
var howToScheduleAppointment = $(".howToScheduleAppointment")
howToScheduleAppointment.hide();
var existingAppointments = $(".existingAppointments")
existingAppointments.hide();
var createAppointment = $(".createAppointment")
createAppointment.hide();
});
$(document).on('click', '#btnCancle', function () {
console.log('opopo');
var examination = $(".examination");
examination.show();
var writeReport = $(".writeReport");
writeReport.hide();
var prescriptMedication = $(".prescriptMedication");
prescriptMedication.hide();
var scheduleNewAppointment = $(".scheduleNewAppointment");
scheduleNewAppointment.hide();
var medInPharmacy = $(".medInPharmacy");
medInPharmacy.hide();
var medNotInPharmacy = $(".medNotInPharmacy");
medNotInPharmacy.hide();
var alternativeMedication = $(".alternativeMedication");
alternativeMedication.hide();
var howToScheduleAppointment = $(".howToScheduleAppointment")
howToScheduleAppointment.hide();
var existingAppointments = $(".existingAppointments")
existingAppointments.hide();
var createAppointment = $(".createAppointment")
createAppointment.hide();
});
$(document).on('click', '#btnAlternative', function () {
var examination = $(".examination");
examination.hide();
var writeReport = $(".writeReport");
writeReport.hide();
var prescriptMedication = $(".prescriptMedication");
prescriptMedication.hide();
var scheduleNewAppointment = $(".scheduleNewAppointment");
scheduleNewAppointment.hide();
var medInPharmacy = $(".medInPharmacy");
medInPharmacy.hide();
var medNotInPharmacy = $(".medNotInPharmacy");
medNotInPharmacy.hide();
var alternativeMedication = $(".alternativeMedication");
alternativeMedication.show();
var howToScheduleAppointment = $(".howToScheduleAppointment")
howToScheduleAppointment.hide();
var existingAppointments = $(".existingAppointments")
existingAppointments.hide();
var createAppointment = $(".createAppointment")
createAppointment.hide();
$("#idAlternativeDropDown").empty();
var myJSON = JSON.stringify({"id":examinationId, "name":imeIzabranogLeka});
$.ajax({
type: "POST",
url: "http://localhost:8081/examinations/getAlternativeMedications",
dataType: "json",
contentType: "application/json",
data: myJSON,
beforeSend: function(xhr) {
if (localStorage.token) {
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token);
}
},
success: function (data) {
$("#idAlternativeDropDown").append("<option> </option>");
console.log('Success', data);
for (i = 0; i < data.length; i++) {
/*var row = "<tr>";
row += "<td>" + data[i]['name'] + "</td>";
var btn = "<button class='btnButton' id = " + data[i]['name'] + ">Proveri</button>";
row += "<td>" + btn + "</td>";
$('#tableMeds').append(row);*/
var name = data[i]['name'];
$("#idAlternativeDropDown").append("<option value='"+name+"'>"+name+"</option>");
}
},
error: function (data) {
console.log('Error', data);
}
});
});
$(document).on('click', '#btnCancleAlternative', function () {
console.log('opopo');
var examination = $(".examination");
examination.show();
var writeReport = $(".writeReport");
writeReport.hide();
var prescriptMedication = $(".prescriptMedication");
prescriptMedication.hide();
var scheduleNewAppointment = $(".scheduleNewAppointment");
scheduleNewAppointment.hide();
var medInPharmacy = $(".medInPharmacy");
medInPharmacy.hide();
var medNotInPharmacy = $(".medNotInPharmacy");
medNotInPharmacy.hide();
var alternativeMedication = $(".alternativeMedication");
alternativeMedication.hide();
var howToScheduleAppointment = $(".howToScheduleAppointment")
howToScheduleAppointment.hide();
var existingAppointments = $(".existingAppointments")
existingAppointments.hide();
var createAppointment = $(".createAppointment")
createAppointment.hide();
});
$(document).on('change', '#idAlternativeDropDown', function () {
//console.log('Something');
var name = $("#idAlternativeDropDown :selected").val();
var duration = $("#chTherapyDurationAlternative").val();
var myJSON = JSON.stringify({"id":examinationId, "name":name,"duration":duration});
$.ajax({
type: "POST",
url: "http://localhost:8081/examinations/savePrescription",
dataType: "json",
contentType: "application/json",
data: myJSON,
beforeSend: function(xhr) {
if (localStorage.token) {
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token);
}
},
success: function (data) {
console.log('Success', data);
var alternativeMedication = $(".alternativeMedication");
alternativeMedication.hide();
var examination = $(".examination");
examination.show();
alert('Lek je prepisan');
},
error: function (data) {
console.log('Error', data);
}
});
});
$(document).on('click', '#btnNewAppointment', function () {
var examination = $(".examination");
examination.hide();
var writeReport = $(".writeReport");
writeReport.hide();
var prescriptMedication = $(".prescriptMedication");
prescriptMedication.hide();
var scheduleNewAppointment = $(".scheduleNewAppointment");
scheduleNewAppointment.hide();
var medInPharmacy = $(".medInPharmacy");
medInPharmacy.hide();
var medNotInPharmacy = $(".medNotInPharmacy");
medNotInPharmacy.hide();
var alternativeMedication = $(".alternativeMedication");
alternativeMedication.hide();
var howToScheduleAppointment = $(".howToScheduleAppointment")
howToScheduleAppointment.show();
var existingAppointments = $(".existingAppointments")
existingAppointments.hide();
var createAppointment = $(".createAppointment")
createAppointment.hide();
});
$(document).on('click', '#btnSelectExistingAppointment', function () {
var examination = $(".examination");
examination.hide();
var writeReport = $(".writeReport");
writeReport.hide();
var prescriptMedication = $(".prescriptMedication");
prescriptMedication.hide();
var scheduleNewAppointment = $(".scheduleNewAppointment");
scheduleNewAppointment.hide();
var medInPharmacy = $(".medInPharmacy");
medInPharmacy.hide();
var medNotInPharmacy = $(".medNotInPharmacy");
medNotInPharmacy.hide();
var alternativeMedication = $(".alternativeMedication");
alternativeMedication.hide();
var howToScheduleAppointment = $(".howToScheduleAppointment")
howToScheduleAppointment.hide();
var existingAppointments = $(".existingAppointments")
existingAppointments.show();
var createAppointment = $(".createAppointment")
createAppointment.hide();
var myJSON = JSON.stringify({"id":examinationId});
$('#tableExistingAppointments').empty();
$.ajax({
type: "POST",
url: "http://localhost:8081/appointments/existingAppointmentsDermatologist",
dataType: "json",
contentType: "application/json",
data: myJSON,
beforeSend: function(xhr) {
if (localStorage.token) {
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token);
}
},
success: function (data) {
console.log("SUCCESS : ", data);
for (i = 0; i < data.length; i++) {
var row = "<tr>";
row += "<td>" + data[i]['beginofappointment'] + "</td>";
row += "<td>" + data[i]['endofappointment'] + "</td>";
row += "<td>" + data[i]['price'] + "</td>";
var btn = "<button class='btnRegisterAppointment' id = " + data[i]['id'] + ">Rezervisi termin</button>";
row += "<td>" + btn + "</td>";
$('#tableExistingAppointments').append(row);
}
},
error: function (data) {
console.log("ERROR : ", data);
}
});
});
$(document).on('click', '#btnCancleScheduling', function () {
var examination = $(".examination");
examination.show();
var writeReport = $(".writeReport");
writeReport.hide();
var prescriptMedication = $(".prescriptMedication");
prescriptMedication.hide();
var scheduleNewAppointment = $(".scheduleNewAppointment");
scheduleNewAppointment.hide();
var medInPharmacy = $(".medInPharmacy");
medInPharmacy.hide();
var medNotInPharmacy = $(".medNotInPharmacy");
medNotInPharmacy.hide();
var alternativeMedication = $(".alternativeMedication");
alternativeMedication.hide();
var howToScheduleAppointment = $(".howToScheduleAppointment")
howToScheduleAppointment.hide();
var existingAppointments = $(".existingAppointments")
existingAppointments.hide();
var createAppointment = $(".createAppointment")
createAppointment.hide();
});
$(document).on('click', '#btnCancleSchedulingFreeAppointments', function () {
var examination = $(".examination");
examination.show();
var writeReport = $(".writeReport");
writeReport.hide();
var prescriptMedication = $(".prescriptMedication");
prescriptMedication.hide();
var scheduleNewAppointment = $(".scheduleNewAppointment");
scheduleNewAppointment.hide();
var medInPharmacy = $(".medInPharmacy");
medInPharmacy.hide();
var medNotInPharmacy = $(".medNotInPharmacy");
medNotInPharmacy.hide();
var alternativeMedication = $(".alternativeMedication");
alternativeMedication.hide();
var howToScheduleAppointment = $(".howToScheduleAppointment")
howToScheduleAppointment.hide();
var existingAppointments = $(".existingAppointments")
existingAppointments.hide();
var createAppointment = $(".createAppointment")
createAppointment.hide();
});
$(document).on('click', '.btnRegisterAppointment', function(){
var appointmentId = this.id;
var myJSON = JSON.stringify({"id":examinationId, "appointmentId":appointmentId});
var examination = $(".examination");
examination.show();
var writeReport = $(".writeReport");
writeReport.hide();
var prescriptMedication = $(".prescriptMedication");
prescriptMedication.hide();
var scheduleNewAppointment = $(".scheduleNewAppointment");
scheduleNewAppointment.hide();
var medInPharmacy = $(".medInPharmacy");
medInPharmacy.hide();
var medNotInPharmacy = $(".medNotInPharmacy");
medNotInPharmacy.hide();
var alternativeMedication = $(".alternativeMedication");
alternativeMedication.hide();
var howToScheduleAppointment = $(".howToScheduleAppointment")
howToScheduleAppointment.hide();
var existingAppointments = $(".existingAppointments")
existingAppointments.hide();
var createAppointment = $(".createAppointment")
createAppointment.hide();
$.ajax({
type: "POST",
url: "http://localhost:8081/appointments/saveAppointmentDermatologist",
dataType: "json",
contentType: "application/json",
data:myJSON,
beforeSend: function (xhr) {
if (localStorage.token) {
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token);
}
},
success: function (data) {
console.log('Success:',data);
alert("Termin je zakazan");
},
error: function (error) {
alert(error);
}
});
});
$(document).on('click', '#btnCreateAppointment', function () {
var examination = $(".examination");
examination.hide();
var writeReport = $(".writeReport");
writeReport.hide();
var prescriptMedication = $(".prescriptMedication");
prescriptMedication.hide();
var scheduleNewAppointment = $(".scheduleNewAppointment");
scheduleNewAppointment.hide();
var medInPharmacy = $(".medInPharmacy");
medInPharmacy.hide();
var medNotInPharmacy = $(".medNotInPharmacy");
medNotInPharmacy.hide();
var alternativeMedication = $(".alternativeMedication");
alternativeMedication.hide();
var howToScheduleAppointment = $(".howToScheduleAppointment")
howToScheduleAppointment.hide();
var existingAppointments = $(".existingAppointments")
existingAppointments.hide();
var createAppointment = $(".createAppointment")
createAppointment.show();
});
$(document).on('click', '#btnCancleCreatingAppointments', function () {
var examination = $(".examination");
examination.show();
var writeReport = $(".writeReport");
writeReport.hide();
var prescriptMedication = $(".prescriptMedication");
prescriptMedication.hide();
var scheduleNewAppointment = $(".scheduleNewAppointment");
scheduleNewAppointment.hide();
var medInPharmacy = $(".medInPharmacy");
medInPharmacy.hide();
var medNotInPharmacy = $(".medNotInPharmacy");
medNotInPharmacy.hide();
var alternativeMedication = $(".alternativeMedication");
alternativeMedication.hide();
var howToScheduleAppointment = $(".howToScheduleAppointment")
howToScheduleAppointment.hide();
var existingAppointments = $(".existingAppointments")
existingAppointments.hide();
var createAppointment = $(".createAppointment")
createAppointment.hide();
});
$(document).on('click', '#btnCreateAppointmentNow', function () {
var examination = $(".examination");
examination.show();
var writeReport = $(".writeReport");
writeReport.hide();
var prescriptMedication = $(".prescriptMedication");
prescriptMedication.hide();
var scheduleNewAppointment = $(".scheduleNewAppointment");
scheduleNewAppointment.hide();
var medInPharmacy = $(".medInPharmacy");
medInPharmacy.hide();
var medNotInPharmacy = $(".medNotInPharmacy");
medNotInPharmacy.hide();
var alternativeMedication = $(".alternativeMedication");
alternativeMedication.hide();
var howToScheduleAppointment = $(".howToScheduleAppointment")
howToScheduleAppointment.hide();
var existingAppointments = $(".existingAppointments")
existingAppointments.hide();
var createAppointment = $(".createAppointment")
createAppointment.hide();
var startOfAppointment = $("#chStartOfAppointment").val();
var endOfAppointment = $("#chEndOfAppointment").val();
//var price = $("#chPrice").val();
var price = 3000;
var myJSON = JSON.stringify({"id":examinationId, "startOfAppointment":startOfAppointment , "endOfAppointment":endOfAppointment, "price":price});
$.ajax({
type: "POST",
url: "http://localhost:8081/appointments/createAppointmentDermatologist",
dataType: "json",
contentType: "application/json",
data:myJSON,
beforeSend: function (xhr) {
if (localStorage.token) {
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token);
}
},
success: function (data) {
if(data['value']==true) {
console.log('Success:', data);
alert("Termin je zakazan");
}
else {
console.log('Success:', data);
alert("Termin nije zakazan, zauzet je.");
}
},
error: function (error) {
alert(error);
}
});
});
$(document).on('click', '#btnExaminationDone', function () {
alert('Pregled je odradjen');
window.location.href="welcomeDermatologist.html";
});
/*$(document).on('change', '#idDropDown', function () {
//console.log('Something');
var name = $("#idDropDown :selected").val();
var myJSON = JSON.stringify({"id":examinationId, "name":name});
console.log(name, examinationId);
var examination = $(".examination");
examination.hide();
var writeReport = $(".writeReport");
writeReport.hide();
var prescriptMedication = $(".prescriptMedication");
prescriptMedication.hide();
var scheduleNewAppointment = $(".scheduleNewAppointment");
scheduleNewAppointment.hide();
var medInPharmacy = $(".medInPharmacy");
medInPharmacy.hide();
var medNotInPharmacy = $(".medNotInPharmacy");
medNotInPharmacy.hide();
$.ajax({
type: "POST",
url: "http://localhost:8081/examinations/checkIfMedicationIsAvailable",
dataType: "json",
contentType: "application/json",
data: myJSON,
beforeSend: function(xhr) {
if (localStorage.token) {
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token);
}
},
success: function (data) {
console.log('Success', data);
var d = data['value'];
console.log('d',d);
if(d === true){
medInPharmacy.show();
var row = "<tr>";
row += "<td>Lek je dostupan u apoteci.</td>";
var btn = "<button class='btnSubmitPrescription' id = " + name + ">Potvrdi</button>";
row += "<td>" + btn + "</td>";
$('#tableMedInPharmacy').append(row);
}
else {
medNotInPharmacy.show();
var row = "<tr>";
row += "<td>Lek je nedostupan. Administrator apoteke je obavesten.</td>";
var btn1 = "<button class='btnCancle'>Odustani od preporucivanja leka</button>";
var btn2 = "<button class='btnAlternativa'>Pogledaj alternative</button>";
row += "<td>" + btn1 + "</td>";
row += "<td>" + btn2 + "</td>";
$('#tableMedNotInPharmacy').append(row);
}
},
error: function (data) {
console.log('Error', data);
}
});
});*/
|
import React from 'react';
import { CoreProvider } from '../../core/AppEngine';
import { Panel, PanelHeader, Group, Cell, Header, List, PanelHeaderBack, CellButton } from '@vkontakte/vkui';
export default function Theory(props) {
const app = React.useContext(CoreProvider);
return (
<Panel id={ props.id }>
<PanelHeader left={ <PanelHeaderBack onClick={ () => app.Event.dispatchEvent("closepanel") } /> }>Теория</PanelHeader>
<Group header={ <Header mode="secondary">Дисциплина</Header> }>
<Cell expandable onClick={ () => app.Event.dispatchEvent("openpanel", ["v-theory", { subject: 'prog'} ]) }>Основы Английского языка</Cell>
<Cell expandable onClick={ () => app.Event.dispatchEvent("openpanel", ["v-theory", { subject: 'geom'} ]) }>Начертательная геометрия</Cell>
<Cell expandable onClick={ () => app.Event.dispatchEvent("openpanel", ["v-theory", { type: 'math'} ]) }>Математический анализ</Cell>
</Group>
</Panel>
);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.