text stringlengths 7 3.69M |
|---|
var util = require('util');
console.log(util.__dirname);
var a={B:{C:{D:1}},
A:'A' };
var b= Object.create(a);
var c = Object.assign(a);
var d = Object.assign(a);
c.B.C.D=2;
// Test Namespace Export
// var namespace_export = require('../namespace-export');
// console.log(namespace_export)
// namespace_export.sayHelloAsync(()=>console.log("Finished"));
// namespace_export.sayHello();
// Test Function export
// as the target module returns a function the module must be importedas
// var function_export = require(<MODULE_NAE>)(); check the () here
// if we leave that off then the exported function would not get executed and we will have nothing but a function
// var function_export = require('../function-export')('Abhishek');
// function_export.sayHello();
// var function_export1 = require('../function-export')('Dilli');
// function_export1.sayHello();
// Test higher order function export
// var higher_order_funciton_export = require('../higherorder-function-export')((greet)=>greet.toUpperCase());
// higher_order_funciton_export.sayHello('abhishek');
// Test constructor export
var Greet = require('../constructor-export');
var greetObj1 = new Greet(`Name`);
util.__proto__.cinspect=function(obj)
{
return this.inspect(obj,false,null,true);
}
console.log(`greetObj1=${util.cinspect((greetObj1))}`);
console.log(`invoking privateGreet [${util.cinspect(greetObj1.privateGreet())}]`);
console.log(`Greet ${util.cinspect(greetObj1.greet())}`);
var greetObj2 = new Greet('ChangedName');
console.log(`greetObj2=${util.cinspect(greetObj2)}`);
console.log(`invoking privateGreet [${util.cinspect(greetObj2.privateGreet())}]`);
console.log(greetObj2.greet());
console.log(greetObj1);
console.log(greetObj1.privateGreet());
console.log(greetObj1.greet());
|
import echarts from 'echarts';
import React from 'react';
class ReactEcharts extends React.Component {
constructor(props) { // 构造函数
super(props);
}
static defaultProps = {
chartsId: '',
stockInfo: {}
}
componentDidMount() {
if (!this.echartsIns && this.props.stockInfo.option) {
this.echartsIns = echarts.init(document.getElementById(this.props.chartId));
this.echartsIns.setOption(this.props.stockInfo.option);
window.addEventListener('resize', this.onWindowResize.bind(this))
if (this.props.chartsClickHandle) {
this.echartsIns.on('click', this.props.chartsClickHandle.bind(this));
}
}
}
onWindowResize(e) {
this.echartsIns.resize();
}
componentDidUpdate() {
if (!this.echartsIns && this.props.stockInfo.option) {
this.echartsIns = echarts.init(document.getElementById(this.props.chartId));
this.echartsIns.setOption(this.props.stockInfo.option);
window.addEventListener('resize', this.onWindowResize.bind(this))
if (this.props.chartsClickHandle) {
this.echartsIns.on('click', this.props.chartsClickHandle.bind(this));
}
}
}
componentWillUpdate() {}
render() {
let className = `J_mainChart ${this.props.className || ''}`
return (
<div className={className} id={this.props.chartId}></div>
);
}
}
export default ReactEcharts; |
export function setUrlHash(hash) {
if (history.pushState) {
history.pushState(null, null, '#' + hash);
}
else {
location.hash = '#' + hash;
}
}
export default setUrlHash; |
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
const config = require('./config/config')();
const VocabAPIController = require('./controllers/VocabAPI')
app.use(bodyParser.json());
app.use(express.static('public'))
// Add your routers here
app.get('/', function (req, res) {
res.send('index.html')
})
app.get('/all', VocabAPIController.getAll);
app.post('/new', VocabAPIController.addNew);
// Error handling here
app.use((req, res) => {
res.status(404).send('We can\' find what you\'re looking for');
})
app.use((err, req, res, next) => {
console.error('got error')
console.log(err)
res.status(500).send('Something broke!')
})
module.exports = app;
|
export const setPlaylist = (playlist) => {
return {
type:"SET_PLAYLIST",
payload:playlist
};
};
export const setCurrentPlaying = (curr_music) => {
return {
type: "SET_CURR_PLAYING",
payload: curr_music
};
}
export const setBannerOpen = (isOpen) => {
return {
type:"SET_BANNER_OPEN",
payload:isOpen
};
};
export const increaseTimesPlayed = (id) => {
return {
type:"INC_TIMES_PLAYED",
payload: id
};
};
export const setSearch = (searchQuery) => {
return {
type:"SET_SEARCH_QUERY",
payload: searchQuery
};
};
export const setMusicLang = (langList) => {
return {
type:"SET_MUSIC_LIST",
payload: langList
};
}; |
var shopCart = {
addCar:function(proData){
this.cart="cart";
localStorage.setItem(this.cart,JSON.stringify(proData));
},
addProData:function(proData,val){
var carts = JSON.parse(localStorage.getItem("cart"));
var bool = true;
if(!carts){
console.log("true")
proData.unmber=parseInt(val)
console.log(proData.unmber)
var creatlist = {
product:[proData],
proUnm:proData.unmber,
prototal:(proData.unmber*proData.price).toFixed(2)
}
this.addCar(creatlist);
}else{
console.log("false")
var getProData = JSON.parse(localStorage.getItem("cart"));
proData.unmber=parseInt(val) ;
var prolist = getProData.product;
for(var i in prolist){
if(prolist[i].id==proData.id){
prolist[i].unmber+=proData.unmber;
prolist[i].totals=parseInt(prolist[i].unmber*prolist[i].price).toFixed(2);
bool = false;
}
}
if(bool){
prolist.push(proData)
}
this.addCar(getProData)
}
}
}
|
const editOwner = document.querySelector('.edit-owner');
const createdAt = document.querySelector('#createdAt');
const createdTo = document.querySelector('#createdTo');
const petSelector = document.querySelector('#owner-pets');
const statusSelector = document.querySelector('#status-selector');
const totalFee = document.querySelector('#totalFee');
const extraServices = document.querySelector('.form-field input[type=checkbox]');
const extraFee = document.querySelector('#extra');
const mediumFee = document.querySelector('#medium');
const smallFee = document.querySelector('#small');
const largeFee = document.querySelector('#large');
$('#createdAt').datetimepicker({
onChangeDateTime: function (dp, $input) {
handleTimeChange();
}
});
$('#createdTo').datetimepicker({
onChangeDateTime: function (dp, $input) {
handleTimeChange();
}
});
MicroModal.init({
awaitCloseAnimation: false, // set to false, to remove close animation
});
document.querySelector('.container-left form').addEventListener('submit', function (e) {
e.preventDefault();
document.querySelector('.modal__content ul').innerHTML = `
<li>Owner: <strong style="margin-left: 10px;">${document.querySelector('#owner').value}</strong></li>
<li>
Pet Name: <strong style="margin-left: 10px;">${document.querySelector('a#owner-pets') ? document.querySelector('#owner-pets').innerText : document.querySelector('#owner-pets')[document.querySelector('#owner-pets').selectedIndex].innerText}</strong>
</li>
<li>
Departure: <strong style="margin-left: 10px;">${document.querySelector('#createdAt').value}</strong>
</li>
<li>
Arrival: <strong style="margin-left: 10px;">${document.querySelector('#createdTo').value}</strong>
</li>
<li>Status: <strong style="margin-left: 10px;">${document.querySelector('#status-selector')[document.querySelector('#status-selector').selectedIndex].innerText}</strong>.</li>
<li>
Extra Services: <strong style="margin-left: 10px;">${document.querySelector('input[name=extra]').checked}</strong>
</li>
<li>
Total Fee: <strong style="margin-left: 10px;">${document.querySelector('#totalFee').value}</strong>
</li>
`;
MicroModal.show('modal-1');
document.querySelector('.modal__footer button.ui.primary').addEventListener('click', () => {
this.submit();
})
})
const handleTotalFeeBooking = (petSize, departure, arrival) => {
const MILLS_IN_DAY = 1000 * 24 * 3600;
const differentInTime = arrival.getTime() - departure.getTime();
const differentInDays = differentInTime / MILLS_IN_DAY;
const differentInWeeks = Math.floor(differentInDays / 7);
const oddDays = differentInDays % 7;
let bookingFee = 0;
if (departure.getTime() && arrival.getTime()) {
switch (petSize) {
case 'small )' :
{
bookingFee += Math.round(smallFee.value * differentInDays);
break;
}
case 'medium )':
{
bookingFee += Math.round(mediumFee.value * differentInDays);
break;
}
case 'large )' :
{
bookingFee += Math.round(largeFee.value * differentInDays);
break;
}
}
}
if (extraServices.checked) {
bookingFee += parseFloat(extraFee.value);
}
totalFee.value = `$${bookingFee}`;
}
if (totalFee) {
extraServices.addEventListener('change', function () {
const currentFee = parseInt(totalFee.value.split("$")[1]);
if (this.checked) {
totalFee.value = `$${currentFee + 5}`;
} else {
totalFee.value = `$${currentFee - 5}`;
}
})
}
if (petSelector) {
petSelector.addEventListener('change', function () {
const petSize = this[this.selectedIndex].innerText;
handleTotalFeeBooking(petSize.split('(')[1].trim(), new Date(createdAt.value), new Date(createdTo.value));
})
}
statusSelector.addEventListener('change', function (e) {
const status = statusSelector[statusSelector.selectedIndex].value;
const userRole = document.querySelector('#userRole');
if (status === 'completed' && userRole !== 'pet owner') {
iziToast.show({
theme: 'dark',
overlay: true,
displayMode: 'once',
title: 'Hey',
message: 'Do you want to receive <strong>feedback</strong> from user ?',
position: 'center', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter
progressBarColor: 'rgb(0, 255, 184)',
buttons: [
['<button>Ok</button>', function (instance, toast) {
const sendFeedbackEle = document.createElement("div");
sendFeedbackEle.classList.add('form-field');
sendFeedbackEle.classList.add('feedback-field');
sendFeedbackEle.innerHTML = `
<label for="feedback"><strong>Send Feedback:</strong></label>
<div style="justify-content: flex-start">
<input type="checkbox" name="feedback" value="feedback" style="display: inline-block; width: auto" checked="checked"/>
</div>`;
document.querySelector('.container-left form').insertBefore(sendFeedbackEle, document.querySelector('.form-action'));
instance.hide({
transitionOut: 'fadeOutUp',
}, toast);
}], // true to focus
['<button>Close</button>', function (instance, toast) {
instance.hide({
transitionOut: 'fadeOutUp',
}, toast);
}]
],
});
} else if (document.querySelector('.feedback-field')) {
document.querySelector('.feedback-field').remove();
}
if (status === 'cancelled' && userRole.value === 'pet owner') {
const newEle = document.createElement('div');
newEle.className = 'form-field';
const label = document.createElement('label');
label.setAttribute('for', 'cancellationNotes');
label.innerHTML = 'Cancellation Notes:';
const textarea = document.createElement('textarea');
textarea.setAttribute('name', 'cancellationNotes');
textarea.setAttribute('rows', '4');
textarea.setAttribute('cols', '50');
textarea.setAttribute('id', 'cancellationNotes');
newEle.appendChild(label);
newEle.appendChild(textarea);
document.querySelector('form').insertBefore(newEle, document.querySelector('.fee-field'));
} else if (status !== 'cancelled' && userRole.value === 'pet owner') {
document.querySelector('.fee-field').previousElementSibling.remove();
}
})
if (editOwner) {
editOwner.addEventListener('click', function () {
fetch(`http://localhost:3000/PRJ321_REST/users/search`, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: "include",
body: JSON.stringify({
"owner": "",
"role": ""
}),
headers: {
"Content-Type": 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
}
})
.then(response => {
return response.json();
})
.then(data => {
if (data.length > 0) {
let temp = `<select id="users" name="users">`;
data.map(user => temp += `<option value=${user.email}>${user.email}</option>`);
temp += "</select>";
iziToast.question({
timeout: 20000,
close: false,
drag: false,
overlay: true,
displayMode: 'once',
id: 'question',
zindex: 999,
title: 'Hey',
message: 'Please Choose One User: ',
position: 'center',
inputs: [
[
temp, 'change', function (instance, toast, select, e) {
}
]
],
buttons: [
['<button><b>Confirm</b></button>', function (instance, toast, button, e, inputs) {
document.querySelector('.container-left #owner').value = inputs[0].options[inputs[0].selectedIndex].value;
fetch(`http://localhost:3000/PRJ321_REST/pets/search/${document.querySelector('.container-left #owner').value}`, {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: "include",
headers: {
"Content-Type": 'application/json'
}
})
.then(response => {
return response.json();
})
.then(data => {
if (data.length > 0) {
let temp = ``;
data.map(pet => temp += `<option value=${pet.id}>${pet.name} (${pet.id})</option>`);
petSelector.innerHTML = temp;
} else {
setTimeout(() => {
iziToast.error({
title: 'error',
message: 'Can\'t Find Any Pet(s) Belong To User !',
});
}, 50);
petSelector.innerHTML = '';
petSelector.nextElementSibling.nextElementSibling.innerHTML = '';
}
})
.catch(err => {
console.log(err);
setTimeout(() => {
iziToast.error({
title: 'error',
message: 'There is some error when searching pets !',
});
}, 50);
});
instance.hide({transitionOut: 'fadeOut'}, toast, 'button');
}, false], // true to focus
['<button>NO</button>', function (instance, toast, button, e) {
instance.hide({transitionOut: 'fadeOut'}, toast, 'button');
}]
],
});
} else {
setTimeout(() => {
iziToast.error({
title: 'error',
message: 'Can\'t Find Any User(s) !',
});
}, 50);
}
})
.catch(err => {
setTimeout(() => {
iziToast.success({
title: 'error',
message: 'There is some error when searching user !',
});
}, 50);
});
});
} |
import { Button, Table } from "react-bootstrap";
import { Link } from "react-router-dom";
export const UsersList = ({ users, onDelete, isActive, onUpdate }) => (
<Table striped bordered size="sm">
<thead>
<tr>
<th>Username</th>
<th>Email</th>
{isActive && <th>Roles</th>}
<th></th>
</tr>
</thead>
<tbody>
{users.map(user => (
<tr key={user.username}>
<td>{user.username}</td>
<td>{user.email}</td>
{isActive && <td>{user.roles.join(', ')}</td>}
<td>
<Link to={`/users/${user.username}`} className="btn btn-primary btn-sm mr-1">View</Link>
<Button variant="danger" size="sm" onClick={() => onDelete(user)}>Delete</Button>
<Button variant="warning" size="sm" className="ml-1" onClick={() => onUpdate(user, !isActive)}>{isActive ? "Block" : "Activate"}</Button>
</td>
</tr>
))}
</tbody>
</Table>
) |
class Craps{
constructor(){
this.spot = 0;
this.rolled = 0;
this.state = 'neutral';
this.passDice = false;
}
static rollDie(){
return Math.floor(Math.random() * Math.floor(6)) + 1
}
static rollDice(ct){
let result = 0;
for(let i = 0; i < ct; i++){
result += Craps.rollDie();
}
return result;
}
async roll(){
this.rolled = Craps.rollDice(2);
if(this.spot === 0){//comeout
if(this.rolled === 7 || this.rolled === 11){
this.state = 'win';
this.passDice = false;
}else if(this.rolled < 4 || this.rolled > 11){
this.state = 'lose';
this.passDice = true;
}else{
this.spot = this.rolled;
this.state = 'neutral';
this.passDice = false;
}
}else{
if(this.rolled === 7){
this.state = 'lose';
this.spot = 0;
this.passDice = true;
}else if(this.rolled === this.spot){
this.state = 'win';
this.spot = 0;
}
}
}
}
module.exports = new Craps();
|
document.addEventListener('keyup', function(e) {
switch(e.keyCode) {
case 37: // left
case 38: // up
case 39: // right
case 40: // down
case 32: // space
game.handleInput(e.keyCode);
break;
}
}); |
/** 关键字是什么? 红宝书 p21 */
/** 浏览器控制台是什么? 浏览器提供的调试工具 */
/** 调试工具有什么用? 帮助你查看代码执行结果,排查故障 */
/** 如何在控制台输出代码执行结果? 使用 console.log()
* 如 console.log(1 + 1); 执行后会输出 2
* 如 console.log("hello"); 执行后会输出 hello
* 如 console.log("hello", 1); 执行后会输出 hello 1
*/
/** 赋值
* = 为赋值运算符,= 左边必须为变量,右边为 表达式 或 变量 或 具体的值
*/
/** 声明变量 */
function variable() {
console.log('声明变量');
/** 使用 var 关键字声明变量 a */
var a;
console.log('a =', a); // 输出结果:undefined
/** 使用 var 关键字声明变量 b,并赋值初始值为 1 */
var b = 1;
console.log('b =', b); // 输出结果:1
/** 重复声明变量 a,并赋值为 2 */
var a = 2;
console.log('a =', a); // 输出结果:2
/** 对变量 a 进行赋值操作,赋值一个具体值 3 */
a = 3;
console.log('a =', a); // 输出结果:3
/** 对变量 a 进行赋值操作,赋值一个变量 b */
a = b;
console.log('a =', a); // 输出结果:1,和上文声明的变量 b 的值一致
/** 再次重新声明 a */
var a;
console.log('a =', a); // 输出结果:1,并不是 undefined,var 声明的变量会 “变量提升”(百度)
/** 直接声明 c(不推荐),会让任何地方都可以访问 c */
c = 3;
console.log('c =', c);
}
/** 声明变量2 */
function variable2() {
console.log('声明变量2');
/** 在上一个步骤直接声明的 c,会让任何地方都可以访问 c */
console.log('c =', c);
/** 使用 let 关键字声明变量 a */
let a;
console.log('a =', a); // 输出结果:undefined
/** 不能使用 let 关键字重复声明同一个变量 */
// let a = 2;
/** 报错:Uncaught SyntaxError: Identifier 'a' has already been declared */
/** 对 a 赋值 */
a = 3;
console.log('a =', a); // 输出结果:3
/** 使用 const 关键字声明变量 */
/** const 用于声明不会改变的变量 */
const b = 2;
console.log('b =', b); // 输出结果:2
/** 不可使用 const 重复声明同一个变量 */
// const b = 4;
/** 报错:Uncaught SyntaxError: Identifier 'a' has already been declared */
/** 不可对 const 声明的变量重新赋值,如果需要重新赋值,应该使用 let 关键字声明变量 */
b = 4; // vUncaught TypeError: Assignment to constant variable.
}
variable();
variable2();
|
var inventory = [{
'name': 'USB Stick',
'options': [{
'id': 1,
'details': '16GB',
'price': 6.95
}, {
'id': 2,
'details': '32GB',
'price': 12.95
}, {
'id': 3,
'details': '64GB',
'price': 25.95
}]
}, {
'name': 'USB Plug',
'options': [{
'id': 4,
'price': 4.35,
'details': '3ft cable'
}, {
'id': 13,
'price': 9,
'details': '6ft cable'
}]
}, {
'name': 'Small Phone',
'options': [{
'id': 5,
'price': 199,
'details': 'Nokia Phone'
}]
}, {
'name': 'Camera',
'options': [{
'id': 6,
'price': 76.50,
'details': 'Blue Camera'
}, {
'id': 7,
'price': 86.50,
'details': 'Red Camera'
}, {
'id': 8,
'price': 55.50,
'details': 'Yellow Camera'
}, {
'id': 9,
'price': 45.50,
'details': 'Purple Camera'
}]
}];
var incart = [{
price: 100,
listitem: 'First Test Product',
quantity: 4,
id: 1
}, {
price: 10,
listitem: 'Another Test Product',
quantity: 2,
id: 2
}];
|
const bcrypt = require('bcrypt');
const Web3 = require ('web3');
const jsonfile = require('jsonfile');
const truffleConf = require('../../truffle-config');
const web3 = new Web3(`ws://${truffleConf.networks.development.host}:${truffleConf.networks.development.port}`);
module.exports = {
loginUser: async (login, password, db, ctx) => {
const accounts = await web3.eth.getAccounts();
if(accounts.indexOf(login) === -1) {
ctx.throw(400, 'No such account');
}
const user = db.findOne({'login': login});
if(!user) {
const passwordHash = await bcrypt.hash(password, 10);
const token = require('crypto').randomBytes(64).toString('hex');
db.insert({ login : login, password: passwordHash, token: token});
ctx.cookies.set('bp_token', token);
return {
status: 201,
token: token
};
}
if(!await bcrypt.compare(password, user.password)) {
ctx.throw(401, 'Bad creditentials');
}
const token = require('crypto').randomBytes(64).toString('hex');
user.token = token;
db.update(user);
ctx.cookies.set('bp_token', token);
return {
status: 200,
token: token
};
},
balance: async address => {
const wei = await web3.eth.getBalance(address);
return web3.utils.fromWei(wei);
},
buyTokens: async (who, gameId, amount) => {
// console.log('BUYING: ', who, gameId, amount);
const trx = {
from: who,
to: await getAddress(gameId),
value: web3.utils.toWei(amount.toString()),
gasLimit: '1000000'
};
const contract = new web3.eth.Contract(
(await jsonfile.readFile(`${__dirname}/../../build/contracts/Lottery.json`)).abi,
await getAddress(gameId)
);
return contract.methods.play(amount).send(trx);
},
gameDetails: async(gameId) => { //gameId not used
const contract = new web3.eth.Contract(
(await jsonfile.readFile(`${__dirname}/../../build/contracts/Lottery.json`)).abi,
await getAddress(gameId)
);
return {
balance: web3.utils.fromWei((await contract.methods.getBalance().call()).toString()),
counter: undefined, //await contract.gamesPlayed.call(),
players: await contract.methods.getNumberOfPlayers().call()
};
}
};
const getAddress = async () => {
const file = `${__dirname}/../../build/contracts/Lottery.json`;
const networkId = truffleConf.networks.development.network_id;
const addr = (await jsonfile.readFile(file)).networks[networkId].address;
return addr;
};
|
// Searchlang global context manager
// =================================
var Context = { cache: null, imports: null, importsMap: null, builtins: {} };
module.exports = Context;
// Imports management
function getImport(url) {
return Context.imports[Context.importsMap[url]];
}
function addImport(url, links) {
var i = (Context.imports.push(links) - 1);
Context.importsMap[url] = i;
}
Context.reset = function() {
// Clear all memory
Context.cache = {};
Context.imports = [];
Context.importsMap = {};
// Copy in builtins
for (var url in Context.builtins) {
addImport(url, Context.builtins[url]);
}
};
Context.fetch = function(url) {
// Check the cache
if (url in Context.cache) {
// Respond with self link
return web.promise(Context.cache[url].get('self'));
}
// Run a head request
return web.head(url)
.then(function(res) {
// Cache the response
Context.cache[url] = res.links;
// Respond with self link
return Context.cache[url].get('self');
});
};
Context.import = function(url, links) {
if (Context.hasImported(url)) {
return web.promise(getImport(url));
}
if (links) {
// Add to cache and imports
Context.cache[url] = links;
addImport(url, links);
return links;
}
// Fetch the links
return Context.fetch(url).then(function() {
// Load from cache into active context
var links = Context.cache[url];
addImport(url, links);
return links;
});
};
Context.hasImported = function(url) {
return (url in Context.importsMap);
};
Context.importBuiltin = function(url) {
return web.head(url).then(function(res) {
Context.builtins[url] = res.links;
return res;
});
};
Context.find = function(terms) {
// Search each import group in sequence
var link;
for (var i=0; i < Context.imports.length; i++) {
link = findIn(Context.imports[i], terms);
if (link)
return link;
}
return false;
};
function findIn(links, terms) {
for (var i=0; i < links.length; i++) {
var link = links[i];
// Stringify link for broad search
if (!link.__stringified) {
Object.defineProperty(link, '__stringified', { value: JSON.stringify(link).toLowerCase() });
}
if (doesLinkMatch(link, terms)) {
return link;
}
}
return false;
}
var uriTokenStart = '\\{([^\\}]*)[\\+\\#\\.\\/\\;\\?\\&]?';
var uriTokenEnd = '(\\,|\\})';
function doesLinkMatch(link, terms) {
for (var j=0; j < terms.length; j++) {
var term = terms[j];
if (term.charAt) {
// Broad search
if (link.__stringified.indexOf(term.toLowerCase()) === -1) {
return false;
}
} else {
// Attribute/value search
var attr = term[0];
var value = term[1];
if (attr in link) {
// Case-insensitive equality
if (value.toLowerCase() !== link[attr].toLowerCase()) {
return false;
}
} else {
// Is the attribute in the href as a URI token?
if (!RegExp(uriTokenStart+attr+uriTokenEnd,'i').test(link.href)) {
return false;
}
}
}
}
return true;
} |
const Generator = require('yeoman-generator');
const shell = require('shelljs');
module.exports = class extends Generator {
constructor(args, opts) {
super(args, opts);
this.option('app', {
type: String,
required: true,
desc: 'App name',
});
}
writing() {
const app = this.options.app;
const allcaps = app.toUpperCase();
this.fs.copy(
this.templatePath('example/env'),
this.destinationPath('example/.env'));
this.fs.copy(
this.templatePath('example/manage.py'),
this.destinationPath('example/manage.py'));
this.fs.copyTpl(
this.templatePath('example/Pipfile'),
this.destinationPath('example/Pipfile'), { app });
this.fs.copy(
this.templatePath('example/exampleapp/__init__.py'),
this.destinationPath('example/exampleapp/__init__.py'));
this.fs.copyTpl(
this.templatePath('example/exampleapp/settings.py'),
this.destinationPath('example/exampleapp/settings.py'), { app, allcaps });
this.fs.copyTpl(
this.templatePath('example/exampleapp/urls.py'),
this.destinationPath('example/exampleapp/urls.py'), { app });
this.fs.copy(
this.templatePath('example/exampleapp/wsgi.py'),
this.destinationPath('example/exampleapp/wsgi.py'));
}
install() {
shell.exec('pipenv install', {
cwd: 'example/',
silent: true,
});
}
};
|
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/haohuola';
exports.run = function(req, res) {
var id = parseInt(req.params.id);
MongoClient.connect(url, function(err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
var collection = db.collection('post');
collection.find({
'id': id
}).limit(1).toArray(function(err, result) {
if (err) {
console.log('find post error');
} else {
if (result.length > 0) {
var post = result[0];
res.render('post', {
'title': post.title,
'content': post.content,
'time': post.time,
'link': post.link,
'tags': post.tag
});
} else {
res.send('<h1 style="text-align:center;font-weight:200;font-size:6em;margin-top:100px;">404<br><span style="font-size:30px;">Not Found</span></h1>', 404);
}
}
})
}
})
} |
import $ from 'jquery';
// plugin to select the first word(s) of a string and capitalize it
$.fn.capitalizeStart = function( numWords ) {
if ( !numWords ) {
numWords = 1;
}
const node = this.contents().filter( function() {
return this.nodeType === 3;
} ).first(),
text = node.text(),
first = text.split( ' ', numWords ).join( ' ' );
if ( !node.length ) {
return;
}
node[ 0 ].nodeValue = text.slice( first.length );
node.before( `<span class="capitalize">${first}</span>` );
};
$.fn.btnBusyState = function( busy ) {
return this.each( function() {
const $button = $( this );
let btnContent = $button.find( '.temp' ).html();
if ( busy && !btnContent ) {
btnContent = $button.html();
$button
.empty()
.append( '<progress></progress>' )
.append( $( '<span class="temp" style="display: none;"/>' ).append( btnContent ) )
.attr( 'disabled', true );
} else if ( !busy && btnContent ) {
$button
.empty()
.append( btnContent )
.removeAttr( 'disabled' );
}
} );
};
// This function facilitates changing button text regardless of its busystate.
$.fn.btnText = function( text ) {
$( this ).add( $( this ).find( 'span' ) ).last()[ 0 ].lastChild.textContent = text;
};
|
import {createMockClient} from 'mock-apollo-client';
const mockGqlClient = createMockClient();
export default mockGqlClient; |
import React from 'react';
import {Link} from 'react-router-dom';
import moment from 'moment';
export default class TestListComponent extends React.Component{
render (){
return <table className="table table-hover">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Duration Time(Minutes)</th>
<th></th>
<th><Link className="btn btn-primary" to ={{
pathname:`${this.props.match.url}/add-test`
,state:{
from:this.props.match.url,
activeSubject:this.props.activeSubject,
courseId:this.props.mockPaper.courseId,
testStartTime:this.props.mockPaper.startDateTime,
paperId:this.props.mockPaper.id} }}
> Add New</Link></th>
</tr>
</thead>
<tbody>
{this.props.tests && Array.isArray(this.props.tests) && this.props.tests.length ?
this.props.tests.map((test,index)=>{
return <tr key={index}>
<td>{test.id}</td>
<td>{test.name}</td>
<td>{test.durationMinutes}</td>
<td><input type="checkbox" checked={this.props.addedTests && this.props.addedTests[test.id] ?this.props.addedTests[test.id]:false} onChange={(e)=> this.props.onTestAddRemove(test.id,e.target.checked)} /></td>
<td>
<Link className="btn btn-primary" to={`${this.props.match.url}/edit-test/`+test.id} >view / edit</Link>
</td>
</tr>;
})
:<tr><td><span className="text-style">Tests not available
<Link to ={{
pathname:`${this.props.match.url}/add-test`
,state:{
from:this.props.match.url,
activeSubject:this.props.activeSubject,
courseId:this.props.mockPaper.courseId,
testStartTime:this.props.mockPaper.startDateTime,
paperId:this.props.mockPaper.id} }}
> Add New Test</Link>
</span></td></tr>}
</tbody>
</table>;
};
} |
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var Book = require('./booksmodel');
//details of all books "/books"
function getBooks(req, res) {
return __awaiter(this, void 0, void 0, function () {
var books, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, Book.findAll()];
case 1:
books = _a.sent();
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(books));
return [3 /*break*/, 3];
case 2:
error_1 = _a.sent();
console.log(error_1);
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
});
}
//searching by id "/books/1"
function searchById(req, res, id) {
return __awaiter(this, void 0, void 0, function () {
var book, error_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, Book.findById(id)];
case 1:
book = _a.sent();
if (!book) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Book does not exist' }));
}
else {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(book));
}
return [3 /*break*/, 3];
case 2:
error_2 = _a.sent();
console.log(error_2);
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
});
}
// search by author
function searchByAuthor(req, res, author) {
return __awaiter(this, void 0, void 0, function () {
var book, error_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, Book.findByAuthor(author)];
case 1:
book = _a.sent();
if (!book) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Book does not exist' }));
}
else {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(book));
}
return [3 /*break*/, 3];
case 2:
error_3 = _a.sent();
console.log(error_3);
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
});
}
//add new book
function addBook(req, res) {
return __awaiter(this, void 0, void 0, function () {
var body_1;
var _this = this;
return __generator(this, function (_a) {
try {
body_1 = '';
req.on('data', function (chunk) {
body_1 += chunk.toString();
});
req.on('end', function () { return __awaiter(_this, void 0, void 0, function () {
var _a, title, author, price, rating, book, newBook;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = JSON.parse(body_1), title = _a.title, author = _a.author, price = _a.price, rating = _a.rating;
book = {
title: title,
author: author,
price: price,
rating: rating
};
return [4 /*yield*/, Book.create(book)];
case 1:
newBook = _b.sent();
res.writeHead(201, { 'Content-Type': 'application/json' });
return [2 /*return*/, res.end(JSON.stringify(newBook))];
}
});
}); });
}
catch (error) {
console.log(error);
}
return [2 /*return*/];
});
});
}
//update book
function updateBook(req, res, id) {
return __awaiter(this, void 0, void 0, function () {
var book_1, body_2, error_4;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, Book.findById(id)];
case 1:
book_1 = _a.sent();
if (!book_1) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Book does not exist' }));
}
else {
body_2 = '';
req.on('data', function (chunk) {
body_2 += chunk.toString();
});
req.on('end', function () { return __awaiter(_this, void 0, void 0, function () {
var _a, title, author, price, rating, bookData, updateBook;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = JSON.parse(body_2), title = _a.title, author = _a.author, price = _a.price, rating = _a.rating;
bookData = {
title: title || book_1.title,
author: author || book_1.author,
price: price || book_1.price,
rating: rating || book_1.rating
};
return [4 /*yield*/, Book.update(id, bookData)];
case 1:
updateBook = _b.sent();
res.writeHead(200, { 'Content-Type': 'application/json' });
return [2 /*return*/, res.end(JSON.stringify(updateBook))];
}
});
}); });
}
return [3 /*break*/, 3];
case 2:
error_4 = _a.sent();
console.log(error_4);
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
});
}
//delete a book by id
function deleteBook(req, res, id) {
return __awaiter(this, void 0, void 0, function () {
var book, error_5;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 5, , 6]);
return [4 /*yield*/, Book.findById(id)];
case 1:
book = _a.sent();
if (!!book) return [3 /*break*/, 2];
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Book does not exist' }));
return [3 /*break*/, 4];
case 2: return [4 /*yield*/, Book.deleted(id)];
case 3:
_a.sent();
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: "book with " + id + " has been removed" }));
_a.label = 4;
case 4: return [3 /*break*/, 6];
case 5:
error_5 = _a.sent();
console.log(error_5);
return [3 /*break*/, 6];
case 6: return [2 /*return*/];
}
});
});
}
module.exports = {
getBooks: getBooks,
searchById: searchById,
searchByAuthor: searchByAuthor,
addBook: addBook,
updateBook: updateBook,
deleteBook: deleteBook
};
|
import Transaction from './transaction';
import Util from './util';
class Block {
constructor(optHash){
this.hash = Util.makeHash();
this.txns = optHash["txns"];
this.previousBlock = optHash["previousBlock"];
}
}
export default Block;
|
const getPrimaryKeys = require('./helpers/getPrimaryKeys');
const executeQuery = require('./helpers/cassandraHelper');
const getStateRoutes = require('./helpers/formatStateData');
const getStopsFromRouteID = require('./helpers/getStops');
const config = require('./config');
const _ = require('lodash');
const axios = require('axios');
const resolvers = {
trynState: async (obj) => {
const { agency, routes } = obj;
let { startTime, endTime } = obj;
startTime = Number(startTime);
endTime = Number(endTime);
const primaryKeys = getPrimaryKeys(startTime, endTime);
// TODO - get these from config file using agency name
const keyspace = agency;
const vehicleTableName = `${agency}_realtime_vehicles`;
const responses = await Promise.all(primaryKeys.map(({vdate, vhour}) =>
executeQuery(
`SELECT * FROM ${keyspace}.${vehicleTableName} WHERE vdate = ? AND vhour = ? AND vtime > ? AND vtime < ?`,
[vdate, vhour, new Date(startTime), new Date(endTime)],
)));
// vehicles are clustered by primary key - so put them into the same list
const vehicles = _.flatten(responses.map(({rows}) => rows));
// cluster vehicles by their individual timestamp
const vehiclesByTime = vehicles.reduce((acc, vehicle) => {
acc[vehicle.vtime] = (acc[vehicle.vtime] || []).concat(vehicle);
return acc;
}, {});
const stateTimes = Object.keys(vehiclesByTime).sort();
const states = await Promise.all(
stateTimes.map(async stateTime => {
const stateVehicles = vehiclesByTime[stateTime];
const routeIDs = _.uniq(stateVehicles.map(vehicle => vehicle.rid));
const stops = await Promise.all(routeIDs.map(getStopsFromRouteID));
return {
time: stateTime,
routes: getStateRoutes(routeIDs, stateVehicles, stops),
};
})
);
return {
agency,
startTime,
endTime,
states,
};
},
}
module.exports = resolvers;
|
import React from "react";
import "./styles/searchbook.css";
import CircularProgress from "@material-ui/core/CircularProgress";
import { NavLink } from "react-router-dom";
import Footer from "../components/Footer";
import MoreIcon from "@material-ui/icons/More";
import Tooltip from "@material-ui/core/Tooltip";
function SearchBook({ searchBook, loading, id }) {
if (loading) {
return (
<CircularProgress
color="secondary"
size="5rem"
style={{ marginTop: "38vh" }}
/>
);
} else {
return (
<>
<div className="search_result">
{searchBook.map((search) => (
<div key={search.id} className="seacrh_box">
<img
src={search.volumeInfo.imageLinks.thumbnail}
alt="Book"
className="search_book_img"
/>
<h3>
Title<span>{search.volumeInfo.title}</span>
</h3>
<h5>
Author <span>{search.volumeInfo.authors}</span>
</h5>
<div className="buttons">
<NavLink to={`/bookdetails/${search.id}/${id}`}>
<Tooltip title="More Details" aria-label="SeachBooks">
<MoreIcon style={{ fontSize: "2rem", color: "red" }}/>
</Tooltip>
</NavLink>
</div>
</div>
))}
</div>
<Footer />
</>
);
}
}
export default SearchBook;
|
define(["jquery", "underscore", "backbone", "./Thumbnail"], function(e, n, i, t) {
"use strict";
return i.View.extend({
tagName: "ul",
className: "unstyled",
initialize: function(e) {
this.images = e, this.render()
},
render: function() {
var e = this;
n.each(this.images, function(n) {
e.renderThumbnail(n)
})
},
renderThumbnail: function(n) {
var i = this,
a = e("<li>");
a.css({
padding: "1em",
display: "inline-block",
verticalAlign: "top"
});
var s = new t({
image: n
});
s.on("remove", function(e) {
a.fadeOut(function() {
s.close(), a.remove()
}), i.trigger("remove", e)
}), s.on("rename", function(e) {
i.trigger("rename", e)
}), a.append(s.$el), this.$el.append(a)
},
closeThumbnails: function() {
this.thumbnails && n.each(this.thumbnails, function(e) {
e.close()
})
},
onClose: function() {
this.closeThumbnails()
}
})
});
|
import React from 'react'
import Menu from './Menu'
import { hamburgerMenuStyles } from 'constants/hamburgerMenuStyles'
import { Sidebar } from 'Containers'
import { MobileLinkIcons } from 'Components'
class ReactBurgerMenu extends React.Component {
render () {
return (
<Menu right styles={hamburgerMenuStyles}>
<MobileLinkIcons />
<div className="spacer"> </div>
<Sidebar isMobile={true} />
</Menu>
)
}
}
export default ReactBurgerMenu
|
import React from 'react';
import {Image} from 'react-native';
export default function LogoTitle() {
return (
<Image
style ={{flex:1}}
source={require('../../images/android-icon-36x36.png')}
resizeMode='contain'
/>
);
} |
import utils from "./utils";
export default function (global, config, reporter) {
var g = global || window;
g.onerror = function (msg, url, line, col, error) {
var newMsg = msg;
if (error && error.stack) {
newMsg = utils.processStackMsg(error);
}
if (utils.isOBJByType(newMsg, "Event")) {
newMsg += newMsg.type ?
("--" + newMsg.type + "--" + (newMsg.target ?
(newMsg.target.tagName + "::" + newMsg.target.src) : "")) : "";
}
if (Math.random() < (config.error.random || config.random)) {
errorPush({
msg: newMsg,
target: url,
rowNum: line,
colNum: col,
_orgMsg: msg
});
}
}
window.addEventListener('error', function (e) {
e.stopImmediatePropagation();
var srcElement = e.srcElement;
if (srcElement === window) {
// 全局错误
// console.log(e.message)
} else {
// 元素错误,比如引用资源报错
// console.log(e)
// console.log(srcElement.tagName)
// console.log(srcElement.src);
if (Math.random() < (config.error.random || config.random)) {
errorPush({
url: srcElement.src || srcElement.href,
tag: srcElement.tagName,
})
}
}
}, true)
window.addEventListener('unhandledrejection', function (e) {
e.preventDefault();
// console.log(e)// unhandledrejection
if (Math.random() < (config.error.random || config.random)) {
errorPush({
msg: e.reason.message || "_",
stack: e.reason.stack || "_",
})
}
})
function errorPush(data) {
reporter.push({
type: 'error',
data: data,
hash: utils.hash(JSON.stringify(data))
})
}
}
|
define(['./section'], function (Section) {
'use strict';
var Container;
Container = (function() {
function Container() {
var sections = [];
this.add = function(section) {
if (section instanceof Section) {
sections.push(section);
} else {
throw new Error("Error");
}
};
this.getData = function() {
var allData = [];
for (var i = 0, len = sections.length; i < len; i++) {
allData.push(sections[i].getData());
}
return allData;
};
}
return Container;
}());
return Container;
}); |
var myApp = angular.module('app', [
'ngAnimate',
'ngSanitize',
'ngTouch',
'topDirectors',
'ui.bootstrap',
'ui.router'
]);
// Routes
//////////////////////////////////////////////////////////
myApp.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider
.otherwise('/home');
$stateProvider
// Home
.state('home', {
url: '/home',
templateUrl: 'pages/home/home.html'
})
// Details
.state('details', {
url: '/details',
templateUrl: 'pages/details/details.html'
})
//About
.state('about', {
url: '/about',
templateUrl: 'pages/about/about.html'
})
// Contact
.state('contact', {
url: '/contact',
templateUrl: 'pages/contact/contact.html'
});
});
//Main
myApp.controller('TopActorsCtrl', function ($scope, $sce) {
$scope.topActorsPopover = {
templateUrl: 'templates/popovers/top-actors.html',
};
});
myApp.controller('TopShowsCtrl', function ($scope, $sce) {
$scope.topShowsPopover = {
templateUrl: 'templates/popovers/top-shows.html',
};
});
//Filmography
myApp.controller('FilmographyCtrl', function ($scope) {
$scope.status = {
directorOpen: true
};
});
//Footer
myApp.controller('FooterCtrl', function ($scope) {
$scope.CurrentDate = new Date();
}); |
import React, {Component} from 'react';
class Camera extends Component {
render() {
const imageBase64 = this.props.camera
// Javascript can automatically convert the base64 string to image source
return (
<div id="camera-div">
<img id="camera-feed" src={"data:image/png;base64," + imageBase64}></img>
</div>
);
}
}
export default Camera; |
angular.module('WeatherDetailCtrl', [])
.controller('WeatherDetailCtrl', function ($scope, WeathersService, SettingFactory) {
$scope.$on("settings-changed", function (event, data) {
loadData();
});
loadData();
function loadData() {
WeathersService.hourlyWeather().then(function (result) {
$scope.hourlyWeathers = result.hourly.data;
$scope.dailyWeathers = result.daily.data;
$scope.cityName = SettingFactory.getCity().name;
$scope.summary = result.daily.summary;
});
}
});
|
/* 通常异步操作和对mutations封装,写在actions里面 */
import * as types from './mutation-types'
import {playMode} from 'js/config'
import {shuffle} from 'js/util' //洗牌
import {saveSearch,deleteOne,deleteAll,saveSong,saveLike,deleteLike} from 'js/cache'
function hasIndex(arr,song) { //返回列表中相同歌曲的下标
return arr.findIndex(item => {
return item.songid === song.songid
})
}
//点击歌曲时,设置播放列表,显示顺序列表,全屏,播放
export const selectMusic = ({commit,state},{list,index}) => {
commit(types.SET_SEQUENCE_LIST,list);
if(state.mode === playMode.random) {
let randomList = shuffle(list);
commit(types.SET_PLAY_LIST,randomList);
index = hasIndex(randomList,list[index]);
} else {
commit(types.SET_PLAY_LIST,list);
}
commit(types.SET_CUR_INDEX,index);
commit(types.SET_PLAYING,true);
commit(types.SET_FULL_SCREEN,true);
}
//点击全部随机播放
export const randomPlayAll = ({commit,state},list) => {
commit(types.SET_PLAY_MODE,playMode.random)
commit(types.SET_SEQUENCE_LIST,list);
let newList = shuffle(list);
commit(types.SET_PLAY_LIST,newList);
commit(types.SET_CUR_INDEX,0);//播放随机列表的第一个
commit(types.SET_PLAYING,true);
commit(types.SET_FULL_SCREEN,true);
}
//在当前播放列表中,插入一首歌
export const insertSong = ({commit,state},song) => {
/* 播放列表 */
let playList = state.playList.slice(); //获取当前播放列表副本
let curIndex = state.curIndex; //获取当前播放歌曲下标
let curSong = playList[curIndex] ; //获取当前歌曲
let playListIndex = hasIndex(playList,song); //播放列表是否已经含有添加的歌曲
curIndex++; //因为是插入的歌曲,所以下标加1
playList.splice(curIndex,0,song); //将点击歌曲放入播放列表数组 ------重点
if(playListIndex > -1) { //大于-1,说明列表已包含点击个歌曲
if(curIndex > playListIndex) { //在播放歌曲前面,删掉,并当前播放下标减1
playList.splice(playListIndex,1);
curIndex--;
} else { //在播放歌曲后面,删掉,并当前播放下标不变
playList.splice(playListIndex+1,1); //因为增加了一个,所以删除的下标要加1
}
}
//为什么单独把sequenceList重新获取,因为playList的顺序模式值是sequenceList赋予了,想改变playList,就要改变sequenceList
let sequenceList = state.sequenceList.slice(); //获取顺序播放列表
let curSIndex = hasIndex(sequenceList,curSong) + 1;//顺序列表sequenceList,插入的位置
let sequenceListIndex = hasIndex(sequenceList,song); //顺序列表中是否已经包含插入的歌曲,返回下标
sequenceList.splice(curSIndex,0,song);//将点击歌曲放入顺序列表数组 ------重点
if(sequenceListIndex > -1) {
if(curSIndex > sequenceListIndex) { //在播放歌曲前面,删掉
sequenceList.splice(sequenceListIndex,1);
//curSIndex--; 不用减了,因为sequenceList不会直接使用,只是给playList赋值
} else { //在播放歌曲后面,删掉,并当前播放下标不变
sequenceList.splice(sequenceListIndex+1,1);//因为增加了一个,所以删除的下标要加1
}
}
commit(types.SET_PLAY_LIST,playList);
commit(types.SET_SEQUENCE_LIST,sequenceList);
commit(types.SET_CUR_INDEX,curIndex);
commit(types.SET_PLAYING,true);
commit(types.SET_FULL_SCREEN,true);
}
//在当前播放列表中,删除一首歌
export const deleteSong = ({commit,state},song) => {
let playList = state.playList.slice();
let sequenceList = state.sequenceList.slice();
let curIndex = state.curIndex;
let sIndex = hasIndex(sequenceList,song); //顺序列表中要删除的下标
sequenceList.splice(sIndex,1);
let pIndex = hasIndex(playList,song); //获取随机列表中要删除的下标
playList.splice(pIndex,1);
if(curIndex > pIndex || curIndex === playList.length) {
curIndex--;
}
commit(types.SET_PLAY_LIST,playList);
commit(types.SET_SEQUENCE_LIST,sequenceList);
commit(types.SET_CUR_INDEX,curIndex);
commit(types.SET_PLAYING,true);
}
//清空播放列表
export const clearPlayList = ({commit}) => {
commit(types.SET_PLAY_LIST,[]);
commit(types.SET_SEQUENCE_LIST,[]);
commit(types.SET_CUR_INDEX,-1);
commit(types.SET_PLAYING,false);
}
//存入缓存
export const saveHistorySearch = ({commit},searchText) => {
commit(types.SET_HISTORY_SEARCH,saveSearch(searchText));
}
//删除搜索历史中某个选项
export const deleteOneHistory = ({commit},searchText) => {
commit(types.SET_HISTORY_SEARCH,deleteOne(searchText));
}
//删除搜索历史中某个选项
export const deleteAllHistory = ({commit}) => {
commit(types.SET_HISTORY_SEARCH,deleteAll());
}
//将播放过的歌曲存入播放历史
export const savePlayingSong = ({commit},song) => {
commit(types.SET_PLAYING_SONGS,saveSong(song))
}
//将喜欢的歌曲收取放入收藏列表
export const saveLikeList = ({commit},song) => {
commit(types.SET_LIKE_LIST,saveLike(song))
}
//将喜欢的歌曲删除
export const deleteLikeSong = ({commit},song) => {
commit(types.SET_LIKE_LIST,deleteLike(song))
} |
function ndepthNormalBuffer() {
this._width = 0;
this._height = 0;
this._blockerBufferWidth = 0;
this._blockerBufferHeight = 0;
this._nearFarPlane = [0.0, 0.0];
this._depthNormal;
this._depthBuffer;
this._blockerDepthNormal;
this.depthNormalShader;
this.resampleShader;
this._invProj = [0.0, 0.0];
this._fromViewtoGrid = [];
this._params = [];
this.depthNormalFramebuffer;
this.depthNormalRenderbuffer;
}
ndepthNormalBuffer.prototype = {
create: function(width, height, nearPlane, farPlane, blockerBufferWidth) {
this._width = width;
this._height = height;
this._nearFarPlane = [nearPlane, farPlane - nearPlane];
// create depth/normal teture
// RG = depth in view space & BA = normal.xy in view space
this._params = new TextureParams();
this._params.magFilter = gl.NEAREST;
this._params.minFilter = gl.NEAREST;
this._params.internalFormat = gl.RGBA;
this._params.sourceFormat = gl.RGBA;
this._depthNormal = new Texture("depthNormal", this._params, this._width, this._height, null);
textureList.push(this._depthNormal);
// create depth/normal buffer
this._depthBuffer = new DepthBuffer();
this._depthBuffer.params = new DepthBufferParams();
this._depthBuffer.create(this._depthBuffer.params, this._width, this._height);
// buffer used to downsample the depthNormal buffer
this._blockerBufferWidth = blockerBufferWidth;
var aspect = width / height;
this._blockerBufferHeight = Math.floor(this._blockerBufferWidth / aspect + 0.5);
// read the view space geometry of the scene
// then create blocking potentials in the geometry volume
this._blockerDepthNormal = new Texture("blockerDepthNormal", this._params, this._blockerBufferWidth, this._blockerBufferHeight, null);
textureList.push(this._blockerDepthNormal);
// create depth normal & resample shader
this.createShader();
// create framebuffer obj.
this.depthNormalFramebuffer = gl.createFramebuffer();
this.depthNormalRenderbuffer = gl.createRenderbuffer();
},
createShader: function() {
this.depthNormalShader = new ShaderResource();
this.depthNormalShader.initShaders("depthNormalShader", depthNormalVertexShader, depthNormalFragmentShader);
shaderList.push(this.depthNormalShader);
this.resampleShader = new ShaderResource();
this.resampleShader.initShaders("resampleShader", resampleVertexShader, resampleFragmentShader);
shaderList.push(this.resampleShader);
},
getBlockerBufferWidth: function() {
return this._blockerBufferWidth;
},
getBlockerBufferHeight: function() {
return this._blockerBufferHeight;
},
getNearFarPlane: function() {
return this._nearFarPlane;
},
getInvProj: function() {
return this._invProj;
},
getViewtoGridMatirx: function() {
return this._fromViewtoGrid;
},
begin: function(viewMatrix, projMatrix, light) {
// set shader
var shader = this.depthNormalShader;
shader.UseProgram();
shader.setMatrixUniforms("projection_matrix", projMatrix);
shader.setMatrixUniforms("view_matrix",viewMatrix);
shader.setUniform2f("near_far_plane", this._nearFarPlane);
this._invProj[0] = 1.0 / mat4.getXAxis(projMatrix)[0];
this._invProj[1] = 1.0 / mat4.getYAxis(projMatrix)[1];
var toWorld = mat4.create();
mat4.inverse(viewMatrix, toWorld);
var gridSpaceRotation = light.getGridSpaceRotation();
mat4.multiply(gridSpaceRotation, toWorld, this._fromViewtoGrid);
var positionBuffer = bufferList[0]._buffer;
shader.setAttributes(positionBuffer, "position", gl.FLOAT);
shader.setAttributes(vertexNormalBuffer, "normal", gl.FLOAT);
gl.viewport(0, 0, this._width, this._height);
gl.clearColor(1.0, 1.0, 1.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// using framebuffer to get shader result.
shader.bindTexToFramebuffer(this.depthNormalFramebuffer, this.depthNormalRenderbuffer, textureList[4]);
},
draw: function() {
// draw test_model object
// needs model position and normal buffer.
//gl.bindTexture(gl.TEXTURE_2D, textureList[4].texture);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, vertexIndexBuffer);
gl.drawElements(gl.TRIANGLES, vertexIndexBuffer.numItems, gl.UNSIGNED_SHORT, 0);
/*gl.copyTexImage2D(gl.TEXTURE_2D, 0, textureList[4].params.internalFormat, 0, 0, this._width, this._height, 0);
gl.bindTexture(gl.TEXTURE_2D, null);*/
// switch main framebuffer
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
},
resample: function() {
// dawnsapmle
// dawnsample depthNormal buffer, this resulting is used to create blocking potentials in view space.
gl.depthMask(false);
gl.disable(gl.DEPTH_TEST);
var shader = this.resampleShader;
shader.UseProgram();
/*shader.setUniformSampler("texture", textureList[4].texture);
shader.activeSampler(textureList[4].texture, 0);*/
shader.setUniformSampler("texture", 4);
shader.activeSampler(textureList[4].texture, 4);
var positionBuffer = this.getScreenPositionBuffer();
shader.setAttributes(positionBuffer, "position", gl.FLOAT);
gl.viewport(0, 0, this._blockerBufferWidth, this._blockerBufferHeight);
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// using framebuffer to get shader result.
shader.bindTexToFramebuffer(this.depthNormalFramebuffer, this.depthNormalRenderbuffer,textureList[5]);
// draw full screen resample texture
this.drawResampleTexture();
shader.unbindFramebuffer();
shader.unbindSampler();
},
getScreenPositionBuffer: function() {
var positionBuffer;
for(var i = 0; i < bufferList.length; i++) {
if(bufferList[i]._name === "fullScreen") {
positionBuffer = bufferList[i]._buffer;
}
}
if(!positionBuffer) {
var posArray = [];
posArray.push( 1.0, -1.0, 0.0);
posArray.push( 1.0, 1.0, 0.0);
posArray.push(-1.0, 1.0, 0.0);
posArray.push( 1.0, -1.0, 0.0);
posArray.push(-1.0, 1.0, 0.0);
posArray.push(-1.0, -1.0, 0.0);
var vbuffer = new nbuffer();
vbuffer.create("fullScreen", posArray, 3);
bufferList.push(vbuffer);
positionBuffer = vbuffer._buffer;
}
return positionBuffer;
},
drawResampleTexture: function(){
gl.drawArrays(gl.TRIANGLES, 0, bufferList[3]._buffer.numItems);
gl.bindTexture(gl.TEXTURE_2D, null);
/*gl.bindTexture(gl.TEXTURE_2D, textureList[5].texture);
gl.copyTexImage2D(gl.TEXTURE_2D, 0, textureList[5].params.internalFormat, 0, 0, this._blockerBufferWidth, this._blockerBufferHeight, 0);
gl.bindTexture(gl.TEXTURE_2D, null);*/
gl.depthMask(true);
gl.enable(gl.DEPTH_TEST);
}
}; |
var express = require('express');
var connect = require('connect');
var sendfile = require(__dirname + "/sendfile.js");
var app1 = express.createServer();
var app2 = express.createServer();
var app3 = express.createServer();
/**
* First application uses connect's static file server
*/
app1.use(express.static(__dirname + "/test"));
/**
* Second application uses connect's static file server + memcache
*/
app2.use(connect.staticCache());
app2.use(express.static(__dirname + "/test"));
/**
* Third application uses node-sendfile
*/
app3.use(sendfile(__dirname + "/test"));
app1.listen(process.argv[2] || 6001);
app2.listen(process.argv[3] || 6002);
app3.listen(process.argv[4] || 6003);
console.log("Static file servers are listening"); |
angular.module('Social')
.controller('UserController',function($scope, $rootScope, $state, $stateParams, $http){
$scope.user_id = $stateParams.id;
$scope.editable = false;
$scope.addingWork = false;
$scope.addingEducation = false;
$scope.isConnection = false;
$scope.requestSent = false;
$scope.requested = false;
$scope.notConnectable = ((($scope.editable || $scope.isConnection) || $scope.requestSent) || $scope.requested);
var isPresent = function(arr, id){
for (var i in arr) {
if (arr[i] && arr[i]._id == id) {
return i+1;
}
}
return 0;
};
var checkConnectivity = function(){
$scope.isConnection = Boolean(isPresent($rootScope.connections, $scope.user_id));
$scope.requestSent = Boolean(isPresent($rootScope.requestsSent, $scope.user_id));
$scope.requested = Boolean(isPresent($rootScope.requestsReceived, $scope.user_id));
$scope.notConnectable = ((($scope.editable || $scope.isConnection) || $scope.requestSent) || $scope.requested);
}
checkConnectivity();
if($rootScope.id == $scope.user_id)
$scope.editable = true;
$scope.sendRequest = function(){
$http.post('api/connect/send/'+$rootScope.id+'/'+$scope.user_id).success(function(data){
$rootScope.requestsSent = data;
checkConnectivity();
}).error(function(error){
console.error(error);
});
}
$scope.acceptRequest = function(){
$http.post('api/connect/accept/'+$rootScope.id+'/'+$scope.user_id).success(function(data){
$rootScope.requestsReceived = data.requestsReceived;
$rootScope.connections = data.connections;
checkConnectivity();
}).error(function(error){
console.error(error);
});
}
$scope.rejectRequest = function(){
$http.post('api/connect/reject/'+$rootScope.id+'/'+$scope.user_id).success(function(data){
$rootScope.requestsReceived = data.requestsReceived;
checkConnectivity();
}).error(function(error){
console.error(error);
});
}
$scope.cancelRequest = function(){
$http.post('api/connect/cancel/'+$rootScope.id+'/'+$scope.user_id).success(function(data){
$rootScope.requestsSent = data.requestsSent;
checkConnectivity();
}).error(function(error){
console.error(error);
});
}
$scope.removeConnection = function(){
$http.post('api/connect/remove/'+$rootScope.id+'/'+$scope.user_id).success(function(data){
$rootScope.connections = data;
checkConnectivity();
}).error(function(error){
console.error(error);
});
}
$scope.cancelAdding = function(){
$scope.addingEducation = false;
$scope.addingWork = false;
}
$scope.userDetails = {
firstName: "",
lastName:"",
currentOrganization: "",
currentDesignation: "",
email: ""
};
$http.get('api/user/'+$scope.user_id).success(function(data){
$scope.userDetails = data;
});
$scope.updatePersonal = function(){
$scope.userDetails = {
firstName: $scope.personal.firstName,
lastName: $scope.personal.lastName,
currentOrganization: $scope.personal.currentOrganization,
currentDesignation: $scope.personal.currentDesignation,
email: $scope.personal.email
};
};
$scope.works = [];
//get all work exp from server
$http.get('api/user/'+$scope.user_id+'/work').success(function(data){
$scope.works = data;
}).error(function(error){
console.log(error);
});
//helper function
$scope.enableAddingWork = function(){
$scope.addingWork = true;
}
//add new work experience
$scope.addWork = function(){
var work = $scope.newWork;
work.userId = $scope.user_id;
work.startDate = new Date(work.startDate);
work.endDate = new Date(work.endDate);
$http.post('api/user/'+$scope.user_id+'/work', work).success(function(data){
$scope.addingWork = false;
$scope.works.push(data);
}).error(function(error){
console.error(error);
});
};
//edit details of work experience
$scope.updateWork = function(editId){
console.log(editId);
// for(i in $scope.works){
// if($scope.works[i].workId == editedWorkId){
// $scope.works[i] = $scope.editedWork;
// break;
// }
// }
};
$scope.educations = [];
//get all education from server
$http.get('api/user/'+$scope.user_id+'/education').success(function(data){
$scope.educations = data;
}).error(function(error){
console.log(error);
});
//helper function
$scope.enableAddingEducation = function(){
$scope.addingEducation = true;
}
//add new education
$scope.addEducation = function(){
var education = $scope.newEducation;
education.userId = $scope.user_id;
education.startDate = new Date(education.startDate);
education.endDate = new Date(education.endDate);
$http.post('api/user/'+$scope.user_id+'/education', education).success(function(data){
$scope.addingEducation = false;
$scope.educations.push(data);
}).error(function(error){
console.error(error);
});
};
//edit details of education
$scope.updateEducation = function(editId){
console.log(editId);
};
}); |
const likeModel = require("../../models/likes"),
dateTime = require('node-datetime'),
socketio = require("../../socket")
exports.like = async (req,res,next) => {
let data = {}
data['type'] = req.body.type.replace("audios",'audio')
data['id'] = req.body.id
data['like_dislike'] = req.body.action
data['owner_id'] = req.user.user_id
data['subType'] = req.body.subType
const reply_comment_id = req.body.reply_comment_id
var dt = dateTime.create();
data.reply_comment_id = reply_comment_id
var formatted = dt.format('Y-m-d H:M:S');
data['creation_date'] = formatted
let likeType = ""
await likeModel.isLiked(data.id,data.type,req,res).then(result => {
if(result){
data['likeId'] = result.like_id
likeType = result.like_dislike
}
})
data['likeType'] = likeType
await likeModel.insert(data,req,res).then(result => {
})
let removeLike = false
let removeDislike = false
let insertLike = false
let insertDislike = false
if(likeType == data['like_dislike']){
//remove like / dislike
if(likeType == "like"){
//remove like
removeLike = true
}else{
//remove dislike
removeDislike = true
}
}else{
if(likeType == "like"){
//remove like and insert dislike
removeLike = true
insertDislike = true
}else if(likeType == "dislike"){
//remove dislike and insert like
removeDislike = true
insertLike = true
}else if(data['like_dislike'] == "like"){
//insert like
insertLike = true
}else{
//insert dislike
insertDislike = true
}
}
socketio.getIO().emit('likeDislike', {
"itemId": req.body.id,
"itemType":data['type'],
"ownerId":req.user.user_id,
"reply_comment_id":reply_comment_id,
"removeLike" : removeLike,
"removeDislike" : removeDislike,
"insertLike" : insertLike,
"insertDislike" : insertDislike
});
return res.send({})
} |
export { default as Loading } from './Loading';
export { default as Theme } from './Theme';
|
let peachTouched = false;
let theyCame = false;
let theyCameTime = -1;
let cumVolume = 1;
let cumPos = {x: 200, y: -5};
let accel = {x: 0, y: 0, z: 0};
let progress = 0;
let pts = [];
let flying = 0;
function preload() {
tfont = loadFont('assets/font/Mabry Pro.otf');
}
function setup() {
createCanvas(window.innerWidth, window.innerHeight);
background(255);
fill(0);
stroke(0);
frameRate(60);
textAlign(CENTER);
textSize(20);
pts = [
[{x: 140, y: 359}, {x: 188, y: 257}, {x: 267, y: 178}, {x: 358, y:197}],
[{x: 98, y: 300}, {x: 172, y: 214}, {x: 249, y: 192}, {x: 358, y:197}],
[{x: 73, y: 242}, {x: 173, y: 192}, {x: 274, y: 184}, {x: 358, y:200}],
[{x: 70, y: 134}, {x: 136, y: 177}, {x: 250, y: 188}, {x: 358, y:197}],
[{x: 121, y: 50}, {x: 177, y: 136}, {x: 256, y: 183}, {x: 358, y:197}]
];
cumPos = {x:width/2, y:-20};
}
function draw() {
background(255);
if(!peachTouched) {
textSize(60);
text("🍑",width/2,height/2);
} else if (peachTouched){
noFill();
let ax = abs(precise(accel.x,3));
let ay = abs(precise(accel.y,3));
let az = abs(precise(accel.z,3));
if((ax+ay) > 10) {
progress += 0.05;
}
let newpt = lerpPenis(progress);
translate(0, 202);
bezier(newpt[0].x, newpt[0].y,
newpt[1].x, newpt[1].y,
newpt[2].x, newpt[2].y,
newpt[3].x, newpt[3].y);
if(theyCame) {
if(millis()-theyCameTime < 2000) {
if((ax+ay) > 10) {
cumVolume+=0.5;
}
} else {
translate(0, -202);
cumPos.x += map(noise(frameCount*0.01), 0, 1, -0.5, 0.5);
cumPos.y += ay*0.2;
textSize(20);
for(let i = 0; i < floor(cumVolume); i++) {
let cumposx = map(noise(i*0.05,flying), 0, 1, 0, width-100);
text("💦", cumposx, cumPos.y-i*20);
}
}
}
}
flying-=0.001;
}
function touchEnded() {
if(!peachTouched) {
requestDeviceMotion();
peachTouched = true;
}
}
function lerpPenis(hardness) {
hardness = constrain(hardness, 0, pts.length+2);
if(hardness == pts.length+2 && !theyCame) {
theyCame = true;
theyCameTime = millis();
}
let lowidx = constrain(floor(hardness),0,pts.length-2);
let highidx = lowidx+1;
let lowpt = pts[lowidx];
let highpt = pts[highidx];
let newpt = [{x: 0, y: 0}, {x: 0, y: 0}, {x: 0, y: 0}, {x: 0, y: 0}];
let fract = hardness - lowidx;
for(let i = 0; i < 4; i++) {
let newptx = lerp(lowpt[i].x,highpt[i].x,fract);
let newpty = lerp(lowpt[i].y,highpt[i].y,fract);
newpt[i].x = newptx;
newpt[i].y = newpty;
}
return newpt;
}
// returns true if device motion is supported on device
function supportsDeviceMotion () {
return window.DeviceMotionEvent;
}
// request device motion from user
function requestDeviceMotion() {
// feature detect
if (typeof DeviceMotionEvent.requestPermission === 'function') {
DeviceMotionEvent.requestPermission()
.then(permissionState => {
if (permissionState === 'granted') {
window.addEventListener('devicemotion', deviceMotionHandler, false);
}
})
.catch(console.error);
} else {
// handle regular non iOS 13+ devices
}
}
function deviceMotionHandler(eventData) {
var info, xyz = "[X, Y, Z]";
// Grab the acceleration from the results
// var acceleration = eventData.acceleration;
// if(acceleration.hasOwnProperty('x')) {
// info = xyz.replace("X", acceleration.x);
// info = info.replace("Y", acceleration.y);
// info = info.replace("Z", acceleration.z);
// // document.getElementById("moAccel").innerHTML = info;
// }
// Grab the acceleration including gravity from the results
var acceleration_gravity = eventData.accelerationIncludingGravity;
if(acceleration_gravity) {
accel.x = acceleration_gravity.x;
accel.y = acceleration_gravity.y;
accel.z = acceleration_gravity.z;
}
// // Grab the refresh interval from the results
info = eventData.interval;
// document.getElementById("moInterval").innerHTML = info;
}
function precise(x,sigfig) {
return Number.parseFloat(x).toPrecision(sigfig);
}
|
const express = require('express');
const router = express.Router();
const stuffController = require("../controllers/stuff");
const Thing = require('../models/thing');
const auth = require("../middleware/auth");
const multer = require("../middleware/multer-config");
router.post('/', auth , multer, stuffController.creatThing);
router.get('/', auth , stuffController.getAllThings);
router.get('/:id', auth , stuffController.getOneThing);
router.put('/:id', auth , multer, stuffController.modifyThing);
router.delete('/:id', auth , stuffController.deleteThing);
module.exports = router; |
'use strict';
(function() {
angular
.module("BookApp")
.factory("GoogleBookService", GoogleBookService);
function GoogleBookService($q, $http) {
var service = {
getBookDetails: getBookDetails,
searchBookByTitle: searchBookByTitle,
searchBookByAuthor: searchBookByAuthor,
searchBookByGenre: searchBookByGenre
};
return service;
function getBookDetails(bookId) {
return $http.get("https://www.googleapis.com/books/v1/volumes/"+bookId);
}
function searchBookByTitle (bookname) {
return $http.get("https://www.googleapis.com/books/v1/volumes?q="+bookname+"&");
}
function searchBookByAuthor (author) {
return $http.get("https://www.googleapis.com/books/v1/volumes?q=inauthor:"+author);
}
function searchBookByGenre (genre) {
return $http.get("https://www.googleapis.com/books/v1/volumes?q=subject:"+genre);
}
}
})();
|
/*
* @lc app=leetcode id=923 lang=javascript
*
* [923] 3Sum With Multiplicity
*/
// @lc code=start
/**
* @param {number[]} A
* @param {number} target
* @return {number}
*/
var threeSumMulti = function (A, target) {
const map = Array(101).fill(0);
for (const i of A) {
map[i]++;
}
let count = 0;
for (let i = 0; i <= 100; i++) {
for (let j = i; j <= 100; j++) {
const k = target - i - j;
if (!(map[i] && map[j] && map[k] && k >= j)) {
continue;
}
if (i === j && j === k) {
count += map[i] * (map[i] - 1) * (map[i] - 2) / 6;
} else if (i === j && j < k) {
count += map[i] * (map[i] - 1) / 2 * map[k]
} else if (i < j && j === k) {
count += map[j] * (map[j] - 1) / 2 * map[i]
} else if (i < j && j < k) {
count += map[i] * map[j] * map[k]
}
}
}
return count % (10 ** 9 + 7);
};
// @lc code=end
threeSumMulti([1, 1, 2, 2, 3, 3, 4, 4, 5, 5], 8);
|
import React from "react";
import { useOverrides, Override, Section } from "@quarkly/components";
import { Button, Hr, Icon, Image, Input, Link, Text, List, Box } from "@quarkly/widgets";
import QuarklycommunityKitAnimation from "./QuarklycommunityKitAnimation";
import QuarklycommunityKitCarousel from "./QuarklycommunityKitCarousel";
import QuarklycommunityKitYoomoneyDonateForm from "./QuarklycommunityKitYoomoneyDonateForm";
import QuarklycommunityKitBackToTop from "./QuarklycommunityKitBackToTop";
import QuarklycommunityKitLoopText from "./QuarklycommunityKitLoopText";
import QuarklycommunityKitScrollIndicator from "./QuarklycommunityKitScrollIndicator";
import QuarklycommunityKitCounter from "./QuarklycommunityKitCounter";
import QuarklycommunityKitFbComment from "./QuarklycommunityKitFbComment";
import QuarklycommunityKitFbLike from "./QuarklycommunityKitFbLike";
import QuarklycommunityKitVkComments from "./QuarklycommunityKitVkComments";
import QuarklycommunityKitVkPage from "./QuarklycommunityKitVkPage";
import QuarklycommunityKitTable from "./QuarklycommunityKitTable";
import QuarklycommunityKitYouTube from "./QuarklycommunityKitYouTube";
import QuarklycommunityKitLiveChat from "./QuarklycommunityKitLiveChat";
import QuarklycommunityKitYandexMap from "./QuarklycommunityKitYandexMap";
import QuarklycommunityKitSvgShape from "./QuarklycommunityKitSvgShape";
import QuarklycommunityKitCollapse from "./QuarklycommunityKitCollapse";
import QuarklycommunityKitVideo from "./QuarklycommunityKitVideo";
import QuarklycommunityKitVimeo from "./QuarklycommunityKitVimeo";
import QuarklycommunityKitDisqusComment from "./QuarklycommunityKitDisqusComment";
import QuarklycommunityKitDisqus from "./QuarklycommunityKitDisqus";
import QuarklycommunityKitAudio from "./QuarklycommunityKitAudio";
import { MdFace } from "react-icons/md";
const defaultProps = {};
const overrides = {
"quarklycommunityKitAnimation": {
"kind": "QuarklycommunityKitAnimation",
"props": {}
},
"quarklycommunityKitCarousel": {
"kind": "QuarklycommunityKitCarousel",
"props": {}
},
"quarklycommunityKitYoomoneyDonateForm": {
"kind": "QuarklycommunityKitYoomoneyDonateForm",
"props": {}
},
"quarklycommunityKitBackToTop": {
"kind": "QuarklycommunityKitBackToTop",
"props": {}
},
"quarklycommunityKitLoopText": {
"kind": "QuarklycommunityKitLoopText",
"props": {}
},
"quarklycommunityKitScrollIndicator": {
"kind": "QuarklycommunityKitScrollIndicator",
"props": {}
},
"quarklycommunityKitCounter": {
"kind": "QuarklycommunityKitCounter",
"props": {}
},
"quarklycommunityKitFbComment": {
"kind": "QuarklycommunityKitFbComment",
"props": {}
},
"quarklycommunityKitFbLike": {
"kind": "QuarklycommunityKitFbLike",
"props": {}
},
"quarklycommunityKitVkComments": {
"kind": "QuarklycommunityKitVkComments",
"props": {}
},
"quarklycommunityKitVkPage": {
"kind": "QuarklycommunityKitVkPage",
"props": {}
},
"quarklycommunityKitTable": {
"kind": "QuarklycommunityKitTable",
"props": {}
},
"quarklycommunityKitVkPage1": {
"kind": "QuarklycommunityKitVkPage",
"props": {}
},
"quarklycommunityKitTable1": {
"kind": "QuarklycommunityKitTable",
"props": {}
},
"quarklycommunityKitYouTube": {
"kind": "QuarklycommunityKitYouTube",
"props": {}
},
"quarklycommunityKitLiveChat": {
"kind": "QuarklycommunityKitLiveChat",
"props": {}
},
"quarklycommunityKitYandexMap": {
"kind": "QuarklycommunityKitYandexMap",
"props": {}
},
"quarklycommunityKitSvgShape": {
"kind": "QuarklycommunityKitSvgShape",
"props": {}
},
"quarklycommunityKitCollapse": {
"kind": "QuarklycommunityKitCollapse",
"props": {}
},
"button": {
"kind": "Button",
"props": {
"children": "Button"
}
},
"quarklycommunityKitVideo": {
"kind": "QuarklycommunityKitVideo",
"props": {}
},
"quarklycommunityKitVimeo": {
"kind": "QuarklycommunityKitVimeo",
"props": {}
},
"quarklycommunityKitDisqusComment": {
"kind": "QuarklycommunityKitDisqusComment",
"props": {}
},
"quarklycommunityKitDisqus": {
"kind": "QuarklycommunityKitDisqus",
"props": {}
},
"quarklycommunityKitAudio": {
"kind": "QuarklycommunityKitAudio",
"props": {}
},
"button1": {
"kind": "Button",
"props": {
"children": "Button"
}
},
"hr": {
"kind": "Hr",
"props": {}
},
"icon": {
"kind": "Icon",
"props": {
"category": "md",
"icon": MdFace
}
},
"image": {
"kind": "Image",
"props": {
"width": "64px",
"height": "64px"
}
},
"input": {
"kind": "Input",
"props": {}
},
"link": {
"kind": "Link",
"props": {
"href": "#",
"children": "Some text"
}
},
"list": {
"kind": "List",
"props": {}
},
"text": {
"kind": "Text",
"props": {
"children": "First item"
}
},
"text1": {
"kind": "Text",
"props": {
"children": "Some text"
}
},
"section": {
"kind": "Section",
"props": {
"padding": "100px 0",
"sm-padding": "40px 0"
}
},
"sectionOverride": {
"kind": "Override",
"props": {
"slot": "SectionContent",
"align-items": "center"
}
},
"text2": {
"kind": "Text",
"props": {
"as": "h2",
"font": "--headline1",
"md-font": "--headline2",
"margin": "20px 0 0 0",
"children": "About Us"
}
},
"text3": {
"kind": "Text",
"props": {
"as": "p",
"font": "--lead",
"margin": "20px 0 0 0",
"children": "Hi! I'm a paragraph. Click here to add your own text and edit me. It’s a piece of cake. I’m a great space for you to tell a story and let your site visitors know more about you. Talk about your business and what products and services you offer. Share how you came up with the idea for your company and what makes you different from your competitors. Make your business stand out and show your visitors who you are."
}
},
"button2": {
"kind": "Button",
"props": {
"font": "--lead",
"margin": "20px",
"children": "Button"
}
},
"box": {
"kind": "Box",
"props": {}
},
"button3": {
"kind": "Button",
"props": {
"children": "Button"
}
},
"hr1": {
"kind": "Hr",
"props": {}
},
"icon1": {
"kind": "Icon",
"props": {
"category": "md",
"icon": MdFace
}
},
"image1": {
"kind": "Image",
"props": {
"width": "64px",
"height": "64px"
}
},
"input1": {
"kind": "Input",
"props": {}
},
"link1": {
"kind": "Link",
"props": {
"href": "#",
"children": "Some text"
}
},
"list1": {
"kind": "List",
"props": {}
},
"text4": {
"kind": "Text",
"props": {
"children": "First item"
}
},
"text5": {
"kind": "Text",
"props": {
"children": "Some text"
}
},
"box1": {
"kind": "Box",
"props": {}
}
};
const Newcomponenteef = props => {
const {
override,
children,
rest
} = useOverrides(props, overrides, defaultProps);
return <Box {...rest}>
<QuarklycommunityKitAnimation {...override("quarklycommunityKitAnimation")} />
<QuarklycommunityKitCarousel {...override("quarklycommunityKitCarousel")} />
<QuarklycommunityKitYoomoneyDonateForm {...override("quarklycommunityKitYoomoneyDonateForm")} />
<QuarklycommunityKitBackToTop {...override("quarklycommunityKitBackToTop")} />
<QuarklycommunityKitLoopText {...override("quarklycommunityKitLoopText")} />
<QuarklycommunityKitScrollIndicator {...override("quarklycommunityKitScrollIndicator")} />
<QuarklycommunityKitCounter {...override("quarklycommunityKitCounter")} />
<QuarklycommunityKitFbComment {...override("quarklycommunityKitFbComment")} />
<QuarklycommunityKitFbLike {...override("quarklycommunityKitFbLike")} />
<QuarklycommunityKitVkComments {...override("quarklycommunityKitVkComments")} />
<QuarklycommunityKitVkPage {...override("quarklycommunityKitVkPage")} />
<QuarklycommunityKitTable {...override("quarklycommunityKitTable")} />
<QuarklycommunityKitVkPage {...override("quarklycommunityKitVkPage1")} />
<QuarklycommunityKitTable {...override("quarklycommunityKitTable1")} />
<QuarklycommunityKitYouTube {...override("quarklycommunityKitYouTube")} />
<QuarklycommunityKitLiveChat {...override("quarklycommunityKitLiveChat")} />
<QuarklycommunityKitYandexMap {...override("quarklycommunityKitYandexMap")} />
<QuarklycommunityKitSvgShape {...override("quarklycommunityKitSvgShape")} />
<QuarklycommunityKitCollapse {...override("quarklycommunityKitCollapse")}>
<Button {...override("button")} />
</QuarklycommunityKitCollapse>
<QuarklycommunityKitVideo {...override("quarklycommunityKitVideo")} />
<QuarklycommunityKitVimeo {...override("quarklycommunityKitVimeo")} />
<QuarklycommunityKitDisqusComment {...override("quarklycommunityKitDisqusComment")} />
<QuarklycommunityKitDisqus {...override("quarklycommunityKitDisqus")} />
<QuarklycommunityKitAudio {...override("quarklycommunityKitAudio")} />
<Button {...override("button1")} />
<Hr {...override("hr")} />
<Icon {...override("icon")} />
<Image {...override("image")} />
<Input {...override("input")} />
<Link {...override("link")} />
<List {...override("list")}>
<Text {...override("text")} />
</List>
<Text {...override("text1")} />
<Section {...override("section")}>
<Override {...override("sectionOverride")} />
<Text {...override("text2")} />
<Text {...override("text3")} />
<Button {...override("button2")} />
</Section>
<Box {...override("box")} />
<Button {...override("button3")} />
<Hr {...override("hr1")} />
<Icon {...override("icon1")} />
<Image {...override("image1")} />
<Input {...override("input1")} />
<Link {...override("link1")} />
<List {...override("list1")}>
<Text {...override("text4")} />
</List>
<Text {...override("text5")} />
<Box {...override("box1")} />
{children}
</Box>;
};
Object.assign(Newcomponenteef, { ...Box,
defaultProps,
overrides
});
export default Newcomponenteef; |
function carregar_video(id_da_palestra, id_do_div_onde_renderizar) {
$(document).ready(function() {
$.post(
'/retornar_video_embed',
{'id_da_palestra': id_da_palestra},
function(resposta) {
$('#'+id_do_div_onde_renderizar).html(resposta[0].embed);
}
);
});
}
function carregar_slide(id_da_palestra, id_do_div_onde_renderizar, id_do_div_da_url) {
$(document).ready(function() {
$.post(
'/retornar_slide_embed_e_url',
{'id_da_palestra': id_da_palestra},
function(resposta) {
$('#'+id_do_div_onde_renderizar).html(resposta[0].embed);
$('#'+id_do_div_da_url).html(
'<a href="'+resposta[0].url+'">Link da apresentaçao no Slideshare</a>');
}
);
});
} |
// @flow
import * as React from 'react';
import { Translation } from '@kiwicom/mobile-localization';
import { TextIcon } from '@kiwicom/mobile-shared';
import { type RouteNamesType, MenuItem } from '@kiwicom/mobile-navigation';
type Props = {|
+title: React.Element<typeof Translation>,
+navigate: (routeName: RouteNamesType) => void,
+routeName: RouteNamesType,
+icon: React.Element<typeof TextIcon>,
|};
export default class FlightServiceMenuItem extends React.Component<Props> {
onPress = () => {
this.props.navigate(this.props.routeName);
};
render() {
return (
<MenuItem
title={this.props.title}
isActive={false}
onPress={this.onPress}
icon={this.props.icon}
/>
);
}
}
|
// Dependencies
var path = require("path");
var mysql = require("mysql");
var connection;
if (process.env.JAWSDB_URL) {
connection = mysql.createConnection(process.env.JAWSDB_URL);
}
else {
var connection = mysql.createConnection({
host: "localhost",
port: 8889,
user: "root",
password: "root",
database: "friends_db"
});
}
connection.connect(function(err) {
if (err) {
console.error(`Error connecting: ${err.stack}`);
//once successfully connected, you may want to query your database for the info you'll need later!
}
console.log(`Connected as ID: ${connection.threadId}`);
});
module.exports = function(app) {
app.get("/api/friends", function(req, res) {
console.log(req);
console.log(res);
});
app.post("/api/friends", function(req, res) {
res.json(req.body);
});
}; |
const express=require('express')
const bent=require('bent')
const getJSON = bent('json')
const hbs=require('hbs')
const path=require('path')
const port=process.env.PORT
const partialDirectoryPath=path.join(__dirname,'../views/partials')
const publicDirectoryPath=path.join(__dirname,'../public')
const app=express()
app.set('view engine','hbs')
app.use(express.static(publicDirectoryPath))
hbs.registerPartials(partialDirectoryPath)
var data
const name='Harjot Singh'
const run=async()=>{
data = await getJSON('https://api.apify.com/v2/key-value-stores/tVaYRsPHLjNdNBu7S/records/LATEST?disableRedirect=true')
data.forEach((country)=>{
total=(country.infected+country.deceased+country.recovered).toString()
country.total=total.replace('NA','')
})
}
var conversion=async(updateDate)=>{
var date1 = new Date(updateDate);
var today=new Date()
var diffMs = (today-date1);
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000);
return diffMins
}
app.get('/',async (req,res)=>{
await run();
res.render('index',{
data,
name,
title:'COVID Statistics'
})
})
const moredetails=async(country)=>{
const body=await data.filter((body)=>{
if(body.country===country)
return body
})
return body[0].moreData
}
app.get('/moreData/:country',async(req,res)=>{
try{
if(!data)
await run();
const link=await moredetails(req.params.country)
const moreData=await getJSON(link)
var {activeCases,recovered,deaths,totalCases,sourceUrl,lastUpdatedAtApify,infected,deceased,infectedByRegion,regionData}=moreData
const lastUpdated=await conversion(lastUpdatedAtApify)
if(!infectedByRegion)
infectedByRegion=""
if(!totalCases)
{
if(recovered==='N/A'||deceased==='N/A'||infected==='N/A')
total='Can\'t Compute'
else
total=parseInt(recovered)+parseInt(deceased)+parseInt(infected)
}
else
total=""
res.render('details',{
title:`COVID Statistics Of ${req.params.country}`,
activeCases,recovered,deaths,totalCases,sourceUrl,lastUpdated,infected,deceased,
regionData,
name,
total,
infectedByRegion
})
}catch(e){
console.log(e)
res.send('Something Went Wrong Please Refresh The Homepage')
}
})
app.get('/about',(req,res)=>{
res.redirect('https://github.com/harjotscs')
})
app.get('/help',(req,res)=>{
res.redirect('https://github.com/harjotscs')
})
app.listen(port,()=>{
console.log(`Server Up And Running On Port ${port}`)
}) |
import i18n from '@/i18n';
import SupportChat from './supportChat';
import Klickart from './index';
jest.mock('./index', () => (
jest.fn().mockImplementation(() => { })
));
jest.mock('@/i18n', () => (
jest.fn().mockImplementation(() => { })
));
i18n.locale = 'pt-BR';
const supportChatPath = `${i18n.locale}/support_chats`;
describe('@/services/api/klickart/supportChat', () => {
let supportChatRequest;
let expectedConfig = {};
describe('When creating a new support chat request', () => {
beforeAll(() => {
expectedConfig.path = supportChatPath;
supportChatRequest = new SupportChat();
});
it('should define a new support chat request', () => {
expect(supportChatRequest).toBeInstanceOf(Klickart);
});
it('should have called Klickart with the expected configurations', () => {
expect(Klickart).toHaveBeenCalledWith(expectedConfig);
});
});
describe('When creating a new support chat request with a configuration', () => {
beforeAll(() => {
const config = {
param: true,
};
expectedConfig = {
path: supportChatPath,
param: true,
};
supportChatRequest = new SupportChat(config);
});
it('should define a new support chat request', () => {
expect(supportChatRequest).toBeDefined();
});
it('should have called Klickart with the expected configurations', () => {
expect(Klickart).toHaveBeenCalledWith(expectedConfig);
});
});
});
|
import React, { PureComponent } from 'react'
import MapContainer from '../containers/MapContainer'
import { ShareMap } from './ShareMap'
export class App extends PureComponent {
componentWillMount () {
this.props.getPins(this.props.match.params.id)
}
render () {
let showMap
if (this.props.user && this.props.match.params.id === this.props.user.uid) {
showMap = <MapContainer match={this.props.match} fetchedPins={this.props.fetchedPins} />
} else {
showMap = <ShareMap match={this.props.match} fetchedPins={this.props.fetchedPins} />
}
return (
<div>
{showMap}
</div>
)
}
}
|
import React, { useState, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Link } from 'react-router-dom';
import Avatar from 'react-avatar';
import { recentActivity } from '../../containers/dashboard/recent-activity-action';
import { paymentDetails } from './payment-details-action';
import { toTimeAgoFormat } from '../../utils/formattor';
import InfoIconBlue from '../../../images/icons/infoIconBlue.svg';
import ArrowIconDownGray from '../../../images/icons/arrowIcondownGray.png';
import ArrowIconRightBlue from '../../../images/icons/arrowIconRightBlue.svg';
import PaymentIconBlue from '../../../images/icons/paymentIconBlue.svg';
const SideBar = ({ show }) => {
const [showUserActive, setShowUserActive] = useState(false);
const [paymentActive, setPaymentActive] = useState(false);
const dispatch = useDispatch();
useEffect(() => {
const pageNumberWithSortingParams = {
pageNumber: 1,
pageSize: 10,
'sorting[0][direction]': 'DESC',
'sorting[0][key]': 'updatedAt',
};
recentActivity(pageNumberWithSortingParams, dispatch);
paymentDetails(pageNumberWithSortingParams, dispatch);
}, []);
const { recentActivityDetails } = useSelector(
(state) => state.recentActivity
);
const { paymentDetailsList } = useSelector((state) => state.paymentDetails);
const handleUserActivity = () => {
setShowUserActive(!showUserActive);
setPaymentActive(false);
};
const paymentUserActivity = () => {
setPaymentActive(!paymentActive);
setShowUserActive(false);
};
return (
<div className="sidebar">
<div
className={`sidebar-header ${
showUserActive ? 'sidebar-header-active' : ''
}`}
>
<div className="sidebar-header-desc">
<label>
<img src={InfoIconBlue} />
</label>
{show ? <p onClick={handleUserActivity}>Users activity</p> : null}
<span></span>
</div>
{show ? (
<label onClick={handleUserActivity}>
{showUserActive ? (
<img src={ArrowIconDownGray} />
) : (
<img src={ArrowIconRightBlue} />
)}
</label>
) : null}
</div>
{showUserActive && show ? (
<div className="sidebar-menu-sec">
<ul className="sidebar-menu">
{recentActivityDetails.map((user, key) => (
<li key={key}>
<div className="sidebar-user-icon">
<Avatar size="40" round={true} name={user.name} />
</div>
<div className="sidebar-user-details">
<Link to={`/users/${user.publicId}`}>
{user.mobileNumber}
</Link>
<p>{user.remark}</p>
<label>{toTimeAgoFormat(user.createdAt)}</label>
</div>
</li>
))}
<li className="viewall">
<p>View All</p>
</li>
</ul>
</div>
) : null}
<div
className={`sidebar-header ${
paymentActive ? 'sidebar-header-active' : ''
}`}
>
<div className="sidebar-header-desc">
<label>
<img src={PaymentIconBlue} />
</label>
{show ? <p onClick={paymentUserActivity}> Payment details</p> : null}
</div>
{show ? (
<label onClick={paymentUserActivity}>
{paymentActive ? (
<img src={ArrowIconDownGray} />
) : (
<img src={ArrowIconRightBlue} />
)}
</label>
) : null}
</div>
{paymentActive && show ? (
<div className="sidebar-menu-sec">
<ul className="sidebar-menu">
{paymentDetailsList &&
paymentDetailsList.map((user, key) => (
<li key={key}>
<div className="sidebar-user-icon">
<Avatar size="40" round={true} name={user.name} />
</div>
<div className="sidebar-user-details">
<Link to={`/users/${user.publicId}`}>
{user.mobileNumber}
</Link>
<p>{`${user.amount} has been ${user.status}`}</p>
<label>{toTimeAgoFormat(user.createdAt)}</label>
</div>
</li>
))}
<li className="viewall">
<p>View All</p>
</li>
</ul>
</div>
) : null}
</div>
);
};
export default SideBar;
|
var FPS = {};
FPS.fps = 1;
FPS.start = Number(new Date());
FPS.count = 0;
FPS.color = "#000000";
FPS.frameComplete = function(){
var now = Number(new Date());
if(now - FPS.start>1000){
FPS.fps = Math.round(FPS.count/(now-FPS.start)*100000)/100;
FPS.start = now;
FPS.count = 0;
}
FPS.count++;
Origami.ctx.fillStyle = FPS.color;
Origami.ctx.textAlign = "left";
Origami.ctx.textBaseline = "top";
Origami.ctx.font = "12px arial, sans-serif";
Origami.ctx.fillText(FPS.fps+"fps", 0, 0);
}; |
var fetchModule = require("tns-core-modules/fetch");
var model = {
userName: "",
userEmail: "",
userQuestion: ""
};
function pageLoaded(args) {
var page = args.object;
page.bindingContext = model;
}
function onSubmit(args) {
var baseURL = "https://script.google.com/macros/s/abcdef12345/exec";
var theURL = baseURL + "?Name=" + model.userName + "&Email=" + model.userEmail + "&Question=" + model.userQuestion;
fetch(theURL, {
headers: getCommonHeaders()
})
//console.log('url', theURL);
//console.log(model.userName);
//console.log(model.userEmail);
//console.log(model.userQuestion);
const button = args.object;
const page = button.page;
page.frame.navigate("pages/thank-you/thank-you");
}
function getCommonHeaders() {
return {
"Content-Type": "application/json"
}
}
exports.pageLoaded = pageLoaded;
exports.onSubmit = onSubmit; |
// Heroku defines the environment variable PORT, and requires the binding address to be 0.0.0.0
var host = process.env.PORT ? '0.0.0.0' : '127.0.0.1';
var port = process.env.PORT || 8080;
(function() {
var cors_api_host = 'cors-anywhere.herokuapp.com';
var cors_api_url = 'https://' + cors_api_host + '/';
var slice = [].slice;
var origin = 'http://' + host;
var open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
var args = slice.call(arguments);
var targetOrigin = /^https?:\/\/([^\/]+)/i.exec(args[1]);
if (targetOrigin && targetOrigin[0].toLowerCase() !== origin &&
targetOrigin[1] !== cors_api_host) {
args[1] = cors_api_url + args[1];
}
return open.apply(this, args);
};
})(); |
import config from '../config'
import TokenService from '../Services/token-service'
const BabyApiService = {
getBabies() {
return fetch(`${config.API_ENDPOINT}/babies`, {
headers: {
'Content-Type': 'application/json',
'authorization': `bearer ${TokenService.getAuthToken()}`
},
})
.then(res =>
(!res.ok)
? res.json().then(e => Promise.reject(e))
: res.json()
)
},
getBaby(id) {
return fetch(`${config.API_ENDPOINT}/babies/${id}`, {
headers: {
'authorization': `bearer ${TokenService.getAuthToken()}`,
},
})
.then(res =>
(!res.ok)
? res.json().then(e => Promise.reject(e))
: res.json()
)
},
getByParentId() {
return fetch(`${config.API_ENDPOINT}/babies/parent/id`, {
headers: {
'authorization': `bearer ${TokenService.getAuthToken()}`,
},
})
.then(res =>
(!res.ok)
? res.json().then(e => Promise.reject(e))
: res.json()
)
},
async postBaby(baby) {
const Response = await fetch(`${config.API_ENDPOINT}/babies`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'authorization': `bearer ${TokenService.getAuthToken()}`,
},
body: JSON.stringify(baby)
})
const json = await Response.json();
return (Response, json)
},
updateBaby(baby) {
return fetch(`${config.API_ENDPOINT}/babies/${baby.id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
'authorization': `bearer ${TokenService.getAuthToken()}`
},
body: JSON.stringify(baby)
})
},
deletBaby(id) {
return fetch(`${config.API_ENDPOINT}/babies/${id}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'authorization': `bearer ${TokenService.getAuthToken()}`
}
})
},
postImageFile(file) {
const options = {
method: 'POST',
headers: {
'Content-Type': '.png, .jpg, .jpeg .gif',
'authorization': `bearer ${TokenService.getAuthToken()}`
},
body: file
}
// Remove 'Content-Type' header to allow browser to add
// along with the correct 'boundary'
delete options.headers['Content-Type'];
return fetch(`${config.API_ENDPOINT}/upload`, options)
}
}
export default BabyApiService |
function successSignUp(result, status) {
console.log('SignUp post success; status: '+ status +'; result: '+ result);
$("#id_alert-signup").html("");
window.location.replace(result.redirect);
}
function errorSignUp(error, status, responseText) {
console.log('SignUp post error; status: '+ status +'; error: '+ error);
$("#id_alert-signup").html("<div class='alert alert-dismissible alert-danger'>" +
"<button type='button' class='close' data-dismiss='alert'>×</button>" +
responseText +
"</div>");
}
$(document).ready(function() {
$( "#id_form-signup" ).submit(function( event ) {
event.preventDefault();
var $form = $( this ),
firstName = $form.find("input[id='inputFirstName']").val(),
lastName = $form.find("input[id='inputLastName']").val(),
email = $form.find("input[id='inputEmail']").val(),
password = $form.find("input[id='inputPassword']").val();
signup(firstName, lastName, email, password, successSignUp, errorSignUp);
});
});
|
import { ENTER_ACCOUNT_INFO, CHANGE_SEARCHED_ACCOUNT } from './constants'
const INITIAL_STATE = {
account: {
acct: "0x3c5ca637008be36e9697F09fdd62367F16a0f573",
privateKey: ''
},
searchedAcct: "0x6C095A05764A23156eFD9D603eaDa144a9B1AF33"
}
export const accountReducer = (state=INITIAL_STATE, action) => {
switch(action.type) {
case ENTER_ACCOUNT_INFO:
let account = action.payload.acct.length < 40 ? INITIAL_STATE.account : action.payload
return {
...state,
searchedAcct: account.acct,
account
}
case CHANGE_SEARCHED_ACCOUNT:
return {
...state,
searchedAcct: action.payload
}
default:
return state
}
} |
(function(){
'use strict';
angular
.module('everycent.account-balances')
.factory('AccountBalancesService', AccountBalancesService);
AccountBalancesService.$inject = ['$http', 'Restangular'];
function AccountBalancesService($http, Restangular){
var service = {
getAccountBalances: getAccountBalances,
netWorth: netWorth,
totalAssets: totalAssets,
totalLiabilities: totalLiabilities,
netCurrentCash: netCurrentCash,
netCashAssets: netCashAssets,
netNonCashAssets: netNonCashAssets,
};
var baseAll = Restangular.all('account_balances');
return service;
function getAccountBalances(params){
return baseAll.getList(params);
}
function netWorth(bankAccounts){
var net = 0;
bankAccounts.forEach(function(bankAccount){
net += bankAccount.current_balance;
});
return net;
}
function totalAssets(bankAccounts){
return bankAccounts
.filter(a => a.account_category == 'asset')
.reduce((acc, curr) => acc + curr.current_balance, 0);
}
function totalLiabilities(bankAccounts){
return bankAccounts
.filter(a => a.account_category == 'liability')
.reduce((acc, curr) => acc + curr.current_balance, 0);
}
function netCurrentCash(bankAccounts){
return bankAccounts
.filter(a => a.account_category == 'current'
|| (a.account_category=='liability' && a.is_cash))
.reduce((acc, curr) => acc + curr.current_balance, 0);
}
function netCashAssets(bankAccounts){
return bankAccounts
.filter(a => a.account_category == 'asset' && a.is_cash)
.reduce((acc, curr) => acc + curr.current_balance, 0);
}
function netNonCashAssets(bankAccounts){
return bankAccounts
.filter(a => (a.account_category == 'asset' || a.account_category == 'liability') && !a.is_cash)
.reduce((acc, curr) => acc + curr.current_balance, 0);
}
}
})();
|
var express = require('express')
var app = express()
app.get('/:palindrome', function(req,res){
var str = req.params.palindrome
var result = checkPalindrom(str)
if(result){
return res.sendStatus(200)
}
return res.sendStatus(400)
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
function checkPalindrom(str) {
if(str.length > 0)
return str == str.split('').reverse().join('');
return false;
}
module.export = app
|
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import { baseApiUrl } from '../../config/config';
export const dayApi = createApi({
reducerPath: 'day',
baseQuery: fetchBaseQuery({
baseUrl: baseApiUrl,
}),
endpoints(buldier) {
return {
fetchToday: buldier.query({
providesTags: ['TODAY'],
query: () => {
return {
url: '/',
method: 'GET',
};
},
}),
fetchDayByDate: buldier.mutation({
query: (date) => {
return {
url: '/day',
method: 'POST',
body: { date },
};
},
}),
};
},
});
export const { useFetchTodayQuery, useFetchDayByDateMutation, useUpdateTodayMutation } = dayApi;
|
$(function(){
$('.addtocartform button').on('click', function(e){
e.preventDefault();
var qt = parseInt($('.addtocart_qt').val());
var vu = parseFloat($('.valor_unit').val());
var action = $(this).attr('data-action');
if(action == 'decrease') {
if(qt-1 >= 1) {
qt = qt - 1;
}
}
else if(action == 'increase') {
qt = qt + 1;
}
var vt = vu*qt;
var texto = vt.toLocaleString("pt-BR", { style: "currency" , currency:"BRL"});
$('.addtocart_qt').val(qt);
$('.valor').text(texto);
});
$('.money').mask('#.##0,00', {reverse: true});
var SPMaskBehavior = function (val) {
return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009';
},
spOptions = {
onKeyPress: function(val, e, field, options) {
field.mask(SPMaskBehavior.apply({}, arguments), options);
}
};
$('.phone').mask(SPMaskBehavior, spOptions);
});
|
var structCryptModule =
[
[ "specs", "structCryptModule.html#aca684e61f08f9bff65a8c64dd4c57f9a", null ]
]; |
import React from 'react';
import PropTypes from 'prop-types';
import { validableField } from 'react-validon';
// import { validableField } from '../../../../../../dist';
import css from './Input.css';
@validableField()
class Input extends React.Component {
onChange = (event) => {
const { onChange, validation, name } = this.props;
onChange && onChange(event);
validation.validate(name, event.target.value);
};
render() {
const { subscribe, unsubscribe, validation, onChange, ...rest } = this.props;
return (
<input
{...rest}
onChange={this.onChange}
className={validation.error ? css[validation.type.toLowerCase()] : undefined}
title={validation.error}
/>
);
}
}
Input.propTypes = {
prop1: PropTypes.string.isRequired,
};
export default Input;
|
import { makeStyles } from "@material-ui/core/styles";
import Card from "@material-ui/core/Card";
import CardContent from "@material-ui/core/CardContent";
import Typography from "@material-ui/core/Typography";
import Grid from "@material-ui/core/Grid";
import Button from "@mui/material/Button";
import { TodoState } from "./context/TodoContext";
const useStyles = makeStyles({
root: {
flexGrow: 1,
},
bullet: {
display: "inline-block",
margin: "0 2px",
transform: "scale(0.8)",
},
title: {
fontSize: 16,
fontWeight: "bold",
},
content: {
fontSize: 14,
},
pos: {
marginBottom: 12,
},
});
const Todos = () => {
const classes = useStyles();
const { changeStatusFun, filteredTodos, currentPage, todosPerPage, search } =
TodoState();
const indexOfLastTodo = currentPage * todosPerPage;
const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
const currentTodos = filteredTodos.slice(indexOfFirstTodo, indexOfLastTodo);
return (
<div>
<Grid container spacing={10}>
{currentTodos &&
currentTodos
.filter(
(obj) =>
obj.title.toLowerCase().includes(search.toLowerCase()) ||
obj.content.toLowerCase().includes(search.toLowerCase())
)
.map((todo) => (
<Grid key={todo.id} item xs={10}>
<Card className={classes.root}>
<CardContent>
<Typography
className={classes.title}
color="textPrimary"
gutterBottom
>
{todo.title}
</Typography>
<Typography
className={classes.content}
color="textPrimary"
gutterBottom
>
{todo.content}
</Typography>
<Typography
variant="body2"
color="textSecondary"
component="p"
>
{new Date(todo.creationTime).toLocaleDateString()}
</Typography>
<Typography
variant="body2"
color="textSecondary"
component="p"
>
{todo.status}
</Typography>
{todo.status === "Active" && (
<Button
variant="contained"
onClick={() => changeStatusFun(todo.id)}
>
Task completed
</Button>
)}
</CardContent>
</Card>
</Grid>
))}
</Grid>
</div>
);
};
export default Todos;
|
import React from 'react'
import personIcon from '../../assets/image/icon-person.svg'
const InputPerson = ({ personValue, personChange }) => {
return(
<span className="relative">
<img src={personIcon} className="absolute top-0 left-4" alt="personIcon" />
<input
type="number"
className="bg-[color:var(--lgc2)] text-[24px] placeholder-gray-300 focus:outline-none text-right text-[color:var(--vdc)] font-bold px-4 py-1"
value={personValue}
onChange={personChange}
placeholder="0"
/>
</span>
)
}
export default InputPerson; |
import { ADS_FETCHED, AD_CREATED } from "../actions/ads";
import { AD_UPDATE_SUCCESS } from "../actions/ad";
export default function reducer(state = null, action = {}) {
switch (action.type) {
case ADS_FETCHED:
return action.ads;
case AD_UPDATE_SUCCESS:
return state.map(ad => (ad.id === action.id ? action.data : ad));
case AD_CREATED:
return [...state, action.ad];
default:
return state;
}
}
|
define(function(require, exports, module) {
exports.exec = {
cn: [{
context: "中文字幕1 测试",
start: 0.000,
end: 0.500
}, {
context: '<a href="#" target="_blank">广告测试</a> 测试字幕内容,也可以是广告.',
start: 0.600,
end: 1.000
}, {
context: "中文字幕2 测试",
start: 1.500,
end: 2.000
}],
en: [{
context: "test1 test",
start: 0.000,
end: 0.500
}, {
context: '<a href="#" target="_blank">AD test</a> adadfasdfas,asdfasdf.',
start: 0.600,
end: 1.000
}, {
context: "test2 test",
start: 1.500,
end: 2.000
}],
};
}); |
import {createSlice} from "@reduxjs/toolkit";
import axios from "axios";
const initialState = {
items: [],
isLoading: false
}
export const productsSlicePath = 'products';
export const productsSlice = createSlice({
name: productsSlicePath,
initialState,
reducers: {
setProducts(state, action) {
state.items = action.payload;
},
setIsLoading(state, action) {
state.isLoading = action.payload;
}
}
})
const setProducts = productsSlice.actions.setProducts;
const setIsLoading = productsSlice.actions.setIsLoading;
export const fetchProducts = () => {
return (dispatch) => {
const url = 'https://react-coffee-629c8-default-rtdb.firebaseio.com/products.json';
dispatch(setIsLoading(true))
// data resolving emulation
setTimeout(() => {
axios.get(url)
.then( response => Object.values(response.data))
.then(products => { dispatch(setProducts(products))})
.then(
dispatch(setIsLoading(false))
);
}, 1000)
}
}
|
import { applyChanges } from './array_utils';
export default applyChanges; |
'use strict';
angular.module('AdCshdwr')
.factory('cdrPaymntManagerResource',['$http', function($http){
var service = {};
var urlBase = '/adinvtry.server/rest/inventory';
service.update = function(invtryHolder){
return $http.put(urlBase+'/update',invtryHolder);
};
service.close = function(invtryHolder){
return $http.put(urlBase+'/close',invtryHolder);
};
return service;
}])
.factory('cdrUtils',['sessionManager','$translate','genericResource','$q',function(sessionManager,$translate,genericResource,$q){
var service = {};
service.urlBase='/adinvtry.server/rest/cdpaymnts';
service.cdrpaymntsUrlBase='/adinvtry.server/rest/cdrpaymntitems';
service.stksectionsUrlBase='/adstock.server/rest/stksections';
service.stkarticlelotsUrlBase='/adstock.server/rest/stkarticlelots';
service.catalarticlesUrlBase='/adcatal.server/rest/catalarticles';
service.loginnamessUrlBase='/adbase.server/rest/loginnamess';
service.stkarticlelot2strgsctnsUrlBase='/adstock.server/rest/stkarticlelot2strgsctns';
service.language=sessionManager.language;
service.currentWsUser=sessionManager.userWsData();
service.translate = function(){
$translate([
'CdrCstmrVchr_amtUsed_description.text',
'CdrCstmrVchr_amtUsed_description.title',
'CdrCstmrVchr_amt_description.text',
'CdrCstmrVchr_amt_description.title',
'CdrCstmrVchr_canceled_description.text',
'CdrCstmrVchr_canceled_description.title',
'CdrCstmrVchr_cashier_description.text',
'CdrCstmrVchr_cashier_description.title',
'CdrCstmrVchr_cdrNbr_description.text',
'CdrCstmrVchr_cdrNbr_description.title',
'CdrCstmrVchr_cstmrName_description.text',
'CdrCstmrVchr_cstmrName_description.title',
'CdrCstmrVchr_cstmrNbr_description.text',
'CdrCstmrVchr_cstmrNbr_description.title',
'CdrCstmrVchr_description.text',
'CdrCstmrVchr_description.title',
'CdrCstmrVchr_dsNbr_description.text',
'CdrCstmrVchr_dsNbr_description.title',
'CdrCstmrVchr_prntDt_description.text',
'CdrCstmrVchr_prntDt_description.title',
'CdrCstmrVchr_restAmt_description.text',
'CdrCstmrVchr_restAmt_description.title',
'CdrCstmrVchr_settled_description.text',
'CdrCstmrVchr_settled_description.title',
'CdrCstmrVchr_vchrNbr_description.text',
'CdrCstmrVchr_vchrNbr_description.title',
'CdrDsPymntItem_amt_description.text',
'CdrDsPymntItem_amt_description.title',
'CdrDsPymntItem_description.text',
'CdrDsPymntItem_description.title',
'CdrDsPymntItem_diffAmt_description.text',
'CdrDsPymntItem_diffAmt_description.title',
'CdrDsPymntItem_dsNbr_description.text',
'CdrDsPymntItem_dsNbr_description.title',
'CdrDsPymntItem_pymntDocNbr_description.text',
'CdrDsPymntItem_pymntDocNbr_description.title',
'CdrDsPymntItem_pymntDocType_description.text',
'CdrDsPymntItem_pymntDocType_description.title',
'CdrDsPymntItem_pymntMode_description.text',
'CdrDsPymntItem_pymntMode_description.title',
'CdrDsPymntItem_rcvdAmt_description.text',
'CdrDsPymntItem_rcvdAmt_description.title',
'CdrPymnt_amt_description.text',
'CdrPymnt_amt_description.title',
'CdrPymnt_cashier_description.text',
'CdrPymnt_cashier_description.title',
'CdrPymnt_cdrNbr_description.text',
'CdrPymnt_cdrNbr_description.title',
'CdrPymnt_description.text',
'CdrPymnt_description.title',
'CdrPymnt_paidBy_description.text',
'CdrPymnt_paidBy_description.title',
'CdrPymnt_pymntDt_description.text',
'CdrPymnt_pymntDt_description.title',
'CdrPymnt_pymntNbr_description.text',
'CdrPymnt_pymntNbr_description.title',
'CdrPymnt_rcptNbr_description.text',
'CdrPymnt_rcptNbr_description.title',
'CdrPymnt_rcptPrntDt_description.text',
'CdrPymnt_rcptPrntDt_description.title',
'CdrPymnt_valueDt_description.text',
'CdrPymnt_valueDt_description.title',
'CdrPymntItem_amt_description.text',
'CdrPymntItem_amt_description.title',
'CdrPymntItem_description.text',
'CdrPymntItem_description.title',
'CdrPymntItem_diffAmt_description.text',
'CdrPymntItem_diffAmt_description.title',
'CdrPymntItem_pymntDocNbr_description.text',
'CdrPymntItem_pymntDocNbr_description.title',
'CdrPymntItem_pymntDocType_description.text',
'CdrPymntItem_pymntDocType_description.title',
'CdrPymntItem_pymntMode_description.text',
'CdrPymntItem_pymntMode_description.title',
'CdrPymntItem_pymntNbr_description.text',
'CdrPymntItem_pymntNbr_description.title',
'CdrPymntItem_rcvdAmt_description.text',
'CdrPymntItem_rcvdAmt_description.title',
'CdrPymntMode_CASH_description.text',
'CdrPymntMode_CASH_description.title',
'CdrPymntMode_CHECK_description.text',
'CdrPymntMode_CHECK_description.title',
'CdrPymntMode_CREDIT_CARD_description.text',
'CdrPymntMode_CREDIT_CARD_description.title',
'CdrPymntMode_VOUCHER_description.text',
'CdrPymntMode_VOUCHER_description.title',
'CdrPymntMode_description.text',
'CdrPymntMode_description.title',
'CdrPymntObject_amt_description.text',
'CdrPymntObject_amt_description.title',
'CdrPymntObject_description.text',
'CdrPymntObject_description.title',
'CdrPymntObject_orgUnit_description.text',
'CdrPymntObject_orgUnit_description.title',
'CdrPymntObject_origDocNbr_description.text',
'CdrPymntObject_origDocNbr_description.title',
'CdrPymntObject_origDocType_description.text',
'CdrPymntObject_origDocType_description.title',
'CdrPymntObject_origItemNbr_description.text',
'CdrPymntObject_origItemNbr_description.title',
'CdrPymntObject_pymntNbr_description.text',
'CdrPymntObject_pymntNbr_description.title',
'CdrPymtHstry_cdrNbr_description.text',
'CdrPymtHstry_cdrNbr_description.title',
'CdrPymtHstry_description.text',
'CdrPymtHstry_description.title',
'CdrPymtHstry_pymntNbr_description.text',
'CdrPymtHstry_pymntNbr_description.title',
'CdrVchrHstry_cdrNbr_description.text',
'CdrVchrHstry_cdrNbr_description.title',
'CdrVchrHstry_description.text',
'CdrVchrHstry_description.title',
'CdrVchrHstry_vchrNbr_description.text',
'CdrVchrHstry_vchrNbr_description.title',
'Entity_show.title',
'Entity_previous.title',
'Entity_list.title',
'Entity_next.title',
'Entity_edit.title',
'Entity_create.title',
'Entity_update.title',
'Entity_Result.title',
'Entity_search.title',
'Entity_cancel.title',
'Entity_save.title',
'Entity_By.title',
'Entity_saveleave.title',
'Entity_add.title'
])
.then(function (translations) {
service.translations = translations;
});
};
service.translate();
return service;
}])
.factory('cdrState',['$rootScope', '$q',function($rootScope,$q){
var service = {
};
var selectedIndexVar=-1;
service.selectedIndex= function(selectedIndexIn){
if(selectedIndexIn)selectedIndexVar=selectedIndexIn;
return selectedIndexVar;
};
var totalItemsVar=0;
service.totalItems = function(totalItemsIn){
if(totalItemsIn)totalItemsVar=totalItemsIn;
return totalItemsVar;
};
var currentPageVar = 0;
service.currentPage = function(currentPageIn){
if(currentPageIn) currentPageVar=currentPageIn;
return currentPageVar;
};
var maxSizeVar = 5;
service.maxSize = function(maxSizeIn) {
if(maxSizeIn) maxSizeVar=maxSizeIn;
return maxSizeVar;
};
var itemPerPageVar = 25;
var searchInputVar = {
entity:{},
fieldNames:[],
start:0,
max:itemPerPageVar
};
service.searchInput = function(searchInputIn){
if(!searchInputIn)
return angular.copy(searchInputVar);
searchInputVar=angular.copy(searchInputIn);
return searchInputIn;
};
service.searchInputChanged = function(searchInputIn){
return angular.equals(searchInputVar, searchInputIn);
};
service.itemPerPage = function(itemPerPageIn){
if(itemPerPageIn)itemPerPageVar=itemPerPageIn;
return itemPerPageVar;
};
//
service.consumeSearchResult = function(searchInput, entitySearchResult) {
// store search
service.searchInput(searchInput);
// Store result
service.invInvtrys(entitySearchResult.resultList);
service.totalItems(entitySearchResult.count);
service.selectedIndex(-1);
};
service.paginate = function(){
searchInputVar.start = ((currentPageVar - 1) * itemPerPageVar);
searchInputVar.max = itemPerPageVar;
return service.searchInput();
};
// returns sets and returns the business partner at the passed index or
// if not set the business partner at the currently selected index.
service.invInvtry = function(index){
if(index && index>=0 && index<invInvtrysVar.length)selectedIndexVar=index;
if(selectedIndexVar<0 || selectedIndexVar>=invInvtrysVar.length) return;
return invInvtrysVar[selectedIndexVar];
};
// replace the current partner after a change.
service.replace = function(invInvtry){
if(!invInvtrysVar || !invInvtry) return;
var currentInvt = service.invInvtry();
if(currentInvt && currentInvt.invtryNbr==invInvtry.invtryNbr){
invInvtrysVar[selectedIndexVar]=invInvtry;
} else {
for (var index in invInvtrysVar) {
if(invInvtrysVar[index].invtryNbr==invInvtry.invtryNbr){
invInvtrysVar[index]=invInvtry;
selectedIndexVar=index;
break;
}
}
}
};
service.set = function(invInvtry){
if(!invInvtrysVar || !invInvtry) return false;
invInvtrysVar[selectedIndexVar]=invInvtry;
return true;
};
// CHeck if the business partner to be displayed is at the correct index.
service.peek = function(invInvtry, index){
if(!invInvtrysVar || !invInvtry) return false;
if(index>=0 && index<invInvtrysVar.length){
selectedIndexVar=index;
return true;
}
return false;
};
service.push = function(invInvtry){
if(!invInvtrysVar || !invInvtry) return false;
var length = invInvtrysVar.push(invInvtry);
selectedIndexVar=length-1;
return true;
};
service.previous = function (){
if(invInvtrysVar.length<=0) return;
if(selectedIndexVar<=0){
selectedIndexVar=invInvtrysVar.length-1;
} else {
selectedIndexVar-=1;
}
return service.invInvtry();
};
service.next = function(){
if(invInvtrysVar.length<=0) return;
if(selectedIndexVar>=invInvtrysVar.length-1 || selectedIndexVar<0){
selectedIndexVar=0;
} else {
selectedIndexVar+=1;
}
return service.invInvtry();
};
service.cdrPaymnt = function () {
}
return service;
}])
.controller('cdrPaymntsCtlr',['$scope','genericResource','cdrUtils','cdrState','$location','$rootScope',
function($scope,genericResource,cdrUtils,cdrState,$location,$rootScope){
$scope.searchInput = cdrState.searchInput();
$scope.itemPerPage=cdrState.itemPerPage;
$scope.totalItems=cdrState.totalItems;
$scope.currentPage=cdrState.currentPage();
$scope.maxSize =cdrState.maxSize;
$scope.cdrPaymnts =cdrState.cdrPaymnts;
$scope.selectedIndex=cdrState.selectedIndex;
$scope.handleSearchRequestEvent = handleSearchRequestEvent;
$scope.handlePrintRequestEvent = handlePrintRequestEvent;
$scope.paginate = paginate;
$scope.error = "";
$scope.cdrUtils=cdrUtils;
$scope.show=show;
$scope.edit=edit;
$scope.cur = "XAF";
var translateChangeSuccessHdl = $rootScope.$on('$translateChangeSuccess', function () {
cdrUtils.translate();
});
$scope.$on('$destroy', function () {
translateChangeSuccessHdl();
});
init();
function handleSearchRequestEvent(){
if($scope.searchInput.acsngUser){
$scope.searchInput.entity.acsngUser=$scope.searchInput.acsngUser.loginName;
} else {
$scope.searchInput.entity.acsngUser='';
}
findCustom($scope.searchInput);
}
function handlePrintRequestEvent(){
// To do
}
function paginate(){
$scope.searchInput = invInvtryState.paginate();
findCustom($scope.searchInput);
};
function paginate(){
$scope.searchInput = invInvtryState.paginate();
findCustom($scope.searchInput);
}
function init(){
}
function show(cdrPymt, index){
}
function edit(cdrPymt, index){
}
}])
.controller('cdrPaymntCreateCtlr',['$scope','cdrUtils','$translate','genericResource','$location','cdrState',
function($scope,cdrUtils,$translate,genericResource,$location,cdrState){
$scope.cdrPaymnt = cdrState.cdrPaymnt();
$scope.create = create;
$scope.error = "";
$scope.stkSection = "";
$scope.startRange = "";
$scope.endRange = "";
$scope.cdrUtils=cdrUtils;
function create(){
};
}])
.controller('cdrPaymntEditCtlr',['$scope','genericResource','$location','cdrUtils','cdrState',
function($scope,genericResource,$location,cdrUtils,cdrState){
$scope.cdrPaymnt = cdrState.cdrPaymnt();
$scope.error = "";
$scope.cdrUtils=cdrUtils;
$scope.update = function (){
genericResource.update(cdrUtils.urlBase, $scope.cdrPaymnt)
.success(function(cdrPaymnt){
if(cdrState.replace(cdrPaymnt)){
$location.path('/CdrPaymnts/show/');
}
})
.error(function(error){
$scope.error = error;
});
};
}])
.controller('cdrPaymntShowCtlr',['$scope','cdrPaymntManagerResource','$location','cdrUtils','cdrState','$rootScope','genericResource','$routeParams',
function($scope,cdrPaymntManagerResource,$location,cdrUtils,cdrState,$rootScope,genericResource,$routeParams){
$scope.cdrPaymnt = cdrState.cdrPaymnt();
$scope.error = "";
if($scope.cdrPaymnt) {
$scope.cdrPaymnt.acsngUser = cdrUtils.currentWsUser.userFullName;
};
function init(){
}
}]);
|
var Util = require('./util');
var BaseTable = require('./basetable');
var ResultSet = require('./resultset');
var View = require('./view');
var ConditionParser = require('./condition-parser');
var jsonQuery = (function() {
var QueryObject = function(table) {
this.table = new BaseTable(table);
this.resultSet = new ResultSet(this.table);
this.view = new View(this.resultSet);
this.cparser = ConditionParser(this.table, this.resultSet);
};
QueryObject.prototype.Select = function(fields) {
this.view.setView(this.table, fields);
return this;
};
QueryObject.prototype.Where = function() {
if(!Util.isArray(arguments[0])) {
throw '.Where('+arguments[0]+'. Argument to Where must be an Array';
}
this.resultSet.result = this.cparser.getResults(arguments[0], this.resultSet);
return this;
};
QueryObject.prototype.OrderBy = function(field, order) {
var idx = this.table.tblAttributes.indexOf(field);
order = order || 'ASC';
this.resultSet.result.sort(function(a, b) {
if(order === 'DESC') {
if(typeof a[idx] === 'number') {
return b[idx] - a[idx];
} else {
return ( a < b ) ? -1 : ( a > b ? 1 : 0 );
}
} else {
if(typeof a[idx] === 'number') {
return a[idx] - b[idx];
} else {
return ( a > b ) ? -1 : ( a < b ? 1 : 0 );
}
}
})
return this;
};
QueryObject.prototype.GroupBy = function(field) {
var idx = this.table.tblAttributes.indexOf(field);
this.groups = this.resultSet.result.reduce(function(groups, row) {
groups[row[idx]] = groups[row[idx]] || [];
groups[row[idx]].push(row);
return groups;
}, {});
this.resultSet.result = Object.keys(this.groups).map(function(key) {
return this.groups[key][0];
}, this);
//console.log(this.groups);
return this;
};
QueryObject.prototype.Execute = function() {
return this.view.getView();
};
return QueryObject;
})();
module.exports = jsonQuery;
|
// peak trajectory on 2D projection map
function projectionMap(where, id, data, peak) {
this.container = d3.select(where);
this.data = data; // [[{}], [], ... []], [], ... []
this.peak = peak; // peak[0]: vertical; peak[1]: honrizontal
this.runNum = this.data.length; // === this.peak[0].length
this.theda = 180 / this.runNum;
this.row = +d3.values(this.data[0][this.data[0].length-1])[0] + 1;
this.col = +d3.values(this.data[0][this.data[0].length-1])[1] + 1;
this.width = this.container.node().clientWidth;
this.height = this.width * (this.row + 1) / (this.col + 1);
this.svg = this.container.append("svg")
.attr("id", id)
.attr("width", this.width)
.attr("height", this.height);
this.cellSize = this.width / (this.col + 1);
this.drawGrid();
for (let i = 0; i < this.runNum; i++) {
this.drawPeak(i, [this.peak[0][i], this.peak[1][i]]);
}
}
projectionMap.prototype.drawGrid = function() {
let _this = this;
for (let i = 0; i < this.row; i++) {
for (let j = 0; j < this.col; j++) {
let cell = this.svg.append("rect")
.attr("x", (j + 1) * this.cellSize)
.attr("y", (this.row - i - 1) * this.cellSize)
.attr("width", this.cellSize)
.attr("height", this.cellSize)
.style("stroke", "darkgray")
.style("stroke-width", 1)
.style("fill", "lightgray")
.on("mouseover", function() {
_this.hightlight(this);
})
.on("click", function() {
_this.selection(this);
});
}
}
}
projectionMap.prototype.hightlight = function(evt) {
let selectX = (evt.x.baseVal.value - this.cellSize) / this.cellSize;
let selectY = this.row - 1 - evt.y.baseVal.value / this.cellSize;
d3.select("#hightlight").remove();
let hightlightCell = this.svg.append("rect")
.attr("id", "hightlight")
.attr("x", (selectX + 1) * this.cellSize)
.attr("y", (this.row - 1 - selectY) * this.cellSize)
.attr("width", this.cellSize)
.attr("height", this.cellSize)
.style("stroke", "black")
.style("stroke-width", 2)
.style("fill", "none");
}
projectionMap.prototype.selection = function(evt) {
let selectX = (evt.x.baseVal.value - this.cellSize) / this.cellSize;
let selectY = this.row - 1 - evt.y.baseVal.value / this.cellSize;
d3.select("#hightlight").remove();
d3.select("#select").remove();
let selectCell = this.svg.append("rect")
.attr("id", "select")
.attr("x", (selectX + 1) * this.cellSize)
.attr("y", (this.row - 1 - selectY) * this.cellSize)
.attr("width", this.cellSize)
.attr("height", this.cellSize)
.style("stroke", "darkred")
.style("stroke-width", 2)
.style("fill", "none");
}
// draw peak trajectory
projectionMap.prototype.drawPeak = function(id, peak) {
let group = this.svg.append("g").attr("id", "run" + id);
for (let t = 0; t < TIME_STEP; t++) {
let pos = [];
let peakNum_X = peak[1][t].length;
let peakNum_Y = peak[0][t].length;
let color = d3.hsl(runHSL[id][0], 0.3 + (runHSL[id][1] - 0.3) * t / (TIME_STEP - 1),
0.7 - (0.7 - runHSL[id][2]) * t / (TIME_STEP - 1));
for (let i = 0; i < peakNum_Y; i++) {
for (let j = 0; j < peakNum_X; j++) {
let x = (peak[1][t][j].index + 1) * this.cellSize;
let y = (this.row - 1 - peak[0][t][i].index) * this.cellSize;
pos.push({xPos: x, yPos: y});
}
}
this.drawPeakGlyph(id, pos, color);
}
}
projectionMap.prototype.drawPeakGlyph = function(id, pos, color) {
let group = this.svg.append("g").attr("class", "peakGlyph").attr("id", "run" + id);
let peakGlyph = group.append("g").selectAll("ellipse")
.data(pos)
.enter()
.append("ellipse")
.attr("transform", (d) => {
return "translate(" + (d.xPos + this.cellSize/2) + "," + (d.yPos + this.cellSize/2) + ") rotate(" + (this.theda * id) + ")";
})
.attr("rx", this.cellSize / 4)
.attr("ry", this.cellSize / 1.5)
.style("stroke", color)
.style("stroke-width", 3)
.style("fill", "none");
// d3.selectAll(".peakGlyph").style("display", "initial");
}
|
#! /usr/bin/env node
var _ = require('underscore');
var cliArgs = require("command-line-args");
var http = require('http');
var logger = require('winston');
var path = require('path');
var spawn = require('child_process').spawn;
var ADMIN_PORT = 8080;
var host = {hostname: process.env.DEV_PROXY_DAEMON || 'localhost', port: ADMIN_PORT, method: 'GET'};
var cli = cliArgs([
{ name: "stop", type: Boolean, alias: "k", description: "kill any running daemon"},
{ name: "help", type: Boolean, alias: 'h', description: "Print usage instructions" },
{ name: "hosts", type: String, defaultOption: true},
{ name: "logfile", type: String, alias: "l", description: "the location relative to ~ to write the logfile"}
]);
var argv = cli.parse();
if (argv.help) {
console.log(cli.getUsage());
process.exit();
}
var withDaemon = function() {
// keep trying to reach the started daemon for like 5 minutes
var done = false;
var interval = 30;
var maxTries = 5000 / interval;
var tries = 0;
var trying = false;
var intervalId = setInterval(function() {
if (done) {
clearInterval(intervalId);
return;
} else if (tries > maxTries) {
clearInterval(intervalId);
logger.info('could not find running daemon, run `ps aux | grep node | grep daemon | tr -s " " | cut -d " " -f 2` to query the daemon\'s process id');
return;
}
if (trying) {
return;
} else {
trying = true;
}
logger.info('ping try:' + tries);
tries = tries + 1;
var pingCallback = function(response) {
done = true;
logger.info('success pinging daemon');
if (argv.stop) {
logger.info('stopping daemon');
var stopCallback = function(response) {
logger.info('stopped daemon');
};
var stopError = function(err) {
logger.info('error stopping daemon');
};
var stopReq = http.request(_(host).extend({path: '/stop'}), stopCallback);
stopReq.on('error', stopError);
stopReq.end();
} else if (argv.hosts) {
logger.info('sending hosts to daemon:' + argv.hosts);
var addHostsCallback = function(response) {
logger.info('added hosts');
};
var addHostError = function(err) {
logger.info('error adding hosts');
logger.error(err);
};
var addHostsReq = http.request(_(host).extend({
path: '/set',
method: 'POST',
headers: {
'Content-Type': 'text/plain',
'Content-Length': Buffer.byteLength(argv.hosts)
}}), addHostsCallback);
addHostsReq.on('error', addHostError);
logger.info('sending hosts:' + argv.hosts);
addHostsReq.write(argv.hosts);
addHostsReq.end();
}
};
var pingError = function(err) {
trying = false;
logger.info('unsuccessful pinging');
};
var pingReq = http.request(_(host).extend({path: '/status'}), pingCallback);
pingReq.on('error', pingError);
pingReq.end();
}, 300);
};
var callback = function(response) {
logger.info('got response from daemon for /status:' + response.statusCode);
if (response.statusCode < 300 && response.statusCode >= 200) {
logger.info('found daemon on port 80');
withDaemon();
} else {
logger.info('port 80 is already in use, not recognizable');
}
};
var onError = function(response) {
logger.info('no daemon found');
if (!argv.stop) {
logger.info('starting daemon');
var logPath;
var child;
try {
if (argv.logfile) {
logPath = path.join(process.env.HOME, argv.logfile);
logger.info('your logs will be at:' + logPath);
child = spawn('nohup', ['dev-proxy-daemon', argv.logfile], {uid: 0, detached: true});
} else {
logPath = path.join(process.env.HOME, '/logs/dev-proxy/daemon.log');
logger.info('find daemon logs at:' + logPath);
child = spawn('nohup', ['dev-proxy-daemon'], {uid: 0, detached: true});
}
child.unref();
logger.info('daemon pid:' + child.pid);
withDaemon();
} catch (e) {
if (e.message.indexOf('spawn') >= 0) {
logger.info('because the daemon binds to 80 and 443 you need to re-run as root');
} else {
logger.error(e.message);
}
}
}
};
logger.info('looking for running daemon');
var req = http.request(_(host).extend({path: '/status'}), callback);
req.on('error', onError);
req.end();
|
import React from "react";
import BeatLoader from "react-spinners/BeatLoader";
const Loader = ({ loading }) => (
<BeatLoader color='yellow' size={20} loading={loading} />
);
export default Loader;
|
// @flow strict
import * as React from 'react';
import { Translation } from '@kiwicom/mobile-localization';
import TripTitleText from './TripTitleText';
type Props = {|
+isOutbound: boolean,
|};
export default function ReturnTitle(props: Props) {
return (
<TripTitleText>
{props.isOutbound ? (
<Translation id="mmb.trip_overview.trip_title.outbound" />
) : (
<Translation id="mmb.trip_overview.trip_title.inbound" />
)}
</TripTitleText>
);
}
|
import React from 'react';
import PropTypes from 'prop-types';
/* eslint max-len: 0 */
const Button = () => {
return (
<button>I am a button</button>
);
};
Button.propTypes = {
};
export default Button;
|
import React, { Component } from 'react';
import Link from 'gatsby-link';
import styles from './styles.scss';
import logo from './../../assets/tangologo.svg';
const NavBar = () => (
<div className="navBar">
<div className="mobileLogoContain">
<img className="mobileLogo" src={logo} alt="Tango Logo"/>
</div>
<div className="navContain">
<div>
<Link to="/">
<img className="navLogo" src={logo} alt="Tango Logo"/>
</Link>
</div>
<span className="navItems">
<Link className="navItem" to="/menu/">Menu</Link>
<a className="navItem" href="#specials">Specials</a>
<a className="navItem" href="#combos">Combos</a>
<a className="navItem" href="#favorites">Favorites</a>
<a className="navItem" href="#location">Location</a>
<a className="navItem" href="#contact">Contact</a>
</span>
</div>
</div>
);
export default NavBar;
|
import React from "react";
import styled from "styled-components";
import { useQuery } from "react-query";
import { useHistory } from "react-router-dom";
import Header from "../header/Header";
import Footer from "../footer/Footer";
import queries from "../../api/queries";
import { BREAKPOINTS } from "../../constants";
import Spinner from "../spinner/Spinner";
const PostsContainer = styled.div`
display: grid;
padding-top: 4rem;
width: 100%;
margin: 0 auto;
margin-bottom: 2.5rem;
@media (min-width: ${BREAKPOINTS.SMALL_DEVICES}) {
width: 65%;
margin-bottom: 0rem;
}
`;
const Wrapper = styled.div`
display: grid;
grid-template-columns: repeat(3, 1fr);
justify-content: center;
grid-gap: 0.5rem;
`;
const Image = styled.img`
object-fit: cover;
height: 20vw;
width: 100%;
cursor: pointer;
`;
function RandomPosts() {
const history = useHistory();
const randomPostsQuery = useQuery("randomPosts", () => queries.randomPosts());
const posts = randomPostsQuery.data?.data || [];
async function showLargerImage(postId) {
history.push(`/post/${postId}`);
}
return (
<div>
<Header />
<PostsContainer>
{randomPostsQuery.isLoading ? (
<Spinner />
) : (
<div>
<Wrapper>
{posts.map((post) => {
return (
<Image
key={post.id}
src={post.url}
onClick={() => showLargerImage(post.id)}
/>
);
})}
</Wrapper>
</div>
)}
</PostsContainer>
<Footer />
</div>
);
}
export default RandomPosts;
|
import React from 'react'
import './BackToTopBtn.css'
import { api } from '../api.js'
const BackToTopBtn = () =>
<section>
<div className="backToTop">
<a onClick={() => window.scrollTo(0, 0)}><img src={`${api}/images/arrow-t.png`} alt="Back to top" id="arrowTop"/><p>Back to top</p></a>
</div>
</section>
export default BackToTopBtn
|
'use strict'
import React from 'react'
import ReactDom from 'react-dom'
import TweetWall from './components/tweetWall'
import './styles/main.scss'
ReactDom.render(<TweetWall />, document.getElementById('TweetWall'))
|
import Immutable from 'immutable'
import _ from 'lodash'
import moment from 'moment'
import { PRESETS } from '../misc/constants'
export function getInitialRoomState (options) {
const room = options.assignment === 'Onscreen room' ? 'O' : 'S'
return Object.assign({
room,
status: 'TENTATIVE',
date: [moment(), moment()],
assistance: [],
equipments: [],
preset: 'no',
startTime: moment('09:00', 'HH:mm'),
endTime: moment('09:00', 'HH:mm'),
usedEquipmentIds: {}
}, options)
}
const initialState = Immutable.Map({
'0': getInitialRoomState({ id: '0' })
})
const bookingsUnfinishedReducer = (state = initialState, action) => {
switch (action.type) {
case 'SAVE_UNFINISHED_BOOKING': {
const { id, name, value } = action.bookingUnfinished
if (name === 'equipments') {
const equipmentsArr = state.get(id).equipments
const index = _.findIndex(equipmentsArr, x => x.equipment === value.equipment)
if (index !== -1) equipmentsArr.splice(index, 0, value)
return state.set(id, { ...state.get(id), ...{ equipments: [...equipmentsArr, value] } })
}
if (name === 'usedEquipmentIds') {
const usedEquipmentIds = state.get(id).usedEquipmentIds
const oldEquipmentIds = usedEquipmentIds[value.equipmentName] || {}
return state.set(id, {
...state.get(id),
...{
usedEquipmentIds:
{
...usedEquipmentIds,
...{
[value.equipmentName]:
{ ...oldEquipmentIds, ...{ [String(value.index)]: value.usedEquipmentId } }
}
}
}
})
}
return state.set(id, { ...state.get(id), ...{ [name]: value } })
}
case 'ADD_BOOKING_ROOM': {
return state.set(action.id, getInitialRoomState({ id: action.id }))
}
case 'REMOVE_BOOKING_ROOM': {
const id = action.id
return state.set(id, { ...state.get(id), ...{ deleted: true } })
}
case 'SAVE_UNFINISHED_JOB': {
if (action.job.name === 'assignment') return initialState
return state
}
case 'REMOVE_EQUIPMENT_UNFINISHED_BOOKING': {
const { bookingId, equipmentId } = action
const equipmentsArr = state.get(bookingId).equipments
const index = _.findIndex(equipmentsArr, x => x.equipment === equipmentId)
_.pullAt(equipmentsArr, [index])
return state.set(bookingId, { ...state.get(bookingId), ...{ equipments: equipmentsArr } })
}
case 'ADD_DEFAULT_EQUIPMENTS': {
const { bookingId, preset } = action
return state.set(bookingId, { ...state.get(bookingId), ...{ equipments: PRESETS[preset] } })
}
default: {
return state
}
}
}
export default bookingsUnfinishedReducer
|
import Vue from 'vue';
import Vuetify from 'vuetify/lib';
Vuetify.config.silent = true
Vue.use(Vuetify);
export default new Vuetify({
icons: {
iconfont: 'mdi',
},
});
|
const request = require('supertest');
const app = require('../../src/app');
const connection = require('../../src/database/connection');
let createONG;
let indexIncidentONG;
let indexIncidents;
describe('ONG', () => {
beforeEach(async () => {
await connection.migrate.rollback();
await connection.migrate.latest();
});
it('should be able to create a new ONG', async () => {
createONG = await request(app)
.post('/ongs')
.send({
name: "Amigos dos Dogs",
email: "contato@amigodogs.com.br",
whatsapp: "12911119333",
city: "Paulistana",
uf: "SP"
});
expect(createONG.body).toHaveProperty('id');
expect(createONG.body.id).toHaveLength(8);
});
});
describe('Incidents', () => {
afterAll(async () => {
await connection.destroy();
});
it('should be able to register new Incident', async () => {
createIncident = await request(app)
.post('/incidents')
.set('Authorization', createONG)
.send({
title: "Caso TESTE",
description: "Descrição do caso TESTE TESTE TESTE",
value: 120
});
expect(createIncident.body).toHaveProperty('id');
});
it('should be able to index all Incidents from an ONG', async () => {
indexIncidentONG = await request(app)
.get('/profile')
.set('Authorization', createONG);
expect(indexIncidentONG.body);
});
it('should be able to index all Incidents from the DB', async () => {
indexIncidents = await request(app)
.get('/incidents');
expect(indexIncidents.body);
});
}) |
import React from 'react';
import PropTypes from 'prop-types';
import Typography from '@material-ui/core/Typography';
import DSASelect from '../controls/DSASelect';
import DSAStepContent from '../controls/DSAStepContent';
import DSAItemList from '../controls/DSAItemList';
import {Attribute} from '../utils/DSATextElements';
const ID = "talent"
export default class DSATalentChooser extends React.Component {
handleChange = (value) => {
const {objecttype} = this.props;
const f = objecttype.talents.find( (c) => c.name === value.value );
this.props.onChange(ID, f);
}
handleBack = () => {
this.props.stepper.back(ID);
}
getOptions() {
const {objecttype} = this.props;
return objecttype.talents.map((c) => {
return {value: c.name, label: c.name};
});
}
render() {
const {stepper, talent} = this.props
const active = talent !== undefined;
return <DSAStepContent active={active} handleNext={stepper.next} handleBack={this.handleBack}>
<Typography>Wähle das Handwerkstalent.</Typography>
<form>
<DSASelect
options={this.getOptions()}
value={active ? talent.name : ""}
onChange={this.handleChange}
label="Wähle"
/>
</form>
{active &&
<DSAItemList items={[{title: talent.name,
items: [
{name: "Talent", value: talent.description},
{name: "Probe", value: Attribute(talent.test)},
]}]} />
}
</DSAStepContent>
}
}
DSATalentChooser.propTypes = {
stepper: PropTypes.object.isRequired,
onChange: PropTypes.func.isRequired,
};
|
import * as skillDb from '../data/skill-db.js'
export{
index,
show
}
function index(req, res) {
skillDb.find({},(err, skills) => {
res.render('skills/index', {
skills,
err
})
})
}
function show(req, res) {
skillDb.findById(req.params.id, (err, skill) => {
res.render('skills/show', {
skill,
err
})
})
} |
// take a slice of the application state and return some data based on that
import { useSelector } from 'react-redux';
export const useActivitiesData = () => {
return useSelector((state) => state.activitiesLogs.activities);
};
export const useActivitiesArrayData = () => {
return useSelector((state) => Object.values(state.activitiesLogs.activities));
};
export const useActivitiesSummaryData = () => {
return useSelector((state) => Object.values(state.activitiesLogs.activities));
};
|
// 引入express模块
const express = require('express')
const path = require('path')
// 创建路由中间件
const studentRouter = express.Router()
// 引入路由中间件所控制的对应的文件
const studentControl = require(path.join(__dirname,'../controllers/studentManageControl.js'))
// 去学生管理系统列表页面
studentRouter.get('/list',studentControl.list)
// 去新增学生信息
studentRouter.get('/add',studentControl.getAddPage)
// 点击保存新增学生信息
studentRouter.post('/add',studentControl.addStudent)
// 去到修改学生信息页面
studentRouter.get('/edit/:studentId',studentControl.getEditPage)
// 修改学生信息
studentRouter.post('/edit/:studentId',studentControl.editStudent)
// 点击删除
studentRouter.get('/delete/:studentId',studentControl.deletePage)
// 暴露出去
module.exports = studentRouter |
angular.module('AdSales').controller('NewSlsSalesStatusController', function ($scope, $location, locationParser, SlsSalesStatusResource ) {
$scope.disabled = false;
$scope.$location = $location;
$scope.slsSalesStatus = $scope.slsSalesStatus || {};
$scope.save = function() {
var successCallback = function(data,responseHeaders){
var id = locationParser(responseHeaders);
$location.path('/SlsSalesStatuss/edit/' + id);
$scope.displayError = false;
};
var errorCallback = function() {
$scope.displayError = true;
};
SlsSalesStatusResource.save($scope.slsSalesStatus, successCallback, errorCallback);
};
$scope.cancel = function() {
$location.path("/SlsSalesStatuss");
};
}); |
atom.declare("Game.Part_engine_2", Game.Part,
{
configure: function method()
{
this.textureMain = Controller.images.get("engine2");
this.deadTexture = Controller.images.get("engine2_broken");
this.HP = 30;
this.buff_thrust = 0.2;
this.type = "engine";
method.previous.call(this);
}
}); |
import { Human } from './models/human';
// For info : https://developer.mozilla.org/en-US/docs/Web/API/Location
// Window > BOM
// Document > DOM
//year = 1956;
// console.log(window.year);
console.log(window.innerWidth);
console.log(innerWidth);
let intervalId = setInterval(() => {
console.log('every 1sec');
}, 1000);
let timeoutId = setTimeout(() => {
console.log('7 sec passed - stop timer');
clearInterval(intervalId);
}, 7000);
console.log(timeoutId);
// clearTimeout(timeoutId);
console.log(window.location.hostname);
console.log(window.location.href);
// Show params in URL like ?useApi=true
console.log(window.location.search);
console.log(document.body);
console.log(document.links);
// document.onClick ...
let element = document.getElementById('first');
element.textContent = 'New content for 1st paragraph';
element.setAttribute('foo', 'fooVal');
element.classList.add('p2');
element.style.color = 'blue';
console.log(element);
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './Components/App/App';
import { BrowserRouter } from 'react-router-dom';
import { BabyProvider } from './Contexts/BabyContext'
import { HamburgerProvider } from './Contexts/HamburgerContext';
ReactDOM.render(
<BrowserRouter>
<BabyProvider>
<HamburgerProvider>
<App />
</HamburgerProvider>
</BabyProvider>
</BrowserRouter>,
document.getElementById('root')
); |
var searchBox = sajari.init({
mode: "search-box",
project: "1588255093746585379", // Set this to your project.
collection: "brightcove-documentation", // Set this to your collection.
instantPipeline: "autocomplete", // Pipeline used as you type
inputPlaceholder: "Search", // Input element placeholder
maxSuggestions: 5, // Maximum number of suggestions to show
attachSearchBox: document.getElementById("nav-search-box") // DOM element to attach to
});
searchBox("sub", "pipeline.search-sent", function (_, query) {
window.location = "/search.html?q=" + encodeURIComponent(query.q);
}); |
import {Route, Switch} from 'react-router-dom'
import Register from './components/Register'
import UsersList from './components/UsersList'
import './App.css'
const App = () => (
<Switch>
<Route exact path="/" component={Register} />
<Route exact path="/users/" component={UsersList} />
</Switch>
)
export default App
|
'use strict';
(function () {
var mySwiper = '';
var breakpoint = window.matchMedia('(max-width: 767px)');
var breakpointChecker = function () {
if (breakpoint.matches) {
if (mySwiper) {
mySwiper.destroy(true, true);
}
mySwiper = new Swiper('.main-screen__slider', {
spaceBetween: 10,
pagination: {
el: '.main-screen__slider-pagination',
type: 'fraction',
},
scrollbar: {
el: '.main-screen__slider-scrollbar',
},
});
return;
} else {
if (mySwiper) {
mySwiper.destroy(true, true);
}
mySwiper = new Swiper('.main-screen__slider', {
pagination: {
el: '.main-screen__slider-pagination',
type: 'bullets',
clickable: true,
renderBullet: function (index, className) {
return '<span class="' + className + '">' + '0' + (index + 1) + '</span>';
},
},
});
}
};
breakpoint.addListener(breakpointChecker);
breakpointChecker();
})();
|
config({
'editor/plugin/local-storage': {requires: ['editor','overlay','editor/plugin/flash-bridge']}
});
|
exports.buildResponse = function (code,description) {
return {code:code,description:description}
} |
#!/usr/bin/env node
'use strict';
process.title = 'arc-docs';
const program = require('commander');
const colors = require('colors/safe');
const docs = require('../lib/arc-docs');
program
.usage('[options] [components...]')
.option('-A, --all', 'Generate docs for all components')
.option('--verbose', 'Display messages');
program.on('--help', () => {
console.log(' Don\'t use --all or list components if you want to generate doc in ' +
'current directory.');
console.log('');
console.log(' Examples:');
console.log('');
console.log(' $ arc docs --all # must be in components main directory');
console.log(' $ arc docs raml-js-parser file-drop # must be in components main directory');
console.log(' $ arc docs # must be in component\'s directory');
console.log('');
});
program.parse(process.argv);
var pkgs = program.args;
console.log();
// if (!pkgs.length && !program.all) {
// console.log(colors.red(' No components specified. Use --all to process all components.'));
// program.outputHelp();
// process.exit(1);
// }
var opts = {
all: program.all || false,
verbose: program.verbose || false
};
if (!program.all) {
opts.components = pkgs;
}
try {
const script = new docs.ArcDocs(opts);
script.run().then(() => {
process.exit(0);
}).catch((err) => {
console.log(colors.red(' ' + err.message));
process.exit(1);
});
} catch (e) {
console.log(colors.red(' ' + e.message));
console.log(e.stack);
program.outputHelp();
process.exit(1);
}
|
//选择器
function JUtils(vArg)
{
//用来保存选中的元素
this.elements=[];
switch(typeof vArg)
{
case 'function':
addEventAction(window, 'load', vArg);
break;
case 'string':
switch(vArg.charAt(0))
{
case '#': //ID
var obj=document.getElementById(vArg.substring(1));
this.elements.push(obj);
break;
case '.': //class
this.elements=getByClass(document, vArg.substring(1));
break;
default: //tagName
this.elements=document.getElementsByTagName(vArg);
}
break;
case 'object':
this.elements.push(vArg);
}
}
//添加方法
JUtils.prototype.extend=function (name, fn)
{
JUtils.prototype[name]=fn;
};
//实例化对象
function $(vArg){
return new JUtils(vArg);
}
JUtils.prototype.click=function (fn)
{
var i=0;
for(i=0;i<this.elements.length;i++)
{
addEventAction(this.elements[i], 'click', fn);
}
return this;
};
JUtils.prototype.dblclick=function (fn)
{
var i=0;
for(i=0;i<this.elements.length;i++)
{
addEventAction(this.elements[i], 'dblclick', fn);
}
return this;
};
JUtils.prototype.show=function ()
{
var i=0;
for(i=0;i<this.elements.length;i++)
{
this.elements[i].style.display='block';
}
return this;
};
JUtils.prototype.hide=function ()
{
var i=0;
for(i=0;i<this.elements.length;i++)
{
this.elements[i].style.display='none';
}
return this;
};
JUtils.prototype.hover=function (fnOver, fnOut)
{
var i=0;
for(i=0;i<this.elements.length;i++)
{
addEventAction(this.elements[i], 'mouseover', fnOver);
addEventAction(this.elements[i], 'mouseout', fnOut);
}
return this;
};
JUtils.prototype.css=function (attr, value)
{
if(arguments.length==2) //设置样式
{
var i=0;
for(i=0;i<this.elements.length;i++)
{
this.elements[i].style[attr]=value;
}
}
else //获取样式
{
if(typeof attr=='string')
{
//return this.elements[0].style[attr];
return getStyle(this.elements[0], attr);
}
else
{
for(i=0;i<this.elements.length;i++)
{
var k='';
for(k in attr)
{
this.elements[i].style[k]=attr[k];
}
}
}
}
return this;
};
JUtils.prototype.attr=function (attr, value)
{
if(arguments.length==2)
{
var i=0;
for(i=0;i<this.elements.length;i++)
{
this.elements[i][attr]=value;
}
}
else
{
return this.elements[0][attr];
}
return this;
};
JUtils.prototype.toggle=function ()
{
var i=0;
var _arguments=arguments;
for(i=0;i<this.elements.length;i++)
{
addToggle(this.elements[i]);
}
function addToggle(obj)
{
var count=0;
addEventAction(obj, 'click', function (){
_arguments[count++%_arguments.length].call(obj);
});
}
return this;
};
JUtils.prototype.eq=function (n)
{
return $(this.elements[n]);
};
function appendArr(arr1, arr2)
{
var i=0;
for(i=0;i<arr2.length;i++)
{
arr1.push(arr2[i]);
}
}
JUtils.prototype.find=function (str)
{
var i=0;
var aResult=[];
for(i=0;i<this.elements.length;i++)
{
switch(str.charAt(0))
{
case '.': //class
var aEle=getByClass(this.elements[i], str.substring(1));
aResult=aResult.concat(aEle);
break;
default: //标签
var aEle=this.elements[i].getElementsByTagName(str);
appendArr(aResult, aEle);
}
}
var newVquery=$();
newVquery.elements=aResult;
return newVquery;
};
function getIndex(obj)
{
var aBrother=obj.parentNode.children;
var i=0;
for(i=0;i<aBrother.length;i++)
{
if(aBrother[i]==obj)
{
return i;
}
}
}
JUtils.prototype.index=function ()
{
return getIndex(this.elements[0]);
};
JUtils.prototype.bind=function (sEv, fn)
{
var i=0;
for(i=0;i<this.elements.length;i++)
{
addEventAction(this.elements[i], sEv, fn);
}
};
//计算元素左边距
JUtils.prototype.extend('getPoint',function() {
//获取某元素浏览器左上角原点坐标
var t =0;
var l =0;
var element=this.elements[0];
if(element){
t = element.offsetTop; //获取该元素对应父容器上边距
l = element.offsetLeft; //对应父容器上边距
//判断否有父容器存则累加其边距
while (element = element.offsetParent) {//等效 obj = obj.offsetParent;while (obj != undefined)
t += element.offsetTop; //叠加父容器上边距
l += element.offsetLeft; //叠加父容器左边距
}
}
return {top:t,left:l};
})
function addEventAction(obj, sEv, fn)
{
if(obj&&obj.attachEvent)
{
obj.attachEvent('on'+sEv, function (){
if(false==fn.call(obj))
{
event.cancelBubble=true;
return false;
}
});
}
else
{
obj.addEventListener(sEv, function (ev){
if(false==fn.call(obj))
{
ev.cancelBubble=true;
ev.preventDefault();
}
}, false);
}
}
function getByClass(oParent, sClass)
{
var aEle=oParent.getElementsByTagName('*');
var aResult=[];
var i=0;
for(i=0;i<aEle.length;i++)
{
if(aEle[i].className==sClass)
{
aResult.push(aEle[i]);
}
}
return aResult;
}
function getStyle(obj, attr)
{
if(obj.currentStyle)
{
return obj.currentStyle[attr];
}
else
{
return getComputedStyle(obj, false)[attr];
}
}
//创建标签
function createPanel(data) {
var panel = document.createElement(data.tagName);
if (data.className)
panel.className = data.className;
if (data.id)
panel.id = data.id;
if (data.name)
panel.name = data.name;
if (data.html)
panel.innerHTML = data.html;
if (data.src)
panel.src = data.src;
if (data.src)
panel.type = data.type;
if (data.data)
panel.data = data.data;
if (data.value)
panel.value = data.value;
if (data.regex)
panel.regex = data.regex;
if (data.msg)
panel.msg = data.msg;
if (data.title)
panel.title = data.title;
return panel;
}
var Tags={
div:"div",
span:"span",
img:"img"
}
var Styles={
marginLeft:"marginLeft",
paddingLeft:"paddingLeft",
marginTop:"marginTop",
background:"background",
width:"width"
}
var Strs={
id:"#",
cls:"."
}
var NodeType={
start:"start",
end:"end",
filter:"filter",
filter1:"filter1"
} |
import {Drawer as MuiDrawer, Paper, Divider} from "@material-ui/core";
import {StyledDrawer} from "./Drawer.style";
import {DrawerContext} from "./DrawerContext";
import Hidden from "@material-ui/core/Hidden";
import IconButton from "~/components/atoms/iconButton/IconButton";
import {useContext} from "react";
import DrawerContent from "./DrawerContent";
const Drawer = function (props) {
const [openDrawer, setOpenDrawer] = useContext(DrawerContext);
const handleClose = () => {
setOpenDrawer(false);
};
return (
<>
<Hidden mdDown implementation="css">
<StyledDrawer variant="permanent" open={true} anchor="left">
<img className="logo" src={require("~/assets/images/logo-text.svg").default} alt="TravelOcto.nl" />
<Divider />
<DrawerContent />
</StyledDrawer>
</Hidden>
<Hidden mdUp implementation="css">
<StyledDrawer
className="mobile-drawer"
variant="temporary"
anchor="left"
open={openDrawer}
anchor="left"
ModalProps={{
keepMounted: true,
}}>
<Paper elevation={4} className="drawer-head">
<img className="logo" src={require("~/assets/images/logo-text.svg").default} alt="TravelOcto.nl" />
<IconButton className="close-button" icon={["fal", "times"]} onClick={handleClose} />
</Paper>
<DrawerContent />
</StyledDrawer>
</Hidden>
</>
);
};
export default Drawer;
|
import Knex from 'knex';
const knex = Knex({});
// $ExpectError - invalid Client
Knex({
client: 'foo',
});
knex.select('foo').withSchema('a').from('bar').where('foo', 2).orWhere('bar', 'foo').whereNot('asd', 1).whereIn('batz', [1, 2]);
knex.select(knex.raw(''))
knex.innerJoin('bar', function () { return this; });
knex.leftJoin('bar', function () { return this; });
knex.rightJoin('bar', function () { return this; });
knex.rightOuterJoin('bar', function () { return this; });
knex.fullOuterJoin('bar', function () { return this; });
knex.crossJoin('bar', function () { return this; });
knex('foo').insert({
a: 1
});
knex('bar').del();
// $ExpectError
knex.from();
knex.destroy();
|
var Company = Backbone.Model.extend({});
var CompanyCollection = Backbone.Collection.extend({
model: Company,
baseUrl: "http://www.back-step.com/api/companies/",
initialize: function(models, args) {
this.url = function() {
return this.baseUrl + '?city=' + args.city;
};
}
}); |
//下拉式選單
$(function() {
$('input[name="op"]').change(function() {
$("#dept").empty();
if ($('input[name="op"]:checked').val() == "學士 Bachelor") {
$("#dept").append("<option value='輔導與諮商學系學校輔導與諮商組 Department of Guidance and Counseling(School Guidance and Counseling Program)'>輔導與諮商學系學校輔導與諮商組 Department of Guidance and Counseling(School Guidance and Counseling Program)</option>");
$("#dept").append("<option value='輔導與諮商學系社區輔導與諮商組 Department of Guidance and Counseling (Community Guidance and Counseling Program)'>輔導與諮商學系社區輔導與諮商組 Department of Guidance and Counseling (Community Guidance and Counseling Program)</option>");
$("#dept").append("<option value='特殊教育學系 Department of Special Education'>特殊教育學系 Department of Special Education</option>");
$("#dept").append("<option value='數學系 Department of Mathematics'>數學系 Department of Mathematics</option>");
$("#dept").append("<option value='物理學系物理組 Department of Physics (Pure Physics Program)'>物理學系物理組 Department of Physics (Pure Physics Program)</option>");
$("#dept").append("<option value='物理學系光電組 Department of Physics (Photonics Program)'>物理學系光電組 Department of Physics (Photonics Program)</option>");
$("#dept").append("<option value='生物學系 Department of Biology'>生物學系 Department of Biology</option>");
$("#dept").append("<option value='化學系 Department of Chemistry'>化學系 Department of Chemistry</option>");
$("#dept").append("<option value='工業教育與技術學系 Department of Industrial Education and Technology'>工業教育與技術學系 Department of Industrial Education and Technology</option>");
$("#dept").append("<option value='財務金融技術學系 Department of Finance'>財務金融技術學系 Department of Finance</option>");
$("#dept").append("<option value='英語學系 Department of English'>英語學系 Department of English</option>");
$("#dept").append("<option value='國文學系 Department of Chinese'>國文學系 Department of Chinese</option>");
$("#dept").append("<option value='地理學系 Department of Geography'>地理學系 Department of Geography</option>");
$("#dept").append("<option value='美術學系 Department of Fine Arts'>美術學系 Department of Fine Arts</option>");
$("#dept").append("<option value='機電工程學系 Department of Mechatronics Engineering'>機電工程學系 Department of Mechatronics Engineering</option>");
$("#dept").append("<option value='電機工程學系 Department of Electrical Engineering'>電機工程學系 Department of Electrical Engineering</option>");
$("#dept").append("<option value='電子工程學系 Department of Electronic Engineering'>電子工程學系 Department of Electronic Engineering</option>");
$("#dept").append("<option value='資訊工程學系 Department of Computer Science and Information Engineering'>資訊工程學系 Department of Computer Science and Information Engineering</option>");
$("#dept").append("<option value='企業管理學系 Department of Business Administration'>企業管理學系 Department of Business Administration</option>");
$("#dept").append("<option value='會計學系 Department of Accounting'>會計學系 Department of Accounting</option>");
$("#dept").append("<option value='資訊管理學系資訊管理組 Department of Information Management (Information Management Program)'>資訊管理學系資訊管理組 Department of Information Management (Information Management Program)</option>");
$("#dept").append("<option value='資訊管理學系數位內容科技與管理組 Department of Information Management (Digital Content Technology and Management Program)'>資訊管理學系數位內容科技與管理組 Department of Information Management (Digital Content Technology and Management Program)</option>");
$("#dept").append("<option value='運動學系 Department of Sports'>運動學系 Department of Sports</option>");
$("#dept").append("<option value='公共事務與公民教育學系公共事務組 Department of Public Affairs and Civic Education (Public Affairs Program)'>公共事務與公民教育學系公共事務組 Department of Public Affairs and Civic Education (Public Affairs Program)</option>");
$("#dept").append("<option value='公共事務與公民教育學系公民教育組 Department of Public Affairs and Civic Education (Civic Education Program)'>公共事務與公民教育學系公民教育組 Department of Public Affairs and Civic Education (Civic Education Program)</option>");
}
if ($('input[name="op"]:checked').val() == "碩士 Master") {
$("#dept").append("<option value='輔導與諮商學系 Department of Guidance and Counseling'>輔導與諮商學系 Department of Guidance and Counseling</option>");
$("#dept").append("<option value='輔導與諮商學系婚姻與家族治療碩士班 Department of Guidance and Counseling (Master’s Program in Marriage and Family Therapy)'>輔導與諮商學系婚姻與家族治療碩士班 Department of Guidance and Counseling (Master’s Program in Marriage and Family Therapy)</option>");
$("#dept").append("<option value='特殊教育學系 Department of Special Education'>特殊教育學系 Department of Special Education</option>");
$("#dept").append("<option value='特殊教育學系資賦優異教育碩士班 Department of Special Education (Master’s Program in Gifted Education)'>特殊教育學系資賦優異教育碩士班 Department of Special Education (Master’s Program in Gifted Education)</option>");
$("#dept").append("<option value='教育研究所 Graduate Institute of Education'>教育研究所 Graduate Institute of Education</option>");
$("#dept").append("<option value='復健諮商研究所 Graduate Institute of Rehabilitation Counseling'>復健諮商研究所 Graduate Institute of Rehabilitation Counseling</option>");
$("#dept").append("<option value='科學教育研究所 Graduate Institute of Science Education'>科學教育研究所 Graduate Institute of Science Education</option>");
$("#dept").append("<option value='數學系 Department of Mathematics'>數學系 Department of Mathematics</option>");
$("#dept").append("<option value='物理學系 Department of Physics'>物理學系 Department of Physics</option>");
$("#dept").append("<option value='生物學系 Department of Biology'>生物學系 Department of Biology</option>");
$("#dept").append("<option value='生物學系生物技術碩士班 Department of Biology (Master’s Program in Biotechnology)'>生物學系生物技術碩士班 Department of Biology (Master’s Program in Biotechnology)</option>");
$("#dept").append("<option value='化學系 Department of Chemistry'>化學系 Department of Chemistry</option>");
$("#dept").append("<option value='光電科技研究所 Graduate Institute of Photonics'>光電科技研究所 Graduate Institute of Photonics</option>");
$("#dept").append("<option value='統計資訊研究所 Graduate Institute of Statistics and Information Science'>統計資訊研究所 Graduate Institute of Statistics and Information Science</option>");
$("#dept").append("<option value='工業教育與技術學系 Department of Industrial Education and Technology'>工業教育與技術學系 Department of Industrial Education and Technology</option>");
$("#dept").append("<option value='工業教育與技術學系數位學習碩士班 Department of Industrial Education and Technology (Master’s Program in E-Learning)'>工業教育與技術學系數位學習碩士班 Department of Industrial Education and Technology (Master’s Program in E-Learning)</option>");
$("#dept").append("<option value='財務金融技術學系 Department of Finance'>財務金融技術學系 Department of Finance</option>");
$("#dept").append("<option value='人力資源管理研究所 Graduate Institute of Human Resource Management'>人力資源管理研究所 Graduate Institute of Human Resource Management</option>");
$("#dept").append("<option value='車輛科技研究所 Graduate Institute of Vehicle Engineering'>車輛科技研究所 Graduate Institute of Vehicle Engineering</option>");
$("#dept").append("<option value='英語學系 Department of English'>英語學系 Department of English</option>");
$("#dept").append("<option value='國文學系 Department of Chinese'>國文學系 Department of Chinese</option>");
$("#dept").append("<option value='地理學系 Department of Geography'>地理學系 Department of Geography</option>");
$("#dept").append("<option value='地理學系環境暨觀光遊憩碩士班 Department of Geography (Master’s Program in Environment, Tourism and Recreation)'>地理學系環境暨觀光遊憩碩士班 Department of Geography (Master’s Program in Environment, Tourism and Recreation)</option>");
$("#dept").append("<option value='美術學系 Department of Fine Arts'>美術學系 Department of Fine Arts</option>");
$("#dept").append("<option value='美術學系藝術教育碩士班 Department of Fine Arts (Master’s Program in Art Education)'>美術學系藝術教育碩士班 Department of Fine Arts (Master’s Program in Art Education)</option>");
$("#dept").append("<option value='兒童英語研究所 Graduate Institute of Children’s English'>兒童英語研究所 Graduate Institute of Children’s English</option>");
$("#dept").append("<option value='翻譯研究所 Graduate Institute of Translation and Interpretation'>翻譯研究所 Graduate Institute of Translation and Interpretation</option>");
$("#dept").append("<option value='台灣文學研究所 Graduate Institute of Taiwanese Literature'>台灣文學研究所 Graduate Institute of Taiwanese Literature</option>");
$("#dept").append("<option value='歷史學研究所 Graduate Institute of History'>歷史學研究所 Graduate Institute of History</option>");
$("#dept").append("<option value='機電工程學系 Department of Mechatronics Engineering'>機電工程學系 Department of Mechatronics Engineering</option>");
$("#dept").append("<option value='電機工程學系 Department of Electrical Engineering'>電機工程學系 Department of Electrical Engineering</option>");
$("#dept").append("<option value='電子工程學系 Department of Electronic Engineering'>電子工程學系 Department of Electronic Engineering</option>");
$("#dept").append("<option value='資訊工程學系 Department of Computer Science and Information Engineering'>資訊工程學系 Department of Computer Science and Information Engineering</option>");
$("#dept").append("<option value='資訊工程學系物聯網碩士班 Department of Computer Science and Information Engineering (Master’s Program in Internet of Things)'>資訊工程學系物聯網碩士班 Department of Computer Science and Information Engineering (Master’s Program in Internet of Things)</option>");
$("#dept").append("<option value='電信工程學研究所 Graduate Institute of Communications Engineering'>電信工程學研究所 Graduate Institute of Communications Engineering</option>");
$("#dept").append("<option value='企業管理學系 Department of Business Administration'>企業管理學系 Department of Business Administration</option>");
$("#dept").append("<option value='企業管理學系行銷與流通管理碩士班 Department of Business Administration (Master’s Program in Marketing and Logistics Management)'>企業管理學系行銷與流通管理碩士班 Department of Business Administration (Master’s Program in Marketing and Logistics Management)</option>");
$("#dept").append("<option value='會計學系 Department of Accounting'>會計學系 Department of Accounting</option>");
$("#dept").append("<option value='資訊管理學系 Department of Information Management'>資訊管理學系 Department of Information Management</option>");
$("#dept").append("<option value='資訊管理學系數位內容科技與管理碩士班 Department of Information Management (Master’s Program in Digital Content Technology and Management)'>資訊管理學系數位內容科技與管理碩士班 Department of Information Management (Master’s Program in Digital Content Technology and Management)</option>");
$("#dept").append("<option value='運動學系應用運動科學碩士班 Department of Sports (Master’s Program in Applied Sports Science)'>運動學系應用運動科學碩士班 Department of Sports (Master’s Program in Applied Sports Science)</option>");
$("#dept").append("<option value='運動健康研究所 Graduate Institute of Sports and Health'>運動健康研究所 Graduate Institute of Sports and Health</option>");
$("#dept").append("<option value='公共事務與公民教育學系 Department of Public Affairs and Civic Education'>公共事務與公民教育學系 Department of Public Affairs and Civic Education</option>");
}
if ($('input[name="op"]:checked').val() == "博士 PhD") {
$("#dept").append("<option value='輔導與諮商學系 Department of Guidance and Counseling'>輔導與諮商學系 Department of Guidance and Counseling</option>");
$("#dept").append("<option value='特殊教育學系 Department of Special Education'>特殊教育學系 Department of Special Education</option>");
$("#dept").append("<option value='教育研究所 Graduate Institute of Education'>教育研究所 Graduate Institute of Education</option>");
$("#dept").append("<option value='科學教育研究所 Graduate Institute of Science Education'>科學教育研究所 Graduate Institute of Science Education</option>");
$("#dept").append("<option value='數學系 Department of Mathematics'>數學系 Department of Mathematics</option>");
$("#dept").append("<option value='物理學系 Department of Physics'>物理學系 Department of Physics</option>");
$("#dept").append("<option value='光電科技研究所 Graduate Institute of Photonics'>光電科技研究所 Graduate Institute of Photonics</option>");
$("#dept").append("<option value='工業教育與技術學系 Department of Industrial Education and Technology'>工業教育與技術學系 Department of Industrial Education and Technology</option>");
$("#dept").append("<option value='財務金融技術學系 Department of Finance'>財務金融技術學系 Department of Finance</option>");
$("#dept").append("<option value='人力資源管理研究所 Graduate Institute of Human Resource Management'>人力資源管理研究所 Graduate Institute of Human Resource Management</option>");
$("#dept").append("<option value='英語學系 Department of English'>英語學系 Department of English</option>");
$("#dept").append("<option value='國文學系 Department of Chinese'>國文學系 Department of Chinese</option>");
$("#dept").append("<option value='地理學系地理暨環境資源博士班 Department of Geography'>地理學系地理暨環境資源博士班 Department of Geography</option>");
$("#dept").append("<option value='機電工程學系 Department of Mechatronics Engineering'>機電工程學系 Department of Mechatronics Engineering</option>");
$("#dept").append("<option value='電機工程學系 Department of Electrical Engineering'>電機工程學系 Department of Electrical Engineering</option>");
}
});
});
//先把error都隱藏
$(function() {
$(".error").hide();
});
function test()
{
var tmp = 0;
if(!document.form1.op[0].checked&&!document.form1.op[1].checked&&!document.form1.op[2].checked)
{
$("#op_error").show();
tmp = 1;
}
else
{
$("#op_error").hide();
}
if(!document.form1.bonus[0].checked&&!document.form1.bonus[1].checked)
{
$("#bonus_error").show();
tmp = 1;
}
else
{
$("#bonus_error").hide();
}
if(!document.form1.gender[0].checked&&!document.form1.gender[1].checked)
{
$("#gender_error").show();
tmp = 1;
}
else
{
$("#gender_error").hide();
}
if(!document.form1.money[0].checked&&!document.form1.money[1].checked&&!document.form1.money[2].checked&&!document.form1.money[3].checked&&!document.form1.money[4].checked)
{
$("#money_error").show();
tmp = 1;
}
else
{
$("#money_error").hide();
}
if(!document.form1.health[0].checked&&!document.form1.health[1].checked&&!document.form1.health[2].checked)
{
$("#health_error").show();
tmp = 1;
}
else
{
$("#health_error").hide();
}
if(!document.form1.listen[0].checked&&!document.form1.listen[1].checked&&!document.form1.listen[2].checked&&!document.form1.listen[3].checked&&!document.form1.listen[4].checked)
{
$("#listen_error").show();
tmp = 1;
}
else
{
$("#listen_error").hide();
}
if(!document.form1.speak[0].checked&&!document.form1.speak[1].checked&&!document.form1.speak[2].checked&&!document.form1.speak[3].checked&&!document.form1.speak[4].checked)
{
$("#speak_error").show();
tmp = 1;
}
else
{
$("#speak_error").hide();
}
if(!document.form1.read[0].checked&&!document.form1.read[1].checked&&!document.form1.read[2].checked&&!document.form1.read[3].checked&&!document.form1.read[4].checked)
{
$("#read_error").show();
tmp = 1;
}
else
{
$("#read_error").hide();
}
if(!document.form1.write[0].checked&&!document.form1.write[1].checked&&!document.form1.write[2].checked&&!document.form1.write[3].checked&&!document.form1.write[4].checked)
{
$("#write_error").show();
tmp = 1;
}
else
{
$("#write_error").hide();
}
if(document.form1.stud_chinese.value=="")
{
$("#stud_ch_error").show();
$("#stud_ch_form_error").hide();
tmp = 1;
}
else
{
var ch = /^[\u4E00-\u9FA5]+$/;
if(ch.test(document.form1.stud_chinese.value))
{
$("#stud_ch_form_error").hide();
}
else
{
$("#stud_ch_form_error").show();
tmp = 1;
}
$("#stud_ch_error").hide();
}
if(document.form1.stud_english.value=="")
{
$("#stud_en_error").show();
$("#stud_en_form_error").hide();
tmp = 1;
}
else
{
var eng = /^[A-Za-z]+$/;
if(eng.test(document.form1.stud_english.value))
{
$("#stud_en_form_error").hide();
}
else
{
$("#stud_en_form_error").show();
tmp = 1;
}
$("#stud_en_error").hide();
}
if(document.form1.nationality.value=="")
{
$("#nation_error").show();
tmp = 1;
}
else
{
$("#nation_error").hide();
}
if(document.form1.year.value==""||document.form1.month.value==""||document.form1.day.value=="")
{
$("#date_error").show();
$("#date_form_error").hide();
tmp = 1;
}
else
{
var monthForm = /^(0?[1-9]|1[0-2])$/;
var dayForm = /^((0?[1-9])|((1|2)[0-9])|30|31)$/;
if(monthForm.test(document.form1.month.value) && dayForm.test(document.form1.day.value)
&& document.form1.year.value > 1900 && document.form1.year.value < 2020)//格式正確
{
$("#date_form_error").hide();
}
else
{
$("#date_form_error").show();
tmp = 1;
}
$("#date_error").hide();
}
if(document.form1.place.value=="")
{
$("#place_error").show();
tmp = 1;
}
else
{
$("#place_error").hide();
}
if(document.form1.passport.value=="")
{
$("#pass_error").show();
$("#pass_form_error").hide();
tmp = 1;
}
else
{
var Form = /^[A-Za-z0-9]{5,12}$/;
if(Form.test(document.form1.passport.value))
{
$("#pass_form_error").hide();
}
else
{
$("#pass_form_error").show();
tmp = 1;
}
$("#pass_error").hide();
}
if(document.form1.language.value=="")
{
$("#lan_error").show();
tmp = 1;
}
else
{
$("#lan_error").hide();
}
if(document.form1.address.value=="")
{
$("#add_error").show();
tmp = 1;
}
else
{
$("#add_error").hide();
}
if(document.form1.phone.value=="")
{
$("#tele_error").show();
$("#tele_form_error").hide();
tmp = 1;
}
else
{
var Form = /^[0-9]{5,11}$/;
if(Form.test(document.form1.phone.value))
{
$("#tele_form_error").hide();
}
else
{
$("#tele_form_error").show();
tmp = 1;
}
$("#tele_error").hide();
}
if(document.form1.mail.value=="")
{
$("#mail_error").show();
$("#mail_form_error").hide();
tmp = 1;
}
else
{
var reg = /^[^\s]+@[^\s]+\.[^\s]{2,3}$/;
if(reg.test(document.form1.mail.value))//格式正確
{
$("#mail_form_error").hide();
}
else
{
$("#mail_form_error").show();
tmp = 1;
}
$("#mail_error").hide();
}
if(document.form1.cellphone.value=="")
{
$("#cell_error").show();
$("#cell_form_error").hide();
tmp = 1;
}
else
{
var phoneForm = /^(09)[0-9]{8}$/;
if( phoneForm.test(document.form1.cellphone.value) )
{
$("#cell_form_error").hide();
}
else
{
$("#cell_form_error").show();
tmp = 1;
}
$("#cell_error").hide();
}
if(document.form1.fa_name.value=="")
{
$("#fa_name_error").show();
tmp = 1;
}
else
{
$("#fa_name_error").hide();
}
if(document.form1.fa_add.value=="")
{
$("#fa_add_error").show();
tmp = 1;
}
else
{
$("#fa_add_error").hide();
}
if(document.form1.fa_phone.value=="")
{
$("#fa_phone_error").show();
tmp = 1;
}
else
{
$("#fa_phone_error").hide();
}
if(document.form1.ma_name.value=="")
{
$("#ma_name_error").show();
tmp = 1;
}
else
{
$("#ma_name_error").hide();
}
if(document.form1.ma_add.value=="")
{
$("#ma_add_error").show();
tmp = 1;
}
else
{
$("#ma_add_error").hide();
}
if(document.form1.ma_phone.value=="")
{
$("#ma_phone_error").show();
tmp = 1;
}
else
{
$("#ma_phone_error").hide();
}
if(document.form1.sc_name.value=="")
{
$("#sc_name_error").show();
tmp = 1;
}
else
{
$("#sc_name_error").hide();
}
if(document.form1.sc_place.value=="")
{
$("#sc_place_error").show();
tmp = 1;
}
else
{
$("#sc_place_error").hide();
}
if(document.form1.sc_degree.value=="")
{
$("#sc_degree_error").show();
tmp = 1;
}
else
{
$("#sc_degree_error").hide();
}
if(document.form1.sc_date.value=="")
{
$("#sc_date_error").show();
tmp = 1;
}
else
{
$("#sc_date_error").hide();
}
if(document.form1.sc_maj.value=="")
{
$("#sc_maj_error").show();
tmp = 1;
}
else
{
$("#sc_maj_error").hide();
}
if(document.form1.sc_min.value=="")
{
$("#sc_min_error").show();
tmp = 1;
}
else
{
$("#sc_min_error").hide();
}
if(document.form1.learn_ch.value=="")
{
$("#learn_ch_error").show();
tmp = 1;
}
else
{
$("#learn_ch_error").hide();
}
if(document.form1.ch_instructor.value=="")
{
$("#ch_instructor_error").show();
tmp = 1;
}
else
{
$("#ch_instructor_error").hide();
}
if(tmp == 1)
{
alert("輸入錯誤! (Inpur Error!)");
return false ;
}
else
{ return (true);}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.