text
stringlengths 7
3.69M
|
|---|
var AWS = require('aws-sdk');
var uuid = require('uuid');
AWS.config.update({ region: 'us-east-1' });
module.exports.handler = (event, context, callback) => {
var dynamodb = new AWS.DynamoDB();
//Get data from post
var teamID = JSON.parse(event.body).teamid;
var userPoolID = JSON.parse(event.body).upoolid;
var name = JSON.parse(event.body).name;
var memberID = uuid.v1();
//Create base response headers
var response = {
"headers": {
"Access-Control-Allow-Origin": '*'
},
"isBase64Encoded": false
};
var params = {
TableName: 'TeamMembersList',
Item: {
'TeamID' : { S: teamID },
'ID' : { S: memberID },
'Name' : { S: name},
'UserPoolID': { S: userPoolID }
}
};
dynamodb.putItem(params, function(err, data) {
if (err) {
response.statusCode = 500;
response.body = JSON.stringify(err);
callback(null, response);
}else {
response.statusCode = 200;
response.body = JSON.stringify({"memberid":memberID});
callback(null, response);
}
})
}
|
const { Router } = require('express');
const express = require('express');
const router = express.Router();
const { AccessRights } = require('../models/AccessRights');
// const { isUser } = require('../middlewares/authMiddlewares')
router.post('/', async (req, res, next) => {
try {
const access = AccessRights({
right: 1,
rightno: 3,
});
await access.save();
return res.status(201).send('access added');
}
catch (e) {
return e;
}
})
module.exports = router;
|
const test = require('tape');
const unionBy = require('./unionBy.js');
test('Testing unionBy', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof unionBy === 'function', 'unionBy is a Function');
t.deepEqual(unionBy([2.1], [1.2, 2.3], Math.floor), [2.1, 1.2], 'Produces the appropriate results');
//t.deepEqual(unionBy(args..), 'Expected');
//t.equal(unionBy(args..), 'Expected');
//t.false(unionBy(args..), 'Expected');
//t.throws(unionBy(args..), 'Expected');
t.end();
});
|
var eid = [];//Array to store employee ID
$(document).ready(function () {
$("#dob").datepicker({ dateFormat: 'dd-mm-yy', maxDate: '0' });
$("#dialog-1").dialog({ autoOpen: false });
$("#save").click(function () {
var valid = true,
message = ''; //To store the validation alert message
$('form input').each(function () //Validating text fields
{
var $this = $(this);
if (!$this.val()) {
valid = false;
message += 'Please enter your ' + $this.attr('name') + '\n';
}
});
if (!valid) {
alert(message);
}
else {
$('#empId').each(function () //Employee id validation
{
if ($.inArray(this.value, eid) >= 0) {
alert("Existing Employee ID. Please enter a unique one.");
return false;
}
else {
eid.push(this.value); //push empID into eid[]
$("#dialog-1").dialog("open");
var id = $("#empId").val();
var name = $("#name").val();
var dateOfBirth = $("#dob").val();
var department = $("#departments").val();
var gender = $("input[name='gender']:checked").val();
var display = "<tr> <td>" + id + "</td> <td>" + name + "</td> <td>" + dateOfBirth + "</td> <td>"
+ department + "</td> <td>" + gender + "</td> </tr>";
$("table").append(display);
$("#form1").trigger('reset');
}
});
}
});
});
|
'use strict';
let koa = require('koa');
let body = require('koa-body');
let logger = require('koa-logger');
let router = require('./router');
let middleware = require('./middleware');
let C = require('./config');
let H = require('./library/helper');
let app = koa();
// 连接数据库
let mongoose = H.connectMongoose('test-backend');
let redis = H.connectRedis();
// 加载数据模型
require('./schema');
app.use(logger());
app.use(function* (next) {
this.mongoose = mongoose;
this.redis = redis;
yield next;
});
app.use(body({formidable:{uploadDir: __dirname}}));
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(C.port, function() {
console.log('App is listenning on port %s.', C.port);
});
|
const Room = require('../BarrageAssistant/room');
const roomID = "67373";
const room = new Room(roomID);
room.on('connect', () => {
console.log('Welcome to douyu room: ' + roomID);
});
room.on('error', (err) => {
console.log('This have some error' + err.toString());
});
room.on('close', (had_error) => {
console.log('There is a ' + had_error);
});
room.on('chatmsg', function(message){
console.log(`[${message.nn}]:${message.txt}`);
// console.log(message);
});
room.open();
|
import { map } from "../map/map"
/**
* @param {string[]} keys The properties to be filtered out
* @param {object} source The source object
*
* @returns {object}
*/
const _pluckOne = (keys, source) => {
const result = {}
for (let i = 0, length = keys.length; i < length; i++) {
const key = keys[i]
const value = source[key]
if (Object.hasOwnProperty.call(source, key)) {
result[key] = value
}
}
return result
}
/**
* @param {string[]} keys
* @param {object|object[]} source
*
* @returns {object|object[]}
*/
const _pluck = (keys, source) =>
Array.isArray(source)
? map(item => _pluckOne(keys, item), source)
: _pluckOne(keys, source)
/**
* Returns a partial copy of an object containing only the keys specified.
* If the key does not exist, the property is ignored.
*
* @param {...any} params
*
* @returns {object|object[]}
*
* @tag Object
* @signature (keys: string[]) => (source: Object): Object
*
* @example
* pluck(
* ["id", "name"],
* {
* id: 2,
* name: "lorem",
* description: "lorem ipsum"
* }
* )
* // => {id: 2, name: lorem}
*/
export const pluck = (...params) => {
// @signature (keys) => (source)
if (params.length <= 1) {
return source => _pluck(params[0], source)
}
// @signature (keys, source)
return _pluck(...params)
}
|
class Product {
dataManager;
colorChosen;
teddy;
constructor() {
this.dataManager = new DataManager();
this.showProduct();
}
/**
* retrieve product id in url, display article and watch for color choice and add to cart btn
*/
async showProduct() {
//find article id in URL
const productId = window.location.search.slice(1);
//retrieve product info from id
this.teddy = await this.dataManager.getProductInfo(productId);
//enregistre la valeur sélectionnée par défaut au lancement de la page
this.colorChosen = this.teddy.colors[0];
document.getElementsByTagName('h1')[0].textContent=`Bonjour, je suis ${this.teddy.name.split(' ')[0]}. Tu veux être mon ami?`;
document.querySelector('.card-img-top').setAttribute(`src`, `${this.teddy.imageUrl}`)
document.getElementsByTagName('h2')[0].textContent = `${this.teddy.name}`;
document.querySelectorAll('p')[0].textContent =`${this.teddy.description}`;
document.querySelectorAll('p')[1].textContent =`Prix : ${this.teddy.price/100} Doudoullars`;
this.dataManager.cartCounter();
//display all avaible colors in select element
for (let color of this.teddy.colors) {
document.getElementById('custon-config').insertAdjacentHTML(
'beforeend',
`<option value="${color}">${color}</option>`);
};
this.colorChoice();
this.addToCart(productId);
};
/**
* watch for selected custom color
*/
colorChoice() {
var colorSelector = document.getElementById('custon-config');
colorSelector.addEventListener('change', (e) => {
this.colorChosen = e.target.value;
});
};
/**
* initialisation du bouton et ajout d'un article dans le panier - alerte et stockage local
*/
addToCart(productId) {
let addCartBtn = document.getElementById('addcart');
addCartBtn.addEventListener('click', () => {
// regroupe les info utiles de l'article sélectionné pour mise en panier
let articleToAdd = [`${this.teddy.name}`, this.colorChosen, `${this.teddy.price}`, productId];
let i = localStorage.length + 1;
// cas d'un article supprimé en milieu de numérotation
while (localStorage[`article${i}`] !== undefined) {
i++;
};
//enregistrement local pour mise en panier
localStorage.setItem(`article${i}`, `${articleToAdd}`);
alert('Nounours ajouté au panier');
//mise à jour du compteur d'article dans le panier dans la nav bar
this.dataManager.cartCounter();
});
};
}
new Product();
|
import React from 'react';
import Cookies from 'js-cookie';
import Header from '../Components/Navbar';
import { FormGroup, FormControl, FormLabel, Button, FormText } from 'react-bootstrap';
import { connect } from 'react-redux';
import { isEmail, isEmpty, isLength, isContainWhiteSpace } from '../Components/validation';
import * as actions from '../store/Actions/Actions';
import '../App.css';
class LoginForm extends React.Component {
constructor(props) {
super(props)
this.state = {
formData: {},
errors: {},
formSubmitted: false,
loading: false
}
}
handleInputChange = (event) => {
const target = event.target;
const value = target.value;
const name = target.name;
let { formData } = this.state;
formData[name] = value;
this.setState({
formData: formData
});
}
validateLoginForm = (e) => {
let errors = {};
const { formData } = this.state;
if (isEmpty(formData.email)) {
errors.email = "Email can't be blank";
} else if (!isEmail(formData.email)) {
errors.email = "Please enter a valid email";
}
if (isEmpty(formData.password)) {
errors.password = "Password can't be blank";
} else if (isContainWhiteSpace(formData.password)) {
errors.password = "Password should not contain white spaces";
} else if (!isLength(formData.password, { gte: 6, lte: 16, trim: true })) {
errors.password = "Password's length must between 6 to 16";
}
if (isEmpty(errors)) {
return true;
} else {
return errors;
}
}
login = (e) => {
e.preventDefault();
const { formData } = this.state;
let errors = this.validateLoginForm();
if(errors === true){
this.props.onAuth(formData.email, formData.password);
} else {
this.setState({
errors: errors,
formSubmitted: true
});
}
}
componentDidMount() {
this.props.onTryAutoSignup();
}
componentDidUpdate() {
if(this.props.user){
if(this.props.user.occupation === 'CO'){
if(this.props.user.is_extra_filled === true){
this.props.history.push('/')
}else {
this.props.history.push('/signup/extra')
}
}else if(this.props.user.occupation === 'CL'){
if(this.props.user.is_extra_filled === true){
this.props.history.push('/')
} else {
this.props.clientsignup();
this.props.history.push('/')
}
}
}
}
render() {
let errormessage = null;
if(this.props.error) {
errormessage = (
<p>Invalid Email and Password</p>
);
}
return (
<div>
<Header {...this.props} />
<div className="auth-wrapper">
<div className="auth-inner-login">
<form onSubmit={this.login}>
<h3>Login</h3>
<FormGroup controlId="email" validationstate={ this.state.formSubmitted ? (this.state.errors.email ? 'error' : 'success') : null }>
<FormLabel style={{fontSize:'18px'}}>Email</FormLabel>
<FormControl type="email" name="email" placeholder="Enter your Email" onChange={this.handleInputChange} />
{ this.state.errors.email &&
<FormText className="Error-message">{this.state.errors.email}</FormText>
}
</FormGroup>
<FormGroup controlId="password" validationstate={ this.state.formSubmitted ? (this.state.errors.password ? 'error' : 'success') : null }>
<FormLabel style={{fontSize:'18px'}}>Password</FormLabel>
<FormControl type="password" name="password" placeholder="Enter your password" onChange={this.handleInputChange} />
{ this.state.errors.password &&
<FormText className="Error-message">{this.state.errors.password}</FormText>
}
</FormGroup>
{errormessage}
{
this.props.loading ?
<div className="text-center">
<div className="spinner-border" role="status">
<span className="sr-only">Loading ...</span>
</div>
</div>
:
<Button type="submit" className="btn btn-primary btn-block mb-3 mt-4">Login</Button>
}
<p className="forgot-password text-right" style={{fontSize:'15px', fontWeight:'500'}}>
New? <a href="/signup">SignUp</a>
</p>
</form>
</div>
</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
loading: state.loading,
error: state.error,
user: state.user,
allDetail: state.usersAllDetail,
isAuthenticated: Cookies.get('token') !== undefined,
}
}
const mapDispatchToProps = dispatch => {
return {
onAuth: (email, password) => dispatch(actions.authLogin(email, password)),
clientsignup: () => dispatch(actions.extraClientSignup()),
onTryAutoSignup: () => {
dispatch(actions.authcheckstate());
}
};
}
export default connect(mapStateToProps,mapDispatchToProps)(LoginForm);
|
import React, { Component } from "react";
import { Link, Redirect } from "react-router-dom";
import authLib from "../../../config/authlib";
class TableWithLinks extends Component {
constructor() {
super();
this.state = {
package: {},
items: [],
isLoading: false,
error: null
};
}
componentDidMount() {
this.setState({ isLoading: true });
const options = authLib.getFetchOptions();
fetch("http://localhost:8000/orderHistory", options)
.then(function(response) {
if (response.ok) {
return response.json();
} else {
throw new Error("Something went wrong ...");
}
})
.then(data => {
console.log(data);
data.forEach(elemnt => {
this.state.items.push(elemnt);
});
this.setState({ isLoading: false });
console.log(this.state.items);
console.log(this.state.items.length);
})
.catch(function(error) {
console.log(error);
});
}
deleteItem = itemId => {
this.setState({
items: this.state.items.filter(item => item.id !== itemId)
});
};
render() {
// let { items, isShowingAlert } = this.state;
return (
<div className="card">
<div className="header">
<h4 className="title">Company Assigned Packages</h4>
{/* <p className="category">Here is a subtitle for this table</p> */}
</div>
<div className="content table-responsive table-full-width">
<table className="table table-hover table-striped">
<thead>
<tr>
<th>ID</th>
<th>Postman ID</th>
<th>Pickup Adress</th>
<th>Pickup Date</th>
<th>Destination</th>
<th>Status</th>
<th className="text-middle">Action</th>
<th className="text-middle">Update Status</th>
</tr>
</thead>
<tbody>
{this.state.items.map(item => (
<tr key={item.OrderID}>
<td>{item.OrderID}</td>
<td>{item.PostmanId}</td>
<td>{item.PickAddressID}</td>
<td>{item.PickDate}</td>
<td>{item.DropAddressID}</td>
<td>{item.Status}</td>
<td className="text-middle">
<Link to={`/assign/${item.OrderID}`}>
<div className="btn btn-wd btn-info">Handover</div>
</Link>
</td>
<td className="text-middle">
<Link to={`/postman/delivery/${item.OrderID}`}>
<div className="btn btn-wd btn-info">Deliver</div>
</Link>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
}
export default TableWithLinks;
|
/**
* Created by hridya on 4/16/16.
*/
module.exports = function (app, model) {
app.get("/api/project/user/:userId/pet", findAllPetsForUser);
app.get("/api/project/pet/:petId", findPetById);
app.post("/api/project/user/:userId/pet", createPet);
app.put("/api/project/pet/:petId", updatePet);
app.delete("/api/project/pet/:petId", deletePet);
function findAllPetsForUser (req, res) {
var userId = req.params.userId;
model.findAllPetsForUser(userId)
.then(function (allPets) {
res.json(allPets);
});
}
function findPetById (req, res) {
var id = req.params.petId;
model.findPetById(id)
.then(function (pet) {
res.json(pet);
});
}
function createPet (req, res) {
var userId = req.params.userId;
var petObj = req.body;
model.createPetForUser(userId, petObj)
.then(function (pets) {
res.json(pets);
});
}
function updatePet (req, res) {
var id = req.params.petId;
var updatedPet = req.body;
model.updatePet(id, updatedPet)
.then(function (allPets) {
res.json(allPets);
});
}
function deletePet (req, res) {
var petId = req.params.petId;
model.deletePet(petId)
.then(function (response) {
res.json(response);
});
}
};
|
const { validationResult } = require('express-validator'),
fieldErrors = require('../../functions/error'),
errorCodes = require("../../functions/statusCodes"),
constant = require("../../functions/constant"),
globalModel = require("../../models/globalModel"),
commonFunction = require("../../functions/commonFunctions"),
ffmpeg = require("fluent-ffmpeg"),
s3Upload = require('../../functions/upload').uploadtoS3,
dateTime = require('node-datetime'),
path = require('path'),
uniqid = require('uniqid'),
movieModel = require("../../models/movies"),
notificationModel = require("../../models/notifications"),
socketio = require("../../socket"),
notifications = require("../../models/notifications"),
categoryModel = require("../../models/categories"),
castnCrewModel = require("../../models/castncrew"),
countryModel = require("../../models/country")
const privacyModel = require("../../models/privacy")
exports.createComonGeneres = (tag,req) => {
return new Promise(async function(resolve) {
await globalModel.custom(req, "SELECT * FROM genres WHERE slug = ?", [tag.key]).then(async result => {
let genere = null
if (result) {
genere = JSON.parse(JSON.stringify(result))[0];
}
if(!genere){
let insertObject = {}
insertObject["title"] = tag.value
insertObject['slug'] = tag.key
if(req.item.type == "movies"){
insertObject['movie_count'] = 1
}else{
insertObject['series_count'] = 1
}
await globalModel.create(req, insertObject, "genres").then(async result => {
insertObject['genre_id'] = result.insertId
resolve(insertObject)
})
}else{
resolve(genere)
}
}).catch(err => {
console.log(err)
resolve(false)
})
});
}
async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
}
exports.insertGeners = (movie_id,tags,req) => {
return new Promise(async function(resolve) {
await asyncForEach(tags, async (tag,i) => {
await exports.createComonGeneres(tag,req).then(async result => {
if(result){
let insertObject = {}
insertObject['genre_id'] = result['genre_id']
insertObject['movie_id'] = movie_id
await globalModel.create(req, insertObject, "movie_genres").then(async result => {
req.generes.push(result.insertId)
})
}
})
if(i == tags.length - 1){
resolve(true)
}
})
})
}
exports.createGeneres = async(req,res) => {
let movie_id = req.body.movie_id
let tags = JSON.parse(req.body.tags);
req.generes = []
await exports.insertGeners(movie_id,tags,req).then(async result => {
if(result){
if(req.generes){
await movieModel.getGeneres(req,{movie_genre_ids:req.generes}).then(result => {
req.generes = null
return res.send({generes:result})
})
}
}
}).catch(() => {
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
})
}
exports.deleteReview = async(req,res) => {
let movie_id = req.body.movie_id
let review_id = req.body.review_id
if(parseInt(review_id) == 0 || parseInt(movie_id) == 0){
return res.send({ error: fieldErrors.errors([{ msg: constant.general.PARAMMISSING }], true), status: errorCodes.invalid }).end();
}
let movie = {}
await globalModel.custom(req, "SELECT * FROM movies WHERE movie_id = ?", [movie_id]).then(async result => {
if (result) {
movie = JSON.parse(JSON.stringify(result))[0];
}else{
}
}).catch(() => {
})
let review = {}
await globalModel.custom(req, "SELECT * FROM reviews WHERE review_id = ?", [review_id]).then(async result => {
if (result) {
review = JSON.parse(JSON.stringify(result))[0];
}else{
}
}).catch(() => {
})
await privacyModel.permission(req, 'movie', 'delete', movie).then(result => {
movie.canDelete = result
}).catch(err => {
})
if(!movie.canDelete && req.user.user_id != review.owner_id){
return res.send({ error: fieldErrors.errors([{ msg: constant.general.PARAMMISSING }], true), status: errorCodes.invalid }).end();
}
await globalModel.custom(req, "DELETE FROM reviews WHERE review_id = ?", [review_id]).then(async result => {
socketio.getIO().emit('reviewMovieDelete', {
"movieID": movie_id,
"id": review_id,
});
}).catch(() => {
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
})
}
exports.deleteGeneres = async(req,res) => {
let movie_id = req.body.movie_id
let genere_id = req.body.id
if(parseInt(genere_id) == 0 || parseInt(movie_id) == 0){
return res.send({ error: fieldErrors.errors([{ msg: constant.general.PARAMMISSING }], true), status: errorCodes.invalid }).end();
}
let isMovie = req.item.type == "movies" ? true : false;
let genere = {}
await globalModel.custom(req, "SELECT * FROM movie_genres WHERE movie_genre_id = ?", [genere_id]).then(async result => {
if (result) {
genere = JSON.parse(JSON.stringify(result))[0];
}else{
}
}).catch(() => {
})
await globalModel.custom(req, "DELETE FROM movie_genres WHERE movie_genre_id = ?", [genere_id]).then(async result => {
// let column = "series_count = series_count - 1"
// if(isMovie){
// column = "movie_count = movie_count - 1"
// }
await globalModel.custom(req, "UPDATE genres SET "+column+" WHERE genre_id = ?", [genere.genre_id]).then(async () => {})
if (result) {
return res.send({ message:constant.movie.DELETEDITEM , status: errorCodes.ok }).end();
}else{
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
}
}).catch(() => {
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
})
}
exports.deleteVideo = async(req,res) => {
let movie_id = req.body.movie_id
let video_id = req.body.id
if(parseInt(video_id) == 0 || parseInt(movie_id) == 0){
return res.send({ error: fieldErrors.errors([{ msg: constant.general.PARAMMISSING }], true), status: errorCodes.invalid }).end();
}
let video = {}
await globalModel.custom(req, "SELECT * FROM movie_videos WHERE movie_video_id = ?", [video_id]).then(async result => {
if (result) {
video = JSON.parse(JSON.stringify(result))[0];
}else{
}
}).catch(() => {
})
await globalModel.custom(req, "DELETE FROM movie_videos WHERE movie_video_id = ?", [video_id]).then(async result => {
if (result) {
commonFunction.deleteImage(req, res, "", "movie/video", video)
return res.send({ message:constant.video.DELETED , status: errorCodes.ok }).end();
}else{
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
}
}).catch(() => {
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
})
}
exports.insertCountries = (movie_id,countries,req) => {
return new Promise(async function(resolve) {
await asyncForEach(countries, async (country,i) => {
let insertObject = {}
insertObject['country_id'] = country.key
insertObject['movie_id'] = movie_id
await globalModel.create(req, insertObject, "movie_countries").then(async result => {
req.countries.push(result.insertId)
})
if(i == countries.length - 1){
resolve(true)
}
})
})
}
exports.createCountry = async(req,res) => {
let movie_id = req.body.movie_id
let countries = JSON.parse(req.body.countries);
req.countries = []
await exports.insertCountries(movie_id,countries,req).then(async result => {
if(result){
if(req.countries){
await countryModel.findAllMoviesCountries(req,{movie_country_ids:req.countries}).then(result => {
req.countries = null
return res.send({movie_countries:result})
})
}
}
}).catch(() => {
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
})
}
exports.deleteCountry = async(req,res) => {
let movie_id = req.body.movie_id
let country_id = req.body.id
if(parseInt(country_id) == 0 || parseInt(movie_id) == 0){
return res.send({ error: fieldErrors.errors([{ msg: constant.general.PARAMMISSING }], true), status: errorCodes.invalid }).end();
}
await globalModel.custom(req, "DELETE FROM movie_countries WHERE movie_country_id = ?", [country_id]).then(async result => {
if (result) {
return res.send({ message:constant.movie.DELETEDITEM , status: errorCodes.ok }).end();
}else{
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
}
}).catch(() => {
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
})
}
exports.moviesCastnCrew = async(req,res) => {
let limit = 17
let page = 1
if(parseInt(req.body.limit)){
limit = parseInt(req.body.limit)
}
if (req.body.page == '') {
page = 1;
} else {
//parse int Convert String to number
page = parseInt(req.body.page) ? parseInt(req.body.page) : 1;
}
let offset = (page - 1) * (limit - 1)
//get all movies as per categories
await castnCrewModel.getCrewMembers(req,{limit: limit, offset: offset}).then(result => {
if (result) {
let pagging = false
let items = result
if (result.length > limit - 1) {
items = result.splice(0, limit - 1);
pagging = true
}
res.send({ casts: items, pagging: pagging })
}
}).catch(() => {
res.send({ casts: [], pagging: false })
})
}
exports.castnCrew = async(req,res) => {
let movieId = req.body.movie_id
let movie = {}
if (movieId) {
//uploaded
await globalModel.custom(req, "SELECT * FROM movies WHERE movie_id = ?", movieId).then(async result => {
if (result && result.length) {
movie = JSON.parse(JSON.stringify(result))[0];
}else{
movieId = null
}
}).catch(() => {
})
} else {
return res.send({})
}
if(!movieId || !Object.keys(movie).length){
return res.send({})
}
//fetch artists
let LimitNumArtist = 17;
let pageArtist = 1
if (req.body.page == '') {
pageArtist = 1;
} else {
//parse int Convert String to number
pageArtist = parseInt(req.body.page) ? parseInt(req.body.page) : 1;
}
let offsetArtist = (pageArtist - 1) * LimitNumArtist
if (movie.artists && movie.artist != "" && req.appSettings['video_artists'] == "1") {
await castnCrewModel.findByIds(movie.artists, req, res, LimitNumArtist, offsetArtist).then(result => {
let pagging = false
if (result) {
pagging = false
if (result.length > LimitNumArtist - 1) {
result = result.splice(0, LimitNumArtist - 1);
pagging = true
}
res.send( {
'pagging': pagging,
artists: result
})
}
}).catch(error => {
console.log(error)
})
} else {
res.send({
'pagging': false,
artists: []
})
}
}
exports.delete = async (req, res) => {
if (!req.item) {
return res.send({ error: fieldErrors.errors([{ msg: constant.general.PERMISSION_ERROR }], true), status: errorCodes.invalid }).end();
}
await movieModel.delete(req.item.movie_id, req).then(result => {
if (result) {
commonFunction.deleteImage(req, res, "", "movie", req.item)
res.send({"message":constant.movie.DELETED})
socketio.getIO().emit('movieDeleted', {
"movie_id": req.item.movie_id,
"message": constant.movie.DELETED,
});
}else{
res.send({})
}
})
}
exports.playCount = async(req,res) => {
let id = req.body.movie_video_id
if(id){
await globalModel.custom(req,"UPDATE movie_videos SET plays = plays + 1 WHERE movie_video_id = ?",[id]).then(result => {
})
}
res.send({status:1})
}
exports.category = async (req, res) => {
req.query.categoryId = req.params.id
req.query.type = "movie"
req.contentType = req.body.type
let category = {}
let send = false
let limit = 21;
let page = 1
if (req.body.page == '') {
page = 1;
} else {
//parse int Convert String to number
page = parseInt(req.body.page) ? parseInt(req.body.page) : 1;
}
let offset = (page - 1) * (limit - 1)
await categoryModel.findByCustomUrl({ id: req.query.categoryId, type: req.query.type }, req, res).then(async result => {
if (result) {
category = result
const data = { limit: limit, offset: offset }
if (category.subcategory_id == 0 && category.subsubcategory_id == 0) {
data['category_id'] = category.category_id
} else if (category.subcategory_id > 0) {
data['subcategory_id'] = category.category_id
} else if (category.subsubcategory_id > 0) {
data['subsubcategory_id'] = category.category_id
}
//get all blogs as per categories
await movieModel.getMovies(req, data).then(result => {
if (result) {
let pagging = false
let items = result
if (result.length > limit - 1) {
items = result.splice(0, limit - 1);
pagging = true
}
send = true
res.send({ pagging: pagging, items: items })
}
})
}
}).catch(() => {
res.send({ pagging: false, items: [] })
return
})
if (!send)
res.send({ pagging: false, items: [] })
}
exports.trailers = async(req,res) => {
let limit = 25
let page = 1
let movie_id = parseInt(req.body.movie_id)
let episode_id = req.body.episode_id ? parseInt(req.body.episode_id) : false
if(parseInt(req.body.limit)){
limit = parseInt(req.body.limit)
}
if (req.body.page == '') {
page = 1;
} else {
//parse int Convert String to number
page = parseInt(req.body.page) ? parseInt(req.body.page) : 1;
}
let offset = (page - 1) * (limit - 1)
//get all movies as per categories
await movieModel.getVideos(req,{resource_id:movie_id,limit:limit,extraVideos:true,limit: limit, offset: offset,episode:episode_id}).then(result => {
if (result) {
let pagging = false
let items = result
if (result.length > limit - 1) {
items = result.splice(0, limit - 1);
pagging = true
}
res.send({ trailers: items, pagging: pagging })
}
}).catch(() => {
res.send({})
})
}
exports.episodes = async (req,res) => {
let limit = 26
let page = 1
if(parseInt(req.body.limit)){
limit = parseInt(req.body.limit)
}
if (req.body.page == '') {
page = 1;
} else {
//parse int Convert String to number
page = parseInt(req.body.page) ? parseInt(req.body.page) : 1;
}
let season = {}
await globalModel.custom(req,"SELECT season_id from seasons where season = ?",[parseInt(req.body.season)]).then(result => {
if (result) {
season = JSON.parse(JSON.stringify(result))[0];
}else{
}
})
let offset = (page - 1) * (limit - 1)
const data = { limit: limit, offset: offset }
data['season_id'] = season.season_id
//get all movies as per categories
await movieModel.getEpisods(req,data).then(async result => {
if (result) {
let pagging = false
let items = result
if (result.length > limit - 1) {
items = result.splice(0, limit - 1);
pagging = true
}
res.send({ episodes: items, pagging: pagging })
}
}).catch(() => {
res.send({})
})
}
exports.reviews = async(req,res) => {
const movie_id = parseInt(req.body.movie_id)
if (!movie_id) {
return res.send({})
}
let LimitNum = 11;
let page = 1
if (req.params.page == '') {
page = 1;
} else {
//parse int Convert String to number
page = parseInt(req.body.page) ? parseInt(req.body.page) : 1;
}
let offset = (page - 1) * (LimitNum - 1)
let reviews = {}
let data = {}
data.limit = LimitNum
data.offset = offset
data.movie_id = movie_id
data.orderBy = true
await movieModel.getReviews(req, data).then(result => {
let pagging = false
if (result) {
pagging = false
if (result.length > LimitNum - 1) {
result = result.splice(0, LimitNum - 1);
pagging = true
}
reviews = {
pagging: pagging,
reviews: result
}
}
})
res.send(reviews)
}
exports.browse = async (req, res) => {
const queryString = req.query
let limit = 21
let page = 1
if(parseInt(req.body.limit)){
limit = parseInt(req.body.limit)
}
if (req.body.page == '') {
page = 1;
} else {
//parse int Convert String to number
page = parseInt(req.body.page) ? parseInt(req.body.page) : 1;
}
let offset = (page - 1) * (limit - 1)
const data = { limit: limit, offset: offset }
data['type'] = queryString.type
if (queryString.q && !queryString.tag && !queryString.genre) {
data['title'] = queryString.q
}
if (queryString.country) {
req.query.search.country = queryString.country
data['country'] = queryString.country
}
if (queryString.language) {
req.query.search.language = queryString.language
data['language'] = queryString.language
}
if(req.body.type == "movies"){
req.contentType = "movies"
}else{
req.contentType = "series"
}
data['pageType'] = req.body.pageType
if (queryString.tag) {
data['tags'] = queryString.tag
}
if (queryString.genre) {
data['genre'] = queryString.genre
}
if (queryString.category_id) {
data['category_id'] = queryString.category_id
}
if (queryString.subcategory_id) {
data['subcategory_id'] = queryString.subcategory_id
}
if (queryString.subsubcategory_id) {
data['subsubcategory_id'] = queryString.subsubcategory_id
}
if (queryString.sort == "latest") {
data['orderby'] = "movies.movie_id desc"
} else if (queryString.sort == "favourite" && req.appSettings['video_favourite'] == 1) {
data['orderby'] = "movies.favourite_count desc"
} else if (queryString.sort == "view") {
data['orderby'] = "movies.view_count desc"
} else if (queryString.sort == "like" && req.appSettings['video_like'] == "1") {
data['orderby'] = "movies.like_count desc"
} else if (queryString.sort == "dislike" && req.appSettings['video_dislike'] == "1") {
data['orderby'] = "movies.dislike_count desc"
} else if (queryString.sort == "rated" && req.appSettings['video_rating'] == "1") {
data['orderby'] = "movies.rating desc"
} else if (queryString.sort == "commented" && req.appSettings['video_comment'] == "1") {
data['orderby'] = "movies.comment_count desc"
}
if (queryString.type == "featured" && req.appSettings['video_featured'] == 1) {
data['is_featured'] = 1
} else if (queryString.type == "sponsored" && req.appSettings['video_sponsored'] == 1) {
data['is_sponsored'] = 1
} else if (queryString.type == "hot" && req.appSettings['video_hot'] == 1) {
data['is_hot'] = 1
}
if(req.body.moviePurchased){
data.purchaseMovie = true
data.purchase_user_id = req.body.purchase_user_id ? req.body.purchase_user_id : req.body.movie_user_id
}
if(req.body.is_cast){
data.cast_crew_member_id = req.body.is_cast
}
//get all movies as per categories
await movieModel.getMovies(req, data).then(result => {
if (result) {
let pagging = false
let items = result
if (result.length > limit - 1) {
items = result.splice(0, limit - 1);
pagging = true
}
res.send({ movies: items, pagging: pagging })
}
}).catch(() => {
res.send({})
})
}
exports.createSeason = async(req,res) => {
let movie_id = parseInt(req.body.movie_id);
if(movie_id == 0){
return res.send({ error: fieldErrors.errors([{ msg: constant.general.PARAMMISSING }], true), status: errorCodes.invalid }).end();
}
await movieModel.createSeasons(req,{movie_id:movie_id}).then(async result => {
if(result){
let sql = "SET @rank:=0;"
sql += "update seasons set season=@rank:=@rank+1 WHERE movie_id = ?";
await globalModel.custom(req,sql,[movie_id]).then(_ => {
return res.send(result);
})
}else{
return res.send({ error: fieldErrors.errors([{ msg: constant.general.PARAMMISSING }], true), status: errorCodes.invalid }).end();
}
})
}
exports.deleteEpisode = async (req,res) => {
let id = parseInt(req.body.id)
let movie_id = parseInt(req.body.movie_id)
if(parseInt(id) == 0 || parseInt(movie_id) == 0){
return res.send({ error: fieldErrors.errors([{ msg: constant.general.PARAMMISSING }], true), status: errorCodes.invalid }).end();
}
let episode = {}
await globalModel.custom(req, "SELECT * FROM episodes WHERE episode_id = ?", id).then(async result => {
if (result) {
episode = JSON.parse(JSON.stringify(result))[0];
}else{
}
}).catch(() => {
})
await movieModel.deleteEpisode(req,episode).then(result => {
if (result) {
commonFunction.deleteImage(req, res, episode.image, "episode")
res.send({"message":constant.movie.DELETEDITEM,season_id:episode.season_id})
}else{
res.send({})
}
})
}
exports.uploadImage = async(req,res) => {
if (req.imageError) {
return res.send({ error: fieldErrors.errors([{ msg: req.imageError }], true), status: errorCodes.invalid }).end();
}
let insertObject = {}
insertObject['image'] = "/upload/images/movies/images/" + req.fileName;
insertObject['resource_id'] = req.params.movie_id
insertObject['resource_type'] = "movies"
await globalModel.create(req, insertObject, "photos").then(async result => {
if (result) {
let editItem = {}
await globalModel.custom(req,"SELECT * FROM photos where photo_id = ?",[result.insertId]).then(result => {
if(result){
editItem = result[0];
}
})
res.send({ message: constant.movie.PHOTOUPLOADED, item:editItem });
} else {
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
}
}).catch(() => {
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
})
}
exports.deleteImage = async(req,res) => {
let id = parseInt(req.body.id)
let movie_id = parseInt(req.body.movie_id)
if(parseInt(id) == 0 || parseInt(movie_id) == 0){
return res.send({ error: fieldErrors.errors([{ msg: constant.general.PARAMMISSING }], true), status: errorCodes.invalid }).end();
}
let photo = {}
await globalModel.custom(req, "SELECT * FROM photos WHERE photo_id = ?", [id]).then(async result => {
if (result) {
photo = JSON.parse(JSON.stringify(result))[0];
}else{
}
}).catch(() => {
})
await globalModel.custom(req, "DELETE FROM photos WHERE photo_id = ?", [id]).then(async result => {
if (result) {
commonFunction.deleteImage(req, res, photo.image, "movie/photo")
return res.send({ message:constant.movie.DELETEDITEM , status: errorCodes.ok }).end();
}else{
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
}
}).catch(() => {
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
})
}
exports.createCastCrew = async(req,res) => {
let cast_id = req.body.cast_id
let id = parseInt(req.body.cast_crew_member_id)
let character = req.body.character
let department = req.body.department
let job = req.body.job
let resource_type = req.body.resource_type
let resource_id = req.body.resource_id
//validate result
let condition = []
condition.push(resource_type)
condition.push(resource_id)
condition.push(id)
let sql = "SELECT cast_crew_id FROM cast_crew WHERE resource_type = ? AND resource_id = ? AND cast_crew_member_id = ?"
if(character){
sql += " AND `character` IS NOT NULL"
if(cast_id){
condition.push(cast_id)
sql += " AND cast_crew_id != ?"
}
}else{
sql += " AND job IS NOT NULL"
if(cast_id){
condition.push(cast_id)
sql += " AND cast_crew_id != ?"
}
}
let valid = true;
await globalModel.custom(req,sql,condition).then(result => {
if(result && result.length){
valid = false;
}
})
if(!valid){
return res.send({ error: constant.movie.ENTRYEXISTS, status: errorCodes.invalid }).end();
}
let insertObject = {}
if(!cast_id){
insertObject['cast_crew_member_id'] = id
insertObject["resource_id"] = resource_id
insertObject["resource_type"] = resource_type
}
if(character)
insertObject["character"] = character
if(job)
insertObject["job"] = job
if(department)
insertObject["department"] = department
if (cast_id) {
await globalModel.update(req, insertObject, "cast_crew", 'cast_crew_id', cast_id).then(async () => {
let editItem = {}
await castnCrewModel.getAllCrewMember(req,{cast_crew_id:cast_id}).then(result => {
if(result){
editItem = result[0];
}
})
res.send({ message:character ? constant.movie.CASTEDITED : constant.movie.CREWEDITED,item:editItem });
}).catch(() => {
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
})
} else {
await globalModel.create(req, insertObject, "cast_crew").then(async result => {
if (result) {
let editItem = {}
await castnCrewModel.getAllCrewMember(req,{cast_crew_id:result.insertId}).then(result => {
if(result){
editItem = result[0];
}
})
res.send({ message: character ? constant.movie.CASTCREATED : constant.movie.CREWCREATED, item:editItem });
} else {
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
}
}).catch(() => {
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
})
}
}
exports.deleteCrew = async (req,res) => {
let id = parseInt(req.body.id)
let movie_id = parseInt(req.body.movie_id)
if(parseInt(id) == 0 || parseInt(movie_id) == 0){
return res.send({ error: fieldErrors.errors([{ msg: constant.general.PARAMMISSING }], true), status: errorCodes.invalid }).end();
}
let cast = {}
await globalModel.custom(req, "SELECT * FROM cast_crew WHERE cast_crew_id = ?", [id]).then(async result => {
if (result) {
cast = JSON.parse(JSON.stringify(result))[0];
}else{
}
}).catch(() => {
})
await globalModel.custom(req, "DELETE FROM cast_crew WHERE cast_crew_id = ?", [id]).then(async result => {
if (result) {
return res.send({ message:constant.movie.DELETEDITEM ,season_id:cast.resource_id, status: errorCodes.ok }).end();
}else{
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
}
}).catch(() => {
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
})
}
exports.deleteSeason = async (req,res) => {
let id = parseInt(req.body.id)
let movie_id = parseInt(req.body.movie_id)
if(parseInt(id) == 0 || parseInt(movie_id) == 0){
return res.send({ error: fieldErrors.errors([{ msg: constant.general.PARAMMISSING }], true), status: errorCodes.invalid }).end();
}
let season = {}
await globalModel.custom(req, "SELECT * FROM seasons WHERE season_id = ?", id).then(async result => {
if (result && result.length) {
season = JSON.parse(JSON.stringify(result))[0];
}else{
}
}).catch(() => {
})
await movieModel.deleteSeason(req,season).then(async result => {
if (result) {
let sql = "SET @rank:=0;"
sql += "update seasons set season=@rank:=@rank+1 WHERE movie_id = ?";
await globalModel.custom(req,sql,[movie_id]).then(_ => {
commonFunction.deleteImage(req, res, season.image, "season")
res.send({"message":constant.movie.DELETEDITEM})
})
}else{
res.send({})
}
})
}
exports.castAutosuggest = async(req,res) => {
let value = req.query.s
castnCrewModel.findAll(req,{name:value,limit:50}).then(result => {
if(result){
res.send({result:result})
}else{
res.send({error:true})
}
})
}
exports.getVideos = async (req, res) => {
const movie_id = parseInt(req.body.movie_id)
if (!movie_id) {
return res.send({})
}
let LimitNum = 51;
let page = 1
if (req.params.page == '') {
page = 1;
} else {
//parse int Convert String to number
page = parseInt(req.body.page) ? parseInt(req.body.page) : 1;
}
let offset = (page - 1) * (LimitNum - 1)
let video = {}
let data = {}
data.limit = LimitNum
data.offset = offset
data.resource_id = movie_id
await movieModel.getVideos(req, data).then(result => {
let pagging = false
if (result) {
pagging = false
if (result.length > LimitNum - 1) {
result = result.splice(0, LimitNum - 1);
pagging = true
}
video = {
pagging: pagging,
videos: result
}
}
})
res.send(video)
}
exports.getMovies = async (req, res) => {
const criteria = req.body.criteria
const value = req.body.value
let LimitNum = 21;
let page = 1
if (req.body.page == '') {
page = 1;
} else {
//parse int Convert String to number
page = parseInt(req.body.page) ? parseInt(req.body.page) : 1;
}
let offset = (page - 1) * (LimitNum - 1)
const data = {}
if (criteria == "search") {
data.title = value
} else if (criteria == "my") {
data.owner_id = req.user ? req.user.user_id : "0"
} else if (criteria == "url") {
var final = value.substr(value.lastIndexOf('/') + 1);
data.custom_url = final
offset = null
page = 1
}
if (req.body.channel_id) {
data.channel_id = req.body.channel_id
}
data.limit = LimitNum
data.offset = offset
data.search = true;
let send = false
await movieModel.getMovies(req, data).then(result => {
if (result && result.length > 0) {
send = true
let pagging = false
if (result.length > LimitNum - 1) {
result = result.splice(0, LimitNum - 1);
pagging = true
}
return res.send({ pagging: pagging, movies: result })
}
}).catch(() => {
})
if (!req.headersSent && !send)
res.send({ pagging: false, movies: [] })
}
exports.password = async (req, res) => {
let password = req.body.password
let id = req.params.id
let movie = {}
await movieModel.findByCustomUrl(id, req, res, true).then(result => {
if (result)
movie = result
}).catch(() => {
})
if (movie.password == password) {
req.session.password.push(movie.movie_id)
res.send({})
return
}
return res.send({ error: fieldErrors.errors([{ msg: "Password you entered is not correct." }], true), status: errorCodes.invalid }).end();
}
exports.addSeasonPhoto = async (req,res) => {
if (req.imageError) {
return res.send({ error: fieldErrors.errors([{ msg: req.imageError }], true), status: errorCodes.invalid }).end();
}
// all set now
let insertObject = {}
let seasonId = req.body.season_id
let seasonObject = {}
if (seasonId) {
//uploaded
await globalModel.custom(req, "SELECT * FROM seasons WHERE season_id = ?", seasonId).then(async result => {
if (result && result.length) {
seasonObject = JSON.parse(JSON.stringify(result))[0];
}
}).catch(() => {
})
}
if (req.fileName) {
insertObject['image'] = "/upload/images/movies/seasons/" + req.fileName;
if(Object.keys(seasonObject).length && seasonObject.image)
commonFunction.deleteImage(req, res, seasonObject.image, 'movie/season/image');
}else{
insertObject['image'] = "";
}
await globalModel.update(req, insertObject, "seasons", 'season_id', seasonId).then(async () => {
let objectImage = {}
objectImage.image = insertObject['image']
res.send({ message:!seasonObject.image ? constant.movie.SEASONIMAGEAdd : constant.movie.SEASONIMAGEEDIT,item:objectImage });
}).catch(() => {
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
})
}
exports.createReview = async(req,res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.send({ error: fieldErrors.errors(errors), status: errorCodes.invalid }).end();
}
let movie_id = req.body.movie_id
let review_id = req.body.review_id
let insertObject = {}
if(!review_id){
var dt = dateTime.create();
var formatted = dt.format('Y-m-d H:M:S');
insertObject["creation_date"] = formatted
insertObject["owner_id"] = req.user.user_id
insertObject["movie_id"] = movie_id
}
insertObject["description"] = req.body.description
insertObject["rating"] = req.body.rating
if(review_id){
//update
await globalModel.update(req, insertObject, "reviews", 'review_id', review_id).then(async result => {
if(result){
await movieModel.getReviews(req,{limit:1,review_id:review_id}).then(result => {
if(result){
let review = JSON.parse(JSON.stringify(result))[0];
socketio.getIO().emit('movieReviewUpdated', {
"review": review,
});
}
});
}
})
}else{
//create
await globalModel.create(req, insertObject, "reviews").then(async result => {
if(result){
let id = result.insertId
await movieModel.getReviews(req,{limit:1,review_id:id}).then(result => {
if(result){
let review = JSON.parse(JSON.stringify(result))[0];
socketio.getIO().emit('movieReviewCreated', {
"review": review
});
}
});
}
});
}
res.send({})
}
exports.episodeCreate = async (req,res) => {
if (req.imageError) {
return res.send({ error: fieldErrors.errors([{ msg: req.imageError }], true), status: errorCodes.invalid }).end();
}
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.send({ error: fieldErrors.errors(errors), status: errorCodes.invalid }).end();
}
// all set now
let insertObject = {}
let episodeId = req.body.episodeId
let eposodeObject = {}
if (episodeId) {
//uploaded
await globalModel.custom(req, "SELECT * FROM episodes WHERE episode_id = ?", episodeId).then(async result => {
if (result && result.length) {
eposodeObject = JSON.parse(JSON.stringify(result))[0];
}else{
episodeId = null
}
}).catch(() => {
})
} else {
insertObject["owner_id"] = req.user.user_id;
}
if(typeof req.body.comments != "undefined"){
insertObject['autoapprove_comments'] = parseInt(req.body.comments)
}
insertObject["title"] = req.body.title
insertObject["description"] = req.body.description ? req.body.description : ""
if (req.body.episodeImage) {
//insertObject['image'] = req.body.movieImage
}else if (req.fileName) {
insertObject['image'] = "/upload/images/movies/episode/" + req.fileName;
}else{
insertObject['image'] = "";
if(Object.keys(eposodeObject).length && eposodeObject.image)
commonFunction.deleteImage(req, res, eposodeObject.image, 'movie/image');
}
var dt = dateTime.create();
var formatted = dt.format('Y-m-d H:M:S');
if (!Object.keys(eposodeObject).length) {
insertObject["creation_date"] = formatted
insertObject['season_id'] = req.body.season_id
insertObject['movie_id'] = req.body.movie_id
}
insertObject["modified_date"] = formatted
insertObject['release_date'] = req.body.release_date;
insertObject['episode_number'] = req.body.episode_number;
if (episodeId) {
//update existing movie
await globalModel.update(req, insertObject, "episodes", 'episode_id', episodeId).then(async () => {
let editItem = {}
await globalModel.custom(req, 'SELECT *,episodes.image as orgImage,IF(episodes.image IS NULL || episodes.image = "","' + req.appSettings['episode_default_photo'] + '",episodes.image) as image FROM episodes WHERE episode_id = ?', episodeId).then(async result => {
if (result && result.length) {
editItem = JSON.parse(JSON.stringify(result))[0];
}
}).catch(() => {
})
res.send({ message:constant.movie.EPISODEEDIT,image:insertObject["image"],item:editItem });
}).catch(() => {
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
})
} else {
//create new movie
await globalModel.create(req, insertObject, "episodes").then(async result => {
if (result) {
let editItem = {}
await globalModel.custom(req, 'SELECT *,episodes.image as orgImage,IF(episodes.image IS NULL || episodes.image = "","' + req.appSettings['episode_default_photo'] + '",episodes.image) as image FROM episodes WHERE episode_id = ?', result.insertId).then(async result => {
if (result && result.length) {
editItem = JSON.parse(JSON.stringify(result))[0];
}
}).catch(() => {
})
res.send({ message: constant.movie.EPISODESUCCESS, image:insertObject["image"],item:editItem });
} else {
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
}
}).catch(err => {
console.log(err)
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
})
}
}
exports.createVideo = async (req,res) => {
if (req.imageError) {
return res.send({ error: fieldErrors.errors([{ msg: req.imageError }], true), status: errorCodes.invalid }).end();
}
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.send({ error: fieldErrors.errors(errors), status: errorCodes.invalid }).end();
}
let insertObject = {}
if(req.body.movie_id)
insertObject["movie_id"] = req.body.movie_id;
let videoId = req.body.videoId
let videoObject = {}
if (videoId) {
//uploaded
await globalModel.custom(req, "SELECT * FROM movie_videos WHERE movie_video_id = ?", videoId).then(async result => {
if (result && result.length) {
videoObject = JSON.parse(JSON.stringify(result))[0];
}else{
videoId = null
}
}).catch(() => {
})
}
let season_id = req.body.season_id ? req.body.season_id : 0
let episode_id = req.body.episode_id ? req.body.episode_id : 0
let category = req.body.category
//check
if(category == "full"){
let condition = [req.body.movie_id]
let sql = "SELECT movie_video_id FROM movie_videos WHERE season_id = ? AND episode_id = ? AND movie_id = ?"
condition.push(season_id)
condition.push(episode_id)
if(videoId){
sql += " AND movie_video_id != ?"
condition.push(videoId)
}
let isValidError = false;
console.log(sql,condition);
await globalModel.custom(req,sql,condition).then(result => {
if (result && result.length) {
isValidError = true
return res.send({ error: fieldErrors.errors([{ msg: constant.movie.EPISODESEASONEXISTS }], true), status: errorCodes.invalid }).end();
}
})
if(isValidError){
return;
}
}
// all set now
insertObject["title"] = req.body.title
if(!req.body.fromEdit)
insertObject["code"] = req.body.code ? req.body.code : null
if (req.body.videoImage) {
//insertObject['image'] = req.body.movieImage
}else if (req.fileName) {
insertObject['image'] = "/upload/images/movies/video/" + req.fileName;
}else{
insertObject['image'] = "";
if(Object.keys(videoObject).length && videoObject.image)
commonFunction.deleteImage(req, res, videoObject.image, 'movie/image');
}
var dt = dateTime.create();
var formatted = dt.format('Y-m-d H:M:S');
if (!Object.keys(videoObject).length) {
insertObject["creation_date"] = formatted
insertObject["owner_id"] = req.user.user_id
}
insertObject['season_id'] = req.body.season_id
insertObject['episode_id'] = !req.body.season_id || req.body.season_id == 0 ? 0 : req.body.episode_id
insertObject['language'] = req.body.language ? req.body.language : "en"
insertObject['quality'] = req.body.quality ? req.body.quality : ""
insertObject['category'] = req.body.category ? req.body.category : "trailer"
if (req.body.type && req.body.type != "undefined"){
insertObject['type'] = req.body.type
}
insertObject["modified_date"] = formatted
if (videoId) {
//update existing movie
await globalModel.update(req, insertObject, "movie_videos", 'movie_video_id', videoId).then(async () => {
insertObject['movie_video_id'] = videoObject.movie_video_id
if(!insertObject['image'])
insertObject['image'] = videoObject.image;
insertObject['completed'] = videoObject.completed
if(!insertObject['type'])
insertObject['type'] = videoObject.type
insertObject['plays'] = videoObject.plays
let data = insertObject
await movieModel.getVideos(req,{movieorg_video_id:videoId,resource_id:videoObject.movie_id}).then(result => {
if(result){
console.log(result);
data = result[0];
}
})
res.send({ message: !req.body.fromEdit ? constant.movie.VIDEOUPLOADPROCESSING : constant.video.EDIT,item:data });
}).catch(() => {
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
})
} else {
insertObject['completed'] = req.body.type == 3 ? 0 : 1
//create new movie
await globalModel.create(req, insertObject, "movie_videos").then(async result => {
if (result) {
insertObject['plays'] = 0
insertObject['movie_video_id'] = result.insertId
let data = insertObject
await movieModel.getVideos(req,{movieorg_video_id:result.insertId,resource_id:insertObject["movie_id"]}).then(result => {
if(result){
data = result[0];
}
})
res.send({ message: req.body.type == 3 ? constant.movie.VIDEOUPLOADPROCESSING : constant.video.SUCCESS, item:data });
} else {
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
}
}).catch(() => {
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
})
}
}
exports.create = async (req, res) => {
await commonFunction.getGeneralInfo(req, res, "", true);
if (req.imageError) {
return res.send({ error: fieldErrors.errors([{ msg: req.imageError }], true), status: errorCodes.invalid }).end();
}
if (req.quotaLimitError) {
return res.send({ error: fieldErrors.errors([{ msg: constant.movie.QUOTAREACHED }], true), status: errorCodes.invalid }).end();
}
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.send({ error: fieldErrors.errors(errors), status: errorCodes.invalid }).end();
}
if(req.body.price){
if(parseFloat(req.body.price) < 0){
return res.send({ error: fieldErrors.errors([{ msg: "Please provide valid price." }], true), status: errorCodes.invalid }).end();
}
}
if(req.body.rent_price){
if(parseFloat(req.body.rent_price) < 0){
return res.send({ error: fieldErrors.errors([{ msg: "Please provide valid rent price." }], true), status: errorCodes.invalid }).end();
}
}
// all set now
let insertObject = {}
let movieId = req.body.movieId
let movieObject = {}
if (movieId) {
//uploaded
await globalModel.custom(req, "SELECT * FROM movies WHERE movie_id = ?", movieId).then(async result => {
if (result && result.length) {
movieObject = JSON.parse(JSON.stringify(result))[0];
}else{
movieId = null
}
}).catch(() => {
})
} else {
insertObject["owner_id"] = req.user.user_id;
}
if(typeof req.body.comments != "undefined"){
insertObject['autoapprove_comments'] = parseInt(req.body.comments)
}
insertObject["title"] = req.body.title
insertObject["description"] = req.body.description ? req.body.description : ""
insertObject["category_id"] = req.body.category_id ? req.body.category_id : 0
insertObject["subcategory_id"] = req.body.subcategory_id ? req.body.subcategory_id : 0
insertObject["subsubcategory_id"] = req.body.subsubcategory_id ? req.body.subsubcategory_id : 0
insertObject["price"] = parseFloat(req.body.price) ? parseFloat(req.body.price) : 0
insertObject["rent_price"] = parseFloat(req.body.rent_price) ? parseFloat(req.body.rent_price) : 0
insertObject["adult"] = req.body.adult ? req.body.adult : 0
insertObject["search"] = req.body.search ? req.body.search : 1
insertObject["view_privacy"] = req.body.privacy ? req.body.privacy : 'everyone'
if (insertObject['view_privacy'] == "password" && req.body.password && req.body.password != "") {
insertObject['password'] = req.body.password
insertObject['is_locked'] = 1
} else {
if (insertObject["view_privacy"] == "password")
insertObject["view_privacy"] = "everyone"
insertObject['password'] = ""
insertObject['is_locked'] = 0
}
if (req.body.movieImage) {
//insertObject['image'] = req.body.movieImage
}else if (req.fileName) {
insertObject['image'] = "/upload/images/movies/movie/" + req.fileName;
}else{
insertObject['image'] = "";
if(Object.keys(movieObject).length && movieObject.image)
commonFunction.deleteImage(req, res, movieObject.image, 'movie/image');
}
var dt = dateTime.create();
var formatted = dt.format('Y-m-d H:M:S');
if (!Object.keys(movieObject).length || !movieObject.custom_url) {
insertObject["custom_url"] = uniqid.process('mov1')
insertObject["is_sponsored"] = req.levelPermissions['movie.sponsored'] == "1" ? 1 : 0
insertObject["is_featured"] = req.levelPermissions['movie.featured'] == "1" ? 1 : 0
insertObject["is_hot"] = req.levelPermissions['movie.hot'] == "1" ? 1 : 0
insertObject["category"] = req.body.category ? req.body.category : "movie"
if (req.levelPermissions["movie.auto_approve"] && req.levelPermissions["movie.auto_approve"] == "1")
insertObject["approve"] = 1
else
insertObject["approve"] = 0
insertObject["creation_date"] = formatted
}else{
insertObject['category'] = movieObject.category
}
insertObject["modified_date"] = formatted
let tags = req.body.tags
if (tags && tags.length > 0)
insertObject["tags"] = tags
else {
insertObject['tags'] = null
}
if(parseFloat(req.body.budget) > 0){
insertObject["budget"] = parseFloat(req.body.budget)
}else{
insertObject["budget"] = 0
}
if(parseFloat(req.body.revenue) > 0){
insertObject["revenue"] = parseFloat(req.body.revenue)
}else{
insertObject["revenue"] = 0
}
if(req.body.movie_release){
insertObject["movie_release"] = req.body.movie_release
}else{
insertObject["movie_release"] = ""
}
if(req.body.language){
insertObject["language"] = req.body.language
}else{
insertObject["language"] = ""
}
req.query.selectType = insertObject['category'];
insertObject['completed'] = 1;
if (movieId) {
//update existing movie
await globalModel.update(req, insertObject, "movies", 'movie_id', movieId).then(() => {
res.send({ message:constant.movie.EDIT });
}).catch(() => {
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
})
} else {
//create new movie
await globalModel.create(req, insertObject, "movies").then(async result => {
if (result) {
let editItem = {}
await movieModel.findById(result.insertId, req,false).then(async movie => {
editItem = movie
}).catch(() => {
})
let dataNotification = {}
dataNotification["type"] = editItem.category == "movie" ? "movies_create" : "series_create"
dataNotification["owner_id"] = req.user.user_id
dataNotification["object_type"] = editItem.category == "movie" ? "movies" : "series"
dataNotification["object_id"] = result.insertId
notificationModel.sendPoints(req,dataNotification,req.user.level_id);
res.send({ message: constant.movie.SUCCESS, editItem:editItem });
} else {
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
}
}).catch(err => {
console.log(err)
return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end();
})
}
}
exports.convertVideo = async(req,videoObject) => {
return new Promise(async (resolve) => {
const res = {}
const videoResolution = videoObject.resolution
const videoLocation = videoObject.video_location
const FFMPEGpath = req.appSettings.video_ffmpeg_path
const videoId = videoObject.movie_video_id
//convert movies
var orgPath = req.serverDirectoryPath + "/public" + videoLocation
let command = ffmpeg(orgPath)
//.audioCodec('libfaac')
.videoCodec('libx264')
.format('mp4');
const videoName = uniqid.process('v')
let watermarkImage = req.levelPermissions['movie.watermark'] != "" ? req.serverDirectoryPath + "/public" + req.levelPermissions["movie.watermark"] : "/public/upload/images/blank.png"
const path_240 = "/public/upload/movies/video/" + videoName + "_240p.mp4"
const path_640 = "/public/upload/movies/video/" + videoName + "_360p.mp4"
const path_854 = "/public/upload/movies/video/" + videoName + "_480p.mp4"
const path_1280 = "/public/upload/movies/video/" + videoName + "_720p.mp4"
const path_1920 = "/public/upload/movies/video/" + videoName + "_1080p.mp4"
const path_2048 = "/public/upload/movies/video/" + videoName + "_2048p.mp4"
const path_3840 = "/public/upload/movies/video/" + videoName + "_4096p.mp4"
let is_validVideo = false
//const sample = "/public/upload/movies/video/" + videoName + "_sample.mp4"
await module.exports.executeFFMPEG(command, req.serverDirectoryPath + path_240, 240, orgPath, FFMPEGpath, watermarkImage).then(async () => {
//upate movie 240
if (req.appSettings.upload_system == "s3" || req.appSettings.upload_system == "wisabi") {
await s3Upload(req, req.serverDirectoryPath + path_240, path_240.replace("/public",'')).then(() => {
//remove local file
commonFunction.deleteImage(req, res, path_240.replace("/public",''), 'locale')
}).catch(() => {
})
}
const updatedObject = {}
updatedObject["240p"] = 1
updatedObject["video_location"] = path_240.replace('/public', '')
await globalModel.update(req, updatedObject, "movie_videos", "movie_video_id", videoId).then(() => {
}).catch(() => {
})
is_validVideo = true
}).catch(() => {
})
// if(is_validVideo && videoObject.category == "full"){
// const filePath = "/public" + "/upload/movies/video/" + videoName+"_sample_same"+path.extname(videoLocation)
// //create sample movie
// await module.exports.createSample(orgPath,filePath,command,req,sample,FFMPEGpath,watermarkImage,res,videoId).then(result => {
// }).catch(err => {
// })
// }
if ((videoResolution >= 640 || videoResolution == 0) && is_validVideo && req.appSettings["movie_upload_movies_type"].indexOf("360") > -1) {
await module.exports.executeFFMPEG(command, req.serverDirectoryPath + path_640, 640, orgPath, FFMPEGpath, watermarkImage).then(async () => {
//upate movie
if (req.appSettings.upload_system == "s3" || req.appSettings.upload_system == "wisabi") {
await s3Upload(req, req.serverDirectoryPath + path_640, path_640.replace("/public",'')).then(() => {
//remove local file
commonFunction.deleteImage(req, res, path_640.replace("/public",''), 'locale')
}).catch(() => {
})
}
const updatedObject = {}
updatedObject["360p"] = 1
await globalModel.update(req, updatedObject, "movie_videos", "movie_video_id", videoId).then(async () => {
}).catch(() => {
})
}).catch(() => {
})
}
if ((videoResolution >= 854 || videoResolution == 0) && is_validVideo && req.appSettings["movie_upload_movies_type"].indexOf("480") > -1) {
await module.exports.executeFFMPEG(command, req.serverDirectoryPath + path_854, 854, orgPath, FFMPEGpath, watermarkImage).then(async () => {
//upate movie
if (req.appSettings.upload_system == "s3" || req.appSettings.upload_system == "wisabi") {
await s3Upload(req, req.serverDirectoryPath + path_854, path_854.replace("/public",'')).then(() => {
//remove local file
commonFunction.deleteImage(req, res, path_854.replace("/public",''), 'locale')
}).catch(() => {
})
}
const updatedObject = {}
updatedObject["480p"] = 1
await globalModel.update(req, updatedObject, "movie_videos", "movie_video_id", videoId).then(async () => {
}).catch(() => {
})
}).catch(() => {
})
}
if ((videoResolution >= 1280 || videoResolution == 0) && is_validVideo && req.appSettings["movie_upload_movies_type"].indexOf("720") > -1) {
await module.exports.executeFFMPEG(command, req.serverDirectoryPath + path_1280, 1280, orgPath, FFMPEGpath, watermarkImage).then(async () => {
//upate movie
if (req.appSettings.upload_system == "s3" || req.appSettings.upload_system == "wisabi") {
await s3Upload(req, req.serverDirectoryPath + path_1280, path_1280.replace("/public",'')).then(() => {
//remove local file
commonFunction.deleteImage(req, res, path_1280.replace("/public",''), 'locale')
}).catch(() => {
})
}
const updatedObject = {}
updatedObject["720p"] = 1
await globalModel.update(req, updatedObject, "movie_videos", "movie_video_id", videoId).then(async () => {
}).catch(() => {
})
}).catch(() => {
})
}
if ((videoResolution >= 1920 || videoResolution == 0) && is_validVideo && req.appSettings["movie_upload_movies_type"].indexOf("1080") > -1) {
await module.exports.executeFFMPEG(command, req.serverDirectoryPath + path_1920, 1920, orgPath, FFMPEGpath, watermarkImage).then(async () => {
//upate movie
if (req.appSettings.upload_system == "s3" || req.appSettings.upload_system == "wisabi") {
await s3Upload(req, req.serverDirectoryPath + path_1920, path_1920.replace("/public",'')).then(() => {
//remove local file
commonFunction.deleteImage(req, res, path_1920.replace("/public",''), 'locale')
}).catch(() => {
})
}
const updatedObject = {}
updatedObject["1080p"] = 1
await globalModel.update(req, updatedObject, "movie_videos", "movie_video_id", videoId).then(async () => {
}).catch(() => {
})
}).catch(() => {
})
}
if ((videoResolution >= 2048 || videoResolution == 0) && is_validVideo && req.appSettings["movie_upload_movies_type"].indexOf("2048") > -1) {
await module.exports.executeFFMPEG(command, req.serverDirectoryPath + path_2048, 2048, orgPath, FFMPEGpath, watermarkImage).then(async () => {
//upate movie
if (req.appSettings.upload_system == "s3" || req.appSettings.upload_system == "wisabi") {
await s3Upload(req, req.serverDirectoryPath + path_2048, path_2048.replace("/public",'')).then(() => {
//remove local file
commonFunction.deleteImage(req, res, path_2048.replace("/public",''), 'locale')
}).catch(() => {
})
}
const updatedObject = {}
updatedObject["2048p"] = 1
await globalModel.update(req, updatedObject, "movie_videos", "movie_video_id", videoId).then(async () => {
}).catch(() => {
})
}).catch(() => {
})
}
if ((videoResolution >= 3840 || videoResolution == 0) && is_validVideo && req.appSettings["movie_upload_movies_type"].indexOf("4096") > -1) {
await module.exports.executeFFMPEG(command, req.serverDirectoryPath + path_3840, 3840, orgPath, FFMPEGpath, watermarkImage).then(async () => {
//upate movie
if (req.appSettings.upload_system == "s3" || req.appSettings.upload_system == "wisabi") {
await s3Upload(req, req.serverDirectoryPath + path_3840, path_3840.replace("/public",'')).then(() => {
//remove local file
commonFunction.deleteImage(req, res, path_3840.replace("/public",''), 'locale')
}).catch(() => {
})
}
const updatedObject = {}
updatedObject["4096p"] = 1
await globalModel.update(req, updatedObject, "movie_videos", "movie_video_id", videoId).then(async () => {
}).catch(() => {
})
}).catch(() => {
})
}
const updatedObject = {}
if (is_validVideo)
updatedObject["completed"] = 1
else
updatedObject["completed"] = 3
//unlink org file
if (videoLocation)
commonFunction.deleteImage(req, res, videoLocation.replace("/public",''), "movie/movie")
await globalModel.update(req, updatedObject, "movie_videos", "movie_video_id", videoId).then(async () => {
//send socket data
}).catch(() => {
})
if (is_validVideo) {
notifications.insert(req, {owner_id:videoObject.owner_id,insert:true, type: "movievideos_processed_complete", subject_type: "users", subject_id: videoObject.owner_id, object_type: "movies", object_id: videoObject.movie_id,forceInsert:true }).then(() => {
}).catch(() => {
})
} else {
notifications.insert(req, {owner_id:videoObject.owner_id,insert:true, type: "movievideos_processed_failed", subject_type: "users", subject_id: videoObject.owner_id, object_type: "movies", object_id: videoObject.movie_id,forceInsert:true }).then(() => {
}).catch(() => {
})
}
socketio.getIO().emit('moviVideoCreated', {
"videoId": videoObject.movie_video_id,
status: is_validVideo ? 1 : 3
});
resolve(true)
})
}
exports.createSample = async (orgPath,filePath,command,req,sample,FFMPEGpath,watermarkImage,res,videoId) => {
return new Promise((resolve,reject) => {
ffmpeg()
.input(orgPath)
.setStartTime('00:00:00')
.setDuration('10')
.output(req.serverDirectoryPath +filePath)
.on('start', function() {
//console.log('Started: ' + commandLine);
})
.on('end', async function(err) {
if(!err)
{
let commandNew = ffmpeg(req.serverDirectoryPath +filePath)
//.audioCodec('libfaac')
.videoCodec('libx264')
.format('mp4');
await module.exports.executeFFMPEG(commandNew, req.serverDirectoryPath + sample, 640, req.serverDirectoryPath +filePath, FFMPEGpath, watermarkImage).then(async () => {
//upate movie
if (req.appSettings.upload_system == "s3" || req.appSettings.upload_system == "wisabi") {
await s3Upload(req, req.serverDirectoryPath + sample, sample.replace("/public",'')).then(() => {
//remove local file
}).catch(() => {
})
commonFunction.deleteImage(req, res, sample.replace("/public",''), 'locale')
}
commonFunction.deleteImage(req, res, filePath.replace("/public",''), 'locale')
const updatedObject = {}
updatedObject["sample"] = 1
await globalModel.update(req, updatedObject, "movie_videos", "movie_video_id", videoId).then(async () => {
}).catch(() => {
})
resolve(true)
}).catch(() => {
reject(false)
})
}
})
.on('error', function(err){
console.log('error: ', +err);
reject(false)
}).run();
})
}
exports.executeFFMPEG = async (command, filePath, resolution) => {
return new Promise((resolve, reject) => {
//let commandString = FFMPEGpath+" -y -i "+orgPath+" -vcodec libx264 -preset slow -filter:v scale="+resolution+":-2 -crf 26 "+filePath+" 2>&1"
command.clone()
//.input(watermarkImage)
// .outputOption([
// "-preset" , "slow",
// "-filter:v","scale="+resolution+":-2"
// ])
// .complexFilter([
// "-filter:v scale="+resolution+":-2 -crf 26"
// ])
.outputOption([
"-preset", req.appSettings['movie_conversion_type'] ? req.appSettings['movie_conversion_type'] : "ultrafast",
"-filter:v", "scale=" + resolution + ":-2"
])
// .complexFilter([
// "[0:v]scale=640:-1[bg];[bg][1:v]overlay=W-w-10:H-h-10"
// ])
.on('start', function () {
//console.log('Spawned Ffmpeg with command: ' + commandLine);
})
.on('progress', () => {
//console.log(`[ffmpeg] ${JSON.stringify(progress)}`);
})
.on('error', () => {
reject(false);
})
.on('end', () => {
resolve(true);
}).save(filePath)
})
}
exports.upload = async (req, res) => {
if (req.imageError) {
return res.send({ error: fieldErrors.errors([{ msg: req.imageError }], true), status: errorCodes.invalid }).end();
}
if (req.uploadLimitError) {
return res.send({ error: fieldErrors.errors([{ msg: constant.movie.LIMITERRROR }], true), status: errorCodes.invalid }).end();
}
// validate upload limit
// validate member role upload count limit
if (req.quotaLimitError) {
return res.send({ error: fieldErrors.errors([{ msg: constant.movie.QUOTAREACHED }], true), status: errorCodes.invalid }).end();
}
let basePath = req.serverDirectoryPath + "/public"
const filePath = basePath + "/upload/movies/video/" + req.fileName
let images = []
let duration = 0
let videoWidth = 0, videoHeight = 0, size = 0
var command =
ffmpeg.ffprobe(filePath, function (err, metadata) {
duration = metadata.format.duration.toString()
videoWidth = metadata.streams[0].width ? metadata.streams[0].width : (metadata.streams[1] ? metadata.streams[1].width : "")
videoHeight = metadata.streams[0].height ? metadata.streams[0].height : (metadata.streams[1] ? metadata.streams[1].height : "")
size = metadata.format.size
ffmpeg(filePath)
.on('filenames', function (filenames) {
images = filenames;
}).on('end', function () {
//append base path in images
let uploadedImages = []
images.forEach(image => {
uploadedImages.push(req.APP_HOST + "/upload/images/movies/video/" + image)
})
//create item movie in table
let videoObject = {}
videoObject["completed"] = 0;
videoObject['image'] = "/upload/images/movies/video/" + images[0];
videoObject["video_location"] = "/upload/movies/video/" + req.fileName
videoObject['type'] = 'upload'
videoObject['title'] = "Untitled"
var dt = dateTime.create();
var formatted = dt.format('Y-m-d H:M:S');
videoObject['creation_date'] = formatted
videoObject['modified_date'] = formatted
videoObject['size'] = size
videoObject["owner_id"] = req.user.user_id
var n = duration.indexOf('.');
duration = duration.substring(0, n != -1 ? n : duration.length)
let d = Number(duration);
var h = Math.floor(d / 3600).toString();
var m = Math.floor(d % 3600 / 60).toString();
var s = Math.floor(d % 3600 % 60).toString();
var hDisplay = h.length > 0 ? (h.length < 2 ? "0" + h : h) : "00"
var mDisplay = m.length > 0 ? ":" + (m.length < 2 ? "0" + m : m) : ":00"
var sDisplay = s.length > 0 ? ":" + (s.length < 2 ? "0" + s : s) : ":00"
const time = hDisplay + mDisplay + sDisplay
videoObject['duration'] = time
globalModel.create(req, videoObject, "movie_videos").then(result => {
res.send({ videoWidth: videoWidth, videoHeight: videoHeight, videoId: result.insertId, images: uploadedImages, name: path.basename(metadata.format.filename, path.extname(metadata.format.filename)) })
})
}).screenshots({
// Will take screens at 20%, 40%, 60% and 80% of the movie
count: 1,
folder: basePath + "/upload/images/movies/video/",
filename: "%w_%h_%b_%i"
});
});
// Kill ffmpeg after 5 minutes anyway
setTimeout(function () {
if (typeof command != "undefined") {
command.on('error', function () {
return res.send({ error: fieldErrors.errors([{ msg: constant.general.GENERAL }], true), status: errorCodes.serverError }).end();
});
command.kill();
}
}, 60 * 5 * 1000);
}
|
const playlistTools = require("./playlist-tools-v2");
const Playlists = playlistTools.Playlists;
// playlist combiner
// 1. given playlist names, find their ids
// 2. using their ids, get the tracks
// 3. using the tracks, create/update a new playlist
// input: playlist names, new playlist name, access_token
const combinePlaylists = async (
access_token,
playlistNames,
newPlaylistName
) => {
// search current user playlists for playlist names
var playlistObjects = [];
console.log("Retrieving User Playlists");
const playlists = await playlistTools.getAllCurrentUserPlaylists(
access_token
);
console.log("Retrieved Playlists");
console.log("Searching for combined playlists");
for (const playlistName of playlistNames) {
console.log(`Finding ${playlistName}`);
const foundPlaylist = playlistTools.getUserPlaylistByName(
playlistName,
playlists
);
if (!foundPlaylist) {
console.log("Uh oh an error occured");
return {
success: false,
error: "One of the playlists could not be found"
};
}
playlistObjects.push(foundPlaylist);
}
console.log("Found all playlists");
// using found playlists, get all of the tracks for them
console.log("Scraping Tracks");
const tracks = await playlistTools.getTrackDataFromPlaylistArray(
playlistObjects,
access_token
);
console.log(tracks.length);
console.log("Creating new playlist if doesn't exist");
// check to see if playlist exists, if it doesnt then create it
var newPlaylist = playlistTools.getUserPlaylistByName(
newPlaylistName,
playlists
);
if (!newPlaylist) {
newPlaylist = await playlistTools.createPlaylist(
newPlaylistName,
access_token
);
}
console.log("Adding tracks to playlist");
// add tracks to playlist
const returns = await Playlists.addTracks(
access_token,
newPlaylist.id,
tracks,
true
);
console.log("Done");
return { success: "success" };
};
const test = async () => {
const playlistNames = [
"DJ Stregz Fresh Squeezed Vol. 2",
"DJ Stregz Fresh Squeezed Vol. 1"
];
const newPlaylistName = "DJ Stregz Fresh Squeezed Full Collection";
const access_token =
"BQABAwh0wXiG4NgzDKrP_mt0DUzwEUIPL6OPUlEqQt60Z_072GMFbz17-ldX2PjofTt4l0HZQfJbiinuEnOGfv92p3C76olS0GN5TgpYFOdHXI7UmmJfREUFqnNuxCoa_82PEnUMqrmNmIB0BHeZoncdgV36NlQXBOE9eB9INhFu2sbxPn0Ayp4VBW1-fthDkLOOKc77vTbUWoonTqxpk1W4fRSyOplin4PoBP7u8H3Oo4aSrXPb5GiPcPU";
combinePlaylists(access_token, playlistNames, newPlaylistName);
};
module.exports = {
combinePlaylists
};
|
import React from 'react';
import {Link} from 'react-router-dom'
function Headrer(){
return (
<div>
<nav class="navbar navbar-light bg-light">
<span class="navbar-brand mb-0 h1">Random Users App</span>
<Link to="/">Home</Link>
<Link to="/users">User List</Link>
<Link to="/users/1">User Detail</Link>
<Link to="/about">About</Link>
</nav>
</div>
)
}
export default Headrer;
|
/*global require:true*/
/*global module:true*/
/*global __dirname:true*/
/*global console:true*/
(function(){
"use strict";
var path = require( "path" );
var os = require( "os" );
var fs = require( "fs-extra" );
var uglify = require("uglify-js");
var jsp = uglify;
var DirectoryColorfy = require( "directory-colorfy" );
var DirectoryEncoder = require( "directory-encoder" );
var svgToPng = require( "svg-to-png" );
var _ = require( "lodash" );
var loadCSSpath = require.resolve( "fg-loadcss" );
var helper = require( "./grunticon-helper.js" );
var defaults = {
datasvgcss: "icons.data.svg.css",
datapngcss: "icons.data.png.css",
urlpngcss: "icons.fallback.css",
previewhtml: "preview.html",
loadersnippet: "grunticon.loader.js",
cssbasepath: path.sep,
customselectors: {},
cssprefix: ".icon-",
defaultWidth: "400px",
defaultHeight: "300px",
colors: {},
dynamicColorOnly: false,
pngfolder: "png",
pngpath: "",
template: "",
tmpPath: os.tmpdir(),
tmpDir: "grunticon-tmp",
previewTemplate: path.join( __dirname, "..", "static", "preview.hbs" ),
compressPNG: false,
optimizationLevel: 3,
enhanceSVG: false,
corsEmbed: false,
verbose: true,
logger: {
verbose: console.info,
fatal: console.error,
ok: console.log
}
};
var disabledLogger = {
verbose: function() {},
fatal: console.error,
ok: function() {}
};
var Grunticon = function(files, output, config){
config = config || {};
if( !Array.isArray( files ) ){
throw new Error( "The first argument passed into the Grunticon constructor must be an array of files" );
}
if( typeof output !== "string" ){
throw new Error( "The second argument passed into the Grunticon constructor must be a string, a path to an output directory" );
}
this.files = files;
this.output = output;
this.options = _.defaultsDeep( config, defaults );
this.logger = this.options.verbose ? this.options.logger : disabledLogger;
};
Grunticon.generateLoader = function( opts ){
opts = opts || {};
var enhanceSVG = opts.enhanceSVG || false;
var corsEmbed = opts.corsEmbed || false;
var logger = opts.verbose || defaults.verbose ? (opts.logger || defaults.logger) : disabledLogger;
var files = {
loader: path.join( __dirname, "..", "static", "grunticon.loader.js"),
embed: path.join( __dirname, "..", "static", "grunticon.embed.js"),
corsEmbed: path.join( __dirname, "..", "static", "grunticon.embed.cors.js"),
banner: path.join( __dirname, "..", "static", "grunticon.loader.banner.js")
};
var min = [];
// minify the source of the grunticon loader and write that to the output
logger.verbose( "grunticon now minifying the stylesheet loader source." );
var banner = fs.readFileSync( files.banner ).toString( "utf-8" );
var loadCSS = fs.readFileSync( loadCSSpath ).toString( "utf-8" );
var onloadCSS = fs.readFileSync( path.dirname(loadCSSpath) + "/onloadCSS.js" ).toString( "utf-8" );
var loaderContents = fs.readFileSync( files.loader ).toString( "utf-8" );
var embedContents, corsEmbedContents;
min = min.concat( "(function(){" );
min = min.concat( loadCSS );
min = min.concat( onloadCSS );
min = min.concat( loaderContents );
if( enhanceSVG ){
embedContents = fs.readFileSync( files.embed ).toString( "utf-8" );
min = min.concat( embedContents );
if( corsEmbed ){
corsEmbedContents = fs.readFileSync( files.corsEmbed ).toString( "utf-8" );
min = min.concat( corsEmbedContents );
}
}
min = min.concat( "})();" );
var code = min.join( "\n" );
var compressed = jsp.minify(code).code;
var ret = banner + "\n" + compressed;
return ret;
};
Grunticon.prototype.process = function(cb){
// folder name (within the output folder) for generated png files
var config = this.options;
var logger = this.logger;
var pngfolder = path.join.apply( null, config.pngfolder.split( path.sep ) );
// create the output directory
fs.mkdirpSync( this.output );
// minify the source of the grunticon loader and write that to the output
var loader = config.min = Grunticon.generateLoader({
enhanceSVG: config.enhanceSVG,
corsEmbed: config.corsEmbed,
logger: logger
});
if( config.loadersnippet === false ) {
} else {
fs.writeFileSync( path.join( this.output, config.loadersnippet ), loader );
logger.verbose( "grunticon loader file created." );
}
var svgToPngOpts = {
defaultWidth: config.defaultWidth,
defaultHeight: config.defaultHeight,
compress: config.compressPNG,
optimizationLevel: config.optimizationLevel,
debug: config.verbose
};
var o = {
pngfolder: pngfolder,
pngpath: config.pngpath,
customselectors: config.customselectors,
template: config.template ? path.resolve( config.template ) : "",
previewTemplate: path.resolve( config.previewTemplate ),
noencodepng: false,
prefix: config.cssprefix
};
var o2 = JSON.parse(JSON.stringify(o)); /* clone object */
o2.noencodepng = true;
logger.verbose("Coloring SVG files");
// create the tmp directory
var tmp = path.join( config.tmpPath, config.tmpDir );
if( fs.existsSync( tmp ) ){
fs.removeSync( tmp );
}
fs.mkdirpSync( tmp );
var dc;
try{
dc = new DirectoryColorfy( this.files, tmp, {
colors: config.colors,
dynamicColorOnly: config.dynamicColorOnly
});
} catch( e ){
logger.fatal(e);
cb( false );
}
dc.convert()
.then(function(){
//copy non color config files into temp directory
var transferFiles = this.files.filter( function( f ){
return !f.match( /\.colors/ );
});
transferFiles.forEach( function( f ){
var filename = path.basename(f);
fs.copySync( f, path.join( tmp, filename ) );
});
logger.verbose("Converting SVG to PNG");
var tmpFiles = fs.readdirSync( tmp )
.map( function( file ){
return path.join( tmp, file );
});
var svgFiles = tmpFiles.filter( function( file ){
return path.extname( file ) === ".svg";
}),
pngFiles = tmpFiles.filter( function( file ){
return path.extname( file ) === ".png";
});
pngFiles.forEach(function( f ){
var filename = path.basename(f);
fs.copySync( f, path.join( this.output, pngfolder, filename ) );
}, this);
// svg-to-png requires a non-empty input array; in such a case skip it and use
// a dummy thenable.
(
svgFiles.length ?
svgToPng.convert( svgFiles, path.join( this.output, pngfolder ), svgToPngOpts ) :
{then: function (callback) {callback();}}
).then( function( result , err ){
if( err ){
logger.fatal( err );
cb( false );
}
var pngs = fs.readdirSync( path.join( this.output, pngfolder ) )
.map(function( file ){
return path.join( this.output, pngfolder, file );
}, this);
var svgde = new DirectoryEncoder( tmpFiles, path.join( this.output, config.datasvgcss ), Object.assign( {}, o, { forcedatauri: true } ) ),
pngde = new DirectoryEncoder( pngs, path.join( this.output, config.datapngcss ), o ),
pngdefall = new DirectoryEncoder( pngs, path.join( this.output, config.urlpngcss ), o2 );
logger.verbose("Writing CSS");
try {
svgde.encode();
pngde.encode();
pngdefall.encode();
} catch( e ){
logger.fatal( e );
cb( false );
}
logger.verbose( "Grunticon now creating Preview File" );
try {
helper.createPreview( tmp, this.output, config );
} catch(er) {
logger.fatal(er);
cb( false );
}
logger.verbose( "Delete Temp Files" );
fs.removeSync( tmp );
logger.ok( "Grunticon processed " + this.files.length + " files." );
cb();
}.bind( this ), logger.fatal);
}.bind( this ));
};
module.exports = Grunticon;
}(typeof exports === 'object' && exports || this));
|
angular.module('googleAnalyticsModule', [])
.constant('_', window._)
|
const mix =
(a) =>
(b) =>
(c) => a + b * c
const mix1 = (b) =>
(c) => 1 + b * c
console.log(mix(1)(2)(3))
console.log(mix1(2)(3))
|
const profile_menu_container = document.getElementById('profile_menu_container');
const header_user_btn = document.getElementById('header_user_btn');
const login = document.getElementById('login');
const login_modal = document.getElementById('login_modal');
const input_box_email = document.getElementById('input_box_email');
const input_box_password = document.getElementById('input_box_password');
const signup_modal = document.getElementById('signup_modal');
const experience=document.getElementById('experience_input');
const stays=document.getElementById('stays_input');
function main_page() {
header_user_btn.addEventListener('click', function (event) {
if (profile_menu_container.style.visibility === 'visible') {
//profile_menu_container.style.display='none';
profile_menu_container.style.visibility = 'hidden';
header_user_btn.className = "header_user_btn";
}
else {
//profile_menu_container.style.display='flex';
profile_menu_container.style.visibility = 'visible';
header_user_btn.className = "header_user_btn_click";
}
console.log(event.target);
});
login.addEventListener('click', (event) => {
login_modal.style.display = "block";
});
document.getElementById('signup').addEventListener('click', (event) => {
signup_modal.style.display = 'block';
});
document.getElementById('close_modal').addEventListener('click', (event) => {
login_modal.style.display = "none";
});
document.getElementById('login_modal').addEventListener('click', (event) => {
if ((event.target.id === 'modal_overlay' || event.target.id === 'modal_container') && login_modal.style.display === "block"){
login_modal.style.display = "none";
}
});
document.getElementById('modal').addEventListener('click', (event) => {
if (event.target.id !== 'login_input_form_email' && input_box_email.className === 'input_box_clicked')
input_box_email.className = 'input_box';
else if (event.target.id !== 'login_input_form_password' && input_box_password.className === 'input_box_clicked')
input_box_password.className = 'input_box';
});
document.getElementById('body_div').addEventListener('click', (event) => {
if (event.target.id !== 'profile_menu' && profile_menu_container.style.visibility === 'visible') {
profile_menu_container.style.visibility = 'hidden';
//profile_menu_container.style.display='flex';
header_user_btn.className = "header_user_btn";
}
});
document.getElementById('login_input_form_email').addEventListener('click', (event) => {
input_box_email.className = "input_box_clicked";
});
document.getElementById('login_input_form_password').addEventListener('click', (event) => {
input_box_password.className = "input_box_clicked";
});
document.getElementById('sign_up_btn').addEventListener('click', (event) => {
login_modal.style.display = 'none';
sign_up_modal.style.display = 'block';
});
}
function main_page_search(){
document.getElementById('experience_text').addEventListener('click',(event)=>{
console.log(stays.className);
experience.className="search_field_select";
experience.style='animation-name: keyframe_2';
experience.setAttribute("aria-selected",true);
if(stays.className==='search_field_select'){
stays.className='search_field_select_not';
stays.style='animation-name: none';
stays.setAttribute("aria-selected",false);
}
});
document.getElementById('stays_text').addEventListener('click',(event)=>{
stays.className="search_field_select";
stays.setAttribute("aria-selected",true);
stays.style='animation-name: keyframe_1';
if(experience.className==='search_field_select'){
experience.className='search_field_select_not';
experience.style='animation-name: none';
experience.setAttribute("aria-selected",false);
}
})
}
function signup_modal_page() {
document.getElementById('signup_checkbox_box').addEventListener('click', (event) => {
const signup_checkbox_fake_area = document.getElementById('signup_checkbox_fake_area');
if (signup_checkbox_fake_area.className === 'checkbox_fake_area') {
signup_checkbox_fake_area.className = "checkbox_fake_area_clicked";
const add_check = document.createElement('span');
const img = document.createElement('img');
img.src = "../images/check-solid.svg";
add_check.appendChild(img);
signup_checkbox_fake_area.appendChild(add_check);
}
else {
signup_checkbox_fake_area.className = "checkbox_fake_area";
signup_checkbox_fake_area.removeChild(signup_checkbox_fake_area.firstChild);
}
});
document.getElementById('close_modal_signup').addEventListener('click', (event) => {
signup_modal.style.display = "none";
});
signup_modal.addEventListener('click', (event) => {
if ((event.target.className === 'modal_overlay' || event.target.className === 'modal_container') && signup_modal.style.display === "block")
signup_modal.style.display = "none";
});
}
function init() {
main_page();
signup_modal_page();
main_page_search();
}
init();
|
const assert = require('assert')
const {findUserByEmail, findUserById} = require('../async')
describe('the async function', function(){
describe('the finduserbyid funnction',function(){
it('should return found user by id', function(){
return findUserById(1).then(result =>{
console.log('@@===>',result)
assert.equal(result.user.name,'bahdcoder')
})
})
it('should throw an error if user was not found', function(){
return findUserById(98756).catch(error => {
assert.equal(error.message, 'User with id: 98756 was not found.')
})
})
it('should return the object when user id passed into',async()=>{
const result = await findUserById(1)
assert.equal(result.user.name ,'bahdcoder')
})
})
describe('the finduserbyemail', function(){
it('should return found user by email', function(){
findUserByEmail('bahdcoder@gmail.com').then(result =>{
assert.equal(result.user.email, 'bahdcoder@gmail.com')
assert.equal(result.user.id, 1)
})
})
it('should throw an error if user was not found', function(){
return findUserByEmail('bahdcoder@notfound.com').catch(error => {
assert.equal(error.message, 'User with email: bahdcoder@notfound.com was not found.')
})
})
})
it('should return the onject when user email passed into', async()=>{
const result= await findUserByEmail('bahdcoder@gmail.com')
assert.equal(result.user.email,'bahdcoder@gmail.com')
})
it('should throw an error if user was not found',async()=>{
try{
await findUserByEmail('bahd@me.com')
assert.fail('Expected_Error')
}catch(error){
if(assert.message==='Expected_Error'){
throw error
}
assert.equal(error.message,'User with email: bahd@me.com was not found.')
}
})
})
|
import React from "react";
export default function Story4() {
return (
<>
<div>
Ruby received her hearing aids on May 11, 2020. The adjustment to them
was a roller coaster; she loved them, hated them, and then loved them
again. We created team Hear With Ruby immediately, and began raising
awareness about hearing loss. We surrounded Ruby with positive images of
others with hearing impairments, doctoring images of her favorite
princesses and role models to wear aids just like her. We received the
gift of a doll wearing pink bilateral aids identical to Ruby’s, and
bought every book we could find about hearing impairment and aids. We
celebrated with a party when they arrived, and friends sent pairs of
charms to add to Ruby’s collection. We told Ruby that everyone is born
with qualities that make them unique and special, and she loves to meet
new people and ask,
</div>
<br />
<center className="center-text">“What makes you unique and special?”</center>
<br />
<div>
We made her a social story all about her aids to share with her friends
at school, and proudly walked with the Walk4Hearing in October 2020.
</div>
</>
);
}
|
import "../libs/csap-modules.js";
import { _dialogs, _dom, _utils, _net } from "../utils/all-utils.js";
_dom.onReady( function () {
let appScope = new Project_Health_Report();
appScope.initialize();
} );
function Project_Health_Report() {
_dom.logHead( "Main module" );
this.initialize = function () {
console.log( "Init in health..." );
$.when( loadHealthInfo() ).then( addTableSorter )
};;
function loadHealthInfo() {
let r = $.Deferred();
let projName = getParameterByName( "projName" );
$.getJSON( "api/report/healthMessage", {
"projectName": projName
} ).done( function ( loadJson ) {
healthMessageSuccess( loadJson );
} );
setTimeout( function () {
console.log( 'loading health info done' );
r.resolve();
}, 500 );
return r;
}
function addTableSorter() {
$( "#healthTable" ).tablesorter( {
sortList: [ [ 0, 0 ] ],
theme: 'csapSummary'
} );
}
function healthMessageSuccess( dataJson ) {
for ( let i = 0; i < dataJson.length; i++ ) {
let hostName = dataJson[ i ].host;
let data = dataJson[ i ].data;
let errors = data.errors;
let errorList = errors[ hostName ];
let healthContent = '<td> ' + hostName + '</td>'
+ '<td> ' + dataJson[ i ].lifecycle + '</td>'
+ '<td> ' + getErrorMessage( errorList ) + '</td>';
let healthContentTr = $( '<tr />', {
'class': "",
html: healthContent
} );
$( '#healthBody' ).append( healthContentTr );
}
}
function getErrorMessage( errorList ) {
let errorMessage = '';
if ( errorList.length > 0 ) {
let containerObject = jQuery( '<div/>' );
let errorObject = jQuery( '<ol/>', {
class: " ",
title: "List of errors"
} ).appendTo( containerObject );
for ( let i = 0; i < errorList.length; i++ ) {
//errorMessage = errorMessage +'\n' +errorList[i] + ' ';
//errorMessage.append()
jQuery( '<li/>', {
class: "",
text: errorList[ i ]
} ).css( {
"padding": "2px"
} ).appendTo( errorObject );
}
errorMessage = containerObject.html();
}
return errorMessage;
/*
if(dataJson[i].errors.states.processes != undefined){
return dataJson[i].errors.states.processes.message;
}
if(dataJson[i].errors.states.memory != undefined){
return dataJson[i].errors.states.memory.message;
}
*/
//return '';
}
function getParameterByName( name ) {
name = name.replace( /[\[]/, "\\\[" ).replace( /[\]]/, "\\\]" );
let regexS = "[\\?&]" + name + "=([^&#]*)", regex = new RegExp( regexS ), results = regex
.exec( window.location.href );
if ( results == null ) {
return "";
} else {
return decodeURIComponent( results[ 1 ].replace( /\+/g, " " ) );
}
}
}
|
import { gql } from 'apollo-server-express';
export default gql`
scalar Date
type Query {
""" PAGINATION USERS ONLY ADMIN """
paginationCars(limit:Int,offset:Int):[Car]
""" TOTAL USERS FOR PAGINATION ADMIN """
totalCars:Int
}
type Mutation {
"""CREATION NEW MTTO CAR"""
newCar(car:InputCar):Car
"""CREATION NEW MTTO CAR FILE EXCEL"""
newCarFileEcxel(car:InputCar):Car
"""EDIT CAR"""
editCar(car:InputCar):Car
"""DELETE CAR"""
deleteCar(placa:String):String
}
type Car {
state:Boolean
message:String
placa:String
modelo:String
tipo:String
marca:String
propietario:String
documento:String
detalle:String
fecha:Date
imageUrl:String
}
input InputCar {
placa:String
modelo:String
tipo:String
marca:String
propietario:String
documento:String
detalle:String
fecha:Date
imageUrl:String
file:Upload
}
` ;
|
import React from 'react';
import {
AsyncStorage,
View
} from 'react-native';
import Spinner from 'react-native-loading-spinner-overlay';
import Strings from '../../src/language/fr';
import { initFolders } from '../../src/utilities/index';
export class EntryPointScreen extends React.Component {
constructor(props) {
super(props);
this._bootstrapAsync();
}
static navigationOptions = {
title: 'ENTRYPOINT',
};
_bootstrapAsync = async () => {
initFolders();
const userSession = await AsyncStorage.getItem('userSession');
const userSessionType = await AsyncStorage.getItem('userSessionType');
const adminPassword = await AsyncStorage.getItem('adminPasswordV8');
let stack = 'Auth';
if (userSession) {
// stack = 'Auth';
stack = 'StackFront';
if (userSessionType == 'admin') {
stack = 'StackAdmin';
// stack = 'Auth';
}
}
if (!adminPassword) {
stack = 'SetupAdmin';
}
setTimeout(() => {
this.props.navigation.navigate(stack, {
func: () => {
}
});
}, 1000);
};
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Spinner visible={true} textContent={Strings.LOADING} textStyle={{ color: '#FFF' }} />
</View>
);
}
}
|
// import SHOPDATA from "./shopdata";
import ShopActionTypes from "./shopType";
const INITIAL_STATE = {
collections: null,
isFetch: false,
errorMessage: undefined,
};
const shopReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case ShopActionTypes.FETCH_COLLECTIONS_START:
return {
...state,
isFetch: true,
};
case ShopActionTypes.FETCH_COLLECTIONS_SUCCESS:
return {
...state,
isFetch: false,
collections: action.payload,
};
case ShopActionTypes.FETCH_COLLECTIONS_FAIL:
return {
...state,
isFetch: false,
errorMessage: action.payload,
};
default:
return state;
}
};
export default shopReducer;
|
var cool = require('cool-ascii-faces');
window.onload = function() {
document.getElementById("cool").innerHTML = cool();
document.getElementById("quote").innerHTML = getQuote();
}
|
import {join} from 'path';
import * as oth from '../../oth';
const base = join(CONFIG_PATH, 'plugins', 'node_modules');
export default function playerParser(id) {
const {name, description} = __non_webpack_require__(join(base, id, 'package.json'));
return {
[name.slice(7)]: {
description,
interactive: false,
testCellClickable: () => false,
...__non_webpack_require__(join(base, id))(oth),
},
};
}
|
const app = getApp();
const config = require("../utils/config.js");
const requestService = require("../service/requestService.js")
/**
* 将 用户信息 存储进 本地
*/
function saveUserInfo(userInfo) {
let userInfoStr = JSON.stringify(userInfo);
try {
wx.setStorageSync(config.Key_UserInfo, userInfoStr);
} catch (e) {
}
}
/**
* 获取 本地存储 用户信息
*/
function getUserInfo() {
try {
let userInfo = JSON.parse(wx.getStorageSync(config.Key_UserInfo));
return userInfo;
} catch (e) {
return null;
}
}
/**
* 获取用户编号
*/
function getMemberNo() {
let userInfo = getUserInfo();
if (userInfo == null || userInfo.openId == null || userInfo.openId.length <= 0) {
return null;
}
return userInfo.memberNo;
}
/**
* 获取openId
*/
function getOpenId() {
let userInfo = getUserInfo();
if (userInfo == null || userInfo.openId == null || userInfo.openId.length <= 0) {
return null;
}
return userInfo.openId;
}
/**
* 根据openid判断是否登陆
*/
function isLogin() {
let openId = getOpenId();
if (openId == null) {
return false;
}
return true;
}
/**
* 登陆
*/
function login(loginCallback) {
wx.showLoading({
title: '登陆中...',
})
console.log("微信登陆")
// 登录
wx.login({
success: res => {
console.log("微信login success => " + res.code);
// 发送 res.code 到后台换取 openId, sessionKey, unionId
let wxCode = res.code;
// 查看是否授权
wx.getSetting({
success(res) {
console.log("获取授权成功")
if (res.authSetting['scope.userInfo']) {
console.log("获取 scope.userInfo 授权成功")
// 已经授权,可以直接调用 getUserInfo 获取头像昵称
wx.getUserInfo({
success(res) {
console.log("微信登陆 => \n" + JSON.stringify(res));
let userInfo = res.userInfo;
// 向服务器请求登陆,返回 本微信 在服务器状态,注册|未注册,
wx.request({
url: config.URL_Service + config.URL_Login, // 服务器地址
data: {
"code": wxCode
}, // 参数
success: res => {
console.log("success => " + JSON.stringify(res));
requestService.handlerSuccessResponse(
res,
function successCallback(resData){
let tempUserInfo = resData;
saveUserInfo(tempUserInfo);
wx.showToast({
title: '登陆成功',
})
if (loginCallback) {
loginCallback(config.Res_Code_Success, "登陆成功");
}
},
function errorCallback(msg, state){
if (loginCallback) {
loginCallback(state, msg);
}
}
)
}, // 请求成功回调 登陆成功 保存 用户信息。登陆失败,跳转注册页面
fail: res => {
console.log("fail => " + JSON.stringify(res));
requestService.handlerFailResponse();
}, // 请求失败回调,弹窗,重新请求
complete: res => {
console.log("complite => " + JSON.stringify(res));
wx.hideLoading();
}, // 请求完成回调,隐藏loading
})
}
})
} else {
wx.hideLoading();
requestService.handlerFailResponse("需要授权以提供服务!");
}
},
fail(res) {
console.log("获取授权失败");
wx.hideLoading();
requestService.handlerFailResponse("获取授权失败!");
},
complete(res) {
console.log("获取授权完成");
},
})
},
fail(res) {
console.log("微信login fail => " + JSON.stringify(res));
wx.hideLoading();
requestService.handlerFailResponse("微信登陆失败");
},
complete(res) {
console.log("微信login complete => " + JSON.stringify(res));
},
})
}
/**
* 检查是否登陆
*/
function checkLogin(alreadyLoginCallback, showAlert) {
if (isLogin()) {
if (alreadyLoginCallback) {
alreadyLoginCallback(true);
}
} else {
if (alreadyLoginCallback) {
alreadyLoginCallback(false);
}
if (showAlert) {
popLoginAlert();
}
}
}
/**
* 登陆弹窗
*/
function popLoginAlert(title, msg, loginConfirmCallback) {
wx.showModal({
title: title!=null?title:"尚未登陆",
content: msg!=null?msg:"该功能需登陆后操作",
confirmText: "前往登陆",
cancelText: "暂不登陆",
success(res){
if (res.confirm) {
if (loginConfirmCallback) {
loginConfirmCallback()
} else {
wx.reLaunch({
url: config.Page_Home,
})
}
}
}
})
}
module.exports = {
saveUserInfo: saveUserInfo,
getUserInfo: getUserInfo,
getMemberNo: getMemberNo,
getOpenId: getOpenId,
isLogin: isLogin,
login: login,
checkLogin: checkLogin,
popLoginAlert: popLoginAlert
}
|
// canvasエレメントの取得
let canvasElement = document.getElementById( 'canvas' );
// WebGL, glCubicの初期化
gl3.initGL( canvasElement );
if( !gl3.ready ) { console.log( 'initialize error' ); return; }
let gl = gl3.gl;
// canvasサイズの決定
let canvasWidth = window.innerWidth;
let canvasHeight = window.innerHeight;
canvasElement.width = canvasWidth;
canvasElement.height = canvasHeight;
// マウスの位置.各次元,0.0-1.0で格納.
let mousePosition = [ 0.0, 0.0 ];
canvasElement.addEventListener( 'mousemove', ( _event ) => {
let i = 1.0 / canvasWidth;
mousePositionP = mousePosition;
mousePosition = [
( _event.clientX - canvas.offsetLeft ) * i,
1.0 - ( _event.clientY - canvas.offsetTop ) * i
];
}, true );
// 正方形ポリゴンの生成
let quadVert = [-1,1,0,-1,-1,0,1,1,0,1,-1,0];
let quadVbo = [ gl3.create_vbo( quadVert ) ];
// シェーダプログラムの作成
let prg = gl3.program.create_from_source(
WE.vs,
WE.fs,
[ 'position' ],
[ 3 ],
[ 'resolution', 'mouse', 'time', 'textureLenna' ],
[ '2fv', '2fv', '1f', '1i' ]
);
if ( !prg ) { return; }
// テクスチャのロード
let textureNumLenna = 0;
gl3.create_texture_canvas( WE.images[ 'lenna.png' ], textureNumLenna );
gl.activeTexture( gl.TEXTURE0 );
gl.bindTexture( gl.TEXTURE_2D, gl3.textures[ 0 ].texture );
// 時間と解像度の変数の初期化
let startTime = Date.now();
let resolution = [ canvasWidth, canvasHeight ];
// ループ
let update = () => {
// 時間の更新
let nowTime = ( Date.now() - startTime ) * 0.001;
// 描画
gl.bindFramebuffer( gl.FRAMEBUFFER, null );
gl3.scene_clear( [ 0.0, 0.0, 0.0, 1.0 ] );
gl3.scene_view( null, 0, 0, canvasWidth, canvasHeight );
prg.set_program();
prg.set_attribute( quadVbo );
prg.push_shader( [ resolution, mousePosition, nowTime, textureNumLenna ] );
gl3.draw_arrays( gl.TRIANGLE_STRIP, 4 );
gl.flush();
// run状態ならループする
if ( WE.run ) { requestAnimationFrame( update ); }
};
WE.run = true;
update();
|
export const CREATE_DISCUSSION = 'CREATE_DISCUSSION';
export const UPDATE_DISCUSSION = 'UPDATE_DISCUSSION';
export const DELETE_DISCUSSION = 'DELETE_DISCUSSION';
export const FETCH_DISCUSSIONS = 'FETCH_DISCUSSIONS';
|
'use strict';
const _ = require('lodash');
module.exports = class versionAttribute {
/**
* Constructor function for this class.
*
* @param {array} pathCrumbs
* An array collection of version paths, one per member, in order.
* The path crumbs indicates from where we will try and ascend.
* @param {object} tree
* An object with version keys and possible other properties.
* @param {string} target
* A property name contained with a semver key.
*/
constructor(tree) {
try {
if (_.keys(tree).length === 0) {
throw new Error('The object with version properties is empty.');
}
this.tree = tree;
}
catch (e) {
throw new Error(e);
}
}
/**
* Function to validate our crumbs arguments.
*
* @param {array} crumbs
* An array collection of version paths, one per member, in order.
* The path crumbs indicates from where we will try and descend.
*
* @return
* A true or falsey value.
*/
crumbsValidator(crumbs) {
if ((typeof crumbs !== 'object') || (crumbs.length === 0)) {
return 'An incorrectly formatted or empty pathCrumb was provided.';
}
if (crumbs.filter(n => (!isNaN(parseInt(n, 10)))).length < crumbs.length) {
return 'An invalid path member was provided.';
}
return true;
}
/**
* Function to test if we have valid target arguments.
*
* @param {string} target
* A target property to search for in a version property object.
*
* @return
* A truth or falsey value.
*/
targetValidator(target) {
if (target === '') {
return 'You must pass a valid object key name';
}
return true;
}
/**
* Function to see if we can descend down this
* tree object from the passed path.
*
* @param {array} crumbs
* An array collection of version paths, one per member, in order.
* The path crumbs indicates from where we will try and descend.
*
* @return {array}
* The furthest descension path possible from this starting point
* as an array collection of version paths, one per member, in order.
*/
descendPath(crumbs) {
// We need to mutate and reference the original.
const tempCrumbs = _.cloneDeep(crumbs);
// The branch we will descend.
let descentPath = _.get(this.tree, tempCrumbs);
let newArray = [];
let prep = [];
let sentinel = false;
const crumbValidate = this.crumbsValidator(crumbs);
if (crumbValidate !== true) {
throw new Error(crumbValidate);
}
// Keep going until we no longer have a branch to descend.
while (descentPath) {
// Does this path have children?
// Get any keys, including non-version keys.
// Sort them, and convert the inverted keys to Ints or (NaNs).
prep = _.chain(descentPath)
.keys()
.invert()
.keysIn()
.map(i => parseInt(i, 10))
.value();
// Do we have any items?
if (prep.length > 0) {
// This particular path has properties.
// It may not have version key children though.
newArray = prep.filter((n) => {
if (isNaN(n)) {
// We don't want any NaNs.
return false;
}
// Only version keys.
return true;
});
// If Anything is left we can descend further.
if (newArray.length) {
// Add the next lowest item to the parent path
// to make a new descent path.
tempCrumbs.push(parseInt(newArray[newArray.length - 1], 10));
descentPath = _.get(this.tree, tempCrumbs);
// Make sure we know that we descended atleast once.
sentinel = true;
}
else {
break;
}
}
else {
// We only had non-version keys, we were at the furthest we could go.
break;
}
}
// If we were ever able to descend, sentinel
// is true and we can return how far we got.
// If sentinel is false no descension possible.
return sentinel ? tempCrumbs : [];
}
/**
* Function to see if we can ascend up this
* tree object from the passed path.
*
* @param {array} crumbs
* An array collection of version paths, one per member, in order.
* The path crumbs indicates from where we will try and ascend.
*
* @return {array}
* The next ascendsion path up as an array collection of
* version paths, one per member, in order.
*/
ascendPath(crumbs) {
let parentCrumbs = [];
let parent = {};
let keys = [];
let keyReturn = [];
let tempKeyReturn = [];
let i;
let item;
const crumbValidate = this.crumbsValidator(crumbs);
if (crumbValidate !== true) {
throw new Error(crumbValidate);
}
const crumbsNanTest = function NanTest(n) {
// If n is not a number, it is another kind of property.
if (isNaN(parseInt(n, 10))) {
return false;
}
// If the current item is larger or equal to pathCrumbs, we remove it.
return n >= crumbs[i];
};
for (i = crumbs.length - 1; i >= 0; i -= 1) {
// From the end to the begining, get slices at i.
parentCrumbs = _.slice(crumbs, 0, i);
parent = _.get(this.tree, parentCrumbs);
// Are we on the base value?
if (i === 0) {
// If we've gotten here, the only ascension possible is moving the base.
if (crumbs[i] === 0) {
// We can't go higher than 0, no ascension possible.
parentCrumbs = [];
break;
}
// To move the base we need parent as the tree at root.
parent = this.tree;
// We also need to specially handle non-existant keys case.
keys = _.keysIn(parent);
// Do we actually have keys higher up the tree or equal to the path?
keyReturn = _.chain(keys)
.map(_.parseInt)
.filter((n) => n <= crumbs[0])
.value();
// This a special case of special case.
if (keyReturn.length === 1 || _.without(_.drop(crumbs, 1), 0).length === 0) {
// Like Jim Morrison, we need to know if we can get much higher.
tempKeyReturn = keyReturn.filter(n => n < crumbs[0]);
if (tempKeyReturn.length > 0) {
// Yeah, we can.
parentCrumbs = [keys[_.findLastKey(keys, (n) => (
n < crumbs[0]
))]];
break;
}
// Nope, this is the paramount location. No ascendancy possible.
parentCrumbs = [];
break;
}
}
// Attempt to ascend by getting key children of the parent.
// We want to see if removing the current key, gives us any siblings.
item = _.chain(parent)
.keysIn()
.sort()
.map(ii => parseInt(ii, 10))
.without(i)
.value();
// Check to see if we are at the lowest possible level in this process.
if (i === (crumbs.length - 1)) {
// In this case we need to remove any value that is not version key.
// We also need to remove any version key that is deeper.
_.remove(item, n => crumbsNanTest(n));
}
if (item.length) {
_.remove(item, isNaN);
if (item.length > 0) {
parentCrumbs.push(item[item.length - 1]);
}
// Parent crumbs is as far as it can go, return.
break;
}
}
return parentCrumbs;
}
/**
* Function to return the next closest version number
* to the one we've passed.
*
* @param {array} crumbs
* An array collection of version paths, one per member, in order.
* The path crumbs indicates from where we will start looking.
*
* @return {array}
* The nearest path upwards, up as an array collection of
* version paths, one per member, in order.
*/
getPreviousClosestVersion(crumbs) {
let ascendPathCrumbs;
let tempPathCrumbs;
const crumbValidate = this.crumbsValidator(crumbs);
if (crumbValidate !== true) {
throw new Error(crumbValidate);
}
// Try to ascend - will give us the first real path above our target.
ascendPathCrumbs = this.ascendPath(crumbs);
if (_.isEqual(ascendPathCrumbs, [])) {
// We could not ascend we are finished.
return [];
}
// We will now try and descend.
tempPathCrumbs = _.cloneDeep(ascendPathCrumbs);
while (tempPathCrumbs.length !== 0) {
// keep going until we get a
tempPathCrumbs = this.descendPath(ascendPathCrumbs);
// Test for [].
if (tempPathCrumbs.length === 0) {
// We could not descend.
break;
}
// Test if this is pathCrumbs.
if (_.isMatch(tempPathCrumbs, crumbs)) {
// This was path crumbs.
// We should pass ascend crumbs without modification
// since modifying it will put us in an unending loop.
break;
}
// We could descend. See if we can descend again.
ascendPathCrumbs = _.clone(tempPathCrumbs, true);
}
return ascendPathCrumbs;
}
/**
* Function to return the highest path on the tree that has
* this target property.
*
* @param {array} crumbs
* An array collection of version paths, one per member, in order.
* The path crumbs indicates from where we will start looking.
* @param {string} target
* A property name contained with a semver key.
*
* @return {array}
* The path that has this target property at or above the path given
* in the tree, expressed as an array collection of version paths,
* one per member, in order.
*/
getVersionHasTarget(crumbs, target) {
const tempTargetCrumbs = _.cloneDeep(crumbs, true);
let answerArray = [];
let ascendPathCrumbs = [];
const crumbValidate = this.crumbsValidator(crumbs);
const targetValidate = this.targetValidator(target);
if (crumbValidate !== true || targetValidate !== true) {
throw new Error('You must pass valid crumbs and targets.');
}
// Lets add the target and see if it exists at this path.
tempTargetCrumbs.push(target);
const tempTarget = _.get(this.tree, tempTargetCrumbs);
if (tempTarget) {
// It does, we are done.
answerArray = _.slice(crumbs, 0, crumbs.length);
}
else {
// It does not exist, we must ascend, as we always come
// from a place of furthest descent.
ascendPathCrumbs = this.getPreviousClosestVersion(crumbs);
if (!(_.isEqual(ascendPathCrumbs, []))) {
// If we have a path we have what we need to move forward.
answerArray = this.getVersionHasTarget(ascendPathCrumbs, target);
}
}
// This means we are returning an empty answer.
return answerArray;
}
/**
* Function to check if this version exists in this object
* and return it or the nearest version upwards in the tree.
*
* @param {array} crumbs
* An array collection of version paths, one per member, in order.
* The path crumbs indicates from where we will start looking.
*
* @return {array}
* The path or nearest path upwards, up as an array collection of
* version paths, one per member, in order.
*/
getVersion(crumbs) {
const crumbValidate = this.crumbsValidator(crumbs);
if (crumbValidate !== true) {
throw new Error(crumbValidate);
}
const tempTarget = _.get(this.tree, crumbs);
if (tempTarget) {
return crumbs;
}
return this.getPreviousClosestVersion(crumbs);
}
/**
* Returns the value of a property for a given object with semver type
* property organization.
*
* @param {array} pathCrumbs
* An array corresponding to a semver [1,0,1]
* @param {string} target
* A property name contained with a semver key.
*
* @return
* The value of the property for that semver.
*/
getVersionAttribute(crumbs, target) {
let targetItem = {};
const crumbValidate = this.crumbsValidator(crumbs);
const targetValidate = this.targetValidator(target);
if (crumbValidate !== true || targetValidate !== true) {
throw new Error('You must pass valid crumbs and targets.');
}
const attributePath = this.getVersionHasTarget(crumbs, target);
if ((typeof attributePath === 'object') && attributePath.length) {
attributePath.push(target);
targetItem = _.get(this.tree, attributePath);
}
return targetItem;
}
};
|
define([
'facebook',
'jquery',
'class/base/BaseObject',
'class/base/GameDefine',
'class/base/GameLog'
], function(facebook,jquery,BaseObject,DEFINE,Log) {
if (typeof createjs === 'undefined' ) {
createjs = window.createjs;
}
var _facebook_instance = null;
function FacebookNetwork() {
this.type="facebook";
this.scope = 'installed,publish_actions,publish_stream,manage_pages,create_event',
this._accesslist = [];
this._loggedin = false;
this._initalized = false;
this._hasAllPermission = false;
this._grantedPermission = [];
this._appid ="";
_facebook_instance = this;
}
var p = createjs.extend(FacebookNetwork, BaseObject);
p.IsInitalized = function(){
return this._initalized;
} ;
p.Initalize = function(data,caller,cb){
FB.init({
appId : data.appid,
xfbml : true,
version : 'v2.1'
});
this._appid = data.appid;
var context = this;
FB.getLoginStatus(this._onLoginResponse);
FB.Event.subscribe('auth.authResponseChange', this._onAuthChange);
this._initalized = true;
cb(DEFINE.OPERATION_RESULT.SUCCESS,{},caller);
} ;
p.IsLoggedIn = function(){
return this._loggedin;
} ;
p.Login = function(data,caller,cb){
var context = this;
FB.login(function(response){
if(response.status == 'connected'){
context._loggedin = true;
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
cb(DEFINE.OPERATION_RESULT.SUCCESS,user_id,caller);
}
} else if (response.status === 'not_authorized') {
cb(DEFINE.OPERATION_RESULT.FAILED,"",caller);
} else {
cb(DEFINE.OPERATION_RESULT.FAILED,"",caller);
}
} ,{scope: this._scope});
} ;
p.likepage = function(pageid,_func){
return false;
} ;
p._onAuthChange = function(response) {
var context = _facebook_instance;
if(response.status == "connected"){
//we need use accesstoken to exchange the page accesstoken
context._loggedin = true;
$.ajax({
url: "https://graph.facebook.com/me/accounts?access_token="+response.authResponse.accessToken,
context: context,
dataType:"json"
}).done(function(res) {
this._accesslist = res.data;
});
}
} ;
createjs.FacebookNetwork = createjs.promote(FacebookNetwork, "BaseObject");
return FacebookNetwork;
});
|
import {LOCATION_CHANGE} from 'react-router-redux';
import {del, get} from '../../../utils/http';
import {REDUCERS_GROUP_PREFIX, ENDPOINT_USERS} from './constants';
import {addErrorToast, addSuccessToast} from '../../../utils/notifications';
const REDUCER_NAME = `${REDUCERS_GROUP_PREFIX}/user`;
const GET_USER_SUCCESS = `${REDUCER_NAME}/GET_USER_SUCCESS`;
const GET_USER_ERROR = `${REDUCER_NAME}/GET_USER_ERROR`;
const CHANGE_DELETE_USER_MODAL_VISIBILITY = `${REDUCER_NAME}/CHANGE_DELETE_USER_MODAL_VISIBILITY`;
const DELETE_USER_SUCCESS = `${REDUCER_NAME}/DELETE_USER_SUCCESS`;
const DELETE_USER_ERROR = `${REDUCER_NAME}/DELETE_USER_ERROR`;
const initState = {
info: {
email: '',
name: '',
gender: '',
avatar: '',
createdAt: 0,
updatedAt: 0
},
error: null,
errorCode: null,
deleteUserModalOpened: false,
deleted: false,
errorDeleteUser: null,
loading: true
};
export default (state = initState, action) => {
switch (action.type) {
case GET_USER_SUCCESS:
return {...state, info: action.response, loading: false, deleted: false};
case GET_USER_ERROR:
return {...initState, error: action.error, loading: false};
case CHANGE_DELETE_USER_MODAL_VISIBILITY:
return {...state, deleteUserModalOpened: action.visible};
case DELETE_USER_SUCCESS:
return {...initState, deleted: true};
case DELETE_USER_ERROR:
return {...state, errorDeleteUser: action.error};
case LOCATION_CHANGE:
return initState;
default:
return state;
}
};
export const getUser = id => {
return dispatch => {
get(`${ENDPOINT_USERS}/${id}`, null, null).then(response => {
dispatch({type: GET_USER_SUCCESS, response: response});
}).catch(response => {
dispatch({type: GET_USER_ERROR, error: response.message});
});
}
};
export const openDeleteUserModal = () => {
return {type: CHANGE_DELETE_USER_MODAL_VISIBILITY, visible: true};
};
export const closeDeleteUserModal = () => {
return {type: CHANGE_DELETE_USER_MODAL_VISIBILITY, visible: false};
};
export const deleteUser = id => {
return dispatch => {
del(`${ENDPOINT_USERS}/${id}`, null, null).then(response => {
dispatch({type: DELETE_USER_SUCCESS});
addSuccessToast(response.message);
}).catch(response => {
dispatch({type: DELETE_USER_ERROR, error: response.message});
addErrorToast(response.message);
});
}
};
|
import Head from 'next/head'
import Layout from '../../components/Layout'
import Link from 'next/link'
import styles from '../../components/styles/Contact.module.css'
export default function Contact() {
return (
<Layout>
<Head>
<title>TokyamaShouta|Contact</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<h1 className={styles.myProfile}>Contact</h1>
<h2 className={styles.myContact}>ご連絡はTwitterのDMでお願い致します。</h2>
<div className={styles.myContact1}>
<a href="#" target="_blank">
<img src="/img/twiiter1.jpg" alt="Twitter"/>
</a>
<a href="https://github.com/tokuyama-shouta" target="_blank">
<img src="/img/github.png" alt="GitHub"/>
</a>
</div>
<div className={styles.soccerAnimation}>
<img src="/img/soccer1.jpg" alt="サッカーボール"/>
</div>
<div className={styles.btnBox}>
<Link href="/">
<button className={styles.btnStyle}>Back to Home</button>
</Link>
</div>
</Layout>
)
}
|
import "../libs/csap-modules.js";
import { _dialogs, _dom, _utils, _net } from "../utils/all-utils.js";
_dom.onReady( function () {
let appScope = new db_stats_report();
appScope.initialize();
} );
function db_stats_report() {
_dom.logHead( "Main module" );
this.initialize = function () {
console.log( "Init in stats" );
$( '#dbSelect' ).change( function () {
loadAll();
} );
$( '#primaryStepDown' ).click( function () {
$.getJSON( api + "/admin/replicaStepDown", {
} )
.done( function ( loadJson ) {
alertify.notify( "result" + JSON.stringify( loadJson, null, "\t" ) );
setTimeout( function () {
loadAll();
}, 500 );
} );
} );
$( '#colSelect' ).change( function () {
loadCollectionStats();
} );
loadAll();
};
function loadAll() {
$( "tbody" ).html( $( "#loadingTemplate" ).html() );
//loadDbNames().done(loadCollectionNames);
$.when( loadDbNames() ).then( loadCollectionNames ).then( loadDbStats ).then( loadCollectionStats );
loadMongoOptions();
}
// function loadCollectionNameDbStatsAndCollectionStats() {
// $.when( loadCollectionNames() ).then( loadDbStats ).then( loadCollectionStats );
// }
function loadDbStats() {
$( 'body' ).css( 'cursor', 'wait' );
var r = $.Deferred();
$.getJSON( api + "/admin/dbStatus", {
"dbname": $( '#dbSelect' ).val()
} )
.done( function ( loadJson ) {
loadDbStatsSuccess( loadJson );
} );
setTimeout( function () {
console.log( 'loading db stats done' );
r.resolve();
}, 500 );
return r;
}
function loadCollectionStats() {
$( 'body' ).css( 'cursor', 'wait' );
$( "#collStatusBody" ).html( $( "#loadingTemplate" ).html() );
var r = $.Deferred();
$.getJSON( api + "/admin/collStatus", {
"dbname": $( '#dbSelect' ).val(),
"collName": $( '#colSelect' ).val()
} )
.done( function ( loadJson ) {
loadCollectionStatsSuccess( loadJson );
} );
setTimeout( function () {
console.log( 'loading coll stats done' );
r.resolve();
}, 500 );
return r;
}
function loadCollectionNames() {
var r = $.Deferred();
$.getJSON( api + "/admin/colls", {
"dbname": $( '#dbSelect' ).val()
} )
.done( function ( loadJson ) {
loadCollectionNameSuccess( loadJson );
} );
setTimeout( function () {
console.log( 'loading coll done' );
r.resolve();
}, 500 );
return r;
}
function loadDbNames() {
var r = $.Deferred();
$.ajax( {
url: api + "/admin/dbs",
dataType: 'json',
async: false,
success: function ( loadJson ) {
loadDbNameSuccess( loadJson );
}
} );
/*
$.getJSON("api/admin/dbs", {
})
.success(function(loadJson) {
loadDbNameSuccess(loadJson);
});
*/
setTimeout( function () {
console.log( 'loading dbs done' );
r.resolve();
}, 500 );
return r.promise();
}
function loadMongoOptions() {
$.getJSON( api + "/admin/mongoOptions", {
} )
.done( function ( loadJson ) {
loadMongoOptionsSuccess( loadJson );
} );
}
function loadDbNameSuccess( dataJson ) {
$( '#dbSelect' ).empty();
for ( var i = 0; i < dataJson.length; i++ ) {
//
var optionContent;
if ( dataJson[ i ] == 'event' ) {
optionContent = '<option selected="selected" value="' + dataJson[ i ] + '">' + dataJson[ i ] + '</option>';
} else {
optionContent = '<option value="' + dataJson[ i ] + '">' + dataJson[ i ] + '</option>';
}
$( '#dbSelect' ).append( optionContent );
}
}
function loadCollectionNameSuccess( dataJson ) {
$( '#colSelect' ).empty();
for ( var i = 0; i < dataJson.length; i++ ) {
var optionContent;
optionContent = '<option value="' + dataJson[ i ] + '">' + dataJson[ i ] + '</option>';
$( '#colSelect' ).append( optionContent );
}
}
function loadDbStatsSuccess( dataJson ) {
$( '#dbName' ).empty();
$( '#dbName' ).append( '( ' + $( '#dbSelect' ).val() + ' )' );
updateTable( dataJson, "dbStatusTable", "dbStatusBody" );
}
function loadCollectionStatsSuccess( dataJson ) {
$( '#collectionName' ).empty();
$( '#collectionName' ).append( '( ' + $( '#colSelect' ).val() + ' )' );
updateTable( dataJson, "collStatusTable", "collStatusBody" );
}
function updateTable( dataJson, tableId, tableBodyId ) {
$( "#" + tableBodyId ).empty();
var primaryServer;
var secondaryServer;
for ( var i = 0; i < dataJson.length; i++ ) {
if ( dataJson[ i ].key == 'serverUsed' ) {
primaryServer = dataJson[ i ].primaryValue;
secondaryServer = dataJson[ i ].secondaryValue;
}
var collStatusTrContent = '<td style="font-size: 1.0em" > ' + getKey( dataJson[ i ].key ) + '</td>' +
'<td style="font-size: 1.0em" > <div>' + statusCheck( dataJson, i ) + convertSizeToMB( dataJson[ i ].key, dataJson[ i ].primaryValue ) + '</div></td>' +
'<td style="font-size: 1.0em" > <div>' + statusCheck( dataJson, i ) + convertSizeToMB( dataJson[ i ].key, dataJson[ i ].secondaryValue ) + '</div></td>'
;
var collStatusTr = $( '<tr />', {
'class': "",
html: collStatusTrContent
} );
$( '#' + tableBodyId ).append( collStatusTr );
}
addResturl( primaryServer, secondaryServer, tableId, tableBodyId );
$( "#" + tableId ).trigger( "update" );
$( 'body' ).css( 'cursor', 'default' );
}
function statusCheck( dataJson, counter ) {
var statusImage = "";
if ( dataJson[ counter ].key == 'collections' || dataJson[ counter ].key == 'count' ) {
if ( dataJson[ counter ].primaryValue == dataJson[ counter ].secondaryValue ) {
statusImage = '<img src="images/correct.gif">';
} else {
statusImage = '<img src="images/warning.png">';
}
}
return statusImage;
}
function getKey( key ) {
if ( key.endsWith( 'Size' ) ) {
return key + '( MB )';
} else {
return key;
}
}
function convertSizeToMB( key, size ) {
var convertedSize = size;
if ( key.endsWith( 'Size' ) ) {
var sizeInMB = ( size / ( 1024 * 1024 ) );
convertedSize = precise_round( sizeInMB, 2 );
}
return convertedSize;
}
function precise_round( value, decPlaces ) {
var val = value * Math.pow( 10, decPlaces );
var fraction = ( Math.round( ( val - parseInt( val ) ) * 10 ) / 10 );
if ( fraction == -0.5 )
fraction = -0.6;
val = Math.round( parseInt( val ) + fraction ) / Math.pow( 10, decPlaces );
return val;
}
function addResturl( primaryServer, secondaryServer, tableId, tableBodyId ) {
var collStatusTrContent = '<td style="font-size: 1.0em" > ' + 'Mongo Rest Interface' + '</td>' +
'<td style="font-size: 1.0em" > <a target="_blank" href="' + getRestUrl( primaryServer ) + '">' + "Click Here" + '</td>' +
'<td style="font-size: 1.0em" > <a target="_blank" href="' + getRestUrl( secondaryServer ) + '">' + "Click Here" + '</td>'
;
var collStatusTr = $( '<tr />', {
'class': "",
html: collStatusTrContent
} );
$( '#' + tableBodyId ).append( collStatusTr );
}
function getRestUrl( serverUsed ) {
var urlarr = serverUsed.split( "/" );
if ( urlarr.length == 1 )
urlarr = serverUsed.split( ":" );
return "http://" + urlarr[ 0 ] + ":28017";
}
function loadMongoOptionsSuccess( dataJson ) {
$( "#mongoOptionsBody" ).empty();
updateDriverInfo( dataJson );
for ( var key in dataJson.mongoOptions ) {
//console.log(key + "-->"+dataJson.mongoOptions[key] );
var mongoOptionsTrContent = '<td style="font-size: 1.0em" > ' + key + '</td>' +
'<td style="font-size: 1.0em" > ' + JSON.stringify( dataJson.mongoOptions[ key ] ) + '</td>'
;
var mongoOptionsTr = $( '<tr />', {
'class': "",
html: mongoOptionsTrContent
} );
$( '#mongoOptionsBody' ).append( mongoOptionsTr );
}
$( "#mongoOptionsTable" ).trigger( "update" );
$( 'body' ).css( 'cursor', 'default' );
}
function updateDriverInfo( dataJson ) {
var mongoOptionsTrContent = '<td style="font-size: 1.0em" > ' + 'Java Driver Version' + '</td>' +
'<td style="font-size: 1.0em" > ' + dataJson.driverInfo + '</td>'
;
var mongoOptionsTr = $( '<tr />', {
'class': "",
html: mongoOptionsTrContent
} );
$( '#mongoOptionsBody' ).append( mongoOptionsTr );
}
}
|
// alert
export const SET_ALERT = "SET_ALERT";
export const REMOVE_ALERT = "REMOVE_ALERT";
// registration
export const REGISTER_SUCCESS = "REGISTER_SUCCESS";
export const REGISTER_FAIL = "REGISTER_FAIL";
// authentication
export const USER_LOADED = "USER_LOADED";
export const AUTH_ERROR = "AUTH_ERROR";
// login
export const LOGIN_SUCCESS = "LOGIN_SUCCESS";
export const LOGIN_FAIL = "LOGIN_FAIL";
// logout
export const LOGOUT = "LOGOUT";
// get profile
export const GET_PROFILE = "GET_PROFILE";
export const GET_PROFILES = "GET_PROFILES";
export const GET_REPOS = "GET_REPOS";
export const PROFILE_ERROR = "PROFILE_ERROR";
// clear profile
export const CLEAR_PROFILE = "CLEAR_PROFILE";
// update profile
export const UPDATE_PROFILE = "UPDATE_PROFILE";
export const GET_EXPERIENCE = "GET_EXPERIENCE";
export const GET_EDUCATION = "GET_EDUCATION";
// update experience in profile
export const UPDATE_EXPERIENCE = "UPDATE_EXPERIENCE";
// update education in profile
export const UPDATE_EDUCATION = "UPDATE_EDUCATION";
// Delete Account
export const ACCOUNT_DELETED = "ACCOUNT_DELETED";
// posts
export const GET_POSTS = "GET_POSTS";
export const GET_POST = "GET_POST";
export const ADD_POST = "ADD_POST";
export const DELETE_POST = "DELETE_POST";
export const POST_ERROR = "POST_ERROR";
// likes
export const UPDATE_LIKES = "UPDATE_LIKES";
// comments
export const ADD_COMMENT = "ADD_COMMENT";
export const REMOVE_COMMENT = "REMOVE_COMMENT";
|
import React from 'react';
import API from '../../utils/api'
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: ""
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event){
const {name, value} = event.target
this.setState({
[name]: value
})
}
handleSubmit(event){
event.preventDefault()
API.login(this.state.email, this.state.password)
}
render (){return (
<div className="container">
<form>
<div class="form-group">
<label for="exampleInputEmail1">Email address: </label>
<input type="username" class="form-control" onChange={this.handleChange} value={this.state.email} id="exampleInputEmail1" name='email' aria-describedby="emailHelp"></input>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password: </label>
<input type="password" class="form-control" onChange={this.handleChange} value={this.state.password} name='password' id="exampleInputPassword1"></input>
<small id="emailHelp" class="form-text text-muted">We'll never share your password with anyone else.</small>
</div>
<button type="submit" onSubmit={this.handleSubmit} class="btn btn-primary">Login</button>
</form>
</div>
)
}
}
export default Form;
|
// @flow
import React from 'react'
import {Match, Redirect} from 'react-router'
import {curry, find} from 'ramda'
import Header from '../header/Header'
import NavBar from '../navbar/Navbar'
import {fullName} from '../../util/user'
import {Tabs, Tab, TabPane} from '../tabs/Tabs'
import {Slider, Slide} from '../slider/Slider'
import VisitorProfileOverview from './VisitorProfileOverview'
import type {Visitor} from '../../Model.js'
type Props = {
visitors: Visitor[],
visitorid: string,
dispatch: Function
}
export default (props:Props) => {
const {visitors, dispatch, visitorid} = props
const visitor = find(x => x.id === visitorid, props.visitors) || {}
const {user, car} = visitor;
const {hash} = location
return (
<div className="flex-column">
<Match pattern="/visitors/:id" exactly render ={()=> <Redirect to={`/visitors/${visitor.id}#overview`}/>}/>
<Header title="Profile"/>
<Tabs hash={hash}>
<Tab href="#overview">overview</Tab>
<Tab href="#timeline">timeline</Tab>
<TabPane href="#overview"></TabPane>
<TabPane href="#timeline"></TabPane>
</Tabs>
<div className="flex-grow-1 scroll-y">
<Slider hash={hash}>
<Slide href="#overview">{VisitorProfileOverview(dispatch, {visitor})}</Slide>
</Slider>
</div>
{NavBar({dispatch, location})}
</div>
)
}
|
import React from "react";
import Avatar from "../../Navigation/TicketsList/Ticket/Avatar/Avatar";
import s from "./Owner.module.css";
const Owner = (props) => {
return (
<div className={s.owner}>
<div className={s.ownerTitleBlock}>
<p className={s.ownerTitle}>Owner</p>
</div>
<div className={s.ownerDetails}>
<Avatar source={props.source} />
<div>
<p
className={s.ownerName}
>{`${props.firstName} ${props.lastName}`}</p>
<p className={`${s.ownerName} ${s.ownerSpec}`}>
{props.specialities}
</p>
</div>
</div>
</div>
);
};
export default Owner;
|
import React from "react";
const HomePackageCardSwiz = props => {
return (
<div className="cardMain">
<div className="cardMain_side cardMain_side--front">
<div className="cardMain_picture cardMain_picture">
<img
className="cardMain_picture cardMain_picture"
src={props.image}
alt="product"
/>
</div>
<h4 className="cardMain_heading">
<span className="cardMain_heading-span cardMain_heading-span">
{props.homePakHead}
</span>
</h4>
<div className="cardMain_details">
<ul>
<li>{props.text6}</li>
<li>{props.text7}</li>
<li>{props.text8}</li>
<li>{props.text9}</li>
<li>{props.text10}</li>
<li>{props.text11}</li>
</ul>
</div>
</div>
<div className="cardMain_side cardMain_side--back cardMain_side--back">
<div className="cardMain_cta">
<div className="card_price-box">
<p className="class cardMain_price-only">
{props.homePakPriceBoxOnly}
</p>
<p className="class cardMain_price-value">
{props.homePakPriceBoxValue}
</p>
</div>
<a href="#popup" className="btn btn-white">
{props.homePakButton}
</a>
</div>
</div>
</div>
);
};
export default HomePackageCardSwiz;
|
import React from "react"
class User extends React.Component {
constructor(props){
super(props)
}
componentDidMount(){
document.getElementById("header").style.display = "block";
document.getElementById("footer").style.display = "block";
}
render(){
return (
<div>个人中心</div>
)
}
}
export default User;
|
//At bubble sort algorithm we have a time error. This algorithm can sort 37 000(max) elements for around 4 sec.
//At quick sort algorithm we have a memory error and can't search the maximum of elements
//This algorithm can sort 2 850 000 elements for around 1 sec.
//На пузырьковой упирается в ограничение по времени, максимум сортирует 37 000 элементов (тратит около 4 сек)
//При тесте алгоритма быстрой сортировки мы упираемся в ограничение по памяти и максимум элементов, которые удалось
//отсорировать - 2 850 000 элементов приблизительно за 1 секунду.
//При всём прочем данный алгоритм быстрой сортировки в отличие от распространенных вариантов не использует дополнительных массивов,
//а производит все перестановки в начальном массиве, соответственно не использует дополнительной памяти.
//Разбиение на сортируемые части в начале функции происходит случайным образом, чтобы функция также эффективно сортировала почти отсортированные массивы.
//Функция получения рандомного числа в заданных пределах
//The function that give us a random integer between min and max value
const getRandomInt = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
//функция быстрой ортировки на месте
//The function of quick sort in place (without any additional arrays)
const quicksort3 = (array) => {
let a=1;
let b=1;
let l=0;
let r=array.length;
if (r<2) {
return array;}
let x=getRandomInt(l,r-1);
let pivot=[array[x]];
array[x]=array[l];
array[l]=pivot[0];
for (let i = 1; i < r; i++) {
if (array[i]<pivot[0]) {
let t=array[i];
array[i]=array[a];
array[a]=t;
a+=1;}
else if (array[i]===pivot[0]) {
array[i]=array[a];
array[a]=array[b];
array[b]=pivot[0];
a+=1;
b+=1;} }
let less=array.slice(b,a);
let greater=array.slice(a,r);
pivot=pivot.concat(array.slice(1,b));
end=quicksort3(less).concat(pivot,quicksort3(greater));
return end;
}
//bubblesort function for comparison
//функция пузырьковой сортировки для сравнения
const bubbleSortMinToMax = (array) => {
let length = array.length;
if (length < 2) {
return array;}
let counter = 1;
while (counter > 0) {
counter = 0;
for (let i = 1; i < length; i++) {
if (array[i] < array[i-1]) {
let temp = array[i];
array[i] = array[i-1];
array[i-1] = temp;
counter += 1;
}
}
}
return array;
}
//Тест Test
const test = (array) => {
let length = array.length;
if (length === 0) {
return 'Empty array';}
else if (length === 1) {
return 'success';}
else {
for (let i = 1; i < length; i++) {
if (array[i] < array[i-i]) {
return `Error at position ${i} in array ${array}`;}}}
return 'success';}
let array = [];
let numbers = 2000000;
for (let i = 0; i<numbers; i++) {
array.push(getRandomInt(1,100));
}
console.log(test(quicksort3(array)));
|
// @flow
import * as React from 'react';
import { connect } from 'react-redux';
import { select } from './store/select';
import { type ChatUser } from './types';
type CP = {
connected: boolean,
viewer: ChatUser,
};
type Props = {
children(CP): React.Node,
};
type State = {};
class Renderer extends React.Component<Props & CP, State> {
render() {
return this.props.connected ? this.props.children(this.props) : null;
}
}
const mapState = (state, props) => ({
connected: select.connected(state),
viewer: select.viewer(state),
channels: select.channels(state),
});
export const ConnectionGate = connect(mapState)(Renderer);
|
import React, {useRef, useState, useEffect} from 'react';
import {View, Text, StyleSheet} from 'react-native';
import {connect} from 'react-redux';
import Animated, {
interpolate,
useCode,
cond,
eq,
set,
SpringUtils,
} from 'react-native-reanimated';
import {
percentage,
SCREEN_HEIGHT,
numberSize,
info,
SCREEN_WIDTH,
} from '../../Variables';
import {withSpringTransition, delay} from 'react-native-redash';
const dImg = require('../images/angryb.png');
import {playerData} from '../store/actions/playerAction';
function TopPlayer({animeoneAnime, playerData, myplayer}) {
const topTrans = useRef(new Animated.Value(0));
const topTrans1 = useRef(new Animated.Value(0));
const imgWidth = percentage(SCREEN_WIDTH, 40);
const imgHeight = percentage(SCREEN_HEIGHT, 55);
const MiddleHeight = percentage(SCREEN_HEIGHT, 70);
const boxesHeight = percentage(SCREEN_HEIGHT, 45);
const scaleLogo = interpolate(animeoneAnime, {
inputRange: [0, 1],
outputRange: [0, 1],
});
const sty1Anime = withSpringTransition(topTrans.current, {
...SpringUtils.makeDefaultConfig(),
overshootClamping: true,
damping: new Animated.Value(20),
});
const sty2Anime = withSpringTransition(topTrans1.current, {
...SpringUtils.makeDefaultConfig(),
overshootClamping: true,
damping: new Animated.Value(20),
});
const sTY2 = interpolate(sty1Anime, {
inputRange: [0, 1],
outputRange: [120, 140],
});
const sTY3 = interpolate(sty2Anime, {
inputRange: [0, 1],
outputRange: [130, 160],
});
useCode(() => [
cond(eq(topTrans.current, 0), [delay(set(topTrans.current, 1), 300)]),
cond(eq(topTrans1.current, 0), [delay(set(topTrans1.current, 1), 400)]),
]);
const [player, setPlayer] = useState([]);
useEffect(() => {
playerData().then(() => {});
}, [player]);
const showImage = player =>
player !== null ? (
<Animated.Image
style={{
width: 300,
height: 300,
resizeMode: 'contain',
}}
source={{uri: player[0].data.segments[1].metadata.imageUrl}}
/>
) : (
<Animated.Image
style={{
width: 300,
height: 300,
resizeMode: 'contain',
}}
source={dImg}
/>
);
const showInfo = player => (
<View
style={{
position: 'absolute',
width: '100%',
height: boxesHeight,
backgroundColor: '#FEFEFE',
translateY: 120,
overflow: 'hidden',
borderRadius: 30,
zIndex: 3,
alignItems: 'center',
justifyContent: 'flex-end',
flex: 1,
}}>
<View
style={{
display: 'flex',
flexDirection: 'row',
justifyContent: 'flex-end',
}}>
<View
style={{
paddingBottom: 15,
flex: 1,
paddingHorizontal: 15,
}}>
<View
style={{
width: 100,
height: 40,
marginTop: 7,
flexDirection: 'row',
alignItems: 'center',
}}>
<Text style={{...info}}>
{player !== null
? player[0].data.platformInfo.platformSlug
: 'xbox'}
</Text>
</View>
<Text
style={{
fontSize: numberSize / 5,
color: '#777B89',
fontFamily: 'Segoe UI',
marginTop: 7,
textTransform: 'uppercase',
fontWeight: '700',
}}>
{player !== null
? player[0].data.metadata.activeLegend
: 'Angry Birds'}
</Text>
<Text
style={{
fontSize: numberSize / 2.8,
fontFamily: 'Segoe UI Bold',
color: '#3F455A',
marginTop: 7,
textTransform: 'lowercase',
fontWeight: '900',
}}>
{player !== null
? player[0].data.platformInfo.platformUserId
: 'Bird Red'}
</Text>
</View>
<View
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-end',
paddingBottom: 20,
paddingRight: 20,
}}>
<Text
style={{
fontSize: numberSize / 3,
fontWeight: '900',
color: '#F2F4F6',
}}>
#{player !== null
? player[0].data.segments[0].stats.rankScore.rank
: '1234'}
</Text>
</View>
</View>
</View>
);
return (
<View
style={{
height: MiddleHeight,
alignItems: 'center',
overflow: 'hidden',
paddingVertical: 5,
flex: 1,
}}>
<View
style={{
width: '100%',
zIndex: 4,
flex: 1,
}}>
<Animated.View
style={{
justifyContent: 'center',
alignItems: 'center',
transform: [{scale: scaleLogo}],
position: 'absolute',
transform: [
{
translateX: imgWidth / 7,
translateY: imgHeight / 10,
},
],
}}>
{showImage(myplayer.myplayer)}
</Animated.View>
</View>
{showInfo(myplayer.myplayer)}
<Animated.View
style={{
position: 'absolute',
width: '92%',
height: boxesHeight,
backgroundColor: '#FDE2E3',
borderRadius: 30,
zIndex: 2,
transform: [{translateY: sTY2}],
}}
/>
<Animated.View
style={{
position: 'absolute',
width: '82%',
height: boxesHeight,
backgroundColor: '#FBD6D5',
borderRadius: 30,
transform: [{translateY: sTY3}],
}}
/>
</View>
);
}
const styles = StyleSheet.create({});
TopPlayer.propTypes = {};
const mapStatToProps = state => ({
myplayer: state.player,
});
export default connect(
mapStatToProps,
{playerData},
)(TopPlayer);
|
import React, { Component, PropTypes } from 'react';
import { findDOMNode } from 'react-dom';
import styles from './styles.scss';
export class ListAnimation extends Component {
static propTypes = {
shouldAnimateForward: PropTypes.bool.isRequired
};
get tableHeaderClassName () {
return `${styles.row} ${styles.tableHeader}`;
}
render () {
return (
<div className={styles.containerBlue}>
<table className={styles.table}>
<tr className={this.tableHeaderClassName}>
<th className={styles.column}>Type</th>
<th className={styles.column}>Author</th>
</tr>
<tr className={styles.row}>
<th className={styles.column}>Alert</th>
<th className={styles.column}>Jerry</th>
</tr>
<tr className={styles.row}>
<th className={styles.column}>Warning</th>
<th className={styles.column}>Shayla</th>
</tr>
<tr className={styles.row}>
<th className={styles.column}>Warning</th>
<th className={styles.column}>Barret</th>
</tr>
</table>
</div>
);
}
}
export default ListAnimation;
|
/**
* @version 1.0
* @author Andrea Maranesi
*/
(function ($) {
/**
* defines the jQuery function name
* @type {string}
*/
const name = "drMouseShadow";
/**
* defines the borderColor of the bubble cursor
* @type {string}
*/
const color = "red";
/**
* defines the backgroundColor of the bubble cursor
* @type {string}
*/
const backgroundColor = "transparent";
/**
* defines the radius of the bubble cursor
* @type {number}
*/
const radius = 5;
/**
* defines the borderSize of the bubble
* @type {number}
*/
const size = 2;
/**
* defines the opacity of the bubble
* @type {number}
*/
const opacity = 1;
/**
* when an element is set as a target, defines how much it should stretch
* @type {number}
*/
const elasticFactor = 1.7;
/**
* the css selector of the element that should follow the mouse cursor when the user is hover it's parent
* @type {string}
*/
const targetElementSelector = "#targetId";
/**
* it will contains all the plugin settings
*/
let settings;
/**
* the id of the html element that will be used to create the "Bubble pointer"
* @type {string}
*/
const id = "dr_mouse_circle";
/**
* if true, it will allows this plugin to stretch a specific element
* @type {boolean}
*/
const expand = true;
let target;
let offsetLeft, offsetTop;
function px(double) {
return double + "px";
}
function transform(x, y) {
return "translateX(" + x + "px) translateY(" + y + "px)";
}
/**
* given a map, iterates it until it finds a match
* @param target
* @param map
* @returns undefined or the value of the index of the map
*/
function checkElement(target, map) {
if (Array.isArray(map)) {
for (const element of map)
if ($(element).is(target)) return true;
return undefined;
}
for (const [key, value] of Object.entries(map))
if ($(key).is(target)) return value;
return map["default"] ?? undefined;
}
/**
*
*
* @param x mouse position respect the window
* @param y mouse position respect the window
* @param element it's the bubble cursor div
*/
function elasticBox(x, y, element) {
if (target !== undefined) {
let width = parseFloat(target.width());
let height = parseFloat(target.height());
let centerX = offsetLeft + width / 2;
let centerY = offsetTop + height / 2;
let diffX = x - centerX;
let diffY = y - centerY;
let elasticFactor = settings.elasticFactor;
let endX = Math.abs(diffX * 2) / width;
let endY = Math.abs(diffY * 2) / height;
let top = diffY / elasticFactor;
let left = diffX / elasticFactor;
target.css({
transform: transform(left, top)
});
let targetElementSelector = settings.targetElementSelector;
target.find(targetElementSelector).css({
pointerEvents: "none",
marginLeft: px(-left),
marginTop: px(-top)
});
let elementWidth = width / 1.5;
let elementHeight = height / 1.5;
let elementLeft =
x -
elementWidth / 2 -
(diffX / Math.abs(diffX)) * ((endX * elementWidth) / 2.2);
let elementTop =
y -
elementHeight / 2 -
(diffY / Math.abs(diffY)) * ((endY * elementHeight) / 2.2);
element.css({
width: px(elementWidth),
height: px(elementHeight),
transform: transform(elementLeft, elementTop)
});
}
}
/**
* defines what happens when the user is hover the interested area
* @param body
*/
function onMouseMove(body) {
$(body).on("mousemove", function (e) {
let x = e.pageX;
let y = e.pageY;
let color = checkElement($(e.target), settings.color);
let backgroundColor = checkElement($(e.target), settings.backgroundColor);
let opacity = checkElement($(e.target), settings.opacity);
let size = checkElement($(e.target), settings.size);
let radius = checkElement($(e.target), settings.radius);
let onHover = checkElement($(e.target), settings.onHover);
let element = $("#" + settings.id);
if (onHover !== undefined) {
element.find(onHover).css("opacity", 1);
} else element.find(":visible").css("opacity", 0);
let expand = settings.expand;
let isTargetElement = checkElement($(e.target), settings.targets) === true;
if (!isTargetElement) {
if (target !== undefined) {
target.css({
transform: "none"
});
target.find(settings.targetElementSelector).css({
marginLeft: 0,
marginTop: 0
});
target = undefined;
}
expand = false;
}
element.css({
borderWidth: size,
borderColor: color,
opacity: opacity,
background: backgroundColor
});
elasticBox(x, y, element);
if (!expand)
element.css({
borderRadius: "100%",
width: px(radius),
height: px(radius),
transform: transform(x - radius / 2, y - radius / 2)
});
else if (target === undefined) {
target = $(e.target);
let width = parseFloat(target.width());
let height = parseFloat(target.height());
let offset = target.offset();
offsetLeft = offset.left;
offsetTop = offset.top;
let topLeft = target.css("borderTopLeftRadius");
let topRight = target.css("borderTopRightRadius");
let bottomRight = target.css("borderBottomRightRadius");
let bottomLeft = target.css("borderBottomLeftRadius");
element.css({
borderBottomLeftRadius: bottomLeft,
borderBottomRightRadius: bottomRight,
borderTopLeftRadius: topLeft,
borderTopRightRadius: topRight,
width: px(width),
height: px(height)
});
}
});
}
$.fn[name] = function (options) {
settings = $.extend(
{
color: {
default: color
},
backgroundColor: {
default: backgroundColor
},
size: {
default: size
},
radius: {
default: radius
},
id: id,
expand: expand,
opacity: {
default: opacity
},
onHover: {
default: undefined
},
targets: ["#menu"],
elasticFactor: elasticFactor,
targetElementSelector: targetElementSelector
},
options
);
onMouseMove(this);
return this;
};
})(jQuery);
|
var mongoose = require('mongoose');
var ScanResult = new mongoose.Schema({
scanId: {
type: String,
unique: true
},
status:String,
repositoryName: String,
findings:Object,
queuedAt:String,
scanningAt:String,
finishedAt:String
},{collection:'scanResult'});
var ScanResult = module.exports = mongoose.model('scanResult', ScanResult);
|
$(function(){
//竞彩足球混合和竞彩篮球混合 除了 $('tbody').on元素不一样意外 其他全一样
//全局变量部分
var nMatchNum = 0;
//每次刷新进来 取消所有胆的input勾选 并禁用所有胆input
$('.dan input').attr({'checked':false, 'disabled':true});
//点击隐藏 隐藏相应日期的赛事列表 点击显示 只显示那行 不显示那行的子表格
$(".hidden").click(function(){
if($(this).html() == "隐藏"){
$(this).html("显示").addClass('hidden2').parent().next().hide();
}else{
$(this).html("隐藏").removeClass('hidden2').parent().next().show();
}
BarInBottom();
});
//点击隐 隐藏相应的那行 也就是整个tbody
$(".td1").click(function(){
$(this).parent().parent().hide();
BarInBottom();
});
//点击 显示全部的table tbody
$(".show_all").click(function(){
$("table").show();
$("tbody").show();
$('.hidden').html("隐藏").removeClass('hidden2');
BarInBottom();
});
// 投注部分变色 并让下面的bar动态显示有哪些串
$('tbody').on('click', ".td8, .td9, .td10, .td12, .td13, .td15, .small_tr td:not(.start)", function(){
$(this).removeClass("hovered_bg");
if($(this).hasClass("checked_bg")){
$(this).removeClass("checked_bg");
if($(this).parent().parent().find('.checked_bg').size()==0){ //如果当前被点击按钮的这场比赛 取消选取后 选中了0个
nMatchNum--; //场次数减1
$('.match_num').html(nMatchNum);
chuan("remove", 4, true); //并且删除相应串
//禁用这场比赛的胆 如果有选胆 胆也去掉 并且移除class 以区别其他未选中的场次 便于AffectDanAndChuan()操作
$(this).parent().parent().find('.dan input').attr('disabled', true).removeAttr('checked').removeClass('match_checked_dan');
}
}else{
$(this).addClass("checked_bg");
if($(this).parent().parent().find('.checked_bg').size()==1){ //如果当前被点击按钮的这场比赛 选取后 选中了1个按钮
nMatchNum++; //场次数加1
$('.match_num').html(nMatchNum);
chuan("append", 4, true); //并且添加相应串
//启用这场比赛的胆 也就是只有选了比赛的胆才可能被勾选 并且添加class 以区别其他未选中的场次 便于AffectDanAndChuan()操作
$(this).parent().parent().find('.dan input').attr('disabled', false).addClass('match_checked_dan');
}
}
AffectDanAndChuan();
outPutCountTotal(true);
});
// //选择全包 选中当前行
// $(".small_tr td.end").toggle(function(){
// $(this).parent().find("td:not(.start)").addClass("checked_bg").css({"background":"#FF7B23","color":"#fff"});
// },function(){
// $(this).parent().find("td:not(.start)").removeClass("checked_bg").css({"background":"#F9F9F9","color":"#666"});
// });
//比分 总进球 半全场 点击展开 显示隐藏子表格
$(".td16").click(function(){
if($(this).parent().next().css("display") == "block"){
$(this).html("展开").removeClass('td161').parent().next().hide().next().hide();
}else{
$(this).html("隐藏").addClass('td161').parent().next().show().next().show();
}
BarInBottom();
});
//content_bar随着滚动条一起滚动
$(window).scroll(function(){
BarInBottom();
});
//bar2随着滚动条一起滚动 原理同上
// alert($(window).scrollTop() - $("#content").offset().top);
// alert($(".bar1").height());
$(window).scroll(function(){
if(!-[1,]&&!window.XMLHttpRequest){ //如果是IE6 就不执行
return;
}
var nBar2Top = $(window).scrollTop() - $("#content").offset().top;
var nBar2StartTop = $(".bar1").height();
if(nBar2Top <= nBar2StartTop){
nBar2Top = nBar2StartTop;
}
$(".bar2").css("position","absolute").css("top",nBar2Top+"px");
});
// //所有过关方式 点击显示 不做所有过关
// $('.show_suoyou').toggle(function(){
// $('.suoyou').show();
// $('.ziyou').hide().find('input').removeAttr('checked');
// $('.lottery_number').html(0);
// $('.lotter_money').html(2*0);
// },function(){
// $('.ziyou').show();
// $('.suoyou').hide().find('input').removeAttr('checked');
// $('.lottery_number').html(0);
// $('.lotter_money').html(2*0);
// });
//勾选胆事件
$('.dan').click(function(){
AffectDanAndChuan();
outPutCountTotal(true);
});
//勾选串事件
$('.ziyou, .suoyou').on('click', 'span input', function(){
AffectDanAndChuan();
outPutCountTotal(true);
});
//倍投输入事件
$('.multiple').keyup(function(event){
var keyCode = event.keyCode;
var sMultiple = $(this).val();
//只能键盘输入数字 退格删除 上下左右 这些键
if((keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <=105) || keyCode == 8 || (keyCode >= 37 && keyCode <= 40)){
if(sMultiple.length > 5){ //最多只能输入5位 大于5为自动删除第六位
$(this).val(sMultiple.substr(0, 5));
}
}else{ //如果输入的不是上面的键 那就清空输入 这样这个input的val就只能是数字0-9了或者空了
$(this).val('');
}
outPutCountTotal(true);
});
// 表单发送sData字符串给后台作为json的一部分
$('.submit').click(function(){
//表单提交前的验证
var nMatchNum = $('.match_num').html();
var nChuanChecked = $('.ziyou input:checked, .suoyou input:checked').size();
var sMultiple = $('.multiple').val();
if($('#dailog_login').html() == '请登录'){
$('#dailog_login').trigger('click');
return;
}
if(nMatchNum < 2){
alert('请选择至少2场比赛');
return;
}
if(nChuanChecked == 0){
alert('请选择过关方式');
return;
}
if(sMultiple == '' || sMultiple == 0){
alert('请选择投注倍数');
return;
}
// alert('弹出付款界面 开始生成dataStr');
//形成json格式字符串dataStr 表单post给后台 一共三种情况 单式过关 不带胆的复式过关 带胆拖的复式过关
var nLotteryNumber = parseInt($('.lottery_number').html());
var nLotteryMoney = parseInt($('.lottery_money').html());
var nMultiple = parseInt($('.multiple').val());
var nDanCheckedNum = $(".match_checked_dan:checked").size();
var gameTypeValue = 17;
var dataStr = '';
$('.td8').attr({title:'00', type:'21'});
$('.td9').attr({title:'01', type:'21'});
$('.td10').attr({title:'00', type:'22'});
$('.td12').attr({title:'01', type:'22'});
$('.td13').attr({title:'01', type:'24'});
$('.td15').attr({title:'02', type:'24'}); //胜负彩的title和type属性在html中设置
dataStr = getDataStr(gameTypeValue, 'jclq');
//输出测试
// console.log(dataStr);
//形成allSmallType字符串
var allSmallType = '';
$('.ziyou input:checked, .suoyou input:checked').each(function(){
allSmallType += $(this).attr('value') + ', ';
});
if(allSmallType.length >= 40){
allSmallType = allSmallType.slice(0,40) + '...';
}
//动态生成确认付款界面弹窗 同时将dataStr做为表单name="data"的value
MoneyDialog({
"当前彩种": $(document).attr("title"),
"选择场次": nMatchNum + '场',
"过关方式": allSmallType,
"总注数": nLotteryNumber + '注',
"倍数": nMultiple + '倍',
"总金额": nLotteryMoney + '元'
}, dataStr);
})
/*{
"memberId":"adomin",
"issueNo": "",
"amount": "164",
"gameType": "17",
"multiple": "1",
"betList": [
{
"smallType": "2*1",
"betWay": "D",
"num": "14",
"content": "{
\"B20140523301\":{\"21\":\"0001\", \"23\":\"02\"},
\"B20140523303\":{\"22\":\"01\", \"23\":\"04\"},
\"B20140523304\":{\"22\":\"01\"},
\"B20140524304\":{\"22\":\"01\"}
}#
{
\"B20140523302\":{\"22\":\"00\", \"24\":\"01\"}
}"
},
{
"smallType": "3*1",
"betWay": "D",
"num": "34",
"content": "{
\"B20140523301\":{\"21\":\"0001\", \"23\":\"02\"},
\"B20140523303\":{\"22\":\"01\", \"23\":\"04\"},
\"B20140523304\":{\"22\":\"01\"},
\"B20140524304\":{\"22\":\"01\"}
}#
{
\"B20140523302\":{\"22\":\"00\", \"24\":\"01\"}
}"
},
{
"smallType": "4*1",
"betWay": "D",
"num": "34",
"content": "{
\"B20140523301\":{\"21\":\"0001\", \"23\":\"02\"},
\"B20140523303\":{\"22\":\"01\", \"23\":\"04\"},
\"B20140523304\":{\"22\":\"01\"},
\"B20140524304\":{\"22\":\"01\"}
}#
{
\"B20140523302\":{\"22\":\"00\", \"24\":\"01\"}
}"
}
]
}*/
});
|
import React from 'react'
import { Component } from 'react';
class FormularioCadastro extends Component {
constructor(props){
super(props);
this.titulo = '';
this.texto = '';
this.categoria = 'Sem categoria';
this.state = {categorias:[]};
this._novasCategorias = this._novasCategorias.bind(this);
}
componentDidMount(){
this.props.categorias.inscrever(this._novasCategorias);
}
componentWillUnmount(){
this.props.categorias.desinscrever(this._novasCategorias);
}
_novasCategorias(categorias){
this.setState({...this.state, categorias});
}
_handleMudancaTitulo(evento){
evento.stopPropagation();
this.titulo = evento.target.value;
}
_handleMudancaTexto(evento){
evento.stopPropagation();
this.texto = evento.target.value;
}
_criarNota(evento){
evento.preventDefault();
evento.stopPropagation();
this.props.criarNota(this.titulo, this.texto, this.categoria);
}
_handleMudancaCategoria(evento){
evento.stopPropagation();
this.categoria = evento.target.value;
}
render(){
return(
<div class="col-sm-4">
<form onSubmit={this._criarNota.bind(this)} >
<div className="form-group">
<select onChange={this._handleMudancaCategoria.bind(this)}>
<option defaultChecked={true}>
Sem categoria
</option>
{this.state.categorias.map((categoria, index) =>{
return <option key={index}>{categoria}</option>
})}
</select>
</div>
<div className="form-group">
<input type="text" placeholder="Titulo"
onChange={this._handleMudancaTitulo.bind(this)}
/>
</div>
<div className="form-group">
<textarea className="form-control" placeholder="Nota"
rows={3}
onChange={this._handleMudancaTexto.bind(this)}
/>
</div>
<div className="form-group">
<button className="btn btn-primary">Criar nota</button>
</div>
</form>
</div>
);
}
}
export default FormularioCadastro;
|
import React from "react";
import './Checkout.css'
import Subtotal from './Subtotal.jsx'
import {useStateValue } from "../State/StateProvider";
import SimpleImageSlider from "react-simple-image-slider";
import FlipMove from 'react-flip-move';
import Checkout__Product from "./Checkout__Product";
function Checkout(){
const [{user,basket},dispatch]=useStateValue();
const Ad=[
{url:"https://images-eu.ssl-images-amazon.com/images/G/31/img16/GiftCards/LPAIndia/Header/170_AP_1500x300.jpg"},
{url:"https://images-eu.ssl-images-amazon.com/images/G/31/img16/GiftCards/LPAIndia/Offers/Yatra/LPA_201_1500x250.jpg"}
]
return(
<div className="checkout">
<div className="checkout_left">
<SimpleImageSlider
width={1150}
height={150}
images={Ad}
showNavs={true}
/>
<>
<h3 className="name">Hello,{user?user.email:'Guest'}</h3>
<h2 className="checkout__title">
Your Shopping Basket
</h2>
{basket.map(element => (
<Checkout__Product
image_slider={element.Image_Slider}
id={element.ID}
title={element.description}
image={element.Image}
price={element.Price}
rating={element.rating}
button_disable={false}
></Checkout__Product>
))}
</>
</div>
<div className="checkout__right">
<Subtotal></Subtotal>
</div>
</div>
)
}
export default Checkout;
|
var initMap = function(){
var center = new google.maps.LatLng(21.003988480567475,105.79211175441742);
var map =new google.maps.Map(document.querySelector("#googleMap"),{
center :center,
zoom :16,
mapTypeId :google.maps.MapTypeId.ROADMAP
});
var service = new google.maps.places.PlacesService(map);
var myLoc = new MyLocation({
map : map,
service : service,
location : center,
radius : 500
});
var select = document.querySelector("select");
select.addEventListener("click",function(e){
var value = select.options[select.selectedIndex].value;
if (value!="Select filter") myLoc.nearbySearch(value);
})
}
function MyLocation(options){
this.options = options;
this.map = this.options.map;
this.service = this.options.service;
this.marker = new google.maps.Marker({
position : this.options.location,
animation : google.maps.Animation.DROP,
map : this.map
});
this.nearby = {};
this.oldSearch = "";
this.search = "";
this.infowindow = new google.maps.InfoWindow();
var circle = new google.maps.Circle({
center : this.options.location,
radius : this.options.radius,
strokeColor : "#0000FF",
strokeOpacity : 0.2,
strokeWeight : 1,
fillColor : "#0000FF",
fillOpacity : 0.1
});
circle.setMap(this.map);
this.setCenter = this.setCenter.bind(this);
this.setMapAll = this.setMapAll.bind(this);
this.nearbySearch = this.nearbySearch.bind(this);
this.searchCallback = this.searchCallback.bind(this);
this.showResult = this.showResult.bind(this);
}
MyLocation.prototype.setCenter = function(){
this.map.setCenter(this.marker.getPosition());
}
//set Null to hide all marker
MyLocation.prototype.setMapAll = function(markers,map){
if (markers)
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
MyLocation.prototype.nearbySearch = function(type){
this.oldSearch = this.search;
this.search = type;
if (!this.nearby[type]) {
this.service.nearbySearch({
location : this.options.location,
radius : this.options.radius,
type : [type]
}, this.searchCallback);
} else this.showResult();
}
MyLocation.prototype.searchCallback = function(results, status){
if (status === google.maps.places.PlacesServiceStatus.OK) {
var arr = [],that = this;
for (var i = 0; i < results.length; i++) {
var r = results[i];
var marker = new google.maps.Marker({
position : r.geometry.location
});
marker.name = r.name;
google.maps.event.addListener(marker, 'click', function() {
that.infowindow.setContent(this.name);
that.infowindow.open(that.map, this);
});
arr.push(marker);
}
this.nearby[this.search] = arr;
}
this.showResult();
}
MyLocation.prototype.showResult = function(){
if (this.oldSearch) this.setMapAll(this.nearby[this.oldSearch],null);
this.setMapAll(this.nearby[this.search],this.map);
}
|
/*
* More details here http://mongoosejs.com/docs/guide.html
*/
var mongoose = require("mongoose");
//connect to database
mdb = "mongodb://localhost:27017";
if (process.MONGOHQ_URI)
console("using MONGOHQ_URI");
if (process.MONGOLAB_URI)
console("using MONGOLAB_URI");
var db = mongoose.connect(process.MONGOHQ_URI || process.MONGOLAB_URI || mdb);
//create schema for blog post
var blogSchema = new mongoose.Schema({
title: String,
author: String,
body: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
hidden: Boolean,
meta: {
votes: Number,
favs: Number
}
});
//compile schema to model
module.exports = db.model('blog', blogSchema)
|
// @flow
/* **********************************************************
* File: Footer.js
*
* Brief: The react footer component
*
* Authors: Craig Cheney, George Whitfield
*
* 2017.04.27 CC - Document created
*
********************************************************* */
import React, { Component } from 'react';
import { Grid, Col, Row } from 'react-bootstrap';
let mitImagePath = '../resources/img/mitLogo.png';
/* Set mitImagePath to new path */
if (process.resourcesPath !== undefined) {
mitImagePath = (`${String(process.resourcesPath)}resources/img/mitLogo.png`);
// mitImagePath = `${process.resourcesPath}resources/img/mitLogo.png`;
}
// const nativeImage = require('electron').nativeImage;
// const mitLogoImage = nativeImage.createFromPath(mitImagePath);
const footerStyle = {
position: 'absolute',
right: 0,
bottom: 0,
left: 0,
color: '#9d9d9d',
backgroundColor: '#222',
height: '25px',
textAlign: 'center'
};
const mitLogoStyle = {
height: '20px'
};
const bilabLogoStyle = {
height: '20px'
};
export default class Footer extends Component<{}> {
render() {
return (
<Grid className='Footer' style={footerStyle} fluid>
<Row>
<Col xs={4}><img src={'../resources/img/mitLogo.png' || mitImagePath} style={mitLogoStyle} alt='MICA' /></Col>
<Col xs={4}>The MICA Group © 2017</Col>
<Col xs={4}><img src='../resources/img/bilabLogo_white.png' style={bilabLogoStyle} alt='BioInstrumentation Lab' /></Col>
</Row>
</Grid>
);
}
}
/* [] - END OF FILE */
|
// FreeCodeCamp :: Bonfire
// [12] Slasher Flick
/*
Instructions:
Return the remaining elements of an array after chopping off n elements from the head.
Tests:
assert.deepEqual(slasher([1, 2, 3], 2), [3], 'should drop the first two elements');
assert.deepEqual(slasher([1, 2, 3], 0), [1, 2, 3], 'should return all elements when n < 1');
assert.deepEqual(slasher([1, 2, 3], 9), [], 'should return an empty array when n >= array.length');
*/
function slasher(arr, howMany) {
// it doesn't always pay to be first
arr.splice(0, howMany);
return arr;
}
slasher([1, 2, 3], 2);
|
$(window).load(function () {
$('.flexslider').flexslider({
directionNav: false,
slideshowSpeed: 3000,
animationSpeed: 1000,
});
$('#galleryView,#album').click(function(){
$('#box').show();
gallery();
});
$('#close').click(function(){
$('#box').hide();
})
});
function gallery() {
$("#gallery").carouFredSel({
responsive : true,
prev : ".left",
next : ".right"
});
//$("#gallery").imagesLoaded(gallery);
}
|
export default function cards(state = [], action) {
switch (action.type) {
case "FETCH_BOARD_SUCCESS": {
const cardsOnly = action.board.lists
.map((list) => {
return list.cards;
})
.flat();
return cardsOnly;
}
case "FETCH_CARD_SUCCESS": {
return state.map(card => {
if (card._id === action.card._id) {
return action.card
}
return card
});
}
case "CREATE_CARD_SUCCESS": {
return state.concat(action.card);
}
default:
return state;
}
}
|
const express = require('express');
const JsLibraries = require('../services/jsLibrariesService')
const router = express.Router();
router.get('', JsLibraries.getLibraries)
module.exports = router;
|
var express=require('express');
var router=express.Router();
var Mock = require('mockjs');
var SearchData=require('./data/search.js')
var request = require('request');
router.get('/',(req,res)=>{
res.send(Mock.mock({
"data|7": [
"@integer(100, 10000)"
]
}))
})
/**
* 登录接口
*/
router.post('/login',(req,res)=>{
var username=req.body.username;
var password=req.body.password;
//判断用户名和密码
if(username&&password){
res.send({
msg:'登录成功',
status:200,
user:{
name:username,
age:22
},
loginToken:'eddhhutdsijwby'
})
}else{
res.send({
msg:'登陆失败',
status:401
})
}
})
/**
* 测试token接口
*/
router.get('/product',(req,res)=>{
var loginToken =req.headers.authorization;
if(loginToken==='eddhhutdsijwby'){
res.send([
{
name:'huahua',
age:20
},
{
name:'iwen',
age:24
}
])
}else{
res.send({
msg:'token验证失败'
})
}
})
/**
* 搜索数据
*/
router.get('/search',(req,res)=>{
var value =req.query.value;
console.log(value);
for(var i=0;i<SearchData.data.length;i++){
if(value===SearchData.data[i].value){
res.send(SearchData.data[i]);
}
}
})
module.exports=router;
|
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import logo from './logo.svg';
import './App.css';
import { MenuItem, ButtonDropdown, Dropdown, DropdownToggle, DropdownMenu, DropdownItem } from 'reactstrap';
import { BrowserRouter as Router, Route, Link, Redirect } from 'react-router-dom';
import { withRouter } from 'react-router';
import { Fragment } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
const Home = () => {
const style = {
textAlign: 'center',
};
return <div style={style}>Welcome home</div>
}
const MyTest = () => {
const style = {
textAlign: 'right',
};
return <div style={style}>Welcome to the test</div>
}
const Hello = () => {
return <div>Welcome home, buddy!</div>
}
const About = () => {
return (
<div>
<button>
<Link to='http://www.pressball.by'>Navigate</Link>
</button>
<div>Welcome about</div>
</div>
);
}
class Test extends React.Component {
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.state = {
dropdownOpen: false,
loggedIn: false,
};
this.handle = this.handle.bind(this);
}
handle() {
this.props.history.push('/test');
// this.setState({
// loggedIn: !this.state.loggedIn,
// })
}
handleClick() {
this.setState({
loggedIn: !this.state.loggedIn,
})
}
toggle() {
this.setState(prevState => ({
dropdownOpen: !prevState.dropdownOpen
}));
}
render () {
if(this.state.loggedIn)
return (
<Router>
<div>
<Redirect push to="/hello"/>
<Route path="/hello" component={Hello}/>
</div>
</Router>
);
return (
<Fragment>
<LogMan loggedIn={this.state.loggedIn} onClick={() => this.handleClick()} />
<button onClick={this.handle}>Route</button>
<Router>
<Fragment>
<ul>
<Link to='/' >Go home</Link>
</ul>
<ul>
<Link to='/about' >Go to about</Link>
</ul>
</Fragment>
</Router>
<ButtonDropdown className="menu" isOpen={this.state.dropdownOpen} toggle={this.toggle}>
<DropdownToggle caret>
Dropdown
</DropdownToggle>
<DropdownMenu right>
<DropdownItem header>Header</DropdownItem>
<DropdownItem disabled>Action</DropdownItem>
<DropdownItem href="https://www.nhl.com">Another Action</DropdownItem>
<DropdownItem divider />
<DropdownItem>Another Action</DropdownItem>
</DropdownMenu>
</ButtonDropdown>
</Fragment>
);
}
}
function LogIn(props) {
return (
<div>
<div>Welcome user!</div>
<button onClick={props.onClick}>Log out</button>
</div>
);
}
function LogOut(props) {
return (
<div>
<div>Please log in</div>
<button onClick={props.onClick}>Log in</button>
</div>
);
}
function LogMan(props) {
if(props.loggedIn)
return (
<LogIn onClick={props.onClick} />
);
return (
<LogOut onClick={props.onClick} />
);
}
export default Test;
|
import React from "react";
const ProductSmallImage = (props) => {
const { imageUrl, imageName, editMode } = props;
//console.log("++++", imageUrl);
//if (imageUrl !== "" || imageName === "imageUrl1") {
return (
<div className="image-group">
{editMode && (
<div className=" flex-item upload-btn-wrapper">
<button className="upload-btn">{props.imageTitle}</button>
<input
type="file"
name={imageName}
placeholder="file"
onChange={props.handleImage}
/>
<button
onClick={() => props.handleDeleteImage(imageName)}
className="upload-btn"
>
X
</button>
</div>
)}
<div className="product-image-item">
{imageUrl !== "" && (
<div
className="product-image-small"
style={{
backgroundImage: `url(${imageUrl})`,
}}
alt=""
onClick={() => props.handleChangeMainImage({ imageUrl })}
/>
)}
</div>
</div>
);
};
export default ProductSmallImage;
|
'use strict';
describe('Service: SprintService', function () {
// load the service's module
beforeEach(module('qaProjectApp'));
// instantiate service
var SprintService;
beforeEach(inject(function (_SprintService_) {
SprintService = _SprintService_;
}));
it('should do something', function () {
// expect(!!SprintService).toBe(true);
});
});
|
const names = ["Benny", "Anna", "Bjorn", "Anna"];
// 1. Loop through the names and print each one
// for (number of names) {
// console.log(number);
// }
// 2. Print every letter from the second name in the list
// [...names[1]].forEach((letter) => {
// console.log(letter);
// });
// 3. Loop through the array and print the length of each name
// names.forEach((names) => {
// console.log(names.length);
// });
// 4. Use an array method to find the index of the name "Bjorn"
// names.findIndex(("Bjorn") {
// console.log(index);
let index = names.indexOf("Bjorn");
console.log(index);
// 5. Loop through the array and print each item in alphabetical order
// EXTENSION
// 1. Sort the array by the length of the names, shortest to largest
const abbaLengthSort = names.sort((a,b) => { return a.length - b.length;});
console.log(abbaLenghtSort);
// 2. Only return names that start with a "B"
// 3. Using the sort and reduce methods, return the word "ABBA" using the array
// 4. Using map, print each name adding "the legend" to the end of each.
const legends = names.map((name) => "${name} the legend");
console.log(legends);
|
const initialState = [];
const student = (state = initialState, action) => {
switch (action.type) {
case "ADD_STUDENT":
return {
...state,
id: action.id,
studentName: action.studentName,
education: [],
};
case "ADD_EDUCATION":
return {
...state,
education: [
...state.education,
{
user_id: action.user_id,
collegeName: action.collegeName,
courseName: action.courseName,
sessionTime: action.sessionTime,
}
]
}
default:
return state;
}
};
export default student;
|
import React from 'react'
import { StyleSheet } from 'quantum'
import { Link as RouterLink } from 'react-router'
const styles = StyleSheet.create({
self: {
color: '#000000',
fontSize: '14px',
textDecoration: 'none',
cursor: 'pointer',
},
decorated: {
textDecoration: 'underline',
},
dashed: {
borderBottom: '1px dashed #000000',
},
small: {
fontSize: '12px',
},
large: {
fontSize: '17px',
},
bold: {
fontWeight: 'bold',
},
'color=gray': {
color: '#9e9e9e',
'&:hover': {
color: '#000000',
},
},
'color=blue': {
color: '#546e7a',
borderBottomColor: '#546e7a',
},
'color=lightBlue': {
color: '#03a9f4',
borderBottomColor: '#03a9f4',
},
})
const Link = ({ children, to, href, target, decorated, dashed, small, bold, large, color, onClick, ...props }) => {
if (to) {
return (
<RouterLink
{...props}
to={to}
className={styles({ decorated, dashed, small, bold, large, color })}
>
{children}
</RouterLink>
)
}
if (href) {
return (
<a
href={href}
target={target}
className={styles({ decorated, dashed, small, bold, large, color })}
>
{children}
</a>
)
}
return (
<span
className={styles({ decorated, dashed, small, bold, large, color })}
onClick={onClick}
>
{children}
</span>
)
}
export default Link
|
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { reducer as formReducer } from 'redux-form';
import thunk from 'redux-thunk';
import navReducer from './reducers/nav-reducer';
const store = createStore(
combineReducers({
form: formReducer,
navRed: navReducer
}),
applyMiddleware(thunk)
);
export default store;
|
export default {
title: "Sachin Saini (@thetinygoat)",
description: "Builder, Tinkerer, Learner.",
social: [
{
name: "twitter",
link: "https://twitter.com/thetinygoat",
},
{
name: "github",
link: "https://github.com/thetinygoat",
},
{
name: "linkedin",
link: "https://www.linkedin.com/in/thetinygoat/",
},
{
name: "external-link",
link: "/Sachin_Saini_Resume.pdf",
},
],
projects: [
{
name: "Parabola",
description: "Parabola is an in-memory key-value database written in Go.",
link: "https://github.com/thetinygoat/parabola",
logo: "/img/parabola.svg",
bg: "#FFFBEB",
},
{
name: "Release Fox",
description:
"Release Fox is a SaaS that provides an easy way to manage your product releases.",
link: "https://github.com/releasefox",
logo: "/img/rf.svg",
bg: "#EFF6FF",
},
{
name: "CoverAll",
description:
"CoverAll is a news app with built in fake news detection using Deep Learning (LSTMs).",
link: "https://coverall.vercel.app/",
logo: "/img/coverall.svg",
bg: "#ECFDF5",
},
{
name: "Bingy.io",
description:
"Bingy is a digital entertainment assistant, it allows users to track and discover digital content from 10+ providers all in one place.",
link: "https://github.com/thetinygoat/bingy",
},
{
name: "Dotfm",
description:
"Dotfm is a CLI utility that helps manage your dotfiles, it provides features like tracking, remote sync, and environments.",
link: "https://github.com/thetinygoat/dotfm",
},
{
name: "Cabchain",
description:
"Cabchain is a decentralized ride sharing app built on top of the Ethereum Blockchain.",
link: "https://github.com/thetinygoat/cabchain",
},
],
};
|
import React, { useState, useEffect } from "react";
import {
BrowserRouter as Router,
Redirect,
Route,
Switch,
} from "react-router-dom";
import DeleteModal from "./components/DeleteModal";
import Header from "./components/Header";
import Footer from "./components/Footer";
import HomePage from "./pages/HomePage";
import SignupPage from "./pages/SignupPage";
import LoginPage from "./pages/LoginPage";
import AuthArticlesPage from "./pages/AuthArticlesPage";
import CreateArticlePage from "./pages/CreateArticlePage";
import UpdateProfilePage from "./pages/UpdateProfilePage";
import SingleArticlePage from "./pages/SingleArticlePage";
import UpdateArticlePage from "./pages/UpdateArticlePage";
import { ToastProvider } from "react-toast-notifications";
function App() {
const [isLogged, setIsLogged] = useState(false);
const [user, setUser] = useState(null);
const [isDeleteModalVisible, setIsDeleteModalVisibile] = useState(false);
useEffect(() => {
if (localStorage.authToken) {
setIsLogged(true);
}
}, []);
function RequireAuth({ children }) {
if (!isLogged) {
return <Redirect to="/" />;
} else {
return children;
}
}
return (
<ToastProvider>
<Router>
<Header isLogged={isLogged} setIsLogged={setIsLogged} user={user} />
<Switch>
{isLogged ? (
<Route exact path="/" component={AuthArticlesPage} />
) : (
<Route exact path="/" component={HomePage} />
)}
<Route exact path="/signup">
<SignupPage setIsLogged={setIsLogged} setUser={setUser} />
</Route>
<Route exact path="/login">
<LoginPage setIsLogged={setIsLogged} setUser={setUser} />
</Route>
<Route exact path="/article/:slug">
{isLogged ? (
<SingleArticlePage
user={user}
setIsDeleteModalVisibile={setIsDeleteModalVisibile}
/>
) : (
<SingleArticlePage />
)}
</Route>
{isDeleteModalVisible ? (
<DeleteModal setIsDeleteModalVisibile={setIsDeleteModalVisibile} />
) : (
false
)}
<RequireAuth>
<Route exact path="/create" component={CreateArticlePage} />
<Route exact path="/user/update">
<UpdateProfilePage user={user} />
</Route>
<Route exact path="/articles/:slug">
<UpdateArticlePage user={user} />
</Route>
</RequireAuth>
</Switch>
<Footer />
</Router>
</ToastProvider>
);
}
export default App;
|
var test = [
{
"IP": "106.13.24.47",
"Occurrences": 2,
"Location": "Beijing",
"Longitude": 116,
"Latitude": 39,
"Identity": "Beijing Baidu Netcom Science and Technology Co., Ltd."
},
{
"IP": "109.235.25.43",
"Occurrences": 2,
"Location": "Moscow",
"Longitude": 37,
"Latitude": 55,
"Identity": "SvyazService Ltd"
},
{
"IP": "112.124.42.80",
"Occurrences": 1,
"Location": "Hangzhou",
"Longitude": 120,
"Latitude": 30,
"Identity": "Hangzhou Alibaba Advertising Co.,Ltd."
},
{
"IP": "109.235.25.43",
"Occurrences": 2,
"Location": "Moscow",
"Longitude": 37,
"Latitude": 55,
"Identity": "SvyazService Ltd"
},
{
"IP": "117.136.26.30",
"Occurrences": 10,
"Location": "Guangzhou",
"Longitude": 113,
"Latitude": 23,
"Identity": "China Mobile"
},
{
"IP": "118.24.97.147",
"Occurrences": 939,
"Location": "Haidian",
"Longitude": 116,
"Latitude": 39,
"Identity": "Shenzhen Tencent Computer Systems Company Limited"
},
{
"IP": "119.39.46.126",
"Occurrences": 1,
"Location": "Yanqing Qu",
"Longitude": 115,
"Latitude": 40,
"Identity": "CHINA UNICOM China169 Backbone"
},
{
"IP": "123.125.114.144",
"Occurrences": 1,
"Location": "Beijing",
"Longitude": 116,
"Latitude": 39,
"Identity": "China Unicom Beijing Province Network"
},
{
"IP": "123.160.174.146",
"Occurrences": 1,
"Location": "Henan",
"Longitude": 113,
"Latitude": 34,
"Identity": "No.31,Jin-rong Street"
},
{
"IP": "124.88.112.215",
"Occurrences": 1,
"Location": "Ürümqi",
"Longitude": 87,
"Latitude": 43,
"Identity": "CHINA UNICOM China169 Backbone"
},
{
"IP": "128.14.133.58",
"Occurrences": 1,
"Location": "Georgetown",
"Longitude": 143,
"Latitude": -18,
"Identity": "Zenlayer Inc"
},
{
"IP": "128.14.134.170",
"Occurrences": 1,
"Location": "Georgetown",
"Longitude": 143,
"Latitude": -18,
"Identity": "Zenlayer Inc"
},
{
"IP": "138.122.20.76",
"Occurrences": 1,
"Location": "Irati",
"Longitude": -52,
"Latitude": -26,
"Identity": "RM INFORMATICA LTDA"
},
{
"IP": "138.204.132.211",
"Occurrences": 1,
"Location": "Campinaçu",
"Longitude": -48,
"Latitude": -13,
"Identity": "FIUZA INFORMÃTICA & TELECOMUNICAÃÃO LTDA ME"
},
{
"IP": "14.231.97.7",
"Occurrences": 1,
"Location": "Hanoi",
"Longitude": 105,
"Latitude": 21,
"Identity": "VNPT Corp"
},
{
"IP": "141.8.183.79",
"Occurrences": 2,
"Location": "Moscow",
"Longitude": 37,
"Latitude": 55,
"Identity": "YANDEX LLC"
},
{
"IP": "159.203.76.218",
"Occurrences": 1,
"Location": "Clifton",
"Longitude": -74,
"Latitude": 40,
"Identity": "ASN block not managed by the RIPE NCC"
},
{
"IP": "162.243.130.23",
"Occurrences": 1,
"Location": "San Francisco",
"Longitude": -122,
"Latitude": 37,
"Identity": "ASN block not managed by the RIPE NCC"
},
{
"IP": "167.172.97.0",
"Occurrences": 1,
"Location": "London",
"Longitude": 0,
"Latitude": 51,
"Identity": ""
},
{
"IP": "172.104.242.173",
"Occurrences": 1,
"Location": "Frankfurt",
"Longitude": 8,
"Latitude": 50,
"Identity": "ASN block not managed by the RIPE NCC"
},
{
"IP": "175.152.109.245",
"Occurrences": 1,
"Location": "Chaowai",
"Longitude": 116,
"Latitude": 39,
"Identity": "CHINA UNICOM China169 Backbone"
},
{
"IP": "175.184.165.143",
"Occurrences": 1,
"Location": "Jinrongjie",
"Longitude": 116,
"Latitude": 39,
"Identity": "CHINA UNICOM China169 Backbone"
},
{
"IP": "176.9.193.37",
"Occurrences": 2,
"Location": "Falkenstein",
"Longitude": 12,
"Latitude": 49,
"Identity": "Hetzner Online GmbH"
},
{
"IP": "178.128.6.69",
"Occurrences": 6,
"Location": "Santa Clara",
"Longitude": -121,
"Latitude": 37,
"Identity": "ASN block not managed by the RIPE NCC"
},
{
"IP": "182.138.158.201",
"Occurrences": 1,
"Location": "Zhongba",
"Longitude": 102,
"Latitude": 30,
"Identity": "No.31,Jin-rong Street"
},
{
"IP": "183.129.159.242",
"Occurrences": 1,
"Location": "Shaoxing Xian",
"Longitude": 120,
"Latitude": 30,
"Identity": "No.31,Jin-rong Street"
},
{
"IP": "184.154.47.2",
"Occurrences": 1,
"Location": "Chicago",
"Longitude": -87,
"Latitude": 41,
"Identity": "SingleHop LLC"
},
{
"IP": "187.226.248.9",
"Occurrences": 1,
"Location": "Mexico City",
"Longitude": -99,
"Latitude": 19,
"Identity": "Uninet S.A. de C.V."
},
{
"IP": "190.122.159.217",
"Occurrences": 1,
"Location": "Buenos Aires City",
"Longitude": -58,
"Latitude": -34,
"Identity": "Atlantica Video Cable S.A."
},
{
"IP": "190.138.5.95",
"Occurrences": 1,
"Location": "Buenos Aires City",
"Longitude": -58,
"Latitude": -34,
"Identity": "Telecom Argentina S.A."
},
{
"IP": "190.94.150.99",
"Occurrences": 1,
"Location": "Quito",
"Longitude": -78,
"Latitude": 0,
"Identity": "ETAPA EP"
},
{
"IP": "191.100.8.216",
"Occurrences": 1,
"Location": "Quito",
"Longitude": -78,
"Latitude": 0,
"Identity": "ETAPA EP"
},
{
"IP": "2.238.139.133",
"Occurrences": 1,
"Location": "Bologna",
"Longitude": 11,
"Latitude": 44,
"Identity": "Fastweb SpA"
},
{
"IP": "201.1.87.161",
"Occurrences": 2,
"Location": "Sao Paulo",
"Longitude": -46,
"Latitude": -23,
"Identity": "TELEFÃNICA BRASIL S.A"
},
{
"IP": "212.75.249.210",
"Occurrences": 1,
"Location": "Saint Petersburg",
"Longitude": 30,
"Latitude": 59,
"Identity": "JSC ER-Telecom Holding"
},
{
"IP": "213.159.213.137",
"Occurrences": 1,
"Location": "Irkutsk",
"Longitude": 104,
"Latitude": 52,
"Identity": "JSC The First"
},
{
"IP": "219.140.116.66",
"Occurrences": 1,
"Location": "Macau",
"Longitude": 113,
"Latitude": 22,
"Identity": "No.31,Jin-rong Street"
},
{
"IP": "220.143.85.88",
"Occurrences": 1,
"Location": "Taipei City",
"Longitude": 121,
"Latitude": 25,
"Identity": "Chunghwa Telecom Co., Ltd."
},
{
"IP": "221.225.77.197",
"Occurrences": 1,
"Location": "Xuzhou",
"Longitude": 117,
"Latitude": 34,
"Identity": "No.31,Jin-rong Street"
},
{
"IP": "222.82.60.115",
"Occurrences": 1,
"Location": "Urumqi",
"Longitude": 87,
"Latitude": 43,
"Identity": "No.31,Jin-rong Street"
},
{
"IP": "223.167.74.196",
"Occurrences": 1,
"Location": "Shanghai",
"Longitude": 121,
"Latitude": 31,
"Identity": "China Unicom Shanghai network"
},
{
"IP": "24.12.69.236",
"Occurrences": 1,
"Location": "Glendale Heights",
"Longitude": -88,
"Latitude": 41,
"Identity": "Comcast Cable Communications, LLC"
},
{
"IP": "31.43.152.44",
"Occurrences": 2,
"Location": "Kyiv",
"Longitude": 30,
"Latitude": 50,
"Identity": "Corbina Telecom Llc."
},
{
"IP": "36.80.37.244",
"Occurrences": 1,
"Location": "Jakarta Pusat",
"Longitude": 106,
"Latitude": -6,
"Identity": "Asia Pacific Network Information Centre"
},
{
"IP": "37.201.222.32",
"Occurrences": 1,
"Location": "Frankfurt",
"Longitude": 8,
"Latitude": 50,
"Identity": "Liberty Global B.V."
},
{
"IP": "42.236.10.108",
"Occurrences": 1,
"Location": "luohe shi",
"Longitude": 113,
"Latitude": 33,
"Identity": "CHINA UNICOM China169 Backbone"
},
{
"IP": "42.236.10.109",
"Occurrences": 1,
"Location": "luohe shi",
"Longitude": 113,
"Latitude": 33,
"Identity": "CHINA UNICOM China169 Backbone"
},
{
"IP": "46.19.227.218",
"Occurrences": 1,
"Location": "Ljubljana",
"Longitude": 14,
"Latitude": 46,
"Identity": "Kujtesa Net Sh.p.k."
},
{
"IP": "46.19.227.218",
"Occurrences": 1,
"Location": "Ljubljana",
"Longitude": 14,
"Latitude": 46,
"Identity": "Kujtesa Net Sh.p.k."
},
{
"IP": "54.214.64.205",
"Occurrences": 1,
"Location": "",
"Longitude": -123,
"Latitude": 44,
"Identity": "Amazon Technologies Inc."
},
{
"IP": "54.36.148.206",
"Occurrences": 1,
"Location": "Roubaix",
"Longitude": 3,
"Latitude": 50,
"Identity": "OVH SAS"
},
{
"IP": "54.36.149.48",
"Occurrences": 1,
"Location": "Roubaix",
"Longitude": 3,
"Latitude": 50,
"Identity": "OVH SAS"
},
{
"IP": "54.36.150.115",
"Occurrences": 1,
"Location": "Gravelines",
"Longitude": 2,
"Latitude": 50,
"Identity": "OVH SAS"
},
{
"IP": "54.36.150.13",
"Occurrences": 1,
"Location": "Gravelines",
"Longitude": 2,
"Latitude": 50,
"Identity": "OVH SAS"
},
{
"IP": "54.36.150.180",
"Occurrences": 1,
"Location": "Gravelines",
"Longitude": 2,
"Latitude": 50,
"Identity": "OVH SAS"
},
{
"IP": "54.36.150.19",
"Occurrences": 1,
"Location": "Gravelines",
"Longitude": 2,
"Latitude": 50,
"Identity": "OVH SAS"
},
{
"IP": "60.191.52.254",
"Occurrences": 1,
"Location": "Shaoxing Xian",
"Longitude": 120,
"Latitude": 29,
"Identity": "No.31,Jin-rong Street"
},
{
"IP": "60.216.141.137",
"Occurrences": 1,
"Location": "Qingdao",
"Longitude": 120,
"Latitude": 36,
"Identity": "CHINA UNICOM China169 Backbone"
},
{
"IP": "61.2.153.204",
"Occurrences": 2,
"Location": "Bengaluru",
"Longitude": 77,
"Latitude": 20,
"Identity": "Bharat Sanchar Nigam Ltd"
},
{
"IP": "62.173.148.243",
"Occurrences": 1,
"Location": "Moscow",
"Longitude": 37,
"Latitude": 55,
"Identity": "Internet-Cosmos LLC"
},
{
"IP": "62.173.149.158",
"Occurrences": 2,
"Location": "Moscow",
"Longitude": 37,
"Latitude": 55,
"Identity": "Internet-Cosmos LLC"
},
{
"IP": "62.173.149.52",
"Occurrences": 1,
"Location": "Moscow",
"Longitude": 37,
"Latitude": 55,
"Identity": "Internet-Cosmos LLC"
},
{
"IP": "71.6.232.4",
"Occurrences": 1,
"Location": "San Diego",
"Longitude": -117,
"Latitude": 32,
"Identity": "CariNet, Inc."
},
{
"IP": "77.247.110.63",
"Occurrences": 6,
"Location": "Tallinn",
"Longitude": 24,
"Latitude": 59,
"Identity": "VITOX TELECOM"
},
{
"IP": "83.219.136.119",
"Occurrences": 1,
"Location": "Kaliningrad",
"Longitude": 20,
"Latitude": 54,
"Identity": "TIS Dialog LLC"
},
{
"IP": "89.36.51.161",
"Occurrences": 1,
"Location": "Iran",
"Longitude": 48,
"Latitude": 34,
"Identity": "Iran Telecommunication Company PJS"
},
{
"IP": "91.217.79.207",
"Occurrences": 1,
"Location": "Lipetsk",
"Longitude": 39,
"Latitude": 52,
"Identity": "EKMA IS LTD"
},
{
"IP": "91.234.102.36",
"Occurrences": 1,
"Location": "Piekary Śląskie",
"Longitude": 18,
"Latitude": 50,
"Identity": "IPI Vision Sp. z o.o."
}
];
|
import React from 'react';
import Api from '../api/api'
import {connect} from 'react-redux';
import {UPDATE_TEAMLIST} from '../data/store'
class Dashboard extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null
};
}
componentWillMount() {
// Tap tap API server
Api.teamlist((json) => {
this.props.updateTeamlist(json);
}, (mes) => {
this.setState({
error: mes
});
})
this.timer = setInterval(() => {
this.setState({now: new Date()})
}.bind(this), 1000);
}
componentWillUnmount() {
clearInterval(this.timer);
}
clearError() {
this.setState({
error: null
});
}
render() {
const {point, solved, teamlist, ranking, countdown} = this.props;
var errorMessage;
if (this.state.error) {
errorMessage = (
<div className="ui floating negative message">
<i className="close icon" onClick={this.clearError.bind(this)}></i>
<div className="header">
Error
</div>
<p>{this.state.error[0]}</p>
</div>
);
}
return (
<div className="ui container">
<h1 className="ui top header blue">Countdown</h1>
<div className="ui segment blue ">
<div className="ui three statistics">
<div className="statistic">
<div className="value">
{countdown.h || 'n/a'}
</div>
<div className="label">
Hours
</div>
</div>
<div className="statistic">
<div className="value">
{countdown.m || 'n/a'}
</div>
<div className="label">
Minutes
</div>
</div>
<div className="statistic">
<div className="value">
{countdown.s || 'n/a'}
</div>
<div className="label">
Seconds
</div>
</div>
</div>
</div>
<h1 className="ui top header purple">Statistics</h1>
<div className="ui three column grid center aligned">
<div className="column">
<div className="ui segment red">
<div className="ui statistic">
<h3 className="ui header">Ranking</h3>
<div className="value">
{ranking}
</div>
<div className="label">
of {teamlist.length}
</div>
</div>
</div>
</div>
<div className="column">
<div className="ui segment orange">
<div className="ui statistic">
<h3 className="ui header">Score</h3>
<div className="value">
{point}
</div>
<div className="label">
points
</div>
</div>
</div>
</div>
<div className="column">
<div className="ui segment violet">
<div className="ui statistic">
<h3 className="ui header">Flags</h3>
<div className="value">
{solved}
</div>
<div className="label">
captured
</div>
</div>
</div>
</div>
</div>
{errorMessage}
</div>
);
}
};
export default connect(
(state) => ({
solved: state.solved,
point: state.point,
teamlist: state.teamList,
ranking: state.ranking,
start: state.config.start,
end: state.config.end,
countdown: state.countdown
}),
(dispatch) => ({updateTeamlist: (data) => dispatch({type: UPDATE_TEAMLIST, data: data})})
)(Dashboard);
|
import React, {
useCallback,
useContext,
useEffect,
useState,
useRef,
} from 'react';
import Media from './../components/Media/Media';
import Chat from './../components/Chat/Chat';
import LoadingSpinner from './../components/UI/LoadingSpinner';
import SignInBox from './../components/SignInBox/SignInBox';
import Button from './../components/UI/Button';
import styled from 'styled-components';
import firebase from './../services/firebase';
import { useParams, useHistory } from 'react-router-dom';
import { UserContext } from '../contexts/UserContext';
import { RoomContext } from '../contexts/RoomContext';
import { SocketContext } from '../contexts/SocketContext';
const MainContainer = styled.div`
background-color: grey;
display: flex;
justify-content: space-between;
padding-top: 5rem;
`;
const Container = styled.div`
height: 100vh;
padding: 5rem;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
background: rgb(0, 33, 36);
background: radial-gradient(
circle,
rgba(0, 33, 36, 1) 0%,
rgba(163, 163, 163, 1) 0%,
rgb(80, 80, 80) 100%
);
`;
const Room = () => {
const history = useHistory();
const socket = useContext(SocketContext);
const auth = useContext(UserContext);
const room = useContext(RoomContext);
const params = useParams();
const joinedRef = useRef(false);
const [user, setUser] = useState(false);
const { roomId } = params;
// setTimeout(() => {
// if (auth.user) {
// history.push('/room/new');
// }
// }, 1000);
const signInHandler = () => {
console.log(1);
setUser(auth.signIn());
console.log(1);
};
if (!room.state) {
room.getRoom(roomId);
} else if (!joinedRef.current) {
socket.emit('join', roomId, auth.user.name);
joinedRef.current = true;
}
return (
<div>
{!room.state ? (
<Container>
<LoadingSpinner />
</Container>
) : (
<React.Fragment>
{room ? (
<React.Fragment>
{!user && !auth.user && (
<Container>
<h1 style={{ margin: 3 + 'rem' }}>
You have to sign in in order to have access.
</h1>
<div onClick={signInHandler}>
<Button>
<i className='fab fa-google'></i>
<span>Sign In with Google</span>
</Button>
</div>
</Container>
)}
{auth.user && (
<MainContainer>
<Media />
<Chat />
</MainContainer>
)}
</React.Fragment>
) : (
<Container>
<h1 style={{ fontSize: 42 + 'px' }}>Room Not Found</h1>
</Container>
)}
</React.Fragment>
)}
</div>
);
};
export default Room;
|
({
baseUrl: './src',
dir: "./dist",
optimize: "uglify",
optimizeCss: "standard",
skipDirOptimize: true,
fileExclusionRegExp: "^text.js|i18n.js|build.js$",
removeCombined: true,
/*generateSourceMaps:true,//需要optimize:"uglify2"*/
preserveLicenseComments: false,
paths: {
"app": "./",
"jquery": "empty:",
"jquery-ui": "empty:",
"underscore": "empty:",
"text": "../lib/text",
"i18n": "empty:",
"domReady": "empty:",
"tinyMCE": "empty:",
"Jcrop": "empty:"
},
shim: {
"jquery-ui": {
deps: ["jquery"],
exports: "jQuery"
},
"tinyMCE": {
exports: "tinyMCE",
init: function () {
this.tinyMCE.DOM.events.domLoaded = true;
return this.tinyMCE;
}
}
},
modules: [
{
name: "app/box",
exclude: [
"tinyMCE",
"jquery",
"jquery-ui",
"underscore",
"Jcrop"
]
},
{
name: "app/workspace",
exclude: [
"tinyMCE",
"jquery",
"jquery-ui",
"underscore",
"Jcrop"
]
}
]
})
|
// Strict Mode On (엄격모드)
"use strict";
"use warning";
/**
* @author Lazuli
*/
var TutorialPopup = new function() {
var INSTANCE = this;
return {
toString: function() {
return "TutorialPopup";
},
init: function(onload) {
onload();
},
start: function() {
},
run: function() {
UIMgr.repaint();
},
paint: function() {
},
stop: function() {
},
onKeyPressed: function(key) {
switch(key) {
case KEY_ENTER :
break;
}
},
onKeyReleased: function(key) {
switch(key) {
case KEY_ENTER :
break;
}
},
getInstance: function() {
return INSTANCE;
}
};
};
|
<script>
var $iW = $(window).innerWidth();
if ($iW < 992){
$('.rightcolumn').insertBefore('.leftcolumn');
}else{
$('.rightcolumn').insertAfter('.leftcolumn');
}
</script>
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var protractor_1 = require("protractor");
var log4jsonconfig_1 = require("../config/log4jsonconfig");
// Group of specs or tests to execute
describe("Non Angular Application Test", function () {
// Get non-angular application url before each test
beforeEach(function () {
//browser.ignoreSynchronization = true;
global.isAngularSite(false);
protractor_1.browser.get("http://qavalidation.com/demo/");
protractor_1.browser.sleep(2000);
});
// Verify application url
log4jsonconfig_1.log4jsconfig.Log().debug("Verifying Application Url");
it("Verify application url", function () {
expect(protractor_1.browser.getTitle()).toContain("Demo : Practice test automation");
//console.log("Browser Title :-" +browser.getTitle());
var browserTitle = protractor_1.browser.getTitle();
browserTitle.then(function (txt) {
//console.log("Browser Title :-" + txt);
log4jsonconfig_1.log4jsconfig.Log().debug("Browser Title :- " + txt);
});
});
// 1st Test to Enter User Details
log4jsonconfig_1.log4jsconfig.Log().debug("Test Started to Enter User details");
it("Add two numbers", function () {
protractor_1.element(protractor_1.by.id("username")).sendKeys("Manas");
protractor_1.element(protractor_1.by.id("email")).sendKeys("Panigrahi");
protractor_1.element(protractor_1.by.id("tel")).sendKeys("45687");
//element(by.id("email")).sendKeys("Panigrahi");
protractor_1.element(protractor_1.by.xpath("/html/body/div[1]/div/div/div/div/section/div[2]/article/div/div[1]/form/fieldset/div[9]/input")).click();
protractor_1.browser.sleep(3000);
log4jsonconfig_1.log4jsconfig.Log().debug("Test Completed with Entering User details");
});
});
|
const fs = require('fs');
const path = require('path');
async function readContent(path){
return await new Promise((resolve, reject)=>{
fs.readFile(path, 'utf8',(error,data)=>{
if(error) reject(error);
resolve(data);
})
})
}
module.exports ={
readContent
}
|
/*
Al presionar el botón pedir números hasta que el usuario quiera,
sumar los que son positivos y multiplicar los negativos.*/
function mostrar() {
let vNum = 0;
let vSuma = 0;
let vMult = 1;
do {
if (vNum < 0) {
vMult = vMult * vNum;
}
else {
vSuma = vSuma + vNum;
}
vNum = parseInt(prompt("Ingresar número o basta para finalizar"));
}
while (!(isNaN(vNum)));
document.getElementById("txtIdSuma").value = vSuma;
document.getElementById("txtIdProducto").value = vMult;
}//FIN DE LA FUNCIÓN
|
#!/usr/bin/env node
const AWSEmulator = require('../aws-emulator');
const awsEmulator = new AWSEmulator({
lambdaPort: 3000,
dynaPort: 3001
});
const createDynaTable = require('../dynamoDB-functions/create-dyna-table').bind(awsEmulator);
const checkDynaTableExists = require('../dynamoDB-functions/check-dynamo-table-exists').bind(awsEmulator);
const putData = require('../dynamoDB-functions/put-data').bind(awsEmulator);
const getData = require('../dynamoDB-functions/get-data').bind(awsEmulator);
const scanTable = require('../dynamoDB-functions/scan-table').bind(awsEmulator);
const deleteDynaTable = require('../dynamoDB-functions/delete-dyna-table').bind(awsEmulator);
const tableName = 'Dictionary';
void (async () => {
await awsEmulator.start();
await createDynaTable(tableName);
while (!(await checkDynaTableExists(tableName))) {}
await putData(tableName, 1, '123');
await putData(tableName, 2, 'qwe');
await putData(tableName, 3, 'asd');
await putData(tableName, 4, 'zxc');
const result = await getData(tableName, 2);
console.log(result);
const scanResult = await scanTable(tableName);
console.log(scanResult);
await deleteDynaTable(tableName);
})();
|
/*
module for removing unused fontface rules - can be used both for the standalone node binary and the phantomjs script
*/
/*jshint unused:false*/
function unusedFontfaceRemover (css) {
var toDeleteSections = []
// extract full @font-face rules
var fontFaceRegex = /(@font-face[ \s\S]*?\{([\s\S]*?)\})/gm,
ff
while ((ff = fontFaceRegex.exec(css)) !== null) {
// grab the font name declared in the @font-face rule
// (can still be in quotes, f.e. 'Lato Web'
var t = /font-family[^:]*?:[ ]*([^;]*)/.exec(ff[1])
if (!t || typeof t[1] === 'undefined')
continue; // no font-family in @fontface rule!
// rm quotes
var fontName = t[1].replace(/['"]/gm, '')
// does this fontname appear as a font-family or font (shorthand) value?
var fontNameRegex = new RegExp('([^{}]*?){[^}]*?font(-family)?[^:]*?:[^;]*' + fontName + '[^,;]*[,;]', 'gmi')
var fontFound = false,
m
while ((m = fontNameRegex.exec(css)) !== null) {
if (m[1].indexOf('@font-face') === -1) {
// log('FOUND, keep rule')
fontFound = true
break
}
}
if (!fontFound) {
// NOT FOUND, rm!
// can't remove rule here as it will screw up ongoing while (exec ...) loop.
// instead: save indices and delete AFTER for loop
var closeRuleIndex = css.indexOf('}', ff.index)
// unshift - add to beginning of array - we need to remove rules in reverse order,
// otherwise indeces will become incorrect again.
toDeleteSections.unshift({
start: ff.index,
end: closeRuleIndex + 1
})
}
}
// now delete the @fontface rules we registed as having no matches in the css
for (var i = 0; i < toDeleteSections.length; i++) {
var start = toDeleteSections[i].start,
end = toDeleteSections[i].end
css = css.substring(0, start) + css.substring(end)
}
return css
}
if (typeof module !== 'undefined') {
module.exports = unusedFontfaceRemover
}
|
export default {
head: {
meta: [{
name: 'viewport',
content: 'width=device-width, initial-scale=1'
}],
script: [{
src: 'https://kit.fontawesome.com/e314b947e0.js',
crossorigin: 'anonymous'
}]
}
}
|
/*jslint browser: true*/
/*global JDY, equal, test*/
test(" jdyviewtest AppRepository creation", function () {
"use strict";
var rep = JDYTEST.meta.createTestRepository(),
allAttrTyp = rep.getClassInfo("AllAttributeTypes");
equal(allAttrTyp.internalName, "AllAttributeTypes", "Class AllAttributeTypes exists");
});
test(" JDY.view.getDisplayAttributesFor", function () {
"use strict";
var rep = JDYTEST.meta.createTestRepository(),
allAttrTyp = rep.getClassInfo("AllAttributeTypes"),
aspectPaths = JDY.view.getDisplayAttributesFor(allAttrTyp),
appRep = JDY.meta.createAppRepository();
equal(aspectPaths.length, 1, "AllAttributeTypes 1 path");
equal(aspectPaths[0].length, 1, "AllAttributeTypes One Attribute in first path");
equal(aspectPaths[0][0].internalName, "IntegerData", "One Attribute in first path");
aspectPaths = JDY.view.getDisplayAttributesFor(appRep.getClassInfo("AppRepository"));
equal(aspectPaths.length, 1, "AppRepository 1 path");
equal(aspectPaths[0].length, 1, "AppRepository One Attribute in first path");
equal(aspectPaths[0][0].internalName, "applicationName", "One Attribute in first path");
aspectPaths = JDY.view.getDisplayAttributesFor(appRep.getClassInfo("AppTextType"));
equal(aspectPaths.length, 3, "AppTextType 3 paths");
equal(aspectPaths[0].length, 1, "AppTextType 1 Attribute in path 0");
equal(aspectPaths[1].length, 2, "AppTextType 2 Attributes in path 1");
equal(aspectPaths[2].length, 3, "AppTextType 3 Attributes in path 2");
equal(aspectPaths[0][0].internalName, "InternalName", "AppTextType 0 0");
equal(aspectPaths[1][0].internalName, "Masterclass", "AppTextType 1 0");
equal(aspectPaths[1][1].internalName, "InternalName", "AppTextType 1 1");
equal(aspectPaths[2][0].internalName, "Masterclass", "AppTextType 2 0");
equal(aspectPaths[2][1].internalName, "Repository", "AppTextType 2 1");
equal(aspectPaths[2][2].internalName, "applicationName", "AppTextType 2 2");
});
|
import reimbursementApi from '@/api/reimbursement'
import commonJS from '@/common/common'
import userApi from '@/api/user'
export default {
data () {
return {
// 总报销金额
reimbursementSum: 10,
// 显示搜索结果
showSearchResult: false,
table: {
content: [],
totalElements: 0,
pageable: {
pageNumber: commonJS.getPageNumber('reimbursementSummaryList.pageNumber'),
pageSize: commonJS.getPageSize('reimbursementSummaryList.pageSize')
}
},
page: {
pageSizes: [10, 30, 50, 100, 300]
},
currentRow: null,
companyList: commonJS.companyList,
searchDialog: false,
search: commonJS.getStorageContentObject('reimbursementSummaryList.search'),
reimbursementMonth: commonJS.getYYYY_MM(new Date()), // 报销月份,默认是当月
roles: [],
jobType: ''
}
},
methods: {
// 表格双击处理
handleRowDblClick (row, column, event) {
this.$router.push({
path: '/salary/reimbursementItemList',
query: {
mode: 'query',
row: row
}
})
},
// 显示控制
showControl (key) {
if (key === 'generateReimbursementSummary' || key === 'edit' || key === 'statistics') {
return commonJS.isAdminInArray(this.roles)
}
// 没有特殊要求的不需要角色
return true
},
// 生成报销摘要
generateReimbursementSummary () {
if (this.reimbursementMonth === null || this.reimbursementMonth === '') {
this.$message({
message: '请选择月份',
type: 'warning',
showClose: true
})
} else {
let msg = '确定要生成' + this.reimbursementMonth + '月的报销吗?'
this.$confirm(msg, '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
center: true
}).then(() => {
let request = {
month: this.reimbursementMonth
}
reimbursementApi.generateReimbursementSummary(request).then(
res => {
if (res.status === 200) {
this.$message({
message: '生成成功!',
type: 'success',
showClose: true
})
this.query()
} else {
this.$message.error('生成失败!')
}
})
})
}
},
// 查询后台数据
query () {
window.localStorage['reimbursementSummaryList.search'] = JSON.stringify((typeof (this.search) === 'undefined' || typeof (this.search) !== 'object') ? {} : this.search)
window.localStorage['reimbursementSummaryList.pageNumber'] = this.table.pageable.pageNumber
window.localStorage['reimbursementSummaryList.pageSize'] = this.table.pageable.pageSize
this.searchDialog = false
let query = {
'currentPage': this.table.pageable.pageNumber,
'pageSize': this.table.pageable.pageSize,
'company': this.search.company,
'userName': this.search.userName,
'paymentMonth': this.search.paymentMonth,
'sum': this.search.sum
}
reimbursementApi.querySummaryPage(query).then(res => {
if (res.status !== 200) {
this.$message.error({
message: '查询失败,请联系管理员!'
})
return
}
this.table = res.data.page
this.reimbursementSum = res.data.sum
this.table.pageable.pageNumber = this.table.pageable.pageNumber + 1
})
},
// 行变化
rowChange (val) {
this.currentRow = val
},
// 页尺寸变化
sizeChange (val) {
this.table.pageable.pageSize = val
this.query()
},
// 当前页变化
currentChange (val) {
this.table.pageable.pageNumber = val
this.query()
},
// 上一页 点击
prevClick (val) {
this.table.pageable.pageNumber = val
this.query()
},
// 下一页 点击
nextClick (val) {
this.table.pageable.pageNumber = val
this.query()
},
// 搜索对话框,确定按钮
sureSearchDialog () {
this.table.pageable.pageNumber = 1
this.query()
},
// 清空查询条件
clearQueryCondition () {
this.search = {}
window.localStorage['reimbursementSummaryList.search'] = {}
},
// 公司转换器
companyFormatter (row) {
for (let c of this.companyList) {
if (c.code === row.company) {
return c.name
}
}
},
// 设置行样式
setRowClassName ({
row,
index
}) {
if (row.company === 'Shanghaihailuorencaikeji') {
return 'row1'
} else if (row.company === 'Shenyanghailuorencaifuwu') {
return 'row2'
} else if (row.company === 'Wuhanhailuorencaifuwu') {
return 'row3'
} else if (row.company === 'Nanjinghailuorencaifuwu') {
return 'row4'
}
},
// 下载报销项
downloadReimbursementSummary () {
let query = {
'currentPage': this.table.pageable.pageNumber,
'pageSize': this.table.pageable.pageSize,
'company': this.search.company,
'userName': this.search.userName,
'paymentMonth': this.search.paymentMonth,
'sum': this.search.sum
}
reimbursementApi.downloadReimbursementSummary(query).then(res => {
if (res.status === 200) {
this.$message({
message: '下载成功!',
type: 'success',
showClose: true
})
}
})
}
},
created () {
// 获取当前用户的角色列表
userApi.findSelf().then(res => {
if (res.status === 200) {
this.roles = res.data.roles
this.jobType = res.data.jobType
}
})
this.query()
}
}
|
$(document).ready(function() {
$('.fade').hover(
function(){
$(this).find('.caption').fadeIn(250);
},
function(){
$(this).find('.caption').fadeOut(250);
}
);
$('#clickme').click(function (){
var newComment = $('#comment').val();
appendItem (newComment);
$('#item').val('');
});
$('#burger').click(function() {
$('.mobile-nav').slideToggle();
});
window.sr = ScrollReveal();
sr.reveal('.blog-image',{ duration: 1000 });
});
function appendItem (newComment) {
$('#list').append('<p>' + newComment + '</p>' );
}
$(window).on("load", function() {
$( '#img1' ).fadeIn( 50, function() {
$( '#img2' ).fadeIn( 75, function() {
$( '#img3' ).fadeIn( 100, function() {
$( '#img4' ).fadeIn( 125, function() {
$( '#img5' ).fadeIn( 150 )
});
});
});
});
});
// $('.intro').fadeIn(200);
// $('#img1').fadeIn(500);
// $('#img2').fadeIn(800);
// $('#img3').fadeIn(1100);
// $('#img4').fadeIn(1400);
// $('#img5').fadeIn(1700);
// Animation complete
// 10 seconds
|
const canvas = document.getElementById('runner'),
ctx = canvas.getContext('2d');
let lastDate,
platforms = [],
viewport = {};
let mouseX, mouseY;
let MODE = -1;
const images = {};
images.emil = new Image();
images.emil.src = "public/emil.png";
function UpdateCanvasDimensions() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
function MouseMove(e) {
mouseX = e.offsetX;
mouseY = e.offsetY;
}
|
import { makeStyles } from '@material-ui/core/styles'
const useStyles = makeStyles((theme) => ({
root: {
marginTop: '50px',
},
loginFromWrap: {
padding: '20px',
},
headerText: {
marginBottom: '20px',
},
input: {
marginBottom: '10px',
},
buttonGroup: {
display: 'flex',
flexDirection: 'column',
alignItems: 'strech',
'& > *': {
margin: theme.spacing(0.5),
},
},
}))
export default useStyles
|
import React, { useState, useEffect } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
TextField,
Grid,
MenuItem,
Typography,
} from '@material-ui/core';
import { Autocomplete } from '@material-ui/lab';
const { ipcRenderer } = require('electron');
const fs = require('fs');
const path = require('path');
const useStyles = makeStyles((theme) => ({
dialogPaper: {
height: '80vh',
},
}));
const types = [
{ value: 'series', label: 'Series' },
{ value: 'episode', label: 'Episode' },
{ value: 'movie', label: 'Movie' },
];
const seasons = [
{ value: 'winter', label: 'Winter' },
{ value: 'spring', label: 'Spring' },
{ value: 'summer', label: 'Summer' },
{ value: 'fall', label: 'Fall' },
];
const MediaEdit = ({ open, onClose, show }) => {
const classes = useStyles();
const [title, setTitle] = useState(show.title);
const [currentSeason, setCurrentSeason] = useState(
show.series_seasons[0].current_season
);
const [airingSeason, setAiringSeason] = useState(show.airing_season);
const [airingYear, setAiringYear] = useState(show.airing_year);
const [imagePath, setImagePath] = useState(
show.series_seasons[0].image_location
);
const [mediaPath, setMediaPath] = useState(
show.series_seasons[0].directory_location
);
const [summary, setSummary] = useState(show.series_seasons[0].summary);
const [tags, setTags] = useState(
show.series_tags.map((series_tag) => series_tag.tag.tag_name)
);
const loaded = React.useRef(false);
useEffect(() => {
if (!loaded.current) {
//#region ipcRenderer
ipcRenderer.on('image:select', (event, paths) => {
setImagePath(JSON.parse(paths)[0]);
});
//#endregion
loaded.current = true;
}
}, []);
//#region Events
const handleTitleChange = (event) => {
setTitle(event.target.value);
};
const handleTypeChange = (event) => {
setType(event.target.value);
};
const handleCurrentSeasonChange = (event) => {
setCurrentSeason(event.target.value);
};
const handleAiringSeasonChange = (event) => {
setAiringSeason(event.target.value);
};
const handleAiringYearChange = (event) => {
setAiringYear(event.target.value);
};
const handleImageClick = (event) => {
ipcRenderer.send('image:click');
};
const handleSummaryChange = (event) => {
setSummary(event.target.value);
};
const handleTagDone = (event, options, reason) => {
setTags(options);
};
const handleClose = () => {
onClose();
};
const handleSave = (event) => {
event.preventDefault();
const updateShow = {
id: show.id,
title,
image_location: imagePath,
current_season: currentSeason,
airing_season: airingSeason,
airing_year: airingYear,
summary,
tags,
};
ipcRenderer.send('series:edit', updateShow);
onClose();
};
//#endregion
return (
<Dialog
open={open}
onClose={handleClose}
fullWidth
maxWidth={'md'}
classes={{ paper: classes.dialogPaper }}
>
<form onSubmit={handleSave}>
<DialogTitle>Add Media</DialogTitle>
<DialogContent style={{ overflowY: 'visible' }}>
<Grid container spacing={3}>
<Grid item xs={9}>
<TextField
required
autoFocus
fullWidth
value={title}
onChange={handleTitleChange}
placeholder="Title..."
helperText="Series Title (Required)"
/>
</Grid>
<Grid item xs={3}>
<TextField
required
type="number"
fullWidth
value={currentSeason}
onChange={handleCurrentSeasonChange}
helperText="Current Season (Required)"
></TextField>
</Grid>
<Grid item xs={6}>
<TextField
select
fullWidth
value={airingSeason}
onChange={handleAiringSeasonChange}
helperText="Airing Season"
>
{seasons.map((season) => (
<MenuItem
key={season.value}
value={season.value}
>
{season.label}
</MenuItem>
))}
</TextField>
</Grid>
<Grid item xs={6}>
<TextField
required
type="number"
fullWidth
value={airingYear}
onChange={handleAiringYearChange}
helperText="Airing Year (Required)"
></TextField>
</Grid>
<Grid item xs={4}>
<Button
fullWidth
variant="outlined"
size="large"
onClick={handleImageClick}
>
Choose image for series
</Button>
</Grid>
<Grid item xs={8}>
<TextField
name="imagePath"
fullWidth
placeholder="Path to image..."
disabled
value={imagePath}
/>
</Grid>
<Grid item xs={12}>
<TextField
multiline
fullWidth
rows={4}
value={summary}
onChange={handleSummaryChange}
helperText="Summary"
/>
</Grid>
<Grid item xs={12}>
<Autocomplete
multiple
options={tags}
fullWidth
freeSolo
value={tags}
onChange={handleTagDone}
renderInput={(params) => (
<TextField
{...params}
helperText="Tags"
variant="standard"
/>
)}
/>
</Grid>
</Grid>
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>Close</Button>
<Button type="submit">Save</Button>
</DialogActions>
</form>
</Dialog>
);
};
export default MediaEdit;
|
/**
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.provide('audioCat.audio.record.MediaSourceObtainer');
goog.require('audioCat.audio.record.Event');
goog.require('audioCat.audio.record.ExceptionType');
goog.require('audioCat.utility.EventTarget');
goog.require('goog.asserts');
/**
* Obtains a media stream for use in say recording. Throws an exception during
* construction if media streaming (ie, getUserMedia) is not available.
* @param {!audioCat.utility.IdGenerator} idGenerator Generates IDs unique
* throughout the application.
* @param {!audioCat.utility.support.SupportDetector} supportDetector Detects
* support for various features and formats.
* @constructor
* @extends {audioCat.utility.EventTarget}
*/
audioCat.audio.record.MediaSourceObtainer = function(
idGenerator,
supportDetector) {
goog.base(this);
/**
* @private {!audioCat.utility.support.SupportDetector}
*/
this.supportDetector_ = supportDetector;
/**
* The default media audio stream. null if not obtained.
* @private {MediaStream}
*/
this.defaultMediaAudioStream_ = null;
// If recording is supported, we should have a getUserMedia method.
// For implications, not p or q is the same thing as if p, then q.
goog.asserts.assert(
!supportDetector.getRecordingSupported() || navigator.getUserMedia);
};
goog.inherits(
audioCat.audio.record.MediaSourceObtainer, audioCat.utility.EventTarget);
/**
* @return {MediaStream} The media stream. null if not obtained.
*/
audioCat.audio.record.MediaSourceObtainer.prototype.getDefaultAudioStream =
function() {
return this.defaultMediaAudioStream_;
};
/**
* Obtains the default audio source. Fires an event when it dones so.
*/
audioCat.audio.record.MediaSourceObtainer.prototype.obtainDefaultAudioStream =
function() {
if (this.supportDetector_.getRecordingSupported()) {
// Only obtain a media stream if the browser supports recording.
var self = this;
navigator.getUserMedia({
'audio': true
},
goog.bind(this.handleDefaultAudioStream_, self),
goog.bind(this.handleStreamObtainingError_, self));
}
};
/**
* Handles what happens when we obtain the default audio stream.
* @param {!MediaStream} mediaStream The media stream.
* @private
*/
audioCat.audio.record.MediaSourceObtainer.prototype.handleDefaultAudioStream_ =
function(mediaStream) {
this.defaultMediaAudioStream_ = mediaStream;
// At this point, the default audio media stream is defined for sure.
this.dispatchEvent(audioCat.audio.record.Event.DEFAULT_AUDIO_STREAM_OBTAINED);
};
/**
* Handles what happens there is an error while obtaining the audio stream.
* @private
*/
audioCat.audio.record.MediaSourceObtainer.prototype.
handleStreamObtainingError_ = function() {
this.dispatchEvent(audioCat.audio.record.Event.AUDIO_STREAM_FAILED_TO_OBTAIN);
};
|
function getDay(year,month){
var days = [31,28,31,30,31,30,31,31,30,31,30,31];
if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) days[1]++;
return days[month-1];
}
function check_list() {
var list = document.getElementById("newList");
if(list.value == "") return false;
return true;
}
function check_search(){
if(document.getElementById("search").value == "")return false;
return true;
}
function TimeCheck(){
var title = document.getElementById("title").value;
var year = document.getElementById("year").value;
var month = document.getElementById("month").value;
var day = document.getElementById("day").value;
var tip = document.getElementById("tip");
if(title == ""){
tip.innerHTML = "标题不能为空";
return false;
}
if(year == "" || isNaN(year) || year < 2000 || year >2100){
tip.innerHTML = "年份不合法";
return false;
}
if(month == "" || isNaN(month) || month < 1 || month > 12){
tip.innerHTML = "月份不合法";
return false;
}
if(day == "" || isNaN(day) || day < 1 || day > getDay(year,month)){
tip.innerHTML = "日期不合法";
return false;
}
return true;
}
function clearForm(){
document.getElementById("title").value = "";
document.getElementById("year").value = "";
document.getElementById("month").value = "";
document.getElementById("day").value = "";
document.getElementById("urg1").checked = "checked";
}
function update(title,time,urg,id,list){
show_cover();
show_thing();
var year = time.substring(0,4);
var month = time.substring(5,7);
var day = time.substring(8,10);
document.getElementById("title").value = title;
document.getElementById("year").value = year;
document.getElementById("month").value = month;
document.getElementById("day").value = day;
document.getElementById("urg"+urg).checked = "checked";
document.getElementById("myform").action = "/updateThing?id="+id+"&list="+list;
}
function show_list(){
document.getElementById("li_list").style.display = "block";
}
function hide_list(){
document.getElementById("li_list").style.display = "none";
}
function show_thing(){
document.getElementById("thing").style.display = "block";
}
function hide_thing(){
document.getElementById("thing").style.display = "none";
}
function show_cover(){
document.getElementById("cover").style.display = "block";
}
function hide_cover(){
document.getElementById("cover").style.display = "none";
}
function addThing(){
document.getElementById("cover").style.display = "block";
document.getElementById("thing").style.display = "block";
}
function hide_all(list){
document.getElementById("cover").style.display = "none";
document.getElementById("thing").style.display = "none";
document.getElementById("myform").action = "/addThing?list="+list;
clearForm();
}
function newList(){
if(document.getElementById("li_list").style.display == "none")show_list();
else hide_list();
}
function deleteList(id){
location.href = "/deleteList?id="+id;
}
window.onload = function() {
if(document.body.clientWidth < 768) {
document.getElementById("nav0").style.display = "none";
}
}
var sing = 0;
//漢堡按鈕
function container() {
if(sing == 0) {
document.getElementById("nav0").style.display = "block";
sing = 1;
} else {
document.getElementById("nav0").style.display = "none";
sing = 0;
}
}
window.onresize = function() {
if(document.body.clientWidth < 768) {
document.getElementById("nav0").style.display = "none";
}
if(document.body.clientWidth >= 768) {
document.getElementById("nav0").style.display = "block";
}
}
|
/*****************************/
/*******초기 환경 설정*********/
/*****************************/
var express = require('express');
var router = express.Router();
var jkh_db_config = require('./process/login_db');
var jkh_suggest = require('./process/suggest_db');
var jkh_product = require('./process/product_db');
/*****************************/
/******db 연결부 코드구현******/
/*****************************/
const db_config = require('../db/db.js')
const conn = db_config.init()
db_config.connect(conn)
/*****************************/
/**********URL 관리***********/
/*****************************/
//접근제한 관련 코드 작성
router.post('/p/m/office',(req,res)=>{
if(req.session.user)
{
res.redirect(302,`/web/office_function.html`);
}else
{
res.redirect(302,'/web/landing/office/index.html');
}
});
router.get('/p/m/industry',(req,res)=>{
if(req.session.user)
{
res.redirect(302,`/web/industry_function.html`);
}else
{
res.redirect(302,'/web/landing/industry/index.html');
}
});
/*****************************/
/**********로그인 설정*********/
/*****************************/
router.post('/login', (req, res) => {
var req_data = {
email: req.body.id,
pw: req.body.password
}
jkh_db_config.userSelect_post(req, res, conn, req_data);
});
//로그인 - 세션등록
router.get('/login', (req, res) => {
try{
var req_data = {
name: req.session.user.name,
email: req.session.user.email,
pw: req.session.user.password
}}
catch(e){
}
jkh_db_config.userSelect_get(req, res, conn, req_data);
})
//로그인 - 닉네임 추출
router.post('/logout', (req, res) => {
jkh_db_config.userdisable(req, res, conn);
})
//로그아웃
router.post('/regi', (req, res) => {
var req_data = {
email: req.body.email,
pw: req.body.password,
name: req.body.username,
}
jkh_db_config.userCreate(req, res, conn, req_data);
});
//회원 가입
router.post('/repw', (req, res) => {
var email = req.body.email;
jkh_db_config.userchage(req, res, conn, email);
});
//비밀번호 찾기
/*****************************/
/*******게시판 환경 소스*******/
/*****************************/
router.post('/suggest', (req, res) => {
var data_sug = {
email: req.body.email,
name: req.body.name,
msg: req.body.message,
title:req.body.title
}
jkh_suggest.addsuggest(req, res, conn, data_sug);
});
router.get('/suggest/list', (req, res) => {
// var data_sug = {
// email: req.body.email,
// name: req.body.name,
// msg: req.body.message,
// title:req.body.title
// }
jkh_suggest.listsuggest(req, res, conn);
});
//건의 사항 접수
/*****************************/
/*********제품 관리 환경*******/
/*********사무실 페이지********/
/*****************************/
router.get('/p/list', (req, res) => {
jkh_product.listSelect(res, conn);
});
//제품리스트 반환
router.post('/p/buy', (req,res) => {
var data_sug = {
listname : req.body.name,
count : req.body.count
}
jkh_product.buySelect(req,res,conn,data_sug);
});
//제품 구매
router.get('/p/order/list', (req,res) => {
jkh_product.order_history_list(res,conn);
})//발주 기록
router.post('/p/buy/out', (req,res) => {
var data_sug = {
listname : req.body.name,
count : req.body.count,
qr_code : req.body.qr_code
}
jkh_product.out_order_history_list(req,res,conn,data_sug);
})//출고 명령
/*****************************/
/******최상위 환경 페이지******/
/*****************************/
router.post('/')
//'//web/landing/industry/index.html' 일때 로그인의 유무를 판단하는 기능 구현
router.get('/', (req, res) => {
req.session;
res.redirect(302, '/web/index.html');
});
//메인페이지로 이동
//
/*****************************/
/**** 공기 청정기 데시보드 ****/
/*****************************/
router.get('/dashboard/info1', (req, res) => {
const response = {
state: 1,
query: null,
msg: 'Succesful'
}
var sql = 'SELECT AIR_database.misae FROM AIR_database WHERE obid=1;'//가져오기
//console.log(sql);
conn.query(sql, function (err, results, field) {
let json1 = results[0].misae;
response.query = json1+"㎍/m³"; // 결과 가져오기
//console.log(response.query)
//return res.send(response.query)
return res.status(200).json(response);
})
// const date = new Date()//시간
// response.query = date;
//return res.status(200).json(response);
})//공기청정기 데이터
router.get('/dashboard/info2', (req, res) => {
const response = {
state: 1,
query: null,
msg: 'Succesful'
}
var pmvalue =0;
const air = require('./air');
//setInterval(air,5000000);
let prov = req.query.prov ? req.query.prov : '경남';
let region = req.query.region ? req.query.region : '삼방동';
air.getAirStatus(prov, region).then(function (res_air) {
res.status(200);
//res.send(res_air.stationName + '의 pm25등급은 ' + res_air.pm25Grade + ' 입니다. 시간 : ' + res_air.dataTime);
pmvalue =res_air.pm25Value+"㎍/m³";
res.end();
}).catch(function (e) {
res.status(500);
res.send(e.message);
pmvalue = 13+"㎍/m³";
res.end();
});
response.query = pmvalue ==0?"38"+"㎍/m³":pmvalue+"㎍/m³";//일일트래픽 다써서 가라침..
return res.status(200).json(response);
})//환경공단 미세먼지 (pm25 , 경남, 삼방동) 데이터 //일일트래픽 다씀
router.get('/dashboard/info3', (req, res) => {``
const response = {
state: 1,
query: null,
msg: 'Succesful'
}
//console.log(sql);
conn.query(sql, function (err, results, field) {
let json1 = results[0].temperature+"˚ / ";//30.5
let json2 = results[0].humidity+"%";//30.5
response.query = json1+json2; // 결과 가져오기
//console.log(response.query)
//return res.send(response.query)
return res.status(200).json(response)
})
//return res.status(200).json(response);//ajax에게 줄때
})//온습도데이터
router.get('/dashboard/info4', (req, res) => {
const response = {
state: 1,
query: null,
msg: 'Succesful'
}
var sql = 'SELECT AIR_database.misae FROM AIR_database WHERE obid=1;'//가져오기
//console.log(sql);
conn.query(sql, function (err, results, field) {
let json1 = 30.5;
response.query = json1+"㎍/m³"; // 결과 가져오기
//console.log(response.query)
//return res.send(response.query)
return res.status(200).json(response)
})
//return res.status(200).json(response);//ajax에게 줄때
})//평균농도
module.exports = router;
|
function theBeatlesPlay(musicians, instruments){
var function1=[]
for (var i=0; i<musicians.length; i++){
function1.push(musicians[i]+ " plays " + instruments[i])
}
return function1
}
function johnLennonFacts(facts){
var i=0;
while (i<facts.length){
facts[i]=facts[i]+"!!!"
i++
}
return facts
}
function iLoveTheBeatles(num){
var first=[]
var i=0;
do {
first.push("I love the Beatles!")
i++
}while (i<=num && num <15)
return first;
}
|
!function () {
function OutstandingCommissionInfoController($scope, $location, oc) {
var totalReceivableCommission,
totalCommissionReceived,
value;
totalReceivableCommission = oc.studentPaidRecords.reduce(function (previousValue, record) {
return previousValue + record.commission;
}, 0);
totalCommissionReceived = oc.commissionReceivedRecords.reduce(function (previousValue, record) {
return previousValue + record.amount;
}, 0);
$scope.totalReceivableCommission = totalReceivableCommission;
$scope.totalCommissionReceived = totalCommissionReceived;
$scope.ocValue = totalReceivableCommission - totalCommissionReceived;
$scope.oc = oc;
}
OutstandingCommissionInfoController.resolve = {
oc: function ($route, $q, outstandingCommissionService) {
var id = $route.current.params.id,
deferred = $q.defer();
if (id) {
deferred = outstandingCommissionService.get({ id: id });
} else {
deferred.resolve({});
}
return deferred.$promise;
}
};
OutstandingCommissionInfoController.$inject = ['$scope', '$location', 'oc'];
function OutstandingCommissionSearchController($scope, outstandingCommissionService) {
$scope.search = function () {
return $scope.results = outstandingCommissionService.query();
};
}
OutstandingCommissionSearchController.$inject = ['$scope', 'outstandingCommissionService'];
angular.module('DNNT')
.controller('outstandingCommissionInfoController', OutstandingCommissionInfoController)
.controller('outstandingCommissionSearchController', OutstandingCommissionSearchController);
window.OutstandingCommissionInfoController = OutstandingCommissionInfoController;
}();
|
const viewEditUser = (req, res) => {
let user_id = req.params.id;
res.render('user_edit', {user_id: user_id});
}
module.exports = {
viewEditUser
}
|
'use strict';
module.exports = require('./csjs');
module.exports.csjs = module.exports;
module.exports.getCss = require('./get-css');
|
import { React, useState, useEffect, useMemo } from 'react';
import { useTable } from 'react-table'
import { COLUMNS } from './DriverResultsColumns'
import { GrandPrixYearSelector } from './GrandPrixYearSelector';
import './DriverResults.scss'
export const DriverResults = ({ results }) => {
const [yearSelected, setYearSelected] = useState(2021);
const [years, setYears] = useState([]);
const columns = useMemo(() => COLUMNS, []);
const [resultsSelected, setResultsSelected] = useState([]);
useEffect(
() => {
let years = new Set();
results.forEach(i => years.add(i.grandPrix.year));
setYears(Array.from(years).sort().reverse());
let maxYear = 1900;
results.forEach(i =>
maxYear = i.grandPrix.year > maxYear ? i.grandPrix.year : maxYear
);
setYearSelected(maxYear);
}, [results]
);
useEffect(
() => {
const filtered = results.filter(value => value.grandPrix.year === yearSelected);
filtered.sort().reverse();
setResultsSelected(filtered);
}, [yearSelected, results]
);
const handleCallback = (childData) => {
setYearSelected(parseInt(childData))
}
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow
} = useTable({
columns: columns,
data: resultsSelected
})
return (
<section className="DriverResult">
<section className="year-selector">
<GrandPrixYearSelector parentCallback={handleCallback} years={years} yearSelected={yearSelected} />
</section>
<section className="scrollable">
<table className="table" {...getTableProps()}>
<thead>{
headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>{column.render('Header')}</th>
))}
</tr>
))
}
<tr>
</tr>
</thead>
<tbody className="table-body" {...getTableBodyProps()}>
{rows.map((row) => {
prepareRow(row)
return (
<tr {...row.getRowProps()} className="table-row">
{row.cells.map(cell => {
return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
})}
</tr>
)
})}
</tbody>
</table>
</section>
</section>
);
}
|
// JScript File
// date field validation (called by other validation functions that specify minYear/maxYear)
function isDate(gField,minYear,maxYear) {
var inputStr = gField.value;
// convert hyphen delimiters to slashes
while (inputStr.indexOf("-") != -1) {
var regexp = /-/;
inputStr = inputStr.replace(regexp,"/"); }
var delim1 = inputStr.indexOf("/")
var delim2 = inputStr.lastIndexOf("/")
if (delim1 != -1 && delim1 == delim2) {
// there is only one delimiter in the string
alert("The date entry is not in an acceptable format.\n\nYou can enter dates in the following formats: mmddyyyy, mm/dd/yyyy, or mm-dd-yyyy. (If the month or date data is not available, enter \'01\' in the appropriate location.)")
gField.focus()
gField.select()
return false }
if (delim1 != -1) {
// there are delimiters; extract component values
var mm = parseInt(inputStr.substring(0,delim1),10)
var dd = parseInt(inputStr.substring(delim1 + 1,delim2),10)
var yyyy = parseInt(inputStr.substring(delim2 + 1, inputStr.length),10)
} else {
// there are no delimiters; extract component values
var mm = parseInt(inputStr.substring(0,2),10)
var dd = parseInt(inputStr.substring(2,4),10)
var yyyy = parseInt(inputStr.substring(4,inputStr.length),10)
}
if (isNaN(mm) || isNaN(dd) || isNaN(yyyy)) {
// there is a non-numeric character in one of the component values
alert("The date entry is not in an acceptable format.\n\nYou can enter dates in the following formats: mmddyyyy, mm/dd/yyyy, or mm-dd-yyyy.")
gField.focus()
gField.select()
return false
}
if (mm < 1 || mm > 12) {
// month value is not 1 thru 12
alert("Months must be entered between the range of 01 (January) and 12 (December).")
gField.focus()
gField.select()
return false
}
if (dd < 1 || dd > 31) {
// date value is not 1 thru 31
alert("Days must be entered between the range of 01 and a maximum of 31 (depending on the month and year).")
gField.focus()
gField.select()
return false
}
// validate year, allowing for checks between year ranges
// passed as parameters from other validation functions
if (yyyy < 100) {
// entered value is two digits, which we allow for 1930-2029
alert("Year must be entered in four-digit format. Please try again!")
gField.focus()
gField.select()
return false
}
if (yyyy < minYear || yyyy > maxYear) {
alert("Year must be entered between the range of " + minYear + " and " + maxYear + ".");
gField.focus()
gField.select()
return false
}
if (!checkMonthLength(mm,dd)) {
gField.focus()
gField.select()
return false
}
if (mm == 2) {
if (!checkLeapMonth(mm,dd,yyyy)) {
gField.focus()
gField.select()
return false
}
}
gField.value = mm + "/" + dd + "/" + yyyy;
return true;
}
// check the entered month for too high a value
function checkMonthLength(mm,dd) {
var months = new
Array("","January","February","March","April","May","June","July","August","September","October","November","December")
if ((mm == 4 || mm == 6 || mm == 9 || mm == 11) && dd > 30) {
alert(months[mm] + " has only 30 days.")
return false
} else if (dd > 31) {
alert(months[mm] + " has only 31 days.")
return false
}
return true
}
// check the entered February date for too high a value
function checkLeapMonth(mm,dd,yyyy) {
if (yyyy % 4 > 0 && dd > 28) {
alert("February of " + yyyy + " has only 28 days.")
return false
} else if (dd > 29) {
alert("February of " + yyyy + " has only 29 days.")
return false
}
return true
}
// get current year
function getTheYear() {
var thisYear = (new Date()).getFullYear();
return thisYear
}
function updatelevel()
{
document.form.action = "userprofile.aspx";
document.form.submit();
}
function admin_changepwd(){
if(document.all['ctl00_MainContent_txtCurpwd'].value == "") {
alert('Please enter password!');
document.all['ctl00_MainContent_txtCurpwd'].focus();
return false;
}
if(document.all['ctl00_MainContent_txtNewpwd'].value=="") {
alert('Please enter password!');
document.all['ctl00_MainContent_txtNewpwd'].focus();
return false;
}
if(document.all['ctl00_MainContent_txtNewpwd'].value.length < 6 && document.all['ctl00_MainContent_txtNewpwd'].value.length > 0){
alert('Password requires at least 6 characters!');
document.all['ctl00_MainContent_txtNewpwd'].focus();
return false;
}
if (document.all['ctl00_MainContent_txtNewpwd'].value != document.all['ctl00_MainContent_txtConfpwd'].value) {
alert('Password does not match! Please re-enter password.');
document.all['ctl00_MainContent_txtConfpwd'].focus();
return false;
}
}
/****************************************************
** Function sendEmail_confrim()
** Description:use to send mail page to confirm the sendmail:whether really want to send Email
** Input:
** Output:
** 02/15/05 - Created(jack)
****************************************************/
function sendEmail_confrim(){
return confirm("Do you really want to send email?");
}
/****************************************************
** Function
** Description:use to send mail page
** Input:
** Output:
** 02/14/05 - Created(jack)
****************************************************/
function copyTex(){
document.getElementById('ctl00_MainContent_txtText').innerText=document.getElementById('myDiv').innerHTML;
//--add by eJay 2/16/05
document.getElementById('ctl00_MainContent_txtFooter').innerText=document.getElementById('divFooter').innerHTML;
//document.all['ctl00_MainContent_txtFile'].value=document.all['browse'].value;
}
function initDiv(){
document.getElementById('myDiv').innerHTML=document.getElementById('ctl00_MainContent_txtText').innerText;
//--add by eJay 2/16/05
if(document.getElementById('myDiv').innerHTML==""&&document.getElementById('ctl00_MainContent_txtEmailadd').value==""){
document.getElementById('ctl00_MainContent_txtFooter').innerText="<TR><td align='center'width='100%' style='FONT-FAMILY: Arial'>Please visit <font color=blue size=3><a href='www.1800fly1800.com'>www.1800fly1800.com</a></font> or </td></TR><TR><td align='center'width='100%' style='FONT-FAMILY: Arial'>Call 1-800-<font color=blue>APEX</font>-1800 to make reservations at your convenience.</td></TR>";
}
document.getElementById('divFooter').innerHTML=document.getElementById('ctl00_MainContent_txtFooter').innerText;
//alert(browse.value);
//document.all['browse'].value=document.all['ctl00_MainContent_txtFile'].value;
//document.all['ctl00_MainContent_txtFile'].style.display='none';
}
function jumpnewwindow(){
window.open('preview_email.aspx','Preview','width=800,height=400,scrollbars=1,resizable=yes');
}
function jumpvipwindow(){
window.open('details.aspx','VipPreview','width=800,height=400,scrollbars=1');
}
/****************************************************
** Function set_defaultinfo_pageload()
** Description:when the page load
** Input:
** Output:
** 12/06/04 - Created(jack)
****************************************************/
function set_defaultinfo_pageload()
{var type=document.all['ctl00_MainContent_ddlCardType'].options[document.all['ctl00_MainContent_ddlCardType'].selectedIndex].value
if (document.all['ctl00_MainContent_txtCardNo'].value!="")
{
document.all["hidcctype" + type].value=document.all['ctl00_MainContent_txtCardNo'].value + "/" +document.all['ctl00_MainContent_ddlMonth'].selectedIndex + "/" + document.all['ctl00_MainContent_ddlYear'].selectedIndex;
}
}
/****************************************************
** Function set_defaultinfo_pageload()
** Description:when the page load
** Input:
** Output:
** 12/24/04 - Created(eJay)
****************************************************/
function set_defaultinfo1_pageload()
{var type=document.all['ctl00_MainContent_ddlCardType1'].options[document.all['ctl00_MainContent_ddlCardType1'].selectedIndex].value
if (document.all['ctl00_MainContent_txtCardNo1'].value!="")
{
document.all["hidcctype1" + type].value=document.all['ctl00_MainContent_txtCardNo1'].value + "/" +document.all['ctl00_MainContent_ddlMonth1'].selectedIndex + "/" + document.all['ctl00_MainContent_ddlYear1'].selectedIndex;
}
}
/****************************************************
** Function set_defaultinfo_cctypechange()
** Description:when the cctype is changed the default info should be show
** Input:
** Output:
** 12/06/04 - Created(jack)
****************************************************/
function set_defaultinfo_cctypechange()
{
var type=document.all['ctl00_MainContent_ddlCardType'].options[document.all['ctl00_MainContent_ddlCardType'].selectedIndex].value
if (type==0){document.all['ctl00_MainContent_txtCardNo'].value="";
document.all['ctl00_MainContent_ddlMonth'].selectedIndex=0;
document.all['ctl00_MainContent_ddlYear'].selectedIndex=0;}
else{
if (document.all["ctl00_MainContent_hidcctype" + type].value.length==0)
{ document.all['ctl00_MainContent_txtCardNo'].value="";
document.all['ctl00_MainContent_ddlMonth'].selectedIndex=0;
document.all['ctl00_MainContent_ddlYear'].selectedIndex=0;
}
else{
var arr=document.all["ctl00_MainContent_hidcctype" + type].value.split('/')
document.all['ctl00_MainContent_txtCardNo'].value=arr[0];
document.all['ctl00_MainContent_ddlMonth'].selectedIndex=arr[1];
document.all['ctl00_MainContent_ddlYear'].selectedIndex=arr[2];
}
}
}
/****************************************************
** Function set_defaultinfo_cctype1change()
** Description:when the cctype is changed the default info should be show
** Input:
** Output:
** 12/24/04 - Created(eJay)
****************************************************/
function set_defaultinfo_cctype1change()
{
var type=document.all['ctl00_MainContent_ddlCardType1'].options[document.all['ctl00_MainContent_ddlCardType1'].selectedIndex].value
if (type==0){document.all['ctl00_MainContent_txtCardNo1'].value="";
document.all['ctl00_MainContent_ddlMonth1'].selectedIndex=0;
document.all['ctl00_MainContent_ddlYear1'].selectedIndex=0;}
else{
if (document.all["hidcctype1" + type].value.length==0)
{ document.all['ctl00_MainContent_txtCardNo1'].value="";
document.all['ctl00_MainContent_ddlMonth1'].selectedIndex=0;
document.all['ctl00_MainContent_ddlYear1'].selectedIndex=0;
}
else{
var arr=document.all["hidcctype1" + type].value.split('/')
document.all['ctl00_MainContent_txtCardNo1'].value=arr[0];
document.all['ctl00_MainContent_ddlMonth1'].selectedIndex=arr[1];
document.all['ctl00_MainContent_ddlYear1'].selectedIndex=arr[2];
}
}
}
/****************************************************
** Function set_defaultinfo_ccinfochange()
** Description:when the card info changed the info will be set to the hidetextbox
** Input:
** Output:
** 12/06/04 - Created(jack)
****************************************************/
function set_defaultinfo_ccinfochange()
{
var type=document.all['ctl00_MainContent_ddlCardType'].options[document.all['ctl00_MainContent_ddlCardType'].selectedIndex].value
document.all["ctl00_MainContent_hidcctype" + type].value=document.all['ctl00_MainContent_txtCardNo'].value + "/" +document.all['ctl00_MainContent_ddlMonth'].selectedIndex + "/" + document.all['ctl00_MainContent_ddlYear'].selectedIndex;
}
/****************************************************
** Function set_defaultinfo_ccinfo1change()
** Description:when the card info 2 changed the info will be set to the hidetextbox
** Input:
** Output:
** 12/24/04 - Created(eJay)
****************************************************/
function set_defaultinfo_ccinfo1change()
{
var type=document.all['ctl00_MainContent_ddlCardType1'].options[document.all['ctl00_MainContent_ddlCardType1'].selectedIndex].value
document.all["ctl00_MainContent_hidcctype1" + type].value=document.all['ctl00_MainContent_txtCardNo1'].value + "/" +document.all['ctl00_MainContent_ddlMonth1'].selectedIndex + "/" + document.all['ctl00_MainContent_ddlYear1'].selectedIndex;
}
/*********************************************************************************
**function:check_max_length
**Description:delte the leading space and the space tail
**Input:s
**Output:s
**11/23/04 - Created (jack)
*********************************************************************************/
function check_max_length(){
if (document.getElementById("ctl00_content_ddlCarType").selectedI,dex==0){
alert('Please select the credit card type');
document.getElementById("ctl00_content_ddlCarType").focus();
}
var checkcardtype=document.getElementById("ctl00_content_ddlCarType").options[document.getElementById("ctl00_content_ddlCarType").selectedIndex].value;
if (checkcardtype==1||checkcardtype==3){
document.getElementById("ctl00_content_txtCardNo").maxLength=15;
}else if (checkcardtype==2||checkcardtype==4||checkcardtype==5||checkcardtype==6){
document.getElementById("ctl00_content_txtCardNo").maxLength=16;
}
}
//-------------------------------------------
//--Function:check_time_frame
//--Description:when the admin login the function use the check the time_frame
//--Input:
//--Output:
//--12/14/04 - Created (jack)
//-------------------------------------------
function check_time_frame()
{
if (document.all['ctl00_MainContent_txtTimeframe'].value=="")
{alert('Please enter the timeframe');
document.all['ctl00_MainContent_txtTimeframe'].focus();
return false;
}
if (isNaN(document.all['ctl00_MainContent_txtTimeframe'].value))
{alert('Please enter numeric values as timeframe');
document.all['ctl00_MainContent_txtTimeframe'].focus();
return false;
}
}
//-------------------------------------------
//--Function:ShowTable
//--Description:Used for setpw1.aspx
//--Input:
//--Output:
//--11/10/04 - Created (eJay_
//-------------------------------------------
function ShowTable(){
if(typeof(document.all['ctl00_MainContent_lblShow'])=='undefined' ){
document.all['ctl00_MainContent_tbUser'].style.display='';
//alert('undefined');
}
else
{ document.all['ctl00_MainContent_tbUser'].style.display='none';
//alert('Defined');
}
}
//--------------------------------------------
//Function:IsValidCardType
//Description:Check if the Card Type is valid
//Input:
//Output:
// 10/29/04 - Created (eJay)
//--------------------------------------------
function IsValidCardType(){
var num;
var index1;
var index2;
num=document.adduserForm.ctl00_MainContent_txtCardNo.value;
index1=document.adduserForm.ctl00_MainContent_ddlCardType.selectedIndex;
index2=document.adduserForm.ctl00_MainContent_ddlMonth.selectedIndex;
if(num!=""){
if(0==index1){
alert("Please select the Credit Card Type");
//return true;
document.adduserForm.ctl00_MainContent_ddlCardType.selectedIndex=1;
return false;
}
else if( (0==index2) || (0==document.adduserForm.ctl00_MainContent_ddlYear.selectedIndex)){
alert("Please enter the credit card expiration date!");
if (0==index2){
document.adduserForm.ctl00_MainContent_ddlMonth.selectedIndex=1;}
if (0==document.all['ctl00_MainContent_ddlYear'].selectedIndex){
document.all['ctl00_MainContent_ddlYear'].selectedIndex=1;
}
return false;
}
}
else
return true;
}
function batchValidate_bkyang(){
if(document.getElementById("ctl00_MainContent_userprofile_txtNewpwd").value.length < 6 && document.getElementById("ctl00_MainContent_userprofile_txtNewpwd").value.length > 0){
alert('Password requires at least 6 characters!');
document.getElementById['ctl00_MainContent_userprofile_txtNewpwd'].focus();
return false;
}
if (document.getElementById("ctl00_MainContent_userprofile_txtNewpwd").value != document.getElementById("ctl00_MainContent_userprofile_txtConfpwd").value) {
alert('Password do not match!');
document.getElementById("ctl00_MainContent_userprofile_txtConfpwd").focus();
return false;
}
if(document.forms[0].ctl00_MainContent_userprofile_ddlCardType.selectedIndex == 0){
alert('Please select the credit card type!');
document.forms[0].ctl00_MainContent_userprofile_ddlCardType.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_userprofile_ddlCardType.selectedIndex != 0 && document.forms[0].ctl00_MainContent_userprofile_txtCardNo.value.length == 0){
alert('Please enter credit card !');
document.forms[0].ctl00_MainContent_userprofile_txtCardNo.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_userprofile_txtCardNo.value.length > 0 && document.forms[0].ctl00_MainContent_userprofile_txtCardNo.value.length !=15 && document.all['ctl00_MainContent_userprofile_ddlCardType'].selectedIndex != 0 && (document.all['ctl00_MainContent_userprofile_ddlCardType'].options[document.all['ctl00_MainContent_userprofile_ddlCardType'].selectedIndex].innerText == "AMEX" || document.all['ctl00_MainContent_userprofile_ddlCardType'].options[document.all['ctl00_MainContent_userprofile_ddlCardType'].selectedIndex].innerText == "DINERS")){
alert("'AMEX' and 'DINERS' should be 15 digits!");
document.forms[0].ctl00_MainContent_userprofile_txtCardNo.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_userprofile_txtCardNo.value.length !=16 && document.all['ctl00_MainContent_userprofile_ddlCardType'].options[document.all['ctl00_MainContent_userprofile_ddlCardType'].selectedIndex].innerText != "AMEX" && document.all['ctl00_MainContent_userprofile_ddlCardType'].options[document.all['ctl00_MainContent_userprofile_ddlCardType'].selectedIndex].innerText != "DINERS"){
alert("Credit Card Number must be 16 digits!");
document.forms[0].ctl00_MainContent_userprofile_txtCardNo.focus();
return false;
}
if(isNaN(document.forms[0].ctl00_MainContent_userprofile_txtCardNo.value)){
alert("Please enter numeric values as credit card !");
document.forms[0].ctl00_MainContent_userprofile_txtCardNo.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_userprofile_txtCardNo.value.length > 0 && (document.forms[0].ctl00_MainContent_userprofile_ddlMonth.selectedIndex == 0 || document.forms[0].ctl00_MainContent_userprofile_ddlYear.selectedIndex == 0 )){
alert("Please enter the credit card expiration date!");
if(document.forms[0].ctl00_MainContent_userprofile_ddlMonth.selectedIndex == 0){
document.all['ctl00_MainContent_userprofile_ddlMonth'].focus();
}
else{
document.all['ctl00_MainContent_userprofile_ddlYear'].focus();
}
return false;
}
if(document.forms[0].ctl00_MainContent_userprofile_txtEmail.value != "" && document.forms[0].ctl00_MainContent_userprofile_txtEmail.value != null && (document.all['ctl00_MainContent_userprofile_txtEmail'].value.match(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/)==null)){
alert("Please enter a valid Email Address!");
document.forms[0].ctl00_MainContent_userprofile_txtEmail.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_userprofile_txtStNo.value!="" && isNaN(document.forms[0].ctl00_MainContent_userprofile_txtStNo.value)){
alert("Please enter numeric values as Street No!");
document.forms[0].ctl00_MainContent_userprofile_txtStNo.focus();
return false;
}
if(isNaN(document.forms[0].ctl00_MainContent_userprofile_txtZip.value)){
alert("Please enter numeric values as zip number!");
document.forms[0].ctl00_MainContent_userprofile_txtZip.focus();
return false;
}
return true;
}
function agent_user_batchValidate(){
if(document.getElementById("ctl00_MainContent_txtFname").value == ""){
alert("Please enter first name!");
document.getElementById("ctl00_MainContent_txtFname").focus();
return false;
}
if(document.getElementById("ctl00_MainContent_txtLname").value == ""){
alert("Please enter last name!");
document.getElementById("ctl00_MainContent_txtLname").focus();
return false;
}
if(document.forms[0].ctl00_MainContent_ddlCardType.selectedIndex == 0){
alert('Please select the credit card type!');
document.forms[0].ctl00_MainContent_ddlCardType.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_ddlCardType.selectedIndex != 0 && document.forms[0].ctl00_MainContent_txtCardNo.value.length == 0){
alert('Please enter credit card !');
document.forms[0].ctl00_MainContent_txtCardNo.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_txtCardNo.value.length > 0 && document.forms[0].ctl00_MainContent_txtCardNo.value.length !=15 && document.all['ctl00_MainContent_ddlCardType'].selectedIndex != 0 && (document.all['ctl00_MainContent_ddlCardType'].options[document.all['ctl00_MainContent_ddlCardType'].selectedIndex].innerText == "AMEX" || document.all['ctl00_MainContent_ddlCardType'].options[document.all['ctl00_MainContent_ddlCardType'].selectedIndex].innerText == "DINERS")){
alert("'AMEX' and 'DINERS' should be 15 digits!");
document.forms[0].ctl00_MainContent_txtCardNo.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_txtCardNo.value.length !=16 && document.all['ctl00_MainContent_ddlCardType'].options[document.all['ctl00_MainContent_ddlCardType'].selectedIndex].innerText != "AMEX" && document.all['ctl00_MainContent_ddlCardType'].options[document.all['ctl00_MainContent_ddlCardType'].selectedIndex].innerText != "DINERS"){
alert("Credit Card Number must be 16 digits!");
document.forms[0].ctl00_MainContent_txtCardNo.focus();
return false;
}
if(isNaN(document.forms[0].ctl00_MainContent_txtCardNo.value)){
alert("Please enter numeric values as credit card !");
document.forms[0].ctl00_MainContent_txtCardNo.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_txtCardNo.value.length > 0 && (document.forms[0].ctl00_MainContent_ddlMonth.selectedIndex == 0 || document.forms[0].ctl00_MainContent_ddlYear.selectedIndex == 0 )){
alert("Please enter the credit card expiration date!");
if(document.forms[0].ctl00_MainContent_ddlMonth.selectedIndex == 0){
document.all['ctl00_MainContent_ddlMonth'].focus();
}
else{
document.all['ctl00_MainContent_ddlYear'].focus();
}
return false;
}
if(document.forms[0].ctl00_MainContent_txtFullName.value == ""){
alert("Please enter cardholder's name!");
document.forms[0].ctl00_MainContent_txtFullName.focus();
return false;
}
//--add by eJay 12/24/04*******************************************************
// if(document.forms[0].ctl00_MainContent_ddlCardType1.selectedIndex != 0 && document.forms[0].ctl00_MainContent_txtCardNo1.value.length == 0){
// alert('Please enter credit card 2!');
// document.forms[0].ctl00_MainContent_txtCardNo1.focus();
// return false;
//
// }
// if(document.forms[0].ctl00_MainContent_txtCardNo1.value.length > 0 && document.forms[0].ctl00_MainContent_txtCardNo1.value.length !=15 && document.all['ctl00_MainContent_ddlCardType1'].selectedIndex != 0 && (document.all['ctl00_MainContent_ddlCardType1'].options[document.all['ctl00_MainContent_ddlCardType1'].selectedIndex].innerText == "AMEX" || document.all['ctl00_MainContent_ddlCardType1'].options[document.all['ctl00_MainContent_ddlCardType1'].selectedIndex].innerText == "DINERS")){
// alert("'AMEX' and 'DINERS' should be 15 digits!");
// document.forms[0].ctl00_MainContent_txtCardNo1.focus();
// return false;
// }
// if(document.all['ctl00_MainContent_ddlCardType1'].selectedIndex != 0 && document.forms[0].ctl00_MainContent_txtCardNo1.value.length !=16 && document.all['ctl00_MainContent_ddlCardType1'].options[document.all['ctl00_MainContent_ddlCardType1'].selectedIndex].innerText != "AMEX" && document.all['ctl00_MainContent_ddlCardType1'].options[document.all['ctl00_MainContent_ddlCardType1'].selectedIndex].innerText != "DINERS"){
// alert("Credit Card Number must be 16 digits!");
// document.forms[0].ctl00_MainContent_txtCardNo1.focus();
// return false;
// }
// if(document.all['ctl00_MainContent_ddlCardType1'].selectedIndex != 0 && isNaN(document.forms[0].ctl00_MainContent_txtCardNo1.value)){
// alert("Please enter numeric values as credit card 2!");
// document.forms[0].ctl00_MainContent_txtCardNo1.focus();
// return false;
// }
// if(document.all['ctl00_MainContent_ddlCardType1'].selectedIndex != 0 && document.forms[0].ctl00_MainContent_txtCardNo1.value.length > 0 && (document.forms[0].ctl00_MainContent_ddlMonth1.selectedIndex == 0 || document.forms[0].ctl00_MainContent_ddlYear1.selectedIndex == 0 )){
// alert("Please enter the credit card 2 expiration date!");
// if(document.forms[0].ctl00_MainContent_ddlMonth1.selectedIndex == 0){
// document.all['ctl00_MainContent_ddlMonth1'].focus();
// }
// else{
// document.all['ctl00_MainContent_ddlYear1'].focus();
// }
// return false;
// }
//************************************************************************
// if(document.all['ctl00_MainContent_ddlCardType1'].selectedIndex != 0 && document.forms[0].ctl00_MainContent_txtCCName2.value == ""){
// alert("Please enter cardholder's name!");
// document.forms[0].ctl00_MainContent_txtCCName2.focus();
// return false;
// }
/*if(document.forms[0].ctl00_MainContent_txtCardNo.value.length > 0 && (document.forms[0].ctl00_MainContent_ddlCardType.selectedIndex == 0)){
alert("Please select the Credit Card Type");
document.forms[0].ctl00_MainContent_ddlCardType.focus();
return false;
}*/
if(document.forms[0].ctl00_MainContent_txtPhoneArea.value == ""){
alert("Please enter a primary phone number!")
document.forms[0].ctl00_MainContent_txtPhoneArea.focus();
return false;
}
if(isNaN(document.forms[0].ctl00_MainContent_txtPhoneArea.value)){
alert("Please enter numeric values as phone number");
document.forms[0].ctl00_MainContent_txtPhoneArea.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_txtPhoneFront.value == ""){
alert("Please enter a primary phone number!")
document.forms[0].ctl00_MainContent_txtPhoneFront.focus();
return false;
}
if(isNaN(document.forms[0].ctl00_MainContent_txtPhoneFront.value)){
alert("Please enter numeric values as phone number");
document.forms[0].ctl00_MainContent_txtPhoneFront.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_txtPhonetail.value == ""){
alert("Please enter a primary phone number!")
document.forms[0].ctl00_MainContent_txtPhonetail.focus();
return false;
}
if(isNaN(document.forms[0].ctl00_MainContent_txtPhonetail.value)){
alert("Please enter numeric values as phone number");
document.forms[0].ctl00_MainContent_txtPhonetail.focus();
return false;
}
/*if(document.forms[0].ctl00_MainContent_txtPhoneext.value == ""){
alert('Please enter a phone ext!');
document.forms[0].ctl00_MainContent_txtPhoneext.focus();
return false;
}*/
if(isNaN(document.forms[0].ctl00_MainContent_txtPhoneext.value)){
alert("Please enter numeric values as phone ext!");
document.forms[0].ctl00_MainContent_txtPhoneext.focus();
return false;
}
/*if(document.forms[0].ctl00_MainContent_txtCellPhoneArea.value == ""){
alert("Please enter a cell phone!");
document.forms[0].ctl00_MainContent_txtCellPhoneArea.focus();
return false;
}*/
if(document.forms[0].ctl00_MainContent_txtCellPhoneArea.value != "" && isNaN(document.forms[0].ctl00_MainContent_txtCellPhoneArea.value)){
alert("Please enter numeric values as phone number!")
document.forms[0].ctl00_MainContent_txtCellPhoneArea.focus();
return false;
}
/*if(document.forms[0].ctl00_MainContent_txtCellPhoneFront.value == ""){
alert("Please enter a cell phone!");
document.forms[0].ctl00_MainContent_txtCellPhoneFront.focus();
return false;
}*/
if(document.forms[0].ctl00_MainContent_txtCellPhoneFront.value != "" && isNaN(document.forms[0].ctl00_MainContent_txtCellPhoneFront.value)){
alert("Please enter numeric values as phone number!")
document.forms[0].ctl00_MainContent_txtCellPhoneFront.focus();
return false;
}
/*if(document.forms[0].ctl00_MainContent_txtCellPhonetail.value == ""){
alert("Please enter a cell phone!");
document.forms[0].ctl00_MainContent_txtCellPhonetail.focus();
return false;
}*/
if(document.forms[0].ctl00_MainContent_txtCellPhonetail.value != "" && isNaN(document.forms[0].ctl00_MainContent_txtCellPhonetail.value)){
alert("Please enter numeric values as phone number!")
document.forms[0].ctl00_MainContent_txtCellPhonetail.focus();
return false;
}
/*if(document.forms[0].ctl00_MainContent_txtFaxArea.value == ""){
alert("Please enter a fax!");
document.forms[0].ctl00_MainContent_txtFaxArea.focus();
return false;
}*/
if(document.forms[0].ctl00_MainContent_txtFaxArea.value != "" && isNaN(document.forms[0].ctl00_MainContent_txtFaxArea.value)){
alert("Please enter numeric values as fax number!")
document.forms[0].ctl00_MainContent_txtFaxArea.focus();
return false;
}
/*if(document.forms[0].ctl00_MainContent_txtFaxFront.value == ""){
alert("Please enter a fax!");
document.forms[0].ctl00_MainContent_txtFaxFront.focus();
return false;
}*/
if(document.forms[0].ctl00_MainContent_txtFaxFront.value != "" && isNaN(document.forms[0].ctl00_MainContent_txtFaxFront.value)){
alert("Please enter numeric values as fax number!")
document.forms[0].ctl00_MainContent_txtFaxFront.focus();
return false;
}
/*if(document.forms[0].ctl00_MainContent_txtFaxtail.value == ""){
alert("Please enter a fax!");
document.forms[0].ctl00_MainContent_txtFaxtail.focus();
return false;
}*/
if(document.forms[0].ctl00_MainContent_txtFaxtail.value != "" && isNaN(document.forms[0].ctl00_MainContent_txtFaxtail.value)){
alert("Please enter numeric values as fax number!")
document.forms[0].ctl00_MainContent_txtFaxtail.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_txtEmail.value == ""){
alert("Please enter email address!");
document.forms[0].ctl00_MainContent_txtEmail.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_txtEmail.value != "" && document.forms[0].ctl00_MainContent_txtEmail.value != null && (document.all['ctl00_MainContent_txtEmail'].value.match(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/)==null)){
alert("Please enter a valid Email Address!");
document.forms[0].ctl00_MainContent_txtEmail.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_txtStNo.value == ""){
alert("Please enter street no!");
document.forms[0].ctl00_MainContent_txtStNo.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_txtStNo.value!="" && isNaN(document.forms[0].ctl00_MainContent_txtStNo.value)){
alert("Please enter numeric values as Street No!");
document.forms[0].ctl00_MainContent_txtStNo.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_txtStName.value == ""){
alert("Please enter street name!");
document.forms[0].ctl00_MainContent_txtStName.focus();
return false;
}
/*if(document.forms[0].ctl00_MainContent_txtAuxAddress.value == ""){
alert("Please enter street address 2!");
document.forms[0].ctl00_MainContent_txtAuxAddress.focus();
return false;
}*/
if(document.forms[0].ctl00_MainContent_txtCity.value == ""){
alert("Please enter city!");
document.forms[0].ctl00_MainContent_txtCity.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_txtState.value == ""){
alert("Please enter state!");
document.forms[0].ctl00_MainContent_txtState.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_txtZip.value==""){
alert("Please enter Zip Code!");
document.forms[0].ctl00_MainContent_txtZip.focus();
return false;
}
if(isNaN(document.forms[0].ctl00_MainContent_txtZip.value)){
alert("Please enter numeric values as zip number!");
document.forms[0].ctl00_MainContent_txtZip.focus();
return false;
}
return true;
}
function admin_user_batchValidate()
{
if(document.all['ctl00_MainContent_txtNewpwd'].value.length < 6 ){
alert('Password requires at least 6 characters!');
document.all['ctl00_MainContent_txtNewpwd'].focus();
return false;
}
if (document.all['ctl00_MainContent_txtNewpwd'].value != document.all['ctl00_MainContent_txtConfpwd'].value) {
alert('Password do not match!');
document.all['ctl00_MainContent_txtConfpwd'].focus();
return false;
}
if(document.getElementById("ctl00_MainContent_txtFname").value == ""){
alert("Please enter first name!");
document.getElementById("ctl00_MainContent_txtFname").focus();
return false;
}
if(document.getElementById("ctl00_MainContent_txtLname").value == ""){
alert("Please enter last name!");
document.getElementById("ctl00_MainContent_txtLname").focus();
return false;
}
if(document.getElementById("ctl00_MainContent_txtUserName").value == ""){
alert("Please enter User Name!");
document.getElementById("ctl00_MainContent_txtUserName").focus();
return false;
}
if(document.forms[0].ctl00_MainContent_txtEmail.value == ""){
alert("Please enter email address!");
document.forms[0].ctl00_MainContent_txtEmail.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_txtEmail.value != "" && document.forms[0].ctl00_MainContent_txtEmail.value != null && (document.all['ctl00_MainContent_txtEmail'].value.match(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/)==null)){
alert("Please enter a valid Email Address!");
document.forms[0].ctl00_MainContent_txtEmail.focus();
return false;
}
}
function admin_user_reset()
{
document.getElementById("ctl00_MainContent_txtEmail").value ="";
document.getElementById("ctl00_MainContent_txtUserName").value ="";
document.getElementById("ctl00_MainContent_txtFname").value ="";
document.getElementById("ctl00_MainContent_txtLname").value ="";
document.all['ctl00_MainContent_txtNewpwd'].value ="";
document.all['ctl00_MainContent_txtConfpwd'].value="";
return false;
}
////////////////////////////////////////////
function add_admin_user_batchValidate()
{
if(document.getElementById("ctl00_MainContent_txtUserName").value == ""){
alert("Please enter User Name!");
document.getElementById("ctl00_MainContent_txtUserName").focus();
return false;
}
if(document.all['ctl00_MainContent_txtNewpwd'].value.length < 6 ){
alert('Password requires at least 6 characters!');
document.all['ctl00_MainContent_txtNewpwd'].focus();
return false;
}
if (document.all['ctl00_MainContent_txtNewpwd'].value != document.all['ctl00_MainContent_txtConfpwd'].value) {
alert('Password do not match!');
document.all['ctl00_MainContent_txtConfpwd'].focus();
return false;
}
if(document.getElementById("ctl00_MainContent_txtFname").value == ""){
alert("Please enter first name!");
document.getElementById("ctl00_MainContent_txtFname").focus();
return false;
}
if(document.getElementById("ctl00_MainContent_txtLname").value == ""){
alert("Please enter last name!");
document.getElementById("ctl00_MainContent_txtLname").focus();
return false;
}
if(document.getElementById("ctl00_MainContent_ddlMonth").selectedIndex == 0){
alert("Please select mouth!");
document.getElementById("ctl00_MainContent_ddlMonth").focus();
return false;
}
if(document.getElementById("ctl00_MainContent_ddlDay").selectedIndex == 0){
alert("Please select day!");
document.getElementById("ctl00_MainContent_ddlDay").focus();
return false;
}
if(document.getElementById("ctl00_MainContent_ddlYear").selectedIndex == 0){
alert("Please select Year!");
document.getElementById("ctl00_MainContent_ddlYear").focus();
return false;
}
if(document.forms[0].ctl00_MainContent_txtEmail.value == ""){
alert("Please enter email address!");
document.forms[0].ctl00_MainContent_txtEmail.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_txtEmail.value != "" && document.forms[0].ctl00_MainContent_txtEmail.value != null && (document.all['ctl00_MainContent_txtEmail'].value.match(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/)==null)){
alert("Please enter a valid Email Address!");
document.forms[0].ctl00_MainContent_txtEmail.focus();
return false;
}
}
/*********************************************************************************
**function:trim
**Description:delte the leading space and the space tail
**Input:s
**Output:s
**11/23/04 - Created (eJay)
*********************************************************************************/
function trim(s)
{
if (s == null)
{
return s;
}
var i;
var beginIndex = 0;
var endIndex = s.length - 1;
for (i=0; i<s.length; i++)
{
if (s.charAt(i) == ' ' || s.charAt(i) == ' ')
{
beginIndex++;
}
else
{
break;
}
}
for (i = s.length - 1; i >= 0; i--)
{
if (s.charAt(i) == ' ' || s.charAt(i) == ' ')
{
endIndex--;
}
else
{
break;
}
}
if (endIndex < beginIndex)
{
return "";
}
return s.substring(beginIndex, endIndex + 1);
}
//author jiafeng
function changedate()
{
var daysInMonth = new Array(31, 28, 31, 30, 31, 30, 31, 31,30, 31, 30, 31);
var mouth=document.getElementById("ctl00_MainContent_ddlMonth").selectedIndex;
var indyear=document.getElementById("ctl00_MainContent_ddlYear").selectedIndex;
var year=document.getElementById("ctl00_MainContent_ddlYear").options[indyear].value;
if(mouth*indyear>0){
var flag=isLeapYear(parseInt(year));
document.getElementById("ctl00_MainContent_ddlDay").length = 0;
var length=daysInMonth[mouth-1];
if((mouth==2)&&(flag==true)){
length=length+1;
}
document.getElementById("ctl00_MainContent_ddlDay").options[0] = new Option("Day","");
var j;
for(j=1;j<=length;j++)
{
document.getElementById("ctl00_MainContent_ddlDay").options[j] = new Option(j,j);
}
}
}
function isLeapYear(oYear)
{
if(oYear%4!=0){
return false;
}
if (((oYear%4==0) && (oYear% 00!=0)) || (oYear%400==0)) {
return true;
}
else{
return false;
}
}
function reset_user_profile_value()
{
try{
document.getElementById("ctl00_MainContent_txtUserName").value="";
document.getElementById("ctl00_MainContent_txtNewpwd").value="";
document.getElementById("ctl00_MainContent_txtConfpwd").value="";
document.getElementById("ctl00_MainContent_txtFname").value="";
document.getElementById("ctl00_MainContent_txtLname").value="";
document.getElementById("ctl00_MainContent_txtEmail").value="";
document.getElementById("ctl00_MainContent_ddlAdminFlag").selectedIndex=0;
document.getElementById("ctl00_MainContent_ddlMonth").selectedIndex=0;
document.getElementById("ctl00_MainContent_ddlDay").selectedIndex=0;
document.getElementById("ctl00_MainContent_ddlYear").selectedIndex=0;
}
catch(ex)
{
//dothingt
}
return false
}
function agent_new_user_Validate()
{
if(document.getElementById("ctl00_MainContent_txtUserName").value == ""){
alert("Please enter User Name!");
document.getElementById("ctl00_MainContent_txtUserName").focus();
return false;
}
if(document.all['ctl00_MainContent_txtNewpwd'].value.length < 6 ){
alert('Password requires at least 6 characters!');
document.all['ctl00_MainContent_txtNewpwd'].focus();
return false;
}
if (document.all['ctl00_MainContent_txtNewpwd'].value != document.all['ctl00_MainContent_txtConfpwd'].value) {
alert('Password do not match!');
document.all['ctl00_MainContent_txtConfpwd'].focus();
return false;
}
if(document.getElementById("ctl00_MainContent_txtFname").value == ""){
alert("Please enter first name!");
document.getElementById("ctl00_MainContent_txtFname").focus();
return false;
}
if(document.getElementById("ctl00_MainContent_txtLname").value == ""){
alert("Please enter last name!");
document.getElementById("ctl00_MainContent_txtLname").focus();
return false;
}
if(document.forms[0].ctl00_MainContent_txtPhoneArea.value == ""){
alert("Please enter a primary phone number!")
document.forms[0].ctl00_MainContent_txtPhoneArea.focus();
return false;
}
if(isNaN(document.forms[0].ctl00_MainContent_txtPhoneArea.value)){
alert("Please enter numeric values as phone number");
document.forms[0].ctl00_MainContent_txtPhoneArea.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_txtPhoneFront.value == ""){
alert("Please enter a primary phone number!")
document.forms[0].ctl00_MainContent_txtPhoneFront.focus();
return false;
}
if(isNaN(document.forms[0].ctl00_MainContent_txtPhoneFront.value)){
alert("Please enter numeric values as phone number");
document.forms[0].ctl00_MainContent_txtPhoneFront.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_txtPhonetail.value == ""){
alert("Please enter a primary phone number!")
document.forms[0].ctl00_MainContent_txtPhonetail.focus();
return false;
}
if(isNaN(document.forms[0].ctl00_MainContent_txtPhonetail.value)){
alert("Please enter numeric values as phone number");
document.forms[0].ctl00_MainContent_txtPhonetail.focus();
return false;
}
if(isNaN(document.forms[0].ctl00_MainContent_txtPhoneext.value)){
alert("Please enter numeric values as phone ext!");
document.forms[0].ctl00_MainContent_txtPhoneext.focus();
return false;
}
if(document.getElementById("ctl00_MainContent_ddlMonth").selectedIndex == 0){
alert("Please select mouth!");
document.getElementById("ctl00_MainContent_ddlMonth").focus();
return false;
}
if(document.getElementById("ctl00_MainContent_ddlDay").selectedIndex == 0){
alert("Please select day!");
document.getElementById("ctl00_MainContent_ddlDay").focus();
return false;
}
if(document.getElementById("ctl00_MainContent_ddlYear").selectedIndex == 0){
alert("Please select Year!");
document.getElementById("ctl00_MainContent_ddlYear").focus();
return false;
}
if(document.forms[0].ctl00_MainContent_txtEmail.value == ""){
alert("Please enter email address!");
document.forms[0].ctl00_MainContent_txtEmail.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_txtEmail.value != "" && document.forms[0].ctl00_MainContent_txtEmail.value != null && (document.all['ctl00_MainContent_txtEmail'].value.match(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/)==null)){
alert("Please enter a valid Email Address!");
document.forms[0].ctl00_MainContent_txtEmail.focus();
return false;
}
}
function reset_agent_profile_value()
{
try{
document.getElementById("ctl00_MainContent_txtUserName").value="";
document.getElementById("ctl00_MainContent_txtNewpwd").value="";
document.getElementById("ctl00_MainContent_txtConfpwd").value="";
document.getElementById("ctl00_MainContent_txtFname").value="";
document.getElementById("ctl00_MainContent_txtLname").value="";
document.getElementById("ctl00_MainContent_txtEmail").value="";
document.getElementById("ctl00_MainContent_ddlMonth").selectedIndex=0;
document.getElementById("ctl00_MainContent_ddlDay").selectedIndex=0;
document.getElementById("ctl00_MainContent_ddlYear").selectedIndex=0;
document.getElementById("ctl00_MainContent_txtPhoneArea").value="";
document.getElementById("ctl00_MainContent_txtPhoneFront").value="";
document.getElementById("ctl00_MainContent_txtPhonetail").value="";
document.getElementById("ctl00_MainContent_txtPhoneext").value="";
}
catch(ex)
{
//dothingt
}
return false
}
function affiliate_user_Validate()
{
if(document.getElementById("ctl00_MainContent_txtName").value == ""){
alert("Please enter Name!");
document.getElementById("ctl00_MainContent_txtName").focus();
return false;
}
if(document.getElementById("ctl00_MainContent_txtUserName").value == ""){
alert("Please enter User Name!");
document.getElementById("ctl00_MainContent_txtUserName").focus();
return false;
}
if(document.all['ctl00_MainContent_txtNewpwd'].value.length < 6 ){
alert('Password requires at least 6 characters!');
document.all['ctl00_MainContent_txtNewpwd'].focus();
return false;
}
if (document.all['ctl00_MainContent_txtNewpwd'].value != document.all['ctl00_MainContent_txtConfpwd'].value) {
alert('Password do not match!');
document.all['ctl00_MainContent_txtConfpwd'].focus();
return false;
}
if(document.forms[0].ctl00_MainContent_txtPhoneArea.value == ""){
alert("Please enter a primary phone number!")
document.forms[0].ctl00_MainContent_txtPhoneArea.focus();
return false;
}
if(isNaN(document.forms[0].ctl00_MainContent_txtPhoneArea.value)){
alert("Please enter numeric values as phone number");
document.forms[0].ctl00_MainContent_txtPhoneArea.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_txtPhoneFront.value == ""){
alert("Please enter a primary phone number!")
document.forms[0].ctl00_MainContent_txtPhoneFront.focus();
return false;
}
if(isNaN(document.forms[0].ctl00_MainContent_txtPhoneFront.value)){
alert("Please enter numeric values as phone number");
document.forms[0].ctl00_MainContent_txtPhoneFront.focus();
return false;
}
if(document.forms[0].ctl00_MainContent_txtPhonetail.value == ""){
alert("Please enter a primary phone number!")
document.forms[0].ctl00_MainContent_txtPhonetail.focus();
return false;
}
if(isNaN(document.forms[0].ctl00_MainContent_txtPhonetail.value)){
alert("Please enter numeric values as phone number");
document.forms[0].ctl00_MainContent_txtPhonetail.focus();
return false;
}
if(document.getElementById("ctl00_MainContent_ddlAffiliateName").selectedIndex == 0){
alert("Please select affiliate name!");
document.getElementById("ctl00_MainContent_ddlAffiliateName").focus();
return false;
}
}
function reset_Affliate_profile_value()
{
try{
document.getElementById("ctl00_MainContent_txtUserName").value="";
document.getElementById("ctl00_MainContent_txtNewpwd").value="";
document.getElementById("ctl00_MainContent_txtConfpwd").value="";
document.getElementById("ctl00_MainContent_txtName").value="";
document.getElementById("ctl00_MainContent_ddlAffiliateName").selectedIndex=0;
document.getElementById("ctl00_MainContent_txtPhoneArea").value="";
document.getElementById("ctl00_MainContent_txtPhoneFront").value="";
document.getElementById("ctl00_MainContent_txtPhonetail").value="";
}
catch(ex)
{
//dothingt
}
return false
}
function batchValidate(verifyCC){
//## 1/25/2008 Change from "CheckPassword" to "batchValidate" (yang)
if(document.getElementById("ctl00_content_password0").value=="" || document.getElementById("ctl00_content_password0").value.length==0){
alert('Plese enter Current Password!');
document.getElementById("ctl00_content_password0").focus();
return false;
}else if(document.getElementById("ctl00_content_password1").value!="" || document.getElementById("ctl00_content_password1").value.length>0){
if(document.getElementById("ctl00_content_password1").value=="" || document.getElementById("ctl00_content_password1").value.length==0){
alert('please enter New Password!');
document.getElementById("ctl00_content_password1").focus();
return false;
}else if (document.getElementById("ctl00_content_password2").value=="" || document.getElementById("ctl00_content_password2").value.length==0){
alert('please enter New Confirm Password!');
document.getElementById("ctl00_content_password2").focus();
return false;
}else if (document.getElementById("ctl00_content_password2").value!=document.getElementById("ctl00_content_password1").value){
alert('New Password and Confirm Password!');
document.getElementById("ctl00_content_password2").focus();
return false;
}
}
if (document.getElementById("ctl00_content_ddlCardType").selectedIndex==0){
alert('Please select the credit card type');
document.getElementById("ctl00_content_ddlCardType").focus();
return false;
}
if(document.getElementById("ctl00_content_txtCardNo").value !="" && document.getElementById("ctl00_content_txtCardNo").value.length > 0){
if(document.getElementById("ctl00_content_txtCardNo").value.length !=15 && document.getElementById("ctl00_content_ddlCardType").options[document.getElementById("ctl00_content_ddlCardType").selectedIndex].text == "AMEX"){
alert("AMEX has 15 digits! Please re-enter.");
document.getElementById("ctl00_content_txtCardNo").focus();
return false;
}else if(document.getElementById("ctl00_content_txtCardNo").value.length > 0 && document.getElementById("ctl00_content_txtCardNo").value.length !=16 && document.getElementById("ctl00_content_ddlCardType").selectedIndex != 0 && (document.getElementById("ctl00_content_ddlCardType").options[document.getElementById("ctl00_content_ddlCardType").selectedIndex].text == "VISA" || document.getElementById("ctl00_content_ddlCardType").options[document.getElementById("ctl00_content_ddlCardType").selectedIndex].text == "MASTERCARD")){
alert("VISA and MASTERCARD has 16 digits! Please re-enter.");
document.getElementById("ctl00_content_txtCardNo").focus();
return false;
}else if(document.getElementById("ctl00_content_txtCardNo").value.length > 0 && document.getElementById("ctl00_content_txtCardNo").value.length !=15 && document.getElementById("ctl00_content_ddlCardType").selectedIndex != 0 && (document.getElementById("ctl00_content_ddlCardType").options[document.getElementById("ctl00_content_ddlCardType").selectedIndex].text == "AMEX" || document.getElementById("ctl00_content_ddlCardType").options[document.getElementById("ctl00_content_ddlCardType").selectedIndex].text == "DINERS")){
alert("'AMEX' and 'DINERS' should be 15 digits!");
document.getElementById("ctl00_content_txtCardNo").focus();
return false;
}else if(document.getElementById("ctl00_content_txtCardNo").value.length !=16 && document.getElementById("ctl00_content_ddlCardType").options[document.getElementById("ctl00_content_ddlCardType").selectedIndex].text != "AMEX" && document.getElementById("ctl00_content_ddlCardType").options[document.getElementById("ctl00_content_ddlCardType").selectedIndex].text != "DINERS"){
alert("Credit Card Number must be 16 digits!");
document.getElementById("ctl00_content_txtCardNo").focus();
return false;
}else if(isNaN(document.getElementById("ctl00_content_txtCardNo").value)){
alert("Please enter numeric values as credit card no!");
document.getElementById("ctl00_content_txtCardNo").focus();
return false;
}else if(document.getElementById("ctl00_content_txtCardNo").value.length > 0 && (document.getElementById("ctl00_content_ddlExpMonth").selectedIndex == 0 || document.getElementById("ctl00_content_ddlExpYear").selectedIndex == 0 )){
alert("Please enter the credit card expiration date!");
if(document.getElementById("ctl00_content_ddlExpMonth").selectedIndex == 0){
document.getElementById("ctl00_content_ddlExpMonth").focus();
}else{
document.getElementById("ctl00_content_ddlExpYear").focus();
}
return false;
}
}else if(document.getElementById("ctl00_content_ddlExpMonth").selectedIndex == 0 || document.getElementById("ctl00_content_ddlExpYear").selectedIndex ==0){
alert("Please enter the credit card expiration date!");
if(document.getElementById("ctl00_content_ddlExpMonth").selectedIndex == 0){
document.getElementById("ctl00_content_ddlExpMonth").focus();
}
else{
document.getElementById("ctl00_content_ddlExpYear").focus();
}
return false;
}
if(document.getElementById("ctl00_content_ddlExpMonth").selectedIndex == 0 || document.getElementById("ctl00_content_ddlExpYear").selectedIndex ==0){
alert("Please enter the credit card expiration date!");
if(document.getElementById("ctl00_content_ddlExpMonth").selectedIndex == 0){
document.getElementById("ctl00_content_ddlExpMonth").focus();
}else{
document.getElementById("ctl00_content_ddlExpYear").focus();
}
return false;
}
if (document.getElementById("ctl00_content_txtCardNo").value!="" && document.getElementById("ctl00_content_txtCardNo").value.length>12){
document.getElementById("ctl00_content_hidcardno").value=document.getElementById("ctl00_content_txtCardNo").value;
}else{
//do nothing
}
var cc_no = document.getElementById("ctl00_content_txtCardNo").value;
var cc_exp = document.getElementById("ctl00_content_ddlExpMonth").options[document.getElementById("ctl00_content_ddlExpMonth").selectedIndex].value +
document.getElementById("ctl00_content_ddlExpYear").options[document.getElementById("ctl00_content_ddlExpYear").selectedIndex].value;
var cc_type = document.getElementById("ctl00_content_ddlCardType").options[document.getElementById("ctl00_content_ddlCardType").selectedIndex].value;
if (cc_no.length>0 && (verifyCC==null || verifyCC==true)){
VerifyCC(null,cc_no,cc_exp,cc_type,"2") //## 1/24/2008 (yang)
}else{
document.getElementById("ctl00_content_SubmitHide").click();}
return false;
}
function check_search_max_length(){
if (document.getElementById("ctl00_content_ddlCardType").selectedIndex==0){
alert('Please select the credit card type');
document.getElementById("ctl00_content_ddlCardType").focus();
}
var checkcardtype=document.getElementById("ctl00_content_ddlCardType").options[document.getElementById("ctl00_content_ddlCardType").selectedIndex].value;
if (checkcardtype==1){
document.getElementById("ctl00_content_txtCardNo").maxLength=15;
//document.getElementById("ctl00_content_txtvcode").maxLength=4;
}else if (checkcardtype==3){
document.getElementById("ctl00_content_txtCardNo").maxLength=15; //modify by daniel for change to 15 length. 15/08/2007
//document.getElementById("ctl00_content_txtvcode").maxLength=15;
}else if (checkcardtype==2||checkcardtype==4||checkcardtype==5||checkcardtype==6){
document.getElementById("ctl00_content_txtCardNo").maxLength=16;
//document.getElementById("ctl00_content_txtvcode").maxLength=3;
}
}
/********************************************************
**funciton add by daniel for some entervalues 12/14/2006
********************************************************/
function entervalues(){
if(event.keyCode==44){
event.returnValue=false;
}else if (event.keyCode==39){
event.returnValue=false;
}
}
|
let arr = [1,20,15,17,12,7,25,14,13,19,30,16];
console.log(arr);
for(let i = 0; i < arr.length - 1; i++){
let min = 999, index, temp;
for(let j = i; j < arr.length; j++){
if(arr[j] < min){
min = arr[j];
index = j
}
}
temp = arr[i];
arr[i] = arr[index];
arr[index] = temp;
}
console.log(arr);
|
import * as types from "../constants/report";
const initialState = {
reports: [],
onRequest: false,
errors: false,
metrics: [],
forms: [],
formQuestions: [],
postReportSuccess: false,
formTypes: []
};
export default function(state = initialState, action) {
switch (action.type) {
case types.GET_REPORT_DATA_REQUEST: {
return {
...state,
onRequest: true
};
}
case types.GET_REPORT_DATA_SUCCESS: {
return {
...state,
onRequest: false,
reports: action.payload
};
}
case types.GET_REPORT_DATA_FAILURE: {
return {
...state,
onRequest: false,
errors: true
};
}
case types.ADD_REPORT_REQUEST: {
return {
...state,
onRequest: true,
errors: false
};
}
case types.ADD_REPORT_SUCCESS: {
return {
...state,
onRequest: false,
postReportSuccess: true
};
}
case types.ADD_REPORT_FAILURE: {
return {
...state,
onRequest: false,
errors: true
};
}
case types.GET_METRICS_REQUEST: {
return {
...state,
onRequest: true,
errors: false
};
}
case types.GET_METRICS_SUCCESS: {
return {
...state,
onRequest: false,
reports: action.payload
};
}
case types.GET_METRICS_FAILURE: {
return {
...state,
onRequest: false,
errors: true
};
}
case types.GET_FORMS_REQUEST: {
return {
...state,
onRequest: true,
errors: false
};
}
case types.GET_FORMS_SUCCESS: {
return {
...state,
onRequest: false,
forms: action.payload
};
}
case types.GET_FORMS_FAILURE: {
return {
...state,
onRequest: false,
errors: true
};
}
case types.GET_FORMS_QUESTIONS_REQUEST: {
return {
...state,
onRequest: true,
errors: false
};
}
case types.GET_FORMS_QUESTIONS_SUCCESS: {
return {
...state,
onRequest: false,
formQuestions: action.payload
};
}
case types.GET_FORMS_QUESTIONS_FAILURE: {
return {
...state,
onRequest: false,
errors: true
};
}
default:
return state;
}
}
|
'use strict';
window.freezeframe_options = {
loading_background_color: 'white',
animation_icon_image: false,
trigger_event: 'click'
};
// to cancel click/hover event on gif
$('div').click(function() {
$('figure.freezeframe-container', this).find('img.freezeframe_done').css('opacity', 0);
});
window.addEventListener('deviceproximity', function(event) {
if(event.value <= 7) {
$('.freezeframe_done').css('opacity', 1);
} else {
$('.freezeframe_done').css('opacity', 0);
}
});
|
angular.module('app')
.controller('UserInfoCtrl', function ($scope, UserInfoSvc, $location) {
var refresh = function() {
UserInfoSvc.fetch()
.then(function (user_list) {
$scope.user_list = user_list
})
};
refresh()
$scope.delete_user = function (user) {
if (user) {
UserInfoSvc.delete_user(user)
.then(function () {
refresh()
})
}
}
$scope.send_user = function (user) {
console.log("send_user")
console.log(user)
UserInfoSvc.setselectuser(user)
}
})
|
var gulp = require('gulp'),
ts = require('gulp-typescript'),
sourcemaps = require('gulp-sourcemaps'),
clean = require('gulp-clean'),
changed = require('gulp-changed'),
concat = require('gulp-concat');
var config = require('./gulp.config');
var tsProject = ts.createProject({
declarationFiles: false,
noExternalResolve: false,
module: 'commonjs'
});
var tsPublicProject = ts.createProject({
declarationFiles: false,
noExternalResolve: false,
target: 'ES5'
});
var tsPublicGameProject = ts.createProject({
declarationFiles: false,
noExternalResolve: false,
target: 'ES5'
});
var tsGameTestsProject = ts.createProject({
declarationFiles: false,
noExternalResolve: false,
target: 'ES5'
});
//main task for dev
gulp.task('start', ['browser-sync', 'watch-game']);
//main task for deploy to heroku
gulp.task('heroku-build', ['clean-deploy', 'copy-package', 'compile-all'], postBuild);
gulp.task('browser-sync', ['start-server'], browserSyncTask);
gulp.task('start-server', ['compile-all'], startServer);
gulp.task('compile-all', ['compile-server', 'compile-public', 'compile-game']);
gulp.task('compile-server', compileServer);
gulp.task('compile-public', compilePublic);
gulp.task('compile-game', compileGame);
gulp.task('watch-all', ['watch-server', 'watch-public', 'watch-game']);
gulp.task('watch-server', ['compile-server'], watchServer);
gulp.task('watch-public', ['compile-public'], watchPublic);
gulp.task('watch-game', ['compile-game'], watchGame);
gulp.task('watch-game-tests', watchGameTests);
gulp.task('clean-deploy', cleanDeploy);
gulp.task('clean-js', cleanJs);
gulp.task('copy-package', copyPackage);
var browserSync = null;
function browserSyncTask(params) {
browserSync = require('browser-sync').create();
browserSync.init(null, {
proxy: "http://localhost:3000",
files: config.browserSync,
browser: "google chrome",
port: 7000,
});
}
function compileServer(params) {
return gulp.src(config.tsServerSrc)
.pipe(sourcemaps.init())
.pipe(ts(config.tsCompiler)).js
.pipe(gulp.dest(config.destServer));
}
function compilePublic(params) {
var tsResult = gulp.src(config.tsPublicSrc)
.pipe(sourcemaps.init())
.pipe(ts(tsPublicProject));
return tsResult.js
.pipe(concat('public.js'))
.pipe(sourcemaps.write('../source-maps'))
.pipe(gulp.dest(config.destPublic + 'app'));
}
function compileGame(params) {
var tsResult = gulp.src(config.tsGameSrc)
.pipe(sourcemaps.init())
.pipe(ts(tsPublicGameProject));
return tsResult.js
.pipe(concat('game.js'))
.pipe(sourcemaps.write('../source-maps'))
.pipe(gulp.dest(config.destPublic + 'app/game/'));
}
function watchGameTests() {
var compileTests = function () {
var tsResult = gulp.src(config.gameTestsSrc)
.pipe(sourcemaps.init())
.pipe(ts(tsGameTestsProject));
return tsResult.js
.pipe(concat('game-tests.js'))
.pipe(sourcemaps.write('../tests-source-maps'))
.pipe(gulp.dest(config.clientApp + 'game/tests'));
}
gulp.watch(config.gameTestsSrc, compileTests).on('change', function(){ log('changed...') });
}
function watchServer(params) {
gulp.watch(config.tsServerSrc, ['compile-server']);
}
function watchPublic(params) {
gulp.watch(config.tsPublicSrc, ['compile-public']);
}
function watchGame(params) {
gulp.watch(config.tsGameSrc, ['compile-game']).on('change', function () {
setTimeout(function () {
browserSync.reload()
}, 500)
});
}
function startServer(cb) {
var started = false;
var nodemon = require('gulp-nodemon');
return nodemon({
script: config.mainFile,
ignore: ["src/public/*.*"],
ext: 'js',
}).on('restart', function () {
}).on('start', function () {
if (!started) {
cb();
started = true;
}
});
}
function copyPackage(params) {
return gulp.src(['package.json', 'Procfile']).pipe(gulp.dest('./deploy'));
}
function cleanDeploy() {
return gulp.src('./deploy', { read: false })
.pipe(clean());
}
function postBuild(params) {
var files = [
'./src/**/*.js',
'./src/**/*.json',
'./src/**/*.png',
'./src/**/*.css',
'./src/**/*.vash',
'./src/**/*.wav',
'./src/**/*.mp3'
];
return gulp.src(files)
.pipe(gulp.dest('./deploy'));
}
function cleanJs(params) {
var paths = [
config.srcServer + '**/*.js',
'!' + config.srcServer + 'public/libs/**/*.js'
]
return gulp.src(paths, { read: false })
.pipe(clean());
}
function log(message, object) {
if(object){
console.log(message, object);
}
else{
console.log(message);
}
}
|
import React from 'react';
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom';
import './styles/App.sass';
import ScrollToTop from './components/ScrollToTop';
import HomePage from './pages/HomePage';
import NewsPage from './pages/NewsPage';
import AboutPage from './pages/AboutPage';
import ContactPage from './pages/ContactPage';
function App() {
return (
<Router basename={process.env.PUBLIC_URL}>
<ScrollToTop>
<Switch>
<Route path='/' exact component={HomePage} />
<Route path='/news' component={NewsPage} />
<Route path='/about' component={AboutPage} />
<Route path='/contact' component={ContactPage} />
<Redirect to='/' />
</Switch>
</ScrollToTop>
</Router >
);
}
export default App;
|
var SessionActions = require('./../actions/session_actions');
var ServerActions = require('../actions/server_actions');
var ErrorActions = require('./../actions/error_actions');
var UserApiUtil = {
signup: function (formData) {
$.ajax({
url: '/api/users',
type: 'POST',
dataType: 'json',
data: {user: formData},
success: function (currentUser) {
SessionActions.receiveCurrentUser(currentUser);
},
error: function (xhr) {
var errors = xhr.responseJSON.errors;
ErrorActions.setErrors("signup", errors);
}
});
},
fetchUserAndPosts: function(id) {
$.ajax({
method: 'GET',
url: '/api/users/' + id,
success: function(userAndPosts) {
// var user = {
// id: userAndPosts.id,
// username: userAndPosts.username
// };
//
// var userPosts = userAndPosts.posts;
// Add Header stuff later
// HeaderAction.receiveUser(user);
// We're just going to pass both the user and his or her posts
// this way we can split up the data at a later point
ServerActions.receiveUserAndAllPosts(userAndPosts);
}
});
},
updateUserProfile: function(currentUserId, profileFormData, closeModal) {
$.ajax({
url: '/api/users/' + currentUserId,
method: 'PATCH',
dataType: 'json',
contentType: false,
processData: false,
data: profileFormData,
success: function(userAndPosts) {
closeModal();
// not going to allow for null's
if ( userAndPosts.bio === "null" ) {
userAndPosts.bio = "";
}
ServerActions.receiveUserAndAllPosts(userAndPosts);
},
error: function(xhr) {
var errors = { "profileError": "Please upload a profile image"};
ErrorActions.setErrors("profile", errors);
}
});
},
fetchUsersThatMatchSearch: function(searchValue) {
if (searchValue === "") {
// skip backend if the search value is ""
ServerActions.fetchUsersAndHashtagsThatMatchSearch([]);
} else {
$.ajax({
url: '/api/users/search',
method: 'GET',
dataType: 'json',
data: {user: {username: searchValue}},
success: function(matchedUsers) {
this.fetchHashtagsThatMatchSearch(searchValue, matchedUsers);
// ServerActions.fetchUsersThatMatchSearch(matchedUsers);
}.bind(this)
});
}
},
fetchHashtagsThatMatchSearch: function(searchValue, matchedUsers) {
$.ajax({
url: '/api/hashtags/search',
method: 'GET',
dataType: 'json',
data: {hashtag: {search_value: searchValue}},
success: function(matchedHashtags) {
var matchedResults = matchedUsers.concat(matchedHashtags);
ServerActions.fetchUsersAndHashtagsThatMatchSearch(matchedResults);
}
});
}
};
// window.api = UserApiUtil;
module.exports = UserApiUtil;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.