text
stringlengths 7
3.69M
|
|---|
/*
* app.js
*
* Main website router
*
* latest-nodejs.org
*
* 20/12/17
*
* Copyright (c) 2018 Damien Clark
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
'use strict' ;
// wget --trust-server-names 'http://localhost:10010/download/lts/linux/binary/ARMv8'
// curl -L -O -J 'http://localhost:10010/download/lts/linux/binary/ARMv8'
const SwaggerExpress = require('swagger-express-mw') ;
const express = require('express') ;
const app = express() ;
const path = require('path') ;
const util = require('util') ;
const htmlToText = require('html-to-text') ;
const fromFile = util.promisify(htmlToText.fromFile) ;
// Add useragent parser
const useragent = require('express-useragent') ;
app.use(useragent.express()) ;
// Load home page according to user-agent type (command line or web browser)
// Note: this must precede app.use(express.static...) or will never be called
app.get('/', (req, res) => {
// Determine user-agent
let agent = req.useragent ;
// if wget/curl then respond with plain text
if(agent.isBot) {
fromFile(__dirname + '/public/index.html', {
wordwrap: 80
})
.then(text => {
res.contentType('text/plain') ;
res.send(text) ;
}) ;
}
// otherwise, respond with html
else {
res.sendFile(__dirname + '/public/index.html') ;
}
}) ;
// Add public directory for home page
let options = {
dotfiles: 'ignore',
extensions: ['html']
} ;
// Load other resources from under public directory
app.use(express.static(path.join(__dirname, 'public'), options)) ;
module.exports = app ; // for testing
let config = {
appRoot: __dirname // required config
} ;
SwaggerExpress.create(config, function(err, swaggerExpress) {
if (err) throw err ;
// install middleware
swaggerExpress.register(app) ;
// Publish the swagger API documentation (swagger.ui) via /docs
app.use(swaggerExpress.runner.swaggerTools.swaggerUi()) ;
let port = process.env.PORT || 10010 ;
let host = process.env.IP || 'localhost' ;
app.listen(port, host) ;
}) ;
|
/*Universidad de Guadalajara
*Centro Universitario de Ciencias Exactas e Ingenierias
*Programacion Web
*Sistema Universitario de Control Escolar SUCE
*Cuauhtemoc Herrera Muņoz
*/
function selectAll( ){
var i = 0;
document.getElementById( "master" );
if( master.checked ){
for( i = 0 ; i < document.form.elements.length; i++ ){
if( document.form.elements[i].type == "checkbox" ){
document.form.elements[i].checked = 1;
}
}
}
else{
for( i = 0 ; i < document.form.elements.length; i++ ){
if( document.form.elements[i].type == "checkbox" ){
document.form.elements[i].checked = 0;
}
}
}
}
function getChecked( ){
var elements = new Array( );
var x = 0;
for( i = 0 ; i < document.form.elements.length; i++ ){
if( document.form.elements[i].type == "checkbox" ){
if( document.form.elements[i].checked == 1 ){
elements[ x ] = document.form.elements[ i ].id;
x = x + 1;
}
}
}
if( x == 0 ){
//Mostrar mensaje de error
}
else{
//Validar y eliminar elementos
var response = confirm( "Realmente desea eliminar esos registros?" );
alert( response );
}
}
function addDay( ){
if( document.getElementById( "freeDays" ) == null ){
var button = document.getElementById( "addD" ).parentNode;
var dayTable = document.createElement( "table" );
dayTable.setAttribute( "id", "freeDays" );
var header = document.createElement( "thead" );
dayTable.appendChild( header );
var headerRow = document.createElement( "tr" );
var headerColumn1 = document.createElement( "th" );
headerColumn1.appendChild( document.createTextNode( "Dia" ) );
var headerColumn2 = document.createElement( "th" );
headerColumn2.appendChild( document.createTextNode( "Razon" ) );
var headerColumn3 = document.createElement( "th" );
headerColumn3.appendChild( document.createTextNode( "Eliminar" ) );
headerRow.appendChild( headerColumn1 );
headerRow.appendChild( headerColumn2 );
headerRow.appendChild( headerColumn3 );
header.appendChild( headerRow );
button.parentNode.insertBefore( dayTable, button.nextSibling );
var body = document.createElement( "tbody" );
body.setAttribute( "id", "tableBody" );
dayTable.appendChild( body );
}
var body = document.getElementById( "tableBody" );
var tRow = document.createElement( "tr" );
body.appendChild( tRow );
tRow.setAttribute( "id", "row" + $( tRow ).index() );
var day = document.createElement( "td" );
tRow.appendChild( day );
var dayInfo = document.createElement( "input" );
dayInfo.setAttribute( "type", "date" );
dayInfo.setAttribute( "class", "inputLess" );
dayInfo.setAttribute( "id", "day" + $( tRow ).index() );
dayInfo.setAttribute( "name", "day" + $( tRow ).index() );
day.appendChild( dayInfo );
var reason = document.createElement( "td" );
tRow.appendChild( reason );
var reasonInfo = document.createElement( "input" );
reasonInfo.setAttribute( "type", "text" );
reasonInfo.setAttribute( "class", "inputLess" );
reasonInfo.setAttribute( "id", "reason" + $( tRow ).index() );
reasonInfo.setAttribute( "name", "reason" + $( tRow ).index() );
reason.appendChild( reasonInfo );
var del = document.createElement( "td" );
tRow.appendChild( del );
var delAction = document.createElement( "input" );
delAction.setAttribute( "value", "X" );
delAction.setAttribute( "type", "button" );
delAction.setAttribute( "onclick", "delDay(" + $( tRow ).index() + ")" );
del.appendChild( delAction );
}
function delDay( position ){
var i;
var body = document.getElementById( "tableBody" );
var elem = "row" + position;
body.removeChild( document.getElementById( elem ) );
for( i = 0; i < body.children.length; i++){
body.children[ i ].children[ 0 ].setAttribute( "id", "row" + $( body.children[ i ] ).index( ) );
body.children[ i ].children[ 0 ].children[ 0 ].setAttribute( "id", "day" + $( body.children[ i ] ).index( ) );
body.children[ i ].children[ 0 ].children[ 1 ].setAttribute( "id", "reason" + $( body.children[ i ] ).index( ) );
body.children[ i ].children[ 0 ].children[ 2 ].setAttribute( "onclick", "delDay(" + $( body.children[ i ] ).index( ) + ")" );
}
if( i == 0 ){
body.parentNode.parentNode.removeChild( body.parentNode );
}
}
function activateWeb( ){
var web = document.getElementById( "webCheck" );
var field = document.getElementById( "web" );
if( web.checked ){
field.disabled = false;
}
else{
field.disabled = true;
field.value=""
}
}
function activateCel( ){
var cel = document.getElementById( "celCheck" );
var field = document.getElementById( "cel" );
if( cel.checked ){
field.disabled = false;
}
else{
field.disabled = true;
field.value=""
}
}
function activateGit( ){
var git = document.getElementById( "gitCheck" );
var field = document.getElementById( "git" );
if( git.checked ){
field.disabled = false;
}
else{
field.disabled = true;
field.value=""
}
}
function deleteTeacher( id ){
var _confirm = confirm( "Esta seguro que desea eliminar a este profesor?" );
if( _confirm ){
window.location.href="./index.php?control=teacher&action=delete&id=" + id;
}
}
function editTeacher( id ){
window.location.href="./index.php?control=teacher&action=edit&id=" + id;
}
function deleteAlumn( id ){
var _confirm = confirm( "Esta seguro que desea eliminar a este Alumno?" );
if( _confirm ){
window.location.href="./index.php?control=alumn&action=delete&id=" + id;
}
}
function editAlumn( id ){
window.location.href="./index.php?control=alumn&action=edit&id=" + id;
}
function editCicle( id ){
window.location.href="./index.php?control=cicle&action=edit&id=" + id;
}
function showDataAlumn( id ){
var r = document.getElementById( "dataBox" );
if( r != null ){
r.parentNode.removeChild( r );
}
var element = document.getElementById( id ).parentNode;
row = element.parentNode;
var nrow = document.createElement( "tr" );
nrow.setAttribute( "id", "dataBox" );
var nelement = document.createElement( "td" );
nelement.setAttribute( "colspan", "6" );
nrow.appendChild( nelement );
row.parentNode.insertBefore( nrow, row.nextSibling );
}
function showDataTeacher( id ){
var r = document.getElementById( "dataBox" );
if( r != null ){
r.parentNode.removeChild( r );
}
var element = document.getElementById( id ).parentNode;
row = element.parentNode;
var nrow = document.createElement( "tr" );
nrow.setAttribute( "id", "dataBox" );
var nelement = document.createElement( "td" );
nelement.setAttribute( "colspan", "6" );
nelement.setAttribute( "id", "dataContainer" );
nrow.appendChild( nelement );
row.parentNode.insertBefore( nrow, row.nextSibling );
getTeacherData( id );
}
function showDataCicle( id ){
var r = document.getElementById( "dataBox" );
if( r != null ){
r.parentNode.removeChild( r );
}
var element = document.getElementById( id ).parentNode;
row = element.parentNode;
var nrow = document.createElement( "tr" );
nrow.setAttribute( "id", "dataBox" );
var nelement = document.createElement( "td" );
nelement.setAttribute( "colspan", "6" );
nelement.setAttribute( "id", "dataContainer" );
nrow.appendChild( nelement );
row.parentNode.insertBefore( nrow, row.nextSibling );
getCicleData( id );
}
function step2( ){
var val = document.getElementById( "n" );
var n = val.value;
if( n == "" ){
//Error
return -1;
}
var table = document.createElement( "table" );
var thead = document.createElement( "thead" );
var thRow = document.createElement( "tr" );
var button = document.getElementById( "endButton" );
var th1 = document.createElement( "th" );
th1.appendChild( document.createTextNode( "Rubro" ) );
var th2 = document.createElement( "th" );
th2.appendChild( document.createTextNode( "Porcentaje" ) );
var th3 = document.createElement( "th" );
th3.appendChild( document.createTextNode( "Hoja Extra?" ) );
var th4 = document.createElement( "th" );
th4.appendChild( document.createTextNode( "N" ) );
thRow.appendChild( th1 );
thRow.appendChild( th2 );
thRow.appendChild( th3 );
thRow.appendChild( th4 );
table.appendChild( thead );
thead.appendChild( thRow );
button.parentNode.insertBefore( table, button.nextSibling );
var nextButton = document.createElement( "input" );
nextButton.setAttribute( "type", "button" );
nextButton.setAttribute( "onclick", "step3( )" );
nextButton.setAttribute( "value", "Siguiente" );
nextButton.setAttribute( "class", "endButton" );
nextButton.setAttribute( "id", "endButton2" );
table.parentNode.appendChild( nextButton );
var tbody = document.createElement( "tbody" );
for( var i = 0; i < parseInt( n ); i++ ){
var tRow = document.createElement( "tr" );
var td1 = document.createElement( "td" );
var td2 = document.createElement( "td" );
var td3 = document.createElement( "td" );
var td4 = document.createElement( "td" );
var r = document.createElement( "input" );
r.setAttribute( "id", "r" + i );
r.setAttribute( "type", "text" );
var val = document.createElement( "input" );
val.setAttribute( "id", "val" + i );
val.setAttribute( "type", "number" );
val.setAttribute( "min", "0" );
var extra = document.createElement( "input" );
extra.setAttribute( "id", "extra" + i );
extra.setAttribute( "type", "checkbox" );
extra.setAttribute( "onclick", "activateN( " + i + " )" );
var nr = document.createElement( "input" );
nr.setAttribute( "id", "nr" + i );
nr.setAttribute( "type", "number" );
nr.setAttribute( "min", "0" );
nr.disabled = true;
td1.appendChild( r );
td2.appendChild( val );
td3.appendChild( extra );
td4.appendChild( nr );
tRow.appendChild( td1 );
tRow.appendChild( td2 );
tRow.appendChild( td3 );
tRow.appendChild( td4 );
tbody.appendChild( tRow );
table.appendChild( tbody );
button.parentNode.insertBefore( table, button.nextSibling );
}
button.parentNode.removeChild( button );
}
function step3( ){
var val = document.getElementById( "n" );
var n = val.value;
if( n == "" ){
document.form.submit( );
return -1;
}
for( var i = 0; i < parseInt( n ); i++ ){
var elem = document.getElementById( "extra" + i );
if( elem.checked ){
var len = document.getElementById( "nr"+ i );
len = len.value;
var table = document.createElement( "table" );
var caption = document.createElement( "caption" );
caption.appendChild( document.createTextNode( document.getElementById( "r"+ i ).value ) );
table.appendChild( caption );
var thead = document.createElement( "thead" );
var thRow = document.createElement( "tr" );
var button = document.getElementById( "endButton2" );
var th1 = document.createElement( "th" );
th1.appendChild( document.createTextNode( "Rubro" ) );
var th2 = document.createElement( "th" );
th2.appendChild( document.createTextNode( "Porcentaje" ) );
thRow.appendChild( th1 );
thRow.appendChild( th2 );
table.appendChild( thead );
thead.appendChild( thRow );
button.parentNode.appendChild( table );
tbody = document.createElement( "tbody" );
var nextButton = document.createElement( "input" );
nextButton.setAttribute( "type", "button" );
nextButton.setAttribute( "onclick", "finish( )" );
nextButton.setAttribute( "value", "Siguiente" );
nextButton.setAttribute( "class", "endButton" );
nextButton.setAttribute( "id", "endButton3" );
table.parentNode.appendChild( nextButton );
for( var j = 0; j < len; j++ ){
var tRow = document.createElement( "tr" );
var td1 = document.createElement( "td" );
var td2 = document.createElement( "td" );
var sr = document.createElement( "input" );
sr.setAttribute( "id", "sr" + j );
sr.setAttribute( "type", "text" );
var sval = document.createElement( "input" );
sval.setAttribute( "id", "sval" + j );
sval.setAttribute( "type", "number" );
sval.setAttribute( "min", "0" );
td1.appendChild( sr );
td2.appendChild( sval );
tRow.appendChild( td1 );
tRow.appendChild( td2 );
tbody.appendChild( tRow );
table.appendChild( tbody);
}
}
}
}
function finish( ){
document.form.submit( );
}
function showDataCourse2( id ){
window.location.href="./index.php?control=course&action=detail&id=" + id;
}
function activateN( n ){
var field = document.getElementById( "nr" + n );
var check = document.getElementById( "extra" + n );
if( check.checked ){
field.disabled = false;
}
else{
field.disabled = true;
}
}
|
import React from "react";
import FootVid1 from "../assets/pics/cubes.mp4"
const Footer = props => {
return (
<footer className="footer">
<div className="row">
<div className="col-1-of-1">
<video className="footer_logo" autoPlay muted loop>
<source src={FootVid1} type="video/mp4" />
<source src={FootVid1} type="video/webm" />
your browser is not supported!
</video>
</div>
</div>
<div className="footer__logo-box">
<img src={props.footerLogo} alt="Full logo" className="footer__logo">
</img>
</div>
<div className="row">
<div className="col-1-of-2">
<div className="footer__navigation">
<ul className="footer__list">
<li className="footer__item">
<a href="#" className="footer__link">
{props.footerLink1}
</a>
</li>
<li className="footer__item">
<a href="#" className="footer__link">
{props.footerLink2}
</a>
</li>
<li className="footer__item">
<a href="#" className="footer__link">
{props.footerLink3}
</a>
</li>
<li className="footer__item">
<a href="#" className="footer__link">
{props.footerLink4}
</a>
</li>
<li className="footer__item">
<a href="#" className="footer__link">
{props.footerLink5}
</a>
</li>
</ul>
</div>
</div>
<div className="col-1-of-2">
<p className="footer__copyright">
{props.copyright1}
<a href="#" className="footer__link">
{props.copyright2}
</a>
{props.copyright3}
<a href="#" className="footer__link">
{props.copyright4}
</a>
{props.copyright5}
</p>
</div>
</div>
</footer>
);
};
export default Footer;
|
import React from 'react'
import {Link} from 'react-router-dom'
import { checkAPIResponse } from '../helpers/api'
import { selectOptionsSequenceFactory } from '../helpers/form'
export default class SeriesManager extends React.Component {
constructor(props) {
super(props);
this._isMounted = false;
this.state = {
id : props.match && props.match.params.id,
loading : true,
error : null,
seriesPosts : [],
name : props.location && props.location.state && props.location.state.name, // TODO - this will not exist when copy/pasting url
postsById : [],
isAdmin : true,
};
this.handleSequenceChange = this.handleSequenceChange.bind(this);
}
getSeriesPostsById(id) {
return new Promise(resolve => {
fetch(`${process.env.REACT_APP_API_URL}/getSeriesPostsById/${id}`)
.then(res => checkAPIResponse(res))
.then(results => {
if(results.seriesPosts && Array.isArray(results.seriesPosts)) {
let postsById = [];
results.seriesPosts.forEach(post => {
postsById[post.entryId] = {
sequence : post.sequence,
title : post.title,
saveStatus : null
}
});
this._isMounted && this.setState({
seriesPosts : results.seriesPosts,
loading : false,
postsById,
isAdmin : results.isAdmin
})
resolve(true);
} else {
throw(new Error("API did not return any posts for this series. Try adding some."))
}
},
error => {
throw(new Error("getSeriesPostsById Error: ", error));
})
})
.catch(error => {
this._isMounted && this.setState({
error
});
})
}
componentDidMount() {
this._isMounted = true;
// Get list of posts, and their sequence in this Series
this.getSeriesPostsById(this.state.id);
}
componentWillUnmount() {
this._isMounted = false;
}
updatePostSeriesSequence(postId, seriesId, sequence, postsById) {
fetch(`${process.env.REACT_APP_API_URL}/updatePostSeriesSequence`,
{
method : 'POST',
body : JSON.stringify({
postId,
seriesId,
sequence
}),
headers : { 'Content-Type': 'application/json'}
})
.then(res => checkAPIResponse(res))
.then(results => {
if(results.saveSequence && results.saveSequence.affectedRows && results.saveSequence.affectedRows === 1) {
// Display success save status of this post's sequence in series
postsById[postId].saveStatus = "Saved Successfully!";
this._isMounted && this.setState({
postsById
});
setTimeout(() => {
// Remove display status
postsById[postId].saveStatus = null;
this._isMounted && this.setState({
postsById
})
}, 5000);
} else {
throw(new Error("Series Posts Update failed. No DB records updated. Refresh and try again."));
}
},
error => {
throw(new Error("Series Posts Update failed. API might be down. Refresh And Try Again. : ", error));
})
.catch(error => {
// Display failed save status of this post's sequence in series
postsById[postId].saveStatus = "Failed saving!!";
this._isMounted && this.setState({
postsById,
error
})
});
}
// The select options drop down of the posts sequence in the series was changed. Initiate an API change
handleSequenceChange(e) {
const sequence = e.target.value,
postId = e.currentTarget.dataset.entryid,
postsById = this.state.postsById,
seriesId = this.state.id;
// Update the sequence of the post
postsById[postId].sequence = sequence;
// API call to DB update this posts series sequence
this.updatePostSeriesSequence(postId, seriesId, sequence, postsById)
}
render() {
const {loading, error, name, seriesPosts, postsById} = this.state,
demoMessage = !this.state.isAdmin && <div className="alert alert-danger">Demo Mode</div>;
if(error) {
return <>Error Loading This Series Post Sequence. Refresh page and try again.</>
} else if(loading) {
return <>Loading...</>
} else {
/* For each post in a series,
display a drop down sequence of numbers,
from 1 to number of posts in the series,
to control the order of each post in the series
*/
return <div className="series-manager">
{demoMessage}
<div className="series-manager-name">{name}</div>
<ul className="series-sequences">
{ this.state.seriesPosts.length ?
// Loop through each post in sequence
this.state.seriesPosts.map(post => (
<li key={post.entryId}>
{/* Select the order this post should show in series list */}
<select name = "sequence"
value = {postsById[post.entryId].sequence}
data-entryid = {post.entryId}
onChange = {this.handleSequenceChange}>
{selectOptionsSequenceFactory(1, seriesPosts.length)}
</select>
<Link to = {`/posts/edit/${post.entryId}`}>
{post.title}
</Link>
<span>{postsById[post.entryId].saveStatus}</span>
</li>
)) : <>No Posts asssigned to this series</>
}
</ul>
</div>
}
}
}
|
import React from "react";
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import reducers from './reducers/index';
import sagaMiddleware, { rootSaga } from './middlewares/index';
import reduxLogger from './middlewares/reduxLogger';
export default (props) => {
const initialState = {};
const store = createStore(
reducers,
initialState,
applyMiddleware(
sagaMiddleware,
reduxLogger
)
);
sagaMiddleware.run(rootSaga);
/**
* Persist the state on page refresh or when browser is closed
*/
window.onbeforeunload = () => {
};
window.onload = () => {
};
return (
<Provider store={store}>
{props.children}
</Provider>
)
};
|
OC.L10N.register(
"settings",
{
"Authentication error" : "Lỗi xác thực",
"%s password changed successfully" : "%smật khẩu đã được thay đổi thành công",
"Couldn't send reset email. Please contact your administrator." : "Không thể gửi email đặt lại. Vui lòng liên hệ với quản trị viên của bạn.",
"installing and updating apps via the market or Federated Cloud Sharing" : "cài đặt và cập nhật ứng dụng thông qua market hoặc Federated Cloud Sharing",
"cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably." : "cURL đang sử dụng một phiên bản %s đã lỗi thời (%s). Vui lòng cập nhật hệ thống hoặc các tính năng của bạn chẳng hạn như %s sẽ không hoạt động nhưu mong đợi.",
"Saved" : "Đã lưu",
"Invalid email address" : "Địa chỉ email không hợp lệ",
"test email settings" : "Kiểm tra cài đặt email",
"A problem occurred while sending the email. Please revise your settings. (Error: %s)" : "Đã xảy ra sự cố khi gửi email. Hãy sửa lại cài đặt của bạn.(Lỗi: %s)",
"Email sent" : "Email đã được gửi",
"You need to set your user email before being able to send test emails." : "Bạn cần đặt email người dùng của mình trước khi có gửi email thử nghiệm.",
"Your full name has been changed." : "Họ và tên đã được thay đổi.",
"Unable to change full name" : "Họ và tên không thể đổi ",
"Create" : "Tạo",
"Change" : "Thay đổi",
"Delete" : "Xóa",
"Share" : "Chia sẻ",
"APCu" : "APCu",
"Redis" : "Redis",
"Language changed" : "Ngôn ngữ đã được thay đổi",
"Invalid request" : "Yêu cầu không hợp lệ",
"Admins can't remove themself from the admin group" : "Quản trị viên không thể loại bỏ chính họ khỏi nhóm quản lý",
"Couldn't remove app." : "Không thể xóa ứng dụng.",
"Official" : "Official",
"Approved" : "Approved",
"All" : "Tất cả",
"Enabled" : "Bật",
"Not enabled" : "Chưa bật",
"No apps found for your version" : "Không tìm thấy phiên bản của ứng dụng",
"Please wait...." : "Xin hãy đợi...",
"Disable" : "Tắt",
"Enable" : "Bật",
"Updating...." : "Đang cập nhật...",
"Error while updating app" : "Lỗi khi cập nhật ứng dụng",
"Updated" : "Đã cập nhật",
"Uninstalling ...." : "Đang gở bỏ....",
"Uninstall" : "Gỡ cài đặt",
"Disconnect" : "Ngắt kết nối",
"Are you sure you want to remove this domain?" : "Bạn có chắc chắn muốn xóa miền này?",
"Sending..." : "Đang gửi...",
"Select a profile picture" : "Chọn một ảnh hồ sơ",
"Groups" : "Nhóm",
"undo" : "lùi lại",
"Delete group" : "Xóa nhóm",
"never" : "không bao gi",
"Cheers!" : "Chúc mừng!",
"Language" : "Ngôn ngữ",
"Apps Management" : "Quản lý ứng dụng",
"Developer documentation" : "Tài liệu của nhà phát triển",
"by %s" : "bởi %s",
"Documentation:" : "Tài liệu:",
"User documentation" : "Tài liệu người dùng",
"Admin documentation" : "Tài liệu quản trị",
"Visit website" : "Truy cập trang web",
"Report a bug" : "Báo cáo lỗi",
"Show description …" : "Hiển thị mô tả ...",
"Hide description …" : "Ẩn mô tả ...",
"Uninstall App" : "Gỡ ứng dụng",
"Show enabled apps" : "Hiện ứng dụng đã bật",
"Show disabled apps" : "Hiện ứng dụng đã tắt",
"Cron" : "Cron",
"Open documentation" : "Mở tài liệu",
"Execute one task with each page loaded" : "Thực thi tác vụ mỗi khi trang được tải",
"Common Name" : "Tên gọi chung",
"Sharing" : "Chia sẻ",
"Allow apps to use the Share API" : "Cho phép các ứng dụng sử dụng chia sẻ API",
"Allow resharing" : "Cho phép chia sẻ lại",
"None" : "Không gì cả",
"Save" : "Lưu",
"Log" : "Log",
"Login" : "Đăng nhập",
"Encryption" : "Mã hóa",
"Server address" : "Địa chỉ máy chủ",
"Port" : "Cổng",
"Credentials" : "Giấy chứng nhận",
"Security & setup warnings" : "Bảo mật và thiết lập cảnh báo",
"All checks passed." : "Tất cả kiểm tra đều thông qua.",
"System Status" : "Trạng thái hệ thống",
"Get the apps to sync your files" : "Nhận ứng dụng để đồng bộ file của bạn",
"Android app" : "Ứng dụng Android",
"iOS app" : "Ứng dụng iOS",
"Show First Run Wizard again" : "Hiện lại việc chạy đồ thuật khởi đầu",
"White-listed Domains" : "Danh sách tên miền cho phép",
"No Domains." : "Không có tên miền.",
"Domain" : "Tên miền",
"Add Domain" : "Thêm tên miền",
"Add" : "Thêm",
"Profile picture" : "Ảnh hồ sơ",
"Upload new" : "Tải lên",
"Select from Files" : "Chọn từ tập tin",
"Remove image" : "Xóa ",
"png or jpg, max. 20 MB" : "png or jpg, tối đa. 20 MB",
"Picture provided by original account" : "Hình ảnh được cung cấp bởi tài khoản gốc",
"Cancel" : "Hủy",
"Choose as profile picture" : "Chọn hình ảnh làm ảnh hồ sơ",
"Full name" : "Họ và tên",
"No display name set" : "Chưa đặt tên hiển thị",
"Email" : "Email",
"Your email address" : "Email của bạn",
"Change email" : "Thay đổi email",
"Set email" : "Thiết lập email",
"For password recovery and notifications" : "Để khôi phục mật khẩu và thông báo",
"No email address set" : "Chưa đặt địa chỉ email",
"You are member of the following groups:" : "Bạn là thành viên của các nhóm sau:",
"You are not a member of any groups." : "Bạn không phải là thành viên của bất kỳ nhóm nào.",
"Password" : "Mật khẩu",
"Unable to change your password" : "Không thể đổi mật khẩu",
"Current password" : "Mật khẩu cũ",
"New password" : "Mật khẩu mới",
"Change password" : "Đổi mật khẩu",
"Help translate" : "Hỗ trợ dịch thuật",
"You are using %s of %s (%s %%)" : "Bạn đang sử dụng %s of %s (%s %%)",
"Sessions" : "Phiên làm việc",
"Browser" : "Trình duyệt",
"Most recent activity" : "Hoạt động gần đây nhất",
"You've linked these apps." : "Bạn đã liên kết các ứng dụng này.",
"Name" : "Tên",
"App name" : "Tên ứng dụng",
"Use the credentials below to configure your app or device." : "Sử dụng các thông tin dưới đây để cấu hình ứng dụng hoặc thiết bị của bạn.",
"Username" : "Tên đăng nhập",
"Done" : "Xong",
"Version" : "Phiên bản",
"Personal" : "Cá nhân",
"Admin" : "Quản trị",
"Settings" : "Thiết lập",
"Group" : "N",
"Default Quota" : "Hạn ngạch mặt định",
"Unlimited" : "Không giới hạn",
"Other" : "Khác",
"Full Name" : "Họ và tên",
"Quota" : "Hạn ngạch",
"change full name" : "Đổi họ và t",
"set new password" : "đặt mật khẩu mới",
"Default" : "Mặc định"
},
"nplurals=1; plural=0;");
|
import {formSubscribe, formSubscribeTitle, formSubscribeInput, formSubscribeBtn} from '../../components/FormSubscribe/FormSubscribe.module.scss'
export const FormSubscribe = () => {
return (
<form className={formSubscribe} action="">
<h4 className={formSubscribeTitle}>
Подпишитесь на нашу расслку и узнайте о акциях быстрее
</h4>
<input className={formSubscribeInput} type="email" required placeholder="Введите Ваш e-mail"/>
<button className={formSubscribeBtn}>Отправить</button>
</form>
);
};
|
import {union,without} from 'underscore';
import ACTIONS from './question-actions';
import {QUESTION_TYPE} from '../../../constants/system-constant';
let initialState = {
id:1,
subject:1,
type:'SINGLE_SELECT',// multiselect, singleSelect single choice
summary:'Sample question heading?',
images:[{"path":"imagePath1"},{"path":"imagePath2"}],
options:[
{ "value":"A" ,"text":"Option -A"},
{ "value":"B" ,"text":"Option -B"},
{ "value":"C" ,"text":"Option -C"},
{ "value":"D" ,"text":"Option -D"},
{ "value":"E" ,"text":"Option -E"},
],
note:"Question Note comes here",
selectedChoice:[]
};
export default function QuestionReducer(state=initialState, action){
switch(action.type){
case ACTIONS.OPTION_CLEARED:
return {...state,selectedChoice:[]};
case ACTIONS.OPTION_CHECKED:
return {...state,selectedChoice:union(state.selectedChoice,[action.payload])};
case ACTIONS.OPTION_UNCHECKED:
return {...state,selectedChoice:without(state.selectedChoice,action.payload)};
default:
return state;
}
}
|
var Activity = Backbone.Model.extend({
validate: function(attrs) {
if (attrs.name.trim().length <= 0) {
return "Please, enter activity name";
}
}
});
var Activities = Backbone.Collection.extend({
model: Activity,
url: "/step/"
});
|
import React, { Component } from 'react';
import './Header.css';
class Header extends Component {
render() {
return(
<div className="Header">
{/* <div className="Header-1">Sterile Proz Maid Services</div> */}
<div className="Header-1">
<img className="s-logo" alt="Logo" src="../../imgs/SPMS-Logo.jpg"/>
</div>
<div className="Header-3">
<img className="fb" src="../../imgs/facebook.png"/>
<img className="ig" src="../../imgs/instagram.png"/>
<img className="twit" src="../../imgs/twitter.png"/>
</div>
<div className="Header-4">1-(800)-500-8246 Call Today!</div>
<div className="Header-5">Get a free quote today</div>
</div>
)
}
}
export default Header;
|
import React, { Component } from "react";
import "./Card.css";
class Card extends Component {
constructor(props) {
super(props);
this.state = {
animate: false
};
this.mouseIn = this.mouseIn.bind(this);
this.mouseOut = this.mouseOut.bind(this);
}
mouseIn() {
this.setState({
animate: true
});
}
mouseOut() {
this.setState({
animate: false
});
}
render() {
const { title, subtitle, icon } = this.props;
const iconClass = this.state.animate
? "icon animated swing " + icon
: "icon " + icon;
return (
<div
className="card"
onMouseOver={this.mouseIn}
onMouseLeave={this.mouseOut}
>
<img className="card_bg_image" src="../assets/card_bg.png" alt="pic" />
<div className="card_title">{title}</div>
<div className="card_subtitle">{subtitle}</div>
<i className={iconClass} />
</div>
);
}
}
export default Card;
|
var winWidth = document.body.clientWidth || document.documentElement.clientWidth;
var winHeight = document.body.clientHeight || document.documentElement.clientHeight;
export {winWidth,winHeight};
|
var $ = require('../js/jquery-1.10.1.min.js');
//加载footer
var l = require('../js/loadfooter.js');
l.loadHtml(3);
//依赖全局对象
var golbalObj = require('./golbalObj.js');
//console.log(golbalObj.box_size.width);
//依赖小车对象
var carObj = require('./carObj.js');
//依赖金币对象
var goldObj = require('./goldObj.js');
//创建实例化小车
function createCar(){
var size = {
width:50,
height:30
};
var pos = {
x:(golbalObj.box_size.width-size.width)/2,
y:golbalObj.box_size.height-size.height
};
//实例化小车,给golbalObj.car
golbalObj.car = new carObj({
size:size,
pos:pos
})
//
golbalObj.car.create();
}
//实例化并创建金币
function createGold(){
var id = getId();
var date = new Date();
var sec = date.getSeconds(); //获取当前时间撮的秒
var colorClass = (sec%2)?"y":"w" ;
golbalObj.goldAll[id] = new goldObj({
id:id,
speed:getSpeed(),
pos:getPos(),
size:getSize(),
class:colorClass
});
golbalObj.goldAll[id].create();
}
//点击开始游戏
clickStartGame();
function clickStartGame(){
$("#start-game").on("click",function(){
$(".shade").hide();
gameInit();
gamePlay();
})
}
//重复游戏和回放游戏
function resetGame(){
golbalObj.car.death();
for(var i in golbalObj.goldAll){
//遍历金币对象,添加move,让金币掉落
golbalObj.goldAll[i].delete();
}
var opt = {
timer:null,
code:0,
car:null,
goldAll:{},
timeMax:20,
sumScore:0
}
$.extend(golbalObj,opt);
}
$(".replay").on("click",function(){
$(".shade1").hide();
gameInit();
gamePlay();
})
$(".review").on("click",function(){
$(".shade1").hide();
gameInit();
})
//查看排行榜
function getRank(){
var userID = localStorage.getItem('username');
var param = {
userID:userID,
gname:golbalObj.gameName
}
$.ajax({
url: 'http://datainfo.duapp.com/gamesinfo/catchgolds/rankinglist.php',
type: 'get',
dataType:'jsonp',
data: param,
success: function (data) {
console.log(data);
}
});
}
$(".getrank").on('click',function(){
getRank();
})
//初始化游
function gameInit(){
var time = "00:00:"+golbalObj.timeMax;
golbalObj.timeBox.innerHTML = time;
golbalObj.scoreBox.innerHTML = golbalObj.sumScore;
}
//开始游戏函数
function gamePlay(){
createCar();
addOperation();
golbalObj.timer = setInterval(function(){
golbalObj.code++;
//每一秒生成一枚金币
if(golbalObj.code%golbalObj.fps==0){
createGold();
golbalObj.timeMax--;
golbalObj.timeBox.innerHTML ="00:00:"+setNum(golbalObj.timeMax);
}
if(golbalObj.timeMax==0){
gameOver();
}
for(var i in golbalObj.goldAll){
//遍历金币对象,添加move,让金币掉落
golbalObj.goldAll[i].move();
}
golbalObj.car.move();
},1000/golbalObj.fps)
}
//游戏结束函数
function gameOver(){
clearInterval(golbalObj.timer);
$(".thisScore").html(golbalObj.sumScore);
$(".shade1").show();
resetGame();
var userID = localStorage.getItem('username');
var param = {
userID:userID,
score:golbalObj.sumScore,
gname:golbalObj.gameName
}
$.ajax({
url: 'http://datainfo.duapp.com/gamesinfo/catchgolds/gamesubmit.php',
type: 'post',
data:param,
success: function(data){
console.log(data);
}
});
}
//给gameBox绑定一个点击事件click、touchstart 操作小车
function addOperation(){
golbalObj.gameBox.addEventListener('click',function(e){
var e = window.event||e;
//鼠标相对于当前元素的位置, offsetX表示左边距离
var oLeft = e.offsetX;
var carLeft = golbalObj.car.config.pos.x + golbalObj.car.config.size.width;
if(oLeft>carLeft){
golbalObj.car.config.dir = "right";
}else{
golbalObj.car.config.dir = "left";
}
})
// function handleOrientation(orientData) {
// var absolute = orientData.absolute;
// var alpha = orientData.alpha; z
// var beta = orientData.beta; x
// var gamma = orientData.gamma; y
// // Do stuff with the new orientation data
// }
// DeviceOrientationEvent.alpha 表示设备沿z轴上的旋转角度,范围为0~360。
// DeviceOrientationEvent.beta 表示设备在x轴上的旋转角度,范围为-180~180。它描述的是设备由前向后旋转的情况。
// DeviceOrientationEvent.gamma 表示设备在y轴上的旋转角度,范围为-90~90。它描述的是设备由左向右旋转的情况。
function handleOrientation(event) {
var x = event.beta; // In degree in the range [-180,180]
var y = event.gamma; // In degree in the range [-90,90]
var z = event.alpha; // In degree in the range [0,360]
// golbalObj.scoreBox.innerHTML = y;
if(y>0){
golbalObj.car.config.dir = "right";
}else{
golbalObj.car.config.dir = "left";
}
}
// 监测设备是否在摆动 deviceorientation
window.addEventListener('deviceorientation', handleOrientation);
}
//随机生成16位ID
function getId(){
var arr = "qwertyuiopasdfghjklzxcvbnm0123456789QWERTYUIOPASDFGHJKLZXCVBNM";
var id = "a";
for (var i = 0;i<15; i++){
id+=arr[Math.floor(Math.random()*62)];
}
return id
}
//获取金币下落的随机速度 2-8
function getSpeed(){
return Math.floor(Math.random()*6)+2;
}
//获取金币随机宽度 10-30
function getSize(){
return Math.floor(Math.random()*20)+10;
}
//获取金币下落的随机 left
function getPos(){
var pos = {
x:Math.floor(Math.random()*(golbalObj.box_size.width-30)),
y:0
}
return pos;
}
function setNum(n){
if(n<10){
n = "0"+n;
}
return n;
}
|
var express = require('express');
var router = express.Router();
var users = require('../models/user.js')
var circles = require('../models/circle.js')
var mongoose = require('mongoose')
var schema = mongoose.Schema
/* GET home page. */
router.get('/', function(req, res, next) {
user = req.session.user;
users.findOne({username : user}, async function(err,user){
circs = []
for(var i = 0; i<user.groups.length;i++)
{
circle_id = user.groups[i]
var oid = new mongoose.Types.ObjectId(circle_id.toString());
circle = await circles.findOne({_id:oid})
circs.push(circle)
}
res.render('circles',{circles : circs})
})
});
router.post('/',function(req,res,next){
var cir = new circles()
cir.name = req.body.circlename
cir.members = [req.session.user]
user = req.session.user
users.findOne({username : user},function(err,user){
cir.save(function(err,circle){
user.groups.push(circle._id)
user.save(function(err,upuser){
})
})
})
res.send({})
});
module.exports = router;
|
jQuery(function($){
$('.predef-querys-all button').click(function(e){
$('.query-input').html();
var data = $(this).attr('data-query');
var query = "select ?x where{ \n ?x a sd:"+data+". \n}";
e.preventDefault();
$('.query-type').val('predefURI');
$('.query-input').val(query);
});
$('.predef-querys-name button').click(function(e){
$('.query-input').html();
var data = $(this).attr('data-query');
var attr = $(this).attr('data-queryattr');
var query = "select ?x ?"+attr+" where{ \n ?x a sd:"+data+". \n ?x sd:"+attr+" ?"+attr+"\n}\nGROUP BY ?name\nORDER BY ASC(?name) ";
e.preventDefault();
$('.query-type').val('predefName');
$('.query-input').val(query);
});
$('.select-station,.orderby').change(function(e){
createQuery();
});
$('.nfd, .dist').keyup(function(){
createQuery();
});
function createQuery(){
var stationId = $('.select-station').val();
var order = $(".orderby").val();
var nfd = $(".nfd").val();
var dist = $(".dist").val();
var query = 'SELECT ?name ?address ?dist ?nfd WHERE {\n';
query += '?ta a sd:ta;\n';
query += ' sd:id ?taId;\n';
query += ' sd:name ?name;\n';
query += ' sd:nfd '+nfd+';\n';
query += ' sd:nfd ?nfd;\n';
query += ' sd:address ?address.\n';
query += '?distance a sd:dist;\n';
query += ' sd:taId ?taId;\n';
query += ' sd:stationId "'+stationId+'";\n';
query += ' sd:distance ?dist.\n';
query += ' FILTER(xsd:double(?dist) <= xsd:double('+dist+'))\n';
query += '}\n';
query += 'GROUP BY ?name\n';
query += 'ORDER BY '+order+'(?dist)';
$('.query-input').val(query);
$('.query-type').val('custom');
}
$('.query-submit').click(function(e){
$('.loading-request-wrap').fadeIn();
$('.query-result').empty();
$('.result-title').text('Nothing located');
var query = $('.query-input').val();
var queryType = $('.query-type').val();
e.preventDefault();
jQuery.ajax({
type: "POST",
url: baseUrl + '/lib/create-sparql-query.php',
data: { query: query, queryType: queryType },
success: function (data, textStatus) {
$('.loading-request-wrap').fadeOut();
$('.query-result-wrap').show();
var counter = 0;
var dataCount = data.length;
$.each(data, function(k, v){
counter++;
if(queryType == 'custom') {
$('.result-title').html(dataCount+' TAs located');
var er = [
'<div class="col-xs-12 col-sm-4">',
'<div class="well ta-object">',
'<div class="ta-title">',
'<h4>' + v.name + '</h4>',
'</div>',
'<div class="ta-address">',
'<span class="glyphicon glyphicon-map-marker" aria-hidden="true"></span>' + v.address,
'</div>',
'<hr>',
'<div class="ta-info">',
'<div class="ta-dist"><span class="glyphicon glyphicon-resize-horizontal" aria-hidden="true"></span><span class="value">' + v.dist + '</span> km Entfernung zur Haltestelle</div>',
'<div class="ta-nfd"><span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span><span class="value">' + v.nfd + '</span> Notfalldienst/e im Jahr 2016</div>',
'</div>',
'<span class="label label-info">No. ' + counter + '</span>',
'</div>',
'</div>'
].join("\n");
}else if(queryType == 'predefURI' || queryType == 'predefName'){
$('.result-title').html(dataCount+' Objects located');
var er = [
'<div class="col-xs-12 col-sm-4">',
'<div class="well ta-object">',
'<div class="ta-title">',
'<h4>' + v.name + '</h4>',
'</div>',
'<span class="label label-info">No. ' + counter + '</span>',
'</div>',
'</div>'
].join("\n");
}
$('.query-result').append(er);
});
$('.query-result').append(data);
},
error: function (data, textStatus) {
$('.loading-request-wrap').fadeOut();
$('.query-result-wrap').show();
$('.query-result').append(data);
}
});
});
});
|
/* eslint-disable no-unused-vars */
import AccountServices from '../Services/accountServices';
import TimelineServices from '../Services/timelineService';
import NotificationServices from '../Services/notificationServices';
import QueryServices from '../Services/queryServices';
import LibraryServices from '../Services/libraryServices';
import MessagingServices from '../Services/messagingServices';
import {GetUserDetails} from '../localHelpers'
import Axios from 'axios';
import decoder from 'jwt-decode';
export default {
UpdateUserProxy({commit}, proxyData){
return new Promise((resolve,reject)=>
{
AccountServices.UpdateUserProxy(proxyData).then(resp=>{
resolve(resp)
}).catch(err=>{
reject(err)
})
})
},
ReAssignUserProxy({commit}, proxyData){
return new Promise((resolve,reject)=>
{
AccountServices.ReAssignUserProxy(proxyData).then(resp=>{
resolve(resp)
}).catch(err=>{
reject(err)
})
})
},
TestProxyConnectivity({commit}, proxyData){
return new Promise((resolve,reject)=>
{
AccountServices.TestProxyConnectivity(proxyData).then(resp=>{
resolve(resp)
}).catch(err=>{
reject(err)
})
})
},
GetUserProxy({commit}, data){
return new Promise((resolve,reject)=>{
AccountServices.GetUserProxy(data.instagramAccountId).then(resp=>{
resolve(resp)
}).catch(err=>reject(err))
})
},
SaveProfileStepSection({commit}, data){
localStorage.setItem('profile-active-step-'+ data.profile, data.step)
},
DeleteComment({commit}, data){
return new Promise((resolve, reject) =>{
MessagingServices.DeleteComment(data.instagramAccountId, data.media, data.comment).then(resp=>{
resolve(resp)
}).catch(err=>reject(err))
})
},
LikeComment({commit}, data){
return new Promise((resolve, reject) =>{
MessagingServices.LikeComment(data.instagramAccountId, data.comment).then(resp=>{
resolve(resp)
}).catch(err=>reject(err))
})
},
UnLikeComment({commit}, data){
return new Promise((resolve, reject) =>{
MessagingServices.UnLikeComment(data.instagramAccountId, data.comment).then(resp=>{
resolve(resp)
}).catch(err=>reject(err))
})
},
ReplyComment({commit}, data){
return new Promise((resolve, reject) =>{
MessagingServices.ReplyComment(data.instagramAccountId, data.media, data.comment, data.message).then(resp=>{
resolve(resp)
}).catch(err=>reject(err))
})
},
CreateComment({commit}, data){
return new Promise((resolve, reject) =>{
MessagingServices.CreateComment(data.instagramAccountId, data.media, data.message).then(resp=>{
resolve(resp)
}).catch(err=>reject(err))
})
},
GetRecentComments({commit},data){
return new Promise((resolve, reject)=>{
QueryServices.GetRecentComments(data.instagramAccountId, data.topic).then(resp=>{
resolve(resp);
}).catch((err)=>{
reject(err);
})
})
},
DMMessage({commit}, data){
return new Promise((resolve, reject)=>{
MessagingServices.SendDM(data.id, data.type, data.message).then(resp=>{
resolve(resp)
}).catch(err=>reject(err))
})
},
GetThread({commit}, data){
return new Promise((resolve, reject)=>{
MessagingServices.GetThread(data.instagramAccountId, data.threadId, data.limit).then(resp=>{
commit('success_thread', resp.data)
resolve(resp);
}).catch((err)=>{
commit('failed_thread')
reject(err);
})
})
},
SearchByTopic({commit}, data){
return new Promise((resolve, reject)=>{
QueryServices.SearchByTopic(data.query, data.instagramAccountId, data.limit).then(resp=>{
resolve(resp);
}).catch((err)=>{
reject(err);
})
})
},
SearchByLocation({commit}, data){
return new Promise((resolve, reject)=>{
QueryServices.SearchByLocation(data.query, data.instagramAccountId, data.limit).then(resp=>{
resolve(resp);
}).catch((err)=>{
reject(err);
})
})
},
GetUserMedias({commit}, data){
return new Promise((resolve, reject)=>{
QueryServices.GetUserMedias(data.instagramAccountId, data.topic).then(resp=>{
resolve(resp);
}).catch((err)=>{
reject(err);
})
})
},
GetUserInbox({commit}, data){
return new Promise((resolve, reject)=>{
QueryServices.GetUserInbox(data.instagramAccountId, data.topic).then(resp=>{
resolve(resp);
}).catch((err)=>{
reject(err);
})
})
},
GetUserFeed({commit}, data){
return new Promise((resolve, reject)=>{
QueryServices.GetUserFeed(data.instagramAccountId, data.topic).then(resp=>{
resolve(resp);
}).catch((err)=>{
reject(err);
})
})
},
GetMediasByLocation({commit}, data){
return new Promise((resolve, reject)=>{
QueryServices.GetMediasByLocation(data.instagramAccountId, data.topic).then(resp=>{
resolve(resp);
}).catch((err)=>{
reject(err);
})
})
},
GetUserFollowerList({commit}, data){
return new Promise((resolve, reject)=>{
QueryServices.GetUserFollowerList(data.instagramAccountId, data.topic).then(resp=>{
resolve(resp);
}).catch((err)=>{
reject(err);
})
})
},
GetUserFollowingList({commit}, data){
return new Promise((resolve, reject)=>{
QueryServices.GetUserFollowingList(data.instagramAccountId, data.topic).then(resp=>{
resolve(resp);
}).catch((err)=>{
reject(err);
})
})
},
GetUserFollowingSuggestionList({commit}, data){
return new Promise((resolve, reject)=>{
QueryServices.GetUserFollowingSuggestions(data.instagramAccountId, data.topic).then(resp=>{
resolve(resp);
}).catch((err)=>{
reject(err);
})
})
},
GetUserTargetLocation({commit}, data){
return new Promise((resolve, reject)=>{
QueryServices.GetUserTargetLocation(data.instagramAccountId, data.topic).then(resp=>{
resolve(resp);
}).catch((err)=>{
reject(err);
})
})
},
GetUsersTargetList({commit}, data){
return new Promise((resolve, reject)=>{
QueryServices.GetUsersTargetList(data.instagramAccountId, data.topic).then(resp=>{
resolve(resp);
}).catch((err)=>{
reject(err);
})
})
},
ReleatedTopicByParent({commit}, parentId)
{
return new Promise((resolve, reject)=>{
QueryServices.ReleatedTopicByParent(parentId).then(resp=>{
resolve(resp);
}).catch((err)=>{
reject(err);
})
})
},
GetEventLogs({commit}, data){
return new Promise((resolve, reject)=>{
NotificationServices.GetEventLogs(data.instagramAccountId, data.limit).then(resp=>{
commit('retrieved_event_logs_in',resp.data);
resolve(resp);
}).catch((err)=>{
commit('failed_to_retrieve_event_logs_in',err);
reject(err);
})
})
},
GetAllEventLogsForUser({commit}, data){
return new Promise((resolve, reject)=>{
NotificationServices.GetAllEventLogsForUser(data.instagramAccountId, data.limit).then(resp=>{
commit('retrieved_event_logs',resp.data);
resolve(resp);
}).catch((err)=>{
commit('failed_to_retrieve_event_logs');
reject(err);
})
})
},
CreatePost({commit}, data){
return new Promise((resolve, reject)=>{
TimelineServices.CreatePost(data.id, data.event).then(resp=>{
commit('create_post', data);
resolve(resp);
}).catch((err)=>{
commit('failed_to_create_post', err);
reject(err);
})
})
},
CreateMessage({commit}, data){
return new Promise((resolve, reject)=>{
TimelineServices.CreateMessage(data.type, data.id, data.messages).then(resp=>{
resolve(resp);
}).catch(err=>{
reject(err);
})
})
},
SetSavedMedias({commit}, medias){
return new Promise((resolve, reject)=>{
LibraryServices.SetSavedMedias(medias).then(resp=>{
commit('set_saved_medias', {request: medias, response: resp});
resolve(resp);
}).catch((err)=>{
commit('failed_to_set_saved_medias', { request: medias, error: err })
reject(err);
})
})
},
//#region SavedCaptions
SetSavedCaption({commit}, caption){
return new Promise((resolve, reject)=>{
LibraryServices.SetSavedCaptions(caption).then(resp=>{
commit('set_saved_caption', {request: caption, response: resp});
resolve(resp);
}).catch((err)=>{
commit('failed_to_set_saved_caption', { request: caption, error: err })
reject(err);
})
})
},
UpdateSavedCaption({commit}, caption){
return new Promise((resolve, reject)=>{
LibraryServices.UpdateSavedCaption(caption).then(resp=>{
//commit('update_saved_caption', {request: caption, response: resp});
resolve(resp);
}).catch((err)=>{
//commit('failed_to_update_saved_caption', { request: caption, error: err })
reject(err);
})
})
},
//#endregion
SetSavedHashtags({commit}, hashtags){
return new Promise((resolve, reject)=>{
LibraryServices.SetSavedHashtags(hashtags).then(resp=>{
commit('set_saved_hashtags', {request: hashtags, response: resp});
resolve(resp);
}).catch((err)=>{
commit('failed_to_set_saved_hashtags', { request: hashtags, error: err })
reject(err);
})
})
},
UpdateSavedHashtags({commit}, hashtags){
return new Promise((resolve, reject)=>{
LibraryServices.UpdateSavedHashtags(hashtags).then(resp=>{
//commit('update_saved_caption', {request: caption, response: resp});
resolve(resp);
}).catch((err)=>{
//commit('failed_to_update_saved_caption', { request: caption, error: err })
reject(err);
})
})
},
DeleteSavedHashtags({commit}, hashtags){
return new Promise((resolve, reject)=>{
LibraryServices.DeleteSavedHashtags(hashtags).then(resp=>{
commit('delete_saved_hashtags', {request: hashtags, response: resp});
resolve(resp);
}).catch((err)=>{
//commit('failed_to_update_saved_caption', { request: caption, error: err })
reject(err);
})
})
},
SetSavedMessages({commit}, message){
return new Promise((resolve, reject)=>{
LibraryServices.SetSavedMessages(message).then(resp=>{
commit('set_saved_message', {request: message, response: resp});
resolve(resp);
}).catch((err)=>{
//commit('failed_to_set_saved_messages', { request: message, error: err })
reject(err);
})
})
},
UpdateSavedMessages({commit}, message){
return new Promise((resolve, reject)=>{
LibraryServices.UpdateSavedMessages(message).then(resp=>{
//commit('update_saved_caption', {request: caption, response: resp});
resolve(resp);
}).catch((err)=>{
//commit('failed_to_update_saved_caption', { request: caption, error: err })
reject(err);
})
})
},
DeleteSavedMessages({commit}, message){
return new Promise((resolve, reject)=>{
LibraryServices.DeleteSavedMessages(message).then(resp=>{
commit('delete_saved_message', {request: message, response: resp});
resolve(resp);
}).catch((err)=>{
//commit('failed_to_update_saved_caption', { request: caption, error: err })
reject(err);
})
})
},
GetSavedMessages({commit}, accountId){
return new Promise((resolve, reject)=>{
LibraryServices.GetSavedMessages(accountId).then(resp=>{
commit('get_saved_messages', {request: accountId, response: resp});
resolve(resp);
}).catch((err)=>{
commit('failed_to_get_saved_message')
reject(err);
})
})
},
GetSavedHashtags({commit}, accountId){
return new Promise((resolve, reject)=>{
LibraryServices.GetSavedHashtags(accountId).then(resp=>{
commit('get_saved_hashtags', {request: accountId, response: resp});
resolve(resp);
}).catch((err)=>{
commit('failed_to_get_saved_hashtags')
reject(err);
})
})
},
DeleteSavedCaption({commit}, caption){
return new Promise((resolve, reject)=>{
LibraryServices.DeleteSavedCaptions(caption).then(resp=>{
commit('delete_saved_caption', {request: caption, response: resp});
resolve(resp);
}).catch((err)=>{
//commit('failed_to_update_saved_caption', { request: caption, error: err })
reject(err);
})
})
},
GetSavedMedias({commit}, accountId){
return new Promise((resolve, reject)=>{
LibraryServices.GetSavedMedias(accountId).then(resp=>{
commit('get_saved_medias', {request: accountId, response: resp});
resolve(resp);
}).catch((err)=>{
commit('failed_to_get_saved_medias')
reject(err);
})
})
},
GetSavedCaption({commit}, accountId){
return new Promise((resolve, reject)=>{
LibraryServices.GetSavedCaptions(accountId).then(resp=>{
commit('get_saved_caption', {request: accountId, response: resp});
resolve(resp);
}).catch((err)=>{
commit('failed_to_get_saved_caption')
reject(err);
})
})
},
GetSavedMediasForUser({commit}, instagramAccountId){
return new Promise((resolve, reject)=>{
LibraryServices.GetSavedMediasForUser(instagramAccountId).then(resp=>{
commit('get_saved_medias_for_user', {request: instagramAccountId, response: resp});
resolve(resp);
}).catch((err)=>{
commit('failed_to_get_saved_medias_for_user')
reject(err);
})
})
},
DeleteSavedMedia({commit}, media){
return new Promise((resolve, reject)=>{
LibraryServices.DeleteSavedMedias(media).then(resp=>{
commit('delete_saved_medias', {request: media, response: resp});
resolve(resp);
}).catch((err)=>{
commit('failed_to_delete_saved_medias')
reject(err);
})
})
},
BuildTags({commit}, data){
return new Promise((resolve, reject)=>{
QueryServices.BuildTags(data).then(resp=>{
resolve(resp);
}).catch((err)=>reject(err));
})
},
ReleatedTopics({commit}, data)
{
return new Promise((resolve,reject)=>{
QueryServices.ReleatedTopic(data.instaId, data.topic).then(resp=>{
resolve(resp);
}).catch((err)=>reject(err))
})
},
UploadFileForProfile({commit}, data){
return new Promise((resolve, reject)=>{
AccountServices.UploadFile(data.instaId, data.profileId, data.formData).then(resp=>{
commit('profile_uploaded_files',data);
resolve(resp);
}).catch((err)=>reject(err))
})
},
ChangeBiography({commit}, data){
return new Promise((resolve, reject)=>{
AccountServices.ChangeBiography(data.instagramAccountId, data.biography).then(resp=>{
commit('update_biography', {request: data, response: resp.data})
resolve(resp);
}).catch((err)=>reject(err));
});
},
ChangeProfilePicture({commit}, data){
return new Promise((resolve,reject)=>{
AccountServices.ChangeProfilePicture(data.instagramAccountId, data.image).then(resp=>{
commit('update_profile_picture', data);
resolve(resp);
}).catch((err)=> reject(err))
})
},
SimilarSearch({commit},data){
return new Promise((resolve,reject)=>{
QueryServices.SimilarImageSearch(data.urls,data.limit, data.offset, data.moreAccurate).then(resp=>{
resolve(resp);
}).catch((err)=>reject(err));
})
},
GooglePlacesSearch({commit},query){
return new Promise((resolve,reject)=>{
QueryServices.GooglePlaceSearch(query).then(resp=>{
resolve(resp);
}).catch(err=>{
reject(err);
})
})
},
GooglePlacesAutoCompleteSearch({commit},queryObject){
return new Promise((resolve, reject)=>{
QueryServices.GooglePlacesAutocomplete(queryObject.query, queryObject.radius).then(resp=>{
resolve(resp);
}).catch(err=>reject(err));
})
},
GetProfileConfig({commit}){
return new Promise((resolve,reject)=>{
QueryServices.GetProfileConfig().then(resp=>{
commit('profile_config_retrieved', resp.data);
resolve(resp);
}).catch(err=>{
commit('failed_to_retrieve_profile_config');
reject(err);
})
})
},
AddProfileTopics({commit}, addProfileTopicRequest){
return new Promise((resolve, reject)=>{
AccountServices.AddProfileTopics(addProfileTopicRequest).then(resp=>{
resolve(resp);
}).catch(err=>{
reject(err);
})
})
},
UpdateProfile({commit}, profileData){
return new Promise((resolve, reject)=>{
AccountServices.UpdateProfile(profileData._id, profileData).then(resp=>{
commit('profile_updates', {profileData: profileData, response:resp});
resolve(resolve);
}).catch(err=>{
commit('failed_profile_update',profileData);
reject(err);
})
});
},
GetProfiles({commit}, userId){
return new Promise((resolve, reject)=>{
AccountServices.GetProfilesForUser(userId).then(resp=>{
commit('profiles_retrieved', resp.data)
resolve(resp);
}).catch(err=>{
commit('failed_to_retieve_profiles')
reject(err);
})
})
},
UpdateEvent({commit}, event){
return new Promise((resolve, reject)=>{
TimelineServices.UpdateEvent(event).then(resp=>{
commit('updated_event', {event, newid: resp.data });
resolve(resp);
}).catch(err=>{
console.log(err)
commit('failed_to_update_event')
reject(err);
})
})
},
EnqueueEventNow({commit}, eventId){
return new Promise((resolve,reject)=>{
TimelineServices.EnqueueNow(eventId).then(resp=>{
commit('event_enqueued',eventId);
resolve(resp);
}).catch(err=>{
commit('failed_to_enqueue_event');
reject(err);
})
})
},
DeleteEvent({commit}, eventId){
return new Promise((resolve,reject)=>{
TimelineServices.DeleteEventFromTimeline(eventId).then(resp=>{
commit('event_deleted',eventId);
resolve(resp);
}).catch(err=>{
commit('failed_to_delete_event');
reject(err);
})
})
},
GetUsersTimeline({commit},id){
return new Promise((resolve, reject)=>{
if(id === undefined || id === null){
resolve('no id')
}
TimelineServices.GetUserTimeline(id).then(resp=>{
commit('retrieved_timeline_data_for_user',resp.data);
resolve(resp)
}).catch(err=>{
commit('failed_to_retrieve_timeline_data_for_user')
reject(err)
})
})
},
RefreshState({commit}, id){
return new Promise((resolve,reject)=>{
AccountServices.RefreshState(id).then(resp=>{
commit('refreshed_state');
resolve(resp)
}).catch(err=>{
commit('failed_to_refresh_state');
reject(err);
})
})
},
ChangeState({commit}, newstate){
return new Promise((resolve,reject)=>{
AccountServices.UpdateAgentState({instagramAccountId: newstate.instaId, newState: parseInt(newstate.state)}).then(resp=>{
commit('updated_agent_state');
resolve(resp);
}).catch(err=>{
commit('failed_to_update_agent_state');
if(err.message.includes('401')){
this.dispatch('logout');
}
reject(err);
})
})
},
AccountDetails({commit}, payload){
return new Promise((resolve, reject)=>{
AccountServices.GetInstagramAccountsForUser({accountId:payload.userId}).then(resp=>{
commit('account_details_retrieved',resp.data);
resolve(resp);
})
.catch(err=>{
commit('failed_to_retrive_account_details');
if (err.message.includes('401')) {
this.dispatch('logout');
}
reject(err);
})
})
},
resendConfirmation({commit}, username){
return new Promise((resolve, reject)=>{
AccountServices.ResendConfirm(username).then(resp=>{
resolve(resp);
}).catch(err=>reject(err))
})
},
refreshToken({commit}){
return new Promise((resolve, reject)=>{
AccountServices.RefreshToken({refreshToken: localStorage.getItem('refresh'), username: this.getters.User}).then(resp=>{
const token = resp.data.idToken;
//const refreshToken = resp.data.refreshToken;
localStorage.setItem('token', token)
// localStorage.setItem('refresh', refreshToken);
Axios.defaults.headers.common['Authorization'] = token;
var decoded = decoder(token);
var role = decoded["cognito:groups"][0];
//localStorage.setItem('user', this.getters.User)
//localStorage.setItem('role', role)
commit('auth_success',
{
Token: token,
User: {
Username: this.getters.User,
Role: role
}
});
decoded = null;
resolve(resp);
}).catch(err=>{
commit('auth_refresh_error')
localStorage.removeItem('token')
this.state.UserAuthenticated = false;
reject(err);
})
});
},
registerAccount({commit},user){
return new Promise((resolve,reject)=>{
AccountServices.Register(user).then(resp=>{
resolve(resp)
}).catch(err=>{
})
})
},
confirmAccount({commit}, confirmData){
return new Promise((resolve,reject)=>{
AccountServices.Confirm(confirmData).then(resp=>{
resolve(resp)
}).catch(err =>{
reject(err)
})
})
},
async login({commit}, user){
return new Promise((resolve, reject) => {
commit('auth_request')
AccountServices.Login(user).then(resp=>{
const token = resp.data.idToken
const refreshToken = resp.data.refreshToken;
localStorage.setItem('token', token)
localStorage.setItem('refresh', refreshToken);
Axios.defaults.headers.common['Authorization'] = token;
var decoded = decoder(token);
var role = decoded["cognito:groups"][0];
localStorage.setItem('user', user.Username)
localStorage.setItem('role', role)
commit('auth_success',
{
Token: token,
User: {
Username: user.Username,
Role: role
}
});
decoded = null;
resolve(resp)
})
.catch(err=>{
commit('auth_error')
localStorage.removeItem('token')
localStorage.removeItem('refresh')
this.state.UserAuthenticated = false;
reject(err)
})
})
},
logout({commit}){
return new Promise((resolve) => {
commit('logout')
localStorage.removeItem('token')
delete Axios.defaults.headers.common['Authorization']
resolve()
})
},
LinkInstagramAccount({commit}, data) {
return new Promise((resolve,reject)=>{
AccountServices.LinkInstagramAccount(data).then(resp=>{
resolve(resp);
}).catch(err=>{
reject(err);
})
})
},
DeleteInstagramAccount({commit}, instagramAccountId){
return new Promise((resolve,reject)=>{
AccountServices.DeleteInstagramAccount(instagramAccountId).then(resp=>{
commit('insta_acc_deleted', instagramAccountId)
resolve(resp)
}).catch(err=>{
reject(err)
})
})
},
SubmitCodeForChallange({commit}, data){
return new Promise((resolve,reject)=>{
AccountServices.SubmitCodeForChallange(data.code, data.instagramAccountId).then(resp=>{
resolve(resp)
}).catch(err=>reject(err));
})
},
SubmitPhoneForChallange({commit}, data){
return new Promise((resolve,reject)=>{
AccountServices.SubmitPhoneForChallange(data.phoneNumber, data.instagramAccountId).then(resp=>{
resolve(resp)
}).catch(err=>reject(err));
})
},
CreateSession({commit}, data){
return new Promise((resolve,reject)=>{
AccountServices.CreateSession(data.ptype,data.curr,data.sauce,data.accid).then(resp=>{
resolve(resp)
}).catch(err=> reject(err))
})
},
AddUserDetails({commit}, data){
return new Promise((resolve,reject)=>{
AccountServices.AddUserDetails(data.userId, data.userInformation).then(res=>{
resolve(res)
}).catch(err=>reject(err))
})
}
}
|
function check_key() {
if (typeof get_key != "undefined") {
console.log("local api-key found");
return get_key();
} else {
console.log("local api-key not found, using environment variable");
return ProcessingInstruction.env.GC - API;
}
}
|
var args = arguments[0] || {};
var endPoint = "http://rsmacfarlane.com/wp-content/uploads/2016/11/Player.json";
var currentAttachment;
$.attachmentQueue = [];
$.sync = function(){
Alloy.apiCall(endPoint, null, $.onSuccess, $.onFail);
};
$.onSuccess = function(e){
var response = JSON.parse(e.data);
_.each(response.players, $.processPlayer);
_.each(response.teams, $.processTeam);
$.processAttachmentQueue();
};
$.processPlayer = function(player){
var playerModel = Alloy.createModel('player', {
FirstName: player.first_name,
LastName: player.last_name,
Fppg: player.fppg,
Injured: player.injured,
InjuryDetails: player.injury_details,
InjuryStatus: player.injury_status,
Played: player.played,
PlayerCardUrl: player.player_card_url,
Position: player.position,
Removed: player.removed,
Salary: player.salary,
alloy_id: player.id,
ImageUrl: player.images.default.url
});
if(player.team && player.team._members){
playerModel.set({"TeamId": player.team._members[0]});
}
playerModel.save();
$.attachmentQueue.push(player.images.default.url);
};
$.processTeam = function(team){
Alloy.createModel('team', {
City: team.city,
Code: team.code,
FullName: team.full_name,
Name: team.name,
alloy_id: team.id
}).save();
};
$.processAttachmentQueue = function(){
if($.attachmentQueue.length > 0){
$.downloadAttachment();
}else{
$.syncComplete();
}
};
$.downloadAttachment = function(){
currentAttachment = $.attachmentQueue.shift();
var fileName = $.getAttachmentFilename();
Alloy.downloadImage(currentAttachment, fileName, $.downloadAttachmentSuccess, $.getImageFail);
};
$.downloadAttachmentSuccess = function(){
$.processAttachmentQueue();
};
$.getAttachmentFilename = function(){
var splitFile = currentAttachment.split('/');
var filename = splitFile[splitFile.length - 1];
return filename;
};
$.getImageFail = function(e){
$.processAttachmentQueue();
};
$.onFail = function(e){
alert(e.code);
};
$.syncComplete = function(){
args.success();
};
|
/**
* Require JS - AMD config.
*/
define(function(){
return require.config({
enforceDefine:true,
waitSeconds:15,
baseUrl:'js',
paths:{
// Libraries
'jquery':'vendor/jquery/dist/jquery',
'underscore':'vendor/underscore/underscore',
'backbone':'vendor/backbone/backbone',
'backbone.paginator':'vendor/backbone.paginator/lib/backbone.paginator',
'text':'vendor/text/text',
'handlebars':'vendor/handlebars/handlebars',
'validation': 'vendor/query-validator/validator',
}
});
});
|
export const OPTIONS = {
a: {
name: "Home",
color: "red",
icon: "fas fa-home fa-3x",
iconStyle: "iconA"
},
b: {
name: "Work",
color: "blue",
icon: "fas fa-briefcase fa-3x",
iconStyle: "iconB"
},
c: {
name: "SCIAL",
color: "green",
icon: "fas fa-user fa-3x",
iconStyle: "iconC"
}
};
export const DATES = {
a: {
name: "Today",
description: "",
color: "green"
},
b: {
name: "Tomorrow",
description: "",
color: "red"
},
c: {
name: "Future",
description: "",
color: "blue"
}
};
|
const config= require('./config');
//https
const fs = require('fs');
const express = require('express');
const port = config.port;
const https = require('https');
const options = {
ca : fs.readFileSync(config.ssl.ca),
key: fs.readFileSync(config.ssl.key),
cert:fs.readFileSync(config.ssl.cert)
}
//linebot
var linebot = require('linebot');
var bot = linebot({
channelId: config.line.channelId,
channelSecret: config.line.channelSecret,
channelAccessToken: config.line.channelAccessToken
})
const line = require('@line/bot-sdk');
const client = new line.Client({
channelAccessToken: confi/g.line.channelAccessToken
});
//google drive
const {google} = require('googleapis');
const oAuth2Client = new google.auth.OAuth2(config.Gdrive.client_id, config.Gdrive.client_secret, config.Gdrive.redirect_uri);
oAuth2Client.setCredentials(config.Gdrive.token);
const async = require('async');
const tmpFolder = '1wRNkxOKTFkpuZTS_ZG9A-8hRpo1PyqTe';
const picFolder = '12XEk5qMiKvH_SJHUmCS4jYEm2p1_qOjU';
//mysql
const mysql = require('mysql')
const connection = mysql.createConnection(config.mysql)
connection.connect(err => {
if (err) {
console.log('fail to connect:', err)
process.exit()
}
})
//temporary record
var tmp_records = {}
const total_qNum = 6
function Record(userId){
this.id = userId;
this.qNum = 0;
this.qStatu = -1;
this.data = [-1, -1, -1, -1, -1, -1, 0];
this.address = "";
this.lon = 0;
this.lat = 0;
}
//changeing
var tmp_change = {}
function Changing(userId, houseId, folderId){
this.uId = userId;
this.hId = houseId;
this.picId = -1;
this.fId = folderId;
}
const platform = require('./reply_platform.js')
bot.on('postback', function (event) {
console.log(event);
var mesg = event.postback.data;
var user = event.source.userId;
//志工
var toDo = mesg.substr(0, 5);
if(toDo == "test:"){
id = Number(mesg.substr(5))
var result = getData(event, id);
return
}
else if (toDo == "info:"){
event.reply("info");
return
}
else if(toDo == "pict:"){
event.reply("請傳送圖片");
pid = Number(mesg.substr(5))
tmp_change[user].picId = pid;
console.log(tmp_change[user]);
return
}
else if(toDo == "end_:"){
event.reply(platform.finalQ)
}
else if (toDo == "call:"){
event.reply("感謝");
Move(oAuth2Client, tmp_change[user]['hId'], tmpFolder, picFolder)
delete tmp_change[user];
}
else if (toDo == "save:"){
event.reply("感謝");
await Move(oAuth2Client, tmp_change[user]['hId'], tmpFolder, picFolder)
delete tmp_change[user];
}
else if (mesg == "查看圖片"){
sendPicture(event);
return
}
//民眾
else if(mesg == "answ:"){
reply = platform.qs[++the_record.qNum];
}
})
//reply
bot.on('message', function (event) {
//new user
var user = event.source.userId;
if (!(user in tmp_records) && !(user in tmp_change)){
tmp_records[user] = new Record(user);
//prepare dir
var dir = './tmp/' + user;
if (!fs.existsSync(dir))
fs.mkdirSync(dir);
}
//the record for this user
the_record = tmp_records[user];
//reply
if (event.message.type=="text"){
var mesg = event.message.text;
var reply = "";
if(user in tmp_change){
if(mesg.substr(0, 6)=='result'){
var f = mesg.split("_");
updateSql(f, event)
}
return
}
if(mesg.substr(0, 5) == "test:"){
id = Number(mesg.substr(5))
console.log('111');
var result = getData(event, id);
return
}
if(the_record.qNum < total_qNum){
switch(the_record.qStatu){
case -1:
reply = platform.askLocation;
break;
case 2:
if(mesg == "確定"){
if(++the_record.qNum == total_qNum){
reply = platform.qs[the_record.qNum];
break;
}
}
case 1:
the_record.data[the_record.qNum] = parseInt(mesg);
if(platform.constrains[the_record.qNum](the_record.data[the_record.qNum])){
reply = "確認為" + the_record.data[the_record.qNum].toString();
reply = platform.getYesNo(reply, "確定" , "重新輸入");
the_record.qStatu = 2;
break;
}
case 0:
reply = platform.qs[the_record.qNum];
the_record.qStatu = 1;
break;
}
console.log(the_record.data);
}
// 拍照模式
else if (the_record.qNum == total_qNum){
if (the_record.qStatu < 3)
reply = "請按照上面指示> <";
else{
switch(mesg){
case "繼續記錄":
the_record.qNum = 2;
reply = platform.qs[the_record.qNum];
the_record.qStatu = 2;
break;
case"結束":
reply = "謝謝><";
WriteDB(the_record);
delete tmp_records[user];
break;
default:
reply = platform.getYesNo("紀錄其他裂化現象?", "繼續記錄" , "結束")
}
}
}
event.reply(reply);
}
else if (event.message.type == "image"){
if((user in tmp_change) && tmp_change[user].picId >= 0){
console.log('get img');
//prepare path
var dir = './tmp/' + user;
var file_path = dir + '/';
file_path += 'tmp.png'
//get image and save
client.getMessageContent(event.message.id).then((stream) => {
f = fs.createWriteStream(file_path);
stream.on('data', (chunk) => {
f.write(chunk);
});
stream.on('end',()=>{
f.end();
Update(oAuth2Client, tmp_change[user], file_path, event)
});
});
}
if(the_record.qNum != total_qNum)
return;
//prepare path
var dir = './tmp/' + user;
var file_path = dir + '/';
for(let i = 2; i <= total_qNum; i++)
file_path += the_record.data[i].toString() + '_';
the_record.data[total_qNum] += 1;
file_path += '.png'
//get image and save
client.getMessageContent(event.message.id).then((stream) => {
f = fs.createWriteStream(file_path);
stream.on('data', (chunk) => {
f.write(chunk);
});
stream.on('end',()=>{
f.end();
});
});
//reply & change statu
if(the_record.qStatu == 2){
reply = '請再拍一張近照';
the_record.qStatu = 1;
} else{
reply = platform.getYesNo("紀錄其他裂化現象?", "繼續記錄" , "結束")
the_record.qStatu = 3;
}
event.reply(reply);
}
//get location
else if (event.message.type == "location"){
the_record.lat = event.message.latitude;
the_record.lon = event.message.longitude;
the_record.address = event.message.address;
the_record.qStatu = 1;
event.reply(platform.qs[the_record.qNum]);
}
console.log(the_record);
});
//follow event
bot.on('follow', (event)=>{
event.reply(platform.getYesNo("是否開始檢測", "開始檢測", "取消"));
})
//listen
var app = express();
var linebotParser = bot.parser();
app.post('/', linebotParser);
var server = https.createServer(options, app).listen(port, function() {
console.log(`port: ${port}`);
})
//write database & upload images & delete local images
function WriteDB(the_record){
connection.query('select count(id) from record', function (error, results, fields) {
if (error) throw error
var num = results[0]['count(id)'];
connection.query(`INSERT INTO record(lineId, id) VALUES ("${the_record.id}", ${num});`);
connection.query(`INSERT INTO location(id, lat, lng, statu, address) VALUES (${num}, ${the_record.lat}, ${the_record.lon}, '1', '${the_record.address}');`);
UploadFolder(oAuth2Client, num.toString(), num, the_record);
})
}
function Update(auth, changing, path, event){
const drive = google.drive({version: 'v3', auth});
console.log('update')
console.log(changing)
var fileMetadata = {
'name': changing.picId + ".jpg",
parents: [changing.fId]
};
var media = {
mimeType: 'image/jpg',
body: fs.createReadStream(path)
};
drive.files.create({
resource: fileMetadata,
media: media,
fields: 'id'
}, async function (err, file) {
if (err)
console.error(err);
else{
console.log('hihi');
await sqlpromise (`UPDATE crack SET fileId = '${file.data.id}' where id = ${changing.hId} and picId = ${changing.picId}`);
sendpicture(event);
fs.unlinkSync(path);
}
});
}
function Upload(drive, folderId, path, filename, houseId){
var f = filename.split("_");
var fileMetadata = {
'name': f[4] + ".jpg",
parents: [folderId]
};
var media = {
mimeType: 'image/jpg',
body: fs.createReadStream(path + filename)
};
drive.files.create({
resource: fileMetadata,
media: media,
fields: 'id'
}, function (err, file) {
if (err)
console.error(err);
else{
var cT = (f[3] > 2)? f[3] - 3 : f[3];
cT = 1 << cT;
var info = (f[3] > 2)? 1 : 0;
info = info << (f[3] - 3)
var sqlins = 'INSERT INTO crack (id, picId, floor, spaceType, crackPart, crackType, info, fileId)' +
`VALUES (${houseId}, ${f[4]}, ${f[0]}, ${f[1]}, ${f[2]},${cT}, ${info}, '${file.data.id}');`;
connection.query(sqlins);
fs.unlinkSync(path + filename);
}
});
}
function UploadFolder(auth, folder, num, the_record){
const drive = google.drive({version: 'v3', auth});
var fileMetadata = {
'name': folder,
parents:[picFolder],
mimeType: 'application/vnd.google-apps.folder'
};
drive.files.create({
resource: fileMetadata,
fields: 'id'
}, function (err, file) {
if (err)
console.error(err);
else {
var folderId = file.data.id;
var path = './tmp/' + the_record['id'] + '/'
connection.query(`INSERT INTO house(id, age, total_floor, folderId) VALUES (${num}, ${the_record.data[0]}, ${the_record.data[1]}, '${folderId}');`);
fs.readdirSync(path).forEach(file => {
Upload(drive, folderId, path, file, Number(folder));
});
}
});
}
function SearchFolder(auth, folder){
const drive = google.drive({version: 'v3', auth});
var pageToken = null;
async.doWhilst(function (callback) {
drive.files.list({
q: `'1GGxFX7j3d3x9GEDY2ihlBAWEQHYVXf0l' in parents and mimeType='application/vnd.google-apps.folder' and name='${folder}'`,
fields: 'nextPageToken, files(id, name)',
spaces: 'drive',
pageToken: pageToken
}, function (err, res) {
if (err) {
// Handle error
console.error(err);
callback(err)
} else {
res.data.files.forEach(function (file) {
console.log('Found file: ', file.name, file.id);
});
pageToken = res.nextPageToken;
callback();
}
});
}, function () {
return !!pageToken;
}, function (err) {
if (err) {
console.error(err);
} else {
// All pages fetched
}
})
}
function Move( auth, hId, folderForm, folderIdTo){
const drive = google.drive({version: 'v3', auth});
const house = await sqlpromise(`select * from house, location where house.id=location.id and house.id = ${hId}`);
drive.files.update({
fileId: house[0]['folderId'],
addParents: folderIdTo,
removeParents: folderForm,
fields: 'id, parents'
}, function (err, file) {
if (err) {
} else {
// File moved.
}
});
}
async function getData(event, id) {
const house = await sqlpromise(`select * from house, location where house.id=location.id and house.id = ${id}`);
if (house.length < 1)
return false;
console.log(house)
var user = event.source.userId;
if (!(user in tmp_change)){
tmp_change[user] = new Changing(user, id, house[0].folderId);
//prepare dir
var dir = './tmp/' + user;
if (!fs.existsSync(dir))
fs.mkdirSync(dir);
}
const c_num = await sqlpromise(`select count(picId) from crack where id = ${id}`);
var reply = `總樓層: ${house[0]['total_floor']}\n`;
reply += `劣化紀錄: ${c_num[0]['count(picId)']>>1}筆`;
question = platform.houseInfo(reply);
await Move(oAuth2Client, id, picFolder, tmpFolder)
event.reply(question);
return true;
}
async function updateSql(f, event){
var sqlins = `UPDATE crack SET crackType=${f[3]}, info=${f[4]},crackPart=${f[5]},crcakCorner=${f[6]},`
+`x=${f[7]},y=${f[8]},length=${f[9]},width=${f[10]} where id = ${f[1]} and picId = ${f[2]}`;
await sqlpromise(sqlins);
var sqlins = `UPDATE crack SET crackType=${f[3]}, info=${f[4]},crackPart=${f[5]},crcakCorner=${f[6]},`
+`x=${f[7]},y=${f[8]},length=${f[9]},width=${f[10]} where id = ${f[1]} and picId = ${++f[2]}`;
await sqlpromise(sqlins);
sendPicture(event)
}
async function sendPicture(event){
var user = event.source.userId;
var crack = await sqlpromise(`select * from crack where id = '${tmp_change[user].hId}' order by picId asc `);
event.reply(platform.sendPic(crack));
}
function sqlpromise (ins) {
return new Promise((resolve, reject) => {
connection.query(ins, (error, results, fields) => {
if (error) reject(error);
resolve(results);
})
})
}
|
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'
import Home from './components/home.vue'
import Search from './components/search.vue'
Vue.use(VueRouter);
//定义路由
const routes = [
{
path:'/',
component:Home
},
{
path:'/home',
component:Home
},{
path:'/search',
component:Search
}
];
//创建router实例,然后穿routes配置
const router = new VueRouter({
routes:routes
});
//创建和挂载根实例,要通过router配置参数注入路由
new Vue({
router,
render: h => h(App)
}).$mount('#app');
|
import ChatActions from './chat-actions'
import ChatMessage from './chat-message'
import Container from './container'
import CountryPicker from './country-picker'
import CurrencyPicker from './currency-picker'
import DateFilter from './date-filter'
import DatetimePicker from './datetime-picker'
import EditRow from './edit-row'
import FilterButton from './filter-button'
import GameItem from './game-item'
import InfoRow from './info-row'
import Loader from './loader'
import LocationDialog from './location-dialog'
import ModalHeader from './modal-header'
import NotesPicker from './notes-picker'
import NumberPicker from './number-picker'
import JoChat from './jo-chat'
import PlacePicker from './place-picker'
import PlayersList from './players-list'
import PlayersPicker from './players-picker'
import PriceFilter from './price-filter'
import PricePicker from './price-picker'
import SportFilter from './sport-filter'
import SportPicker from './sport-picker'
import Toast from './toast'
export {
ChatActions,
ChatMessage,
Container,
CountryPicker,
CurrencyPicker,
DateFilter,
DatetimePicker,
EditRow,
FilterButton,
GameItem,
InfoRow,
Loader,
LocationDialog,
ModalHeader,
NotesPicker,
NumberPicker,
JoChat,
PlacePicker,
PlayersList,
PlayersPicker,
PriceFilter,
PricePicker,
SportFilter,
SportPicker,
Toast,
}
|
new Vue({
methods: {
el: "txt1",
submit: function () {
alert("点击了");
}
}
})
|
var path = require('path'); //根路径
var webpack = require('webpack'); //webpack模块
var HtmlWebpackPlugin = require('html-webpack-plugin'); //webpack html 打包模块
var node_modules = path.resolve(__dirname, '../node_modules'); //node包模块
var basepath = __dirname + '/../doc/src/'; //源码路径
var config = {
entry:{
"index" : [basepath+'app.js'], //入口文件
"common":['vue', 'vue-router'], //vue全家桶公共引入
"polyfill": ['babel-polyfill'], //补全es6原生对象
},
output: {
path: path.join(__dirname,'../doc/dist/'), //构建目录
//filename: '[name].[chunkhash:8].js' //文件名规则 [name]表示 和 入口一致
filename: '[name].js'
},
module: {
// preLoaders: [
// {
// test: /\.js$/,
// exclude: /node_modules/,
// loader: 'eslint-loader'
// },
// ],
loaders: [
{ //对大于6000字节 的图片采取base64处理
test: /\.(png|jpg|gif)$/,
loader: 'url?limit=6000'
},{
test: /\.css$/, //css 加载器
loader: 'style-loader!css-loader'
},{
test: /\.js$/, //js 加载器
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015'] //转换 es6编码为 es5
}
}, {
test: /\.vue$/, //vue 模板加载器
loader: 'vue-loader'
},
{ test: /\.less$/, loaders: [ 'style', 'css', 'less' ] }
]
},
babel: {
presets: ['es2015'],
plugins: ['transform-runtime']
},
resolve: {
//配置别名,在项目中可缩减引用路径
alias: {
'util' : __dirname+ '/../src/utils/util.js',
'vue' : path.resolve(node_modules, 'vue/dist/vue.common.js')
}
},
plugins: [
//提供全局的变量,在模块中使用无需用require引入
new webpack.ProvidePlugin({
util:__dirname + '/../src/utils/util.js',
}),
// new webpack.LoaderOptionsPlugin({
// minimize: true,
// debug: false,
// options: {
// context: __dirname
// }
// }),
//将公共代码抽离出来合并为一个文件
new webpack.optimize.CommonsChunkPlugin({name:['common'],minChunks:Infinity}),
new HtmlWebpackPlugin({ //根据模板插入css/js等生成最终HTML
//favicon:'src/favicon.ico', //favicon路径
filename:'index.html', //生成的html存放路径,相对于 path
template:basepath + 'index.html', //html模板路径
inject:true, //允许插件修改哪些内容,包括head与body
//hash:true, //为静态资源生成hash值
minify:{ //压缩HTML文件
removeComments:true, //移除HTML中的注释
collapseWhitespace:false //删除空白符与换行符
}
})
]
};
module.exports = config;
|
import gridCore from './ui.data_grid.core';
import { errorHandlingModule } from '../grid_core/ui.grid_core.error_handling';
gridCore.registerModule('errorHandling', errorHandlingModule);
|
// 初始化
export const INIT = 'INIT';
// 初始化 缓存的历史记录
export const INITTALIZE_HISTORY ='INITTALIZE_HISTORY';
// 登录
export const SIGN_IN = 'SIGN_IN';
//播放
export const PLAY = 'PLAY';
export const PAUSE = 'PAUSE';
// 正在播放的音乐
export const PLAY_SONGS = 'PLAY_SONGS';
// 百分比进度
export const PERCENTAGE = 'PERCENTAGE';
// 播放歌曲总时间长度
export const TOTAL_TIME = 'TOTAL_TIME';
// 现在播放的时间
export const CURRENT_TIME = 'CURRENT_TIME';
// 改变播放进度
export const CHANGE_SCHEDULE = 'CHANGE_SCHEDULE';
// 下一首
export const NEXT_SONG = 'NEXT_SONG';
// 上一首
export const PREVIOUS_SONG ='PREVIOUS_SONG';
// 播放图片加载
export const SONG_PIC_LOAD = 'SONG_PIC_LOAD';
// 收藏
export const COLLECTION = 'COLLECTION';
// 取消收藏
export const CANCEL_COLLECTION = 'CANCEL_COLLECTION';
// 更新加载进度
export const UPDATA_LOAD_PROGRESS = 'UPDATA_LOAD_PROGRESS';
|
const User = require('../models/User');
class LoginController {
// async store(req, res) {
// const login = await Login.create(req.body);
// return res.json(login);
// }
async show(req, res) {
console.log(req.query);
const login = await User.findOne({ username: req.query.username,
password: req.query.password });
console.log(login)
return res.json(login);
}
}
module.exports = new LoginController();
|
import React from 'react';
import DataLineIcon from './DataLineIcon';
import "./Decision.css";
class ProductDataFactory extends React.Component {
constructor(props){
super(props)
}
render() {
return (
<div className="GroupOfDecisions">
<h3 className="HeadlineDecision">הרחבה</h3>
<DataLineIcon ValueOfField={this.props.ExpendLevOne} Datatext={"הרחבה שלב 1"} handleChange={this.props.handleChange} name={"ExpendLevOne"} SerialNum={19} iconText={'time'}/>
<DataLineIcon ValueOfField={this.props.ExpendLevTwo} Datatext={"הרחבה שלב 2"} handleChange={this.props.handleChange} name={"ExpendLevTwo"} SerialNum={20} iconText={'time'}/>
<DataLineIcon ValueOfField={this.props.EngineringResearch} Datatext={"מחקר הנדסי"} handleChange={this.props.handleChange} name={"EngineringResearch"} SerialNum={21} iconText={'dollar'}/>
</div>
)
}
}
export default ProductDataFactory;
|
import React from "react";
import Avatar from "@material-ui/core/Avatar";
import Button from "@material-ui/core/Button";
import CssBaseline from "@material-ui/core/CssBaseline";
import TextField from "@material-ui/core/TextField";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import Checkbox from "@material-ui/core/Checkbox";
import Link from "@material-ui/core/Link";
import Paper from "@material-ui/core/Paper";
import Box from "@material-ui/core/Box";
import Grid from "@material-ui/core/Grid";
import LockOutlinedIcon from "@material-ui/icons/LockOutlined";
import Typography from "@material-ui/core/Typography";
import { createMuiTheme } from "@material-ui/core/styles";
import { withStyles } from "@material-ui/core";
import { withRouter } from "react-router-dom";
import BaseComponent from "core/BaseComponent/BaseComponent";
import { sensitiveStorage } from "core/services/SensitiveStorage";
import imageBackground from "assets/img/login.png";
import { UserRole } from "core/Enum";
function Copyright() {
return (
<Typography variant="body2" color="textSecondary" align="center">
{"Copyright © "}
<Link color="inherit" href="https://material-ui.com/">
Roll Call System
</Link>{" "}
{new Date().getFullYear()}
{"."}
</Typography>
);
}
const useStyles = (theme) => ({
root: {
height: "100vh",
},
image: {
backgroundImage: `url(${imageBackground})`,
backgroundRepeat: "no-repeat",
backgroundColor:
theme.palette.type === "light"
? theme.palette.grey[50]
: theme.palette.grey[900],
backgroundSize: "cover",
backgroundPosition: "center",
},
paper: {
margin: theme.spacing(8, 4),
display: "flex",
flexDirection: "column",
alignItems: "center",
},
avatar: {
margin: theme.spacing(1),
backgroundColor: theme.palette.secondary.main,
},
form: {
width: "100%", // Fix IE 11 issue.
marginTop: theme.spacing(1),
},
submit: {
margin: theme.spacing(3, 0, 2),
},
backdrop: {
zIndex: theme.zIndex.drawer + 1,
color: "#fff",
},
});
class Login extends BaseComponent {
constructor(props) {
super(props);
this.state = {
username: "",
password: "",
error: false,
errorMessage: "",
isRemember: false,
};
}
componentDidMount() {
document.addEventListener("keypress", this.handleKeyEnter);
this._checkLogin();
}
componentWillUnmount() {
document.removeEventListener("keypress", this.handleKeyEnter);
}
handleKeyEnter = (e) => {
const { username, password, isRemember } = this.state;
if (username != "" && password != "" && e.keyCode == 13) {
this._onClickLogin();
}
};
_error = (message) => {
if (typeof message == "string") {
this.setState({
error: true,
errorMessage: message,
});
} else {
this.setState({
error: false,
errorMessage: "",
});
}
};
_onClickLogin = () => {
console.log("login");
const { username, password, isRemember } = this.state;
if (username == "" || password == "") {
this._error("username và password không được để trống!");
return;
}
let loginInfor = {
username: username,
password: password,
isRemember: isRemember,
};
this.ajaxPost({
url: "/api/account/login",
data: loginInfor,
blockUI: true,
success: (apiResult) => {
this.login(apiResult);
},
unsuccess: (apiResult) => {
this.error(apiResult.messages[0]);
},
});
};
_hanldeOnchangeUserName = (e) => {
this.setState({
username: e.target.value,
});
};
_hanldeOnChangePassword = (e) => {
this.setState({
password: e.target.value,
});
};
_hanledRemember = (e) => {
this.setState({
isRemember: !this.state.isRemember,
});
};
_checkLogin = () => {
const userId = sensitiveStorage.getUserId();
const userRole = sensitiveStorage.getUserRole();
if (userId && userRole == UserRole.teacher) {
this.goTo("/teacher/teaching-schedule");
} else if (userId && userRole == UserRole.student) {
this.goTo("/student/subject");
} else {
sensitiveStorage.removeUserId();
sensitiveStorage.removeUserRole();
sensitiveStorage.removeStudentId();
sensitiveStorage.removeTeacherId();
}
};
renderBody() {
const { classes } = this.props;
return (
<Grid container component="main" className={classes.root}>
<CssBaseline />
<Grid item xs={false} sm={4} md={7} className={classes.image} />
<Grid item xs={12} sm={8} md={5} component={Paper} elevation={6} square>
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Đăng nhập
</Typography>
<form className={classes.form} noValidate>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="email"
label="Tài khoản"
name="username"
autoComplete="email"
value={this.state.username}
onChange={(e) => this._hanldeOnchangeUserName(e)}
autoFocus
/>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label="Mật khẩu"
type="password"
id="password"
autoComplete="current-password"
value={this.state.password}
onChange={(e) => this._hanldeOnChangePassword(e)}
/>
<FormControlLabel
control={
<Checkbox
value={this.state.isRemember}
onChange={(e) => this._hanledRemember(e)}
color="primary"
/>
}
label="Ghi nhớ"
/>
{this.state.error ? (
<Typography color="error">{this.state.errorMessage}</Typography>
) : null}
<Button
onClick={this._onClickLogin}
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
Đăng nhập
</Button>
<Grid container>
<Grid item xs>
<Link href="#" variant="body2">
Quên mật khẩu ?
</Link>
</Grid>
</Grid>
<Box mt={5}>
<Copyright />
</Box>
</form>
</div>
</Grid>
</Grid>
);
}
}
export default withRouter(withStyles(useStyles)(Login));
|
(function() {
angular
.module('loc8rApp')
.service('pharmaDetails', pharmaDetails);
pharmaDetails.$inject = ['$http'];
function pharmaDetails ($http) {
var getPharmacogenomicDetails = function (profile_id, offset, limit) {
return $http.get('/api/getPharmacogenomicDetails?profile_id=' + profile_id);
};
return {
getPharmacogenomicDetails : getPharmacogenomicDetails
};
}
})();
|
var searchData=
[
['o_5fnofollow',['O_NOFOLLOW',['../file_8c.html#a82d4d551b214905742c9e045185d352a',1,'file.c']]],
['op',['OP',['../md5_8c.html#a6945bb408d7121af76c8886e25c90ad5',1,'OP(): md5.c'],['../md5_8c.html#af765a46d94e72e053fe0fd44d48f5911',1,'OP(): md5.c']]],
['ops',['OPS',['../opcodes_8h.html#a793497c19233c0cb263fb0f29b3f1f8a',1,'opcodes.h']]],
['ops_5fautocrypt',['OPS_AUTOCRYPT',['../opcodes_8h.html#ae3f5f30e23125c206c53581d239b9143',1,'opcodes.h']]],
['ops_5fcore',['OPS_CORE',['../opcodes_8h.html#a02f0daf9d5f73550e2978678f8ada319',1,'opcodes.h']]],
['ops_5fcrypt',['OPS_CRYPT',['../opcodes_8h.html#a10dc02264bc5e92c86f14516e6165760',1,'opcodes.h']]],
['ops_5fmix',['OPS_MIX',['../opcodes_8h.html#a17de7be8a7158e9b62c2ad34c619a4d1',1,'opcodes.h']]],
['ops_5fnotmuch',['OPS_NOTMUCH',['../opcodes_8h.html#afbe0451583de35d909258d05fbe374e5',1,'opcodes.h']]],
['ops_5fpgp',['OPS_PGP',['../opcodes_8h.html#a6e9b2ac2bb205f8c5ce71d5196404aca',1,'opcodes.h']]],
['ops_5fsidebar',['OPS_SIDEBAR',['../opcodes_8h.html#a5eae12cf8a02208854009b63647ee655',1,'opcodes.h']]],
['ops_5fsmime',['OPS_SMIME',['../opcodes_8h.html#ab16cda2c4e8f6d8ac2e75f7f16805c53',1,'opcodes.h']]]
];
|
'use strict';
var path = require('path');
module.exports = function(grunt) {
// Project configuration
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
mustache_mustache: {
files: 'views/**/*.mustache',
task: [ 'mustache_mustache' ]
},
express: {
options: {
// Override defaults here
},
dev: {
options: {
script: 'app.js'
}
}
},
watch: {
options: {
livereload: true,
},
mustache_mustache: {
files: 'views/**/*.mustache',
tasks: [ 'mustache_mustache' ],
options: {
livereload: true,
spawn: false
}
},
express: {
files: [ 'app.js', 'routes.js' ],
tasks: [ 'express:dev' ],
options: {
livereload: true,
spawn: false
}
}
}
});
// Load the plugin that provides the 'express' task
[
'grunt-mustache-mustache',
'grunt-express-server',
'grunt-contrib-watch'
].forEach(function (task) {
grunt.loadNpmTasks(task);
});
// Default task(s)
grunt.registerTask('default', [
'mustache_mustache',
'express:dev',
'watch'
]);
};
|
import React from "react";
import { Provider } from "react-redux";
import configureMockStore from "redux-mock-store";
import Adapter from "enzyme-adapter-react-16";
import { mount, shallow, configure } from "enzyme";
import expect from "expect";
import App from "./index";
import Header from "../../components/Header";
const mockStore = configureMockStore();
configure({ adapter: new Adapter() });
describe("<App/>", () => {
let store;
beforeEach(() => {
store = configureMockStore()({
list: {
items: [],
loading: true
}
});
});
describe("render()", () => {
it("renders without crashing", () => {
const component = shallow(
<Provider store={store}>
<App />
</Provider>
);
expect(component.toJSON()).toMatchSnapshot();
});
it("renders header", () => {
const component = mount(
<Provider store={store}>
<App />
</Provider>
);
expect(component.find(Header)).to.have.lengthOf(1);
});
});
});
|
dojo.provide("dojox.encoding.tests.digests._base");
dojo.require("dojox.encoding.digests._base");
try{
dojo.require("dojox.encoding.tests.digests.MD5");
}catch(e){
doh.debug(e);
}
|
import TextEmphasis from "../src/index"
import stripLeadingWhitespace from "../utils/stripLeadingWhitespace"
describe("basics", () => {
it("simple", () => {
document.body.innerHTML = stripLeadingWhitespace`
<p>
こうやって<em>圏点を打つ</em>。
</p>
`
new TextEmphasis({
selector: "em",
})
const p = document.querySelector("p")
expect(p.outerHTML).toEqual(
stripLeadingWhitespace`
<p>こうやって
<em>
<ruby class="js-textEmphasis-ruby" aria-label="圏点を打つ">
<rb aria-hidden="true">圏</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>
<rb aria-hidden="true">点</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>
<rb aria-hidden="true">を</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>
<rb aria-hidden="true">打</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>
<rb aria-hidden="true">つ</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>
</ruby>
</em>。
</p>
`,
)
})
it("include whitespaces", () => {
document.body.innerHTML = "<p>こうやって<em>圏\t点 を 打つ</em>。</p>"
new TextEmphasis({
selector: "em",
})
const p = document.querySelector("p")
expect(p.outerHTML).toEqual(
'<p>こうやって' +
'<em>' +
'<ruby class="js-textEmphasis-ruby" aria-label="圏">' +
'<rb aria-hidden="true">圏</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>' +
'</ruby>' +
'\t' +
'<ruby class="js-textEmphasis-ruby" aria-label="点">' +
'<rb aria-hidden="true">点</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>' +
'</ruby>' +
' ' +
'<ruby class="js-textEmphasis-ruby" aria-label="を">' +
'<rb aria-hidden="true">を</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>' +
'</ruby>' +
' ' +
'<ruby class="js-textEmphasis-ruby" aria-label="打つ">' +
'<rb aria-hidden="true">打</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>' +
'<rb aria-hidden="true">つ</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>' +
'</ruby>' +
'</em>。' +
'</p>'
)
})
it("nested", () => {
document.body.innerHTML = stripLeadingWhitespace`
<p>
こうやって<em><span>圏点</span>を打つ</em>。
</p>
`
new TextEmphasis({
selector: "em",
})
const p = document.querySelector("p")
expect(p.outerHTML).toEqual(
stripLeadingWhitespace`
<p>こうやって
<em>
<span>
<ruby class="js-textEmphasis-ruby" aria-label="圏点">
<rb aria-hidden="true">圏</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>
<rb aria-hidden="true">点</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>
</ruby>
</span>
<ruby class="js-textEmphasis-ruby" aria-label="を打つ">
<rb aria-hidden="true">を</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>
<rb aria-hidden="true">打</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>
<rb aria-hidden="true">つ</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>
</ruby>
</em>。
</p>
`,
)
})
it("deep nested", () => {
document.body.innerHTML = stripLeadingWhitespace`
<p>
こうやって<em><span><a href=""><i>圏</i>点</a></span>を打つ</em>。
</p>
`
new TextEmphasis({
selector: "em",
})
const p = document.querySelector("p")
expect(p.outerHTML).toEqual(
stripLeadingWhitespace`
<p>こうやって
<em>
<span>
<a href="">
<i>
<ruby class="js-textEmphasis-ruby" aria-label="圏">
<rb aria-hidden="true">圏</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>
</ruby>
</i>
<ruby class="js-textEmphasis-ruby" aria-label="点">
<rb aria-hidden="true">点</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>
</ruby>
</a>
</span>
<ruby class="js-textEmphasis-ruby" aria-label="を打つ">
<rb aria-hidden="true">を</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>
<rb aria-hidden="true">打</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>
<rb aria-hidden="true">つ</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>
</ruby>
</em>。
</p>
`,
)
})
it("nested target", () => {
document.body.innerHTML = stripLeadingWhitespace`
<p>
こうやって<em><em>圏点</em>を打つ</em>。
</p>
`
new TextEmphasis({
selector: "em",
})
const p = document.querySelector("p")
expect(p.outerHTML).toEqual(
stripLeadingWhitespace`
<p>こうやって
<em>
<em>
<ruby class="js-textEmphasis-ruby" aria-label="圏点">
<rb aria-hidden="true">圏</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>
<rb aria-hidden="true">点</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>
</ruby>
</em>
<ruby class="js-textEmphasis-ruby" aria-label="を打つ">
<rb aria-hidden="true">を</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>
<rb aria-hidden="true">打</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>
<rb aria-hidden="true">つ</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>
</ruby>
</em>。
</p>
`,
)
})
it("with ruby", () => {
document.body.innerHTML = stripLeadingWhitespace`
<p>
こうやって<em><ruby>圏点<rp>(</rp><rt>けんてん</rt><rp>)</rp></ruby>を打つ</em>。
</p>
`
new TextEmphasis({
selector: "em",
})
const p = document.querySelector("p")
expect(p.outerHTML).toEqual(
stripLeadingWhitespace`
<p>こうやって
<em>
<ruby>
圏点<rp>(</rp><rt>けんてん</rt><rp>)</rp>
</ruby>
<ruby class="js-textEmphasis-ruby" aria-label="を打つ">
<rb aria-hidden="true">を</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>
<rb aria-hidden="true">打</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>
<rb aria-hidden="true">つ</rb><rt class="js-textEmphasis-rt" aria-hidden="true">•</rt>
</ruby>
</em>。
</p>
`,
)
})
})
|
import React, {Component} from "react";
import {connect} from "react-redux";
import {
acceptRequest,
fetchInComingRequest,
fetchPendingRequests,
rejectRequest
} from "../actions/friendsRequestsActions";
import PendingRequest from "../components/PendingRequest";
import InComingRequest from "../components/InComingRequest";
class ManageRequestsPage extends Component {
state = {
content: ''
};
componentDidMount() {
this.props.handleFetchPendingRequests();
this.props.handleFetchInComingRequest();
}
render() {
let {pendingRequests, inComingRequest} = this.props;
return (
<div>
<InComingRequest inComingRequest={inComingRequest}
onAcceptRequest={this.props.handleAcceptRequest}
onRejectRequest={this.props.handleRejectRequest}/>
<PendingRequest pendingRequests={pendingRequests}/>
</div>
);
}
}
ManageRequestsPage.propTypes = {};
const mapStateToProps = ({pendingRequests, inComingRequest}) => {
return {
pendingRequests,
inComingRequest
};
};
function mapDispatchToProps(dispatch) {
return ({
handleFetchPendingRequests: () => {
dispatch(fetchPendingRequests());
},
handleFetchInComingRequest: () => {
dispatch(fetchInComingRequest());
},
handleAcceptRequest: (id, email) => {
dispatch(acceptRequest(id, email));
},
handleRejectRequest: (id, email) => {
dispatch(rejectRequest(id, email));
}
})
}
export default connect(mapStateToProps, mapDispatchToProps)(ManageRequestsPage);
|
const next_btn = document.querySelector('#next')
const prev_btn = document.querySelector('#prev')
const slider = document.querySelector('.slider')
let first_slide
let last_slide
var slidertimer = setInterval(TimerHandler, 8000);
let projects = [
{
title: "2019/2020 VIRTUAL MATRICULATION CEREMONY",
type: "Matriculation Ceremony",
content: "Matriculation ceremony for 2019/2020 session holds virtually. Date: Tuesday 15, 2020. Time: 10:00 AM",
image: "./assets/images/slider/matric_virtual_slider.jpg",
link: "https://news.uniben.edu/index.php/2020/09/12/watch-live2019-2020-virtual-matriculation-ceremony/",
linktitle: "Click Here to Link Up"
},
{
title: "Welcome",
type: "University of Benin",
content: "Welcome to The University of Benin",
image: "./assets/images/slider/UNIBEN_NEW_LOOK.jpeg",
link: "#",
linktitle: "Click to Read More"
},
{
title: "2020/2021 ADMISSION SCREENING EXERCISE",
type: "Application",
content: "Apply Now to study at UNIBEN",
image: "./assets/images/slider/matriculating students.JPG",
link: "https://news.uniben.edu/index.php/2020/08/17/2020-2021-admission-screening-exercise/",
linktitle: "Click Here to Read More"
},
{
title: "The First of Many to Come",
type: "Ongoing Major Projects",
content: "TETFUND COMMENCES CONSTRUCTION OF 28-EXECUTIVE-ROOM INTERNATIONAL HOSTEL",
image: "./assets/images/slider/tetfund hostel project.jpeg",
link: "https://news.uniben.edu/index.php/2020/07/10/tetfund-commences-construction-of-28-executive-room-international-hostel-at-uniben/",
linktitle: "Click to Read More"
},
{
title: "Uniben Orientation",
type: "New Students",
content: "We welcome our new Students",
image: "./assets/images/slider/2.jpg",
link: "#",
linktitle: "Click to Read More"
},
{
title: "2019/2020 Convocation",
type: "Graduating Students",
content: "Our students are preprared to serve humanity",
image: "./assets/images/slider/3.jpg",
link: "#",
linktitle: "Click to Read More"
},
{
title: "Uniben sets the pace",
type: "Serene Environment",
content: "The University environment is conducive for learning",
image: "./assets/images/slider/4.jpg",
link: "#",
linktitle: "Click to Read More"
}
]
projects.forEach(({title, type, content, image, link, linktitle}, i) => {
const slide = document.createElement('div');
slide.classList.add('slider__slide')
slide.style.backgroundImage = "url('" + image + "')"
if (i == 0) {
first_slide = slide
slide.classList.add('active')
} else if (i + 1 == projects.length) {
last_slide = slide
}
const content_link = document.createElement('a')
content_link.href = link; // Insted of calling setAttribute
content_link.innerHTML = linktitle // <a>INNER_TEXT</a>
content_link.classList.add("secondary-menu-link")
content_link.classList.add("secondary-menu-link-slider")
const space_slider1 = document.createElement('div')
space_slider1.innerHTML = '<br>'
const slide_content = document.createElement('div')
slide_content.classList.add('slider__content')
const content_title = document.createElement('h3')
content_title.classList.add('slider__title')
content_title.textContent = title
const content_type = document.createElement('span')
content_type.textContent = type
const content_content = document.createElement('div')
content_content.classList.add('slider__desc')
content_content.textContent = content
content_title.appendChild(content_type)
slide_content.appendChild(content_title)
slide_content.appendChild(content_content)
slide_content.appendChild(space_slider1)
if (link != '#') {
slide_content.appendChild(content_link)
}
slide.appendChild(slide_content)
slider.appendChild(slide)
})
next_btn.addEventListener('click', () => {
const active_slide = document.querySelector('.slider__slide.active')
let nextSibling = active_slide.nextElementSibling
if (nextSibling == null) {
nextSibling = first_slide
}
if (nextSibling.classList.contains('slider__slide')) {
active_slide.classList.remove('active')
nextSibling.classList.add('active')
}
})
prev_btn.addEventListener('click', () => {
const active_slide = document.querySelector('.slider__slide.active')
let nextSibling = active_slide.previousElementSibling
if (nextSibling == null || !nextSibling.classList.contains('slider__slide')) {
nextSibling = last_slide
}
if (nextSibling.classList.contains('slider__slide')) {
active_slide.classList.remove('active')
nextSibling.classList.add('active')
}
})
function TimerHandler () {
const active_slide = document.querySelector('.slider__slide.active')
let nextSibling = active_slide.nextElementSibling
if (nextSibling == null) {
nextSibling = first_slide
}
if (nextSibling.classList.contains('slider__slide')) {
active_slide.classList.remove('active')
nextSibling.classList.add('active')
}
}
|
import React, { useContext, useState } from 'react';
import { useHistory } from 'react-router-dom';
import { UserContext } from './../../contexts/UserContext';
import Button from './../UI/Button';
import classes from './WelcomePage.module.css';
import video from './../../welcomeVideo.mp4';
const WelcomePage = () => {
const history = useHistory();
const auth = useContext(UserContext);
const [user, setUser] = useState();
setTimeout(() => {
if (auth.user) {
history.push('/room/new');
}
}, 1000);
const signInHandler = () => {
setUser(auth.signIn());
if (auth.user) history.push('/room/new');
};
return (
<div className={classes['main']}>
<video autoPlay loop muted>
<source src={video} />
</video>
<div className={classes['content-container']}>
<h1>Watchparty</h1>
<p>
<span className={classes['highlight']}>Lorem ipsum</span> dolor sit
amet{' '}
<span className={classes['highlight']}>
consectetur adipisicing elit.
</span>{' '}
Ex, ad cum sapiente reiciendis voluptate.
</p>
<div className={classes['sign-in']}>
<div onClick={signInHandler}>
<Button className={classes['btn-home']}>
<i className='fab fa-google'></i>
<span>Sign In with Google</span>
</Button>
</div>
</div>
</div>
</div>
);
};
export default WelcomePage;
|
import { Meteor } from 'meteor/meteor';
import { Events } from './events';
import { Foods } from '../foods/foods';
import { Groups } from '../groups/groups';
import { check } from 'meteor/check';
Meteor.publish('events.getList', function getListEvents() {
if (!this.userId) {
return this.ready();
}
return Events.find();
});
Meteor.publish('events.getGroupsEvents', function getGroupsEvents(groupId) {
if (!this.userId) {
return this.ready();
}
return Events.find({usersGroupId: groupId});
});
Meteor.publish('events.getEventById', function getEventById(eventId) {
if (!this.userId) {
return this.ready();
}
return Events.find({_id: eventId});
});
Meteor.publishComposite('events.details', function eventsDetails(eventId) {
check(eventId, String);
if (!this.userId) {
return this.ready();
}
return {
find() {
return Events.find({ _id: eventId });
},
children: [
{
find({usersGroupId}) {
return Groups.find({_id: usersGroupId});
},
children: [
{
find({menuItems}) {
const menuItemsIds = menuItems.map(item => item.foodId);
return Foods.find({_id: {$in: menuItemsIds}});
}
}
]
},
{
find({participants, invitedParticipants, eventCreator}) {
return Meteor.users.find({ $or: [
{_id: {$in: participants}},
{_id: {$in: invitedParticipants}},
{_id: eventCreator }
]}, { fields: {username: 1, _id: 1, emails: 1}});
}
}
],
};
});
|
import React, {PureComponent} from 'react';
import {
ActivityIndicator, Dimensions, FlatList, Image, ScrollView, StatusBar, Text, TouchableOpacity,
View
} from "react-native";
import {Default_Photos} from "../style/BaseContant";
import {MainColor} from "../style/BaseStyle";
export default class TestPage extends PureComponent {
static navigationOptions = {
header: null,
};
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<Text>hello</Text>
)
}
}
|
const glob = require('glob');
const main = async function (src) {
return new Promise(r => {
glob(src + '/**/*.test.scss', (err, result) => {
if (err) {
console.log('Error', err);
} else {
r(result.map(f => `./${f}`));
}
});
});
}
//main();
module.exports = main;
|
import React from 'react';
import ButtonLink from './ButtonLink';
const PrimaryButtonLink = (props) => (
<ButtonLink
{...props}
className={'btn-primary'}
/>
)
export default PrimaryButtonLink;
|
let timeVar = new Date(1903069076)
console.log(timeVar)
|
import page from "./../node_modules/page/page.mjs";
import { LitRenderer } from "./rendering/litRenderer.js";
import authService from "./services/authService.js";
import booksService from "./services/booksService.js";
import likesService from "./services/likesService.js";
import nav from "./nav/nav.js";
import loginPage from "./pages/login/loginPage.js";
import registerPage from "./pages/register/registerPage.js";
import createPage from "./pages/create/createPage.js";
import editPage from "./pages/edit/editPage.js";
import detailsPage from "./pages/details/detailsPage.js";
import dashboardPage from "./pages/dashboard/dashboardPage.js";
import myBooksPage from "./pages/myBooks/myBooksPage.js";
let appElement = document.querySelector("main#site-content");
let navElement = document.querySelector("nav.navbar");
let renderer = new LitRenderer();
let navRenderHandler = renderer.createRenderHandler(navElement);
let appRenderHandler = renderer.createRenderHandler(appElement);
nav.initialize(page, navRenderHandler, authService);
dashboardPage.initialize(page, appRenderHandler, booksService);
loginPage.initialize(page, appRenderHandler, authService);
registerPage.initialize(page, appRenderHandler, authService);
createPage.initialize(page, appRenderHandler, booksService);
editPage.initialize(page, appRenderHandler, booksService);
detailsPage.initialize(page, appRenderHandler, authService, booksService, likesService);
myBooksPage.initialize(page, appRenderHandler, authService, booksService);
page(decorateUser);
page(nav.getView);
page("/dashboard", dashboardPage.getView);
page("/login", loginPage.getView);
page("/register", registerPage.getView);
page("/create", createPage.getView);
page("/edit/:id", editPage.getView);
page("/details/:id", detailsPage.getView);
page("/my-books", myBooksPage.getView);
page("/index.html", "/dashboard");
page("/", "/dashboard");
page.start();
function decorateUser(context, next) {
let user = authService.getUser();
context.user = user;
next();
}
|
function add_new_line(){
var newRow = "<tr><form action=\"../user/add_user\" method=\"post\">"+
"<td><input type=\"text\" name=\"username\" id=\"username\" /></td>"+
"<td><input type=\"text\" name=\"department\" id=\"department\" /></td>"+
"<td><input type=\"text\" name=\"passwd\" id=\"passwd\" /></td>"+
"<td>0</td>"+
"<td> <button id=\"form_submit\" type=\"submit\" class=\"btn btn-sm btn-primary\">添加</button></td>"+
"</form></tr>";
$("#user_list tr:last").after(newRow);
$("#form_submit").click(function(){
var b_empty = true;
var check = $("input").each(function(){
if($(this).val()==0){
b_empty = false;
return false;
}
});
if(b_empty==false){
alert("表单数据不能为空");
return false;
}
});
}
$(function(){
$(".edit_user").each(function(){
$(this).click(function(){
var $this_tr = $(this).closest('tr');
var $td_list = $this_tr.children("td");
var $edit_input = "<form id=\"edit_input\" action=\"../user/edit_user/"+$td_list[0].innerHTML+"\" method=\"post\">"+
"<input type=\"text\" name=\"passwd\" id=\"passwd\" value=\""+$td_list[2].innerHTML+"\"/>"+
"</form>";
$td_list[2].innerHTML = $edit_input;
var $submit_btn = "<a href=\"javascript:form_submit();\" class=\"btn btn-xs btn-primary edit_user\"><span class=\"glyphicon glyphicon-pencil\"></span>提交</a>";
$td_list[4].innerHTML = $submit_btn;
});
});
});
function form_submit(){
if($("#passwd").val()==0){
alert("重设密码不能为空!");
}else{
$("#edit_input").submit();
}
}
|
import { combineReducers, createStore } from "redux";
const DEFAULT_ACTION = {
type: ""
};
const DEFAULT_ALBUMS = {
list: [],
loading: false
};
const DEFAULT_ALBUMS_DETAILS = {
loading: false,
map: {},
error: null
};
const DEFAULT_STATE = {
albums: DEFAULT_ALBUMS,
albumsDetails: DEFAULT_ALBUMS_DETAILS
};
export const ACTIONS = {
SET_ALBUMS: "SET_ALBUMS",
SET_LOADING: "SET_LOADING",
SET_ALUBUM_DETAILS: "SET_ALUBUM_DETAILS",
SET_ALUBUM_DETAILS_LOADING: "SET_ALUBUM_DETAILS_LOADING",
SET_ALBUM_DETAILS_ERROR: "SET_ALBUM_DETAILS_ERROR"
};
const albums = (state = DEFAULT_ALBUMS, action = DEFAULT_ACTION) => {
switch (action.type) {
case ACTIONS.SET_ALBUMS:
return {
...state,
list: action.payload.albums,
loading: false
};
case ACTIONS.SET_LOADING:
return {
...state,
loading: true
};
default:
return state;
}
};
const albumsDetails = (
state = DEFAULT_ALBUMS_DETAILS,
action = DEFAULT_ACTION
) => {
switch (action.type) {
case ACTIONS.SET_ALUBUM_DETAILS: {
let albumInState = state.map[action.payload.albumid];
if (!albumInState) {
albumInState = { photo: [] };
}
return {
...state,
map: {
...state.map,
[action.payload.albumid]: {
...albumInState,
...action.payload.albumDetails,
photo: [...albumInState.photo, ...action.payload.albumDetails.photo]
}
},
loading: false
};
}
case ACTIONS.SET_ALUBUM_DETAILS_LOADING:
return {
...state,
loading: true
};
case ACTIONS.SET_ALBUM_DETAILS_ERROR:
return {
...state,
loading: false,
error: action.payload.error
};
default:
return state;
}
};
const albumStore = createStore(
combineReducers({ albums, albumsDetails }),
DEFAULT_STATE,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
export { albumStore };
|
(function() {
'use strict';
var jinn = null;
// On page loaded
document.addEventListener('DOMContentLoaded', function() {
jinn = new JinnApp();
var model = new jinn.Model({
data: {
number: null
}
});
var view1 = new jinn.View({
render: function() {
this.label1 = document.getElementById('label');
this.label1.innerHTML = this.models[0].get('number');
}
}, model);
var view3 = new jinn.View({
render: function() {
this.label1 = document.getElementById('label2');
this.label1.innerHTML = this.models[0].get('number');
}
}, model);
var view2 = new jinn.View({
init: function() {
this.p = document.getElementById('input');
var element = this.p;
var model = this.models[0];
var setModel = function() {
model.set('number', element.value);
}
this.p.addEventListener('input', setModel);
}
}, model);
_.l(view1);
_.l(view2);
_.l(model);
});
})();
|
/**
* Controller for the Sharingear Add tech profile view.
* @author: Chris Hjorth
*/
/*jslint node: true */
'use strict';
var _ = require('underscore'),
$ = require('jquery'),
GoogleMaps = require('../libraries/mscl-googlemaps.js'),
Moment = require('moment-timezone'),
Config = require('../config.js'),
ViewController = require('../viewcontroller.js'),
App = require('../app.js'),
Localization = require('../models/localization.js'),
ContentClassification = require('../models/contentclassification.js'),
TechProfile = require('../models/techprofile.js'),
countryDefault = 'Select country:';
function AddTechProfile(options) {
ViewController.call(this, options);
}
AddTechProfile.prototype = new ViewController();
AddTechProfile.prototype.didInitialize = function() {
if (App.user.data.id === null) {
this.ready = false;
App.router.navigateTo('home');
return;
}
Moment.locale('en-custom', {
week: {
dow: 1,
doy: 4
}
});
this.isLoading = false;
this.submerchantFormVC = null;
this.templateParameters = {
currency: App.user.data.currency
};
this.newTechProfile = new TechProfile({
rootURL: Config.API_URL
});
this.newTechProfile.initialize();
this.hasDelivery = false;
this.shownMoment = new Moment.tz(Localization.getCurrentTimeZone());
this.selections = {}; //key value pairs where keys are months and values are arrays of start and end dates
this.alwaysFlag = 1; //New tech profiles are always available by default
this.dragMakeAvailable = true; //Dragging on availability sets to available if this parameter is true, sets to unavailable if false
this.geocoder = new GoogleMaps.Geocoder();
this.setTitle('Sharingear - Add technician profile');
this.setDescription('Add your technician profile to showcase your skills.');
};
AddTechProfile.prototype.didRender = function() {
this.addTechProfileIcons();
this.populateCountries($('#dashboard-addtechprofileprice-country', this.$element));
$('#dashboard-addtechprofileprice-form #price_a', this.$element).val(this.newTechProfile.data.price_a);
$('#dashboard-addtechprofileprice-form #price_b', this.$element).val(this.newTechProfile.data.price_b);
$('#dashboard-addtechprofileprice-form #price_c', this.$element).val(this.newTechProfile.data.price_c);
this.setupEvent('click', '.cancel-btn', this, this.handleCancel);
this.setupEvent('click', '.next-btn', this, this.handleNext);
this.setupEvent('change', '#addtechprofile-form-type .addtechprofilebuttonlist-container input[type="radio"]', this, this.handleTechProfileRadio);
this.setupEvent('click', '#addtechprofile-startyear', this, this.handleExperienceStartYearChange);
this.setupEvent('change', '.price', this, this.handlePriceChange);
window.mixpanel.track('View addtechprofile');
};
AddTechProfile.prototype.getTabID = function() {
var tabID = null;
$('.addtechprofile-panel').each(function() {
var $this = $(this);
if ($this.hasClass('hidden') === false) {
tabID = $this.attr('id');
}
});
return tabID;
};
AddTechProfile.prototype.populatePriceSuggestions = function() {
var techProfileClassification = ContentClassification.data.roadieClassification,
view = this,
i, suggestionA, suggestionB, suggestionC;
for (i = 0; i < techProfileClassification.length; i++) {
if (techProfileClassification[i].roadie_type === view.newTechProfile.data.roadie_type) {
suggestionA = techProfileClassification[i].price_a_suggestion;
suggestionB = techProfileClassification[i].price_b_suggestion;
suggestionC = techProfileClassification[i].price_c_suggestion;
i = techProfileClassification.length;
}
}
Localization.convertPrices([suggestionA, suggestionB, suggestionC], 'EUR', App.user.data.currency, function(error, convertedPrices) {
if (error) {
console.error('Could not convert price suggestions: ' + error);
return;
}
$('#addtechprofile-price_a-suggestion', view.$element).html(Math.ceil(convertedPrices[0]));
$('#addtechprofile-price_b-suggestion', view.$element).html(Math.ceil(convertedPrices[1]));
$('#addtechprofile-price_c-suggestion', view.$element).html(Math.ceil(convertedPrices[2]));
});
};
AddTechProfile.prototype.toggleLoading = function() {
if (this.isLoading === true) {
$('.next-btn', this.$element).html('Next <i class="fa fa-arrow-circle-right"></i>');
this.isLoading = false;
} else {
$('.next-btn', this.$element).html('<i class="fa fa-circle-o-notch fa-fw fa-spin">');
this.isLoading = true;
}
};
AddTechProfile.prototype.addTechProfileIcons = function() {
var view = this,
techProfileClassification = ContentClassification.data.roadieClassification,
html = '',
techProfileType, i;
for (i = 0; i < techProfileClassification.length; i++) {
techProfileType = techProfileClassification[i].roadie_type.replace(/\s/g, ''); //Remove spaces
html += '<div class="custom-radio custom-radio-small">';
html += '<input type="radio" name="techprofile-radio" id="addtechprofile-radio-' + techProfileClassification[i].roadie_type + '" value="' + techProfileClassification[i].roadie_type + '">';
html += '<label for="addtechprofile-radio-' + techProfileClassification[i].roadie_type + '">';
html += '<div class="custom-radio-icon sg-icon icon-addtechprofile-' + techProfileType.toLowerCase() + '"></div>';
html += '<span>' + techProfileClassification[i].roadie_type + '</span>';
html += '</label>';
html += '</div>';
}
$('.addtechprofilebuttonlist-container', view.$element).append(html);
};
/**
* @assertion: techProfileClassification has been loaded
*/
AddTechProfile.prototype.handleTechProfileRadio = function(event) {
var view = event.data;
$('.hint1', view.$element).addClass('hidden');
};
AddTechProfile.prototype.saveTechProfile = function() {
var view = this,
newData;
if (view.isLoading === true) {
return;
}
//Create new tech profile model object from form data
newData = {
roadie_type: $('#addtechprofile-form-type .addtechprofilebuttonlist-container input[type="radio"]:checked').val(),
about: $('#addtechprofile-form-about').val(),
currently: $('#addtechprofile-form-currently').val(),
genres: $('#addtechprofile-form-genres').val(),
currency: App.user.data.currency
};
//Validate
if (!newData.roadie_type || newData.roadie_type === '') {
alert('Please select a type of technician.');
return;
}
this.toggleLoading();
_.extend(this.newTechProfile.data, newData);
this.newTechProfile.createTechProfile(function(error) {
if (error) {
alert('Error saving tech profile');
return;
}
view.showPanel('#addtechprofile-panel-experience');
view.populateYearsOfExperience();
view.toggleLoading();
window.mixpanel.track('View addgear-experience');
});
};
AddTechProfile.prototype.populateYearsOfExperience = function() {
var $startYear = $('#addtechprofile-startyear', this.$element),
$endYear = $('#addtechprofile-endyear', this.$element),
startYearSelectHTML = '',
endYearSelectHTML = '',
currentYear = (new Moment.tz(Localization.getCurrentTimeZone())).year(),
startYear, endYear, i;
startYear = $startYear.val();
if (startYear === null) {
startYear = Config.MIN_XP_START_YEAR;
}
endYear = $endYear.val();
if (endYear === null) {
endYear = currentYear;
}
if (endYear < startYear) {
endYear = startYear;
}
for (i = Config.MIN_XP_START_YEAR; i < startYear; i++) {
startYearSelectHTML += '<option value="' + i + '">' + i + '</option>';
}
for (i = startYear; i <= currentYear; i++) {
startYearSelectHTML += '<option value="' + i + '">' + i + '</option>';
endYearSelectHTML += '<option value="' + i + '">' + i + '</option>';
}
$startYear.html(startYearSelectHTML);
$startYear.val(startYear);
$endYear.html(endYearSelectHTML);
$endYear.val(endYear);
};
AddTechProfile.prototype.handleExperienceStartYearChange = function(event) {
var view = event.data;
view.populateYearsOfExperience();
};
AddTechProfile.prototype.saveExperience = function() {
_.extend(this.newTechProfile.data, {
experience: $('#addtechprofile-experience', this.$element).val(),
xp_years: $('#addtechprofile-startyear', this.$element).val() + '-' + $('#addtechprofile-endyear', this.$element).val(),
tours: $('#addtechprofile-tours', this.$element).val(),
companies: $('#addtechprofile-companies', this.$element).val(),
bands: $('#addtechprofile-bands').val()
});
this.populatePriceSuggestions();
this.showPanel('#addtechprofile-panel-pricelocation');
window.mixpanel.track('View addtechprofile-pricelocation');
};
AddTechProfile.prototype.populateCountries = function($select) {
var html = $('option', $select).first()[0].outerHTML,
countriesArray, i;
countriesArray = Localization.getCountries();
for (i = 0; i < countriesArray.length; i++) {
html += '<option value="' + countriesArray[i].code + '">' + countriesArray[i].name.replace(/\b./g, function(m) {
return m.toUpperCase();
}) + '</option>';
}
$select.html(html);
};
AddTechProfile.prototype.handlePriceChange = function() {
var $this = $(this),
price;
price = parseInt($this.val(), 10);
if (isNaN(price)) {
price = '';
}
$this.val(price);
};
AddTechProfile.prototype.savePriceLocation = function() {
var view = this,
isLocationSame, addressOneliner, newTechProfileData, saveCall,
currentAddress, currentPostalCode, currentCity, currentRegion, currentCountry, didLocationChange;
if (view.isLoading === true) {
return;
}
//We cannot proceed without Google Maps anyhow
if (GoogleMaps.isLoaded() === false) {
setTimeout(function() {
view.savePriceLocation();
}, 10);
return;
}
view.geocoder = new GoogleMaps.Geocoder();
currentAddress = this.newTechProfile.address;
currentPostalCode = this.newTechProfile.postal_code;
currentCity = this.newTechProfile.city;
currentRegion = this.newTechProfile.region;
currentCountry = this.newTechProfile.country;
didLocationChange = false;
_.extend(this.newTechProfile.data, {
price_a: $('#price_a', this.$element).val(),
price_b: $('#price_b', this.$element).val(),
price_c: $('#price_c', this.$element).val(),
currency: App.user.data.currency,
address: $('#dashboard-addtechprofileprice-address', this.$element).val(),
postal_code: $('#dashboard-addtechprofileprice-postalcode', this.$element).val(),
city: $('#dashboard-addtechprofileprice-city', this.$element).val(),
country: $('#dashboard-addtechprofileprice-country option:selected').val()
});
if (this.hasDelivery === true) {
this.newTechProfile.data.delivery_price = $('#dashboard-addtechprofileprice-form input[name="delivery_price"]', this.$element).val();
this.newTechProfile.data.delivery_distance = $('#dashboard-addtechprofileprice-form input[name="delivery_distance"]', this.$element).val();
}
newTechProfileData = this.newTechProfile.data;
//Validation
if (newTechProfileData.price_a === '') {
alert('Price is missing.');
return;
}
if (newTechProfileData.price_a % 1 !== 0) {
alert('Hourly price is invalid.');
return;
}
if (newTechProfileData.price_b === '') {
alert('Price is missing.');
return;
}
if (newTechProfileData.price_b % 1 !== 0) {
alert('Daily is invalid.');
return;
}
if (newTechProfileData.price_c === '') {
alert('Price is missing.');
return;
}
if (newTechProfileData.price_c % 1 !== 0) {
alert('Weekly is invalid.');
return;
}
if (this.hasDelivery === true && newTechProfileData.delivery_price === '') {
alert('Delivery price is missing.');
return;
}
if (this.hasDelivery === true && newTechProfileData.delivery_distance === '') {
alert('Delivery distance is missing.');
return;
}
if (newTechProfileData.address === '') {
alert('Address is missing');
return;
}
if (newTechProfileData.postal_code === '') {
alert('Postal code is missing.');
return;
}
if (newTechProfileData.city === '') {
alert('City is missing.');
return;
}
if (newTechProfileData.country === '' || newTechProfileData.country === countryDefault) {
alert('Country is missing.');
return;
}
isLocationSame = (currentAddress === newTechProfileData.address &&
currentPostalCode === newTechProfileData.postal_code &&
currentCity === newTechProfileData.city &&
currentRegion === newTechProfileData.region &&
currentCountry === newTechProfileData.country);
view.toggleLoading();
saveCall = function() {
view.newTechProfile.save(function(error) {
view.toggleLoading();
if (error) {
alert('Error saving data');
return;
}
view.showPanel('#addtechprofile-panel-availability');
if (App.user.isSubMerchant() === false) {
view.renderSubmerchantForm();
window.mixpanel.track('View addtechprofile-submerchantform');
} else {
view.renderAvailability();
window.mixpanel.track('View addtechprofile-availability');
}
});
};
if (isLocationSame === false) {
addressOneliner = newTechProfileData.address + ', ' + newTechProfileData.postal_code + ' ' + newTechProfileData.city + ', ' + newTechProfileData.country;
view.geocoder.geocode({
'address': addressOneliner
}, function(results, status) {
if (status === GoogleMaps.GeocoderStatus.OK) {
view.newTechProfile.data.longitude = results[0].geometry.location.lng();
view.newTechProfile.data.latitude = results[0].geometry.location.lat();
saveCall();
} else {
console.error('Error geocoding: ' + status);
alert('Address error');
view.toggleLoading();
}
});
} else {
saveCall();
}
};
AddTechProfile.prototype.renderAvailability = function() {
var view = this,
$calendarContainer, CalendarVC, calendarVT;
$calendarContainer = $('#addtechprofile-availability-calendar', this.$element);
$calendarContainer.removeClass('hidden');
$('#addtechprofile-darkgray-left', this.$element).hide();
$('#addtechprofile-darkgray-left-calendar', this.$element).removeClass('hidden');
CalendarVC = require('./availabilitycalendar.js');
calendarVT = require('../../templates/availabilitycalendar.html');
view.calendarVC = new CalendarVC({
name: 'availabilitycalendar',
$element: $calendarContainer,
template: calendarVT,
passedData: {
technician: view.newTechProfile
}
});
view.calendarVC.initialize();
view.newTechProfile.getAvailability(function(error, result) {
var selections = {},
availabilityArray, i, startMoment, endMoment;
if (error) {
console.error('Error retrieving techprofile availability: ' + error);
if(error.code === Config.ERR_AUTH) {
alert('Your login session expired.');
App.router.navigateTo('home');
}
return;
}
availabilityArray = result.availabilityArray;
for (i = 0; i < availabilityArray.length; i++) {
startMoment = new Moment.tz(availabilityArray[i].start, 'YYYY-MM-DD HH:mm:ss', Localization.getCurrentTimeZone());
endMoment = new Moment.tz(availabilityArray[i].end, 'YYYY-MM-DD HH:mm:ss', Localization.getCurrentTimeZone());
if (Array.isArray(selections[startMoment.year() + '-' + (startMoment.month() + 1)]) === false) {
selections[startMoment.year() + '-' + (startMoment.month() + 1)] = [];
}
selections[startMoment.year() + '-' + (startMoment.month() + 1)].push({
startMoment: startMoment,
endMoment: endMoment
});
}
view.calendarVC.setAlwaysState(result.alwaysFlag);
view.calendarVC.setSelections(selections);
view.calendarVC.render();
});
};
AddTechProfile.prototype.renderSubmerchantForm = function() {
var $submerchantFormContainer = $('#addtechprofile-availability-calendar', this.$element),
view = this,
SubmerchantFormVC, submerchantFormVT;
SubmerchantFormVC = require('./submerchantregistration.js');
submerchantFormVT = require('../../templates/submerchantregistration.html');
view.submerchantFormVC = new SubmerchantFormVC({
name: 'submerchantform',
$element: $submerchantFormContainer,
template: submerchantFormVT
});
view.submerchantFormVC.initialize();
view.submerchantFormVC.render();
};
AddTechProfile.prototype.saveAvailability = function() {
var view = this,
availabilityArray = [],
selections, alwaysFlag, month, monthSelections, selection, j;
if (view.isLoading === true) {
return;
}
view.toggleLoading();
if (view.calendarVC !== null) {
selections = view.calendarVC.getSelections();
alwaysFlag = view.calendarVC.getAlwaysFlag();
} else {
//For some reason the availability calendar did not load, so we set to never available as default.
selections = {};
alwaysFlag = 0;
}
for (month in selections) {
monthSelections = selections[month];
for (j = 0; j < monthSelections.length; j++) {
selection = monthSelections[j];
availabilityArray.push({
start_time: selection.startMoment.format('YYYY-MM-DD') + ' 00:00:00',
end_time: selection.endMoment.format('YYYY-MM-DD') + ' 23:59:59'
});
}
}
view.newTechProfile.setAvailability(availabilityArray, alwaysFlag, function(error) {
if (error) {
alert('Error saving tech profile availability.');
console.error(error);
return;
}
view.toggleLoading();
$('.footer', view.$element).addClass('hidden');
view.showPanel('#addtechprofile-panel-final');
view.setupEvent('click', '.profile-btn', view, view.handleViewTechProfile);
view.setupEvent('click', '.addmore-btn', view, view.handleAddMoreTechProfiles);
window.mixpanel.track('View addtechprofile-final');
});
};
AddTechProfile.prototype.handleCancel = function() {
App.router.closeModalView();
};
AddTechProfile.prototype.handleNext = function(event) {
var view = event.data,
currentTabID;
currentTabID = view.getTabID();
switch (currentTabID) {
case 'addtechprofile-panel-type':
view.saveTechProfile();
break;
case 'addtechprofile-panel-experience':
view.saveExperience();
break;
case 'addtechprofile-panel-pricelocation':
view.savePriceLocation();
break;
case 'addtechprofile-panel-availability':
if (view.submerchantFormVC !== null) {
view.toggleLoading();
view.submerchantFormVC.submitForm(function(error) {
view.toggleLoading();
if (!error) {
view.submerchantFormVC.close();
view.submerchantFormVC = null;
view.renderAvailability();
window.mixpanel.track('View addtechprofile-availability');
}
});
} else {
view.saveAvailability();
}
break;
default:
console.error('Something went wrong in addtechprofile viewcontroller method handleNext.');
}
};
AddTechProfile.prototype.handleViewTechProfile = function(event) {
var view = event.data;
App.router.closeModalView();
App.router.navigateTo('techprofile/' + view.newTechProfile.data.id);
};
AddTechProfile.prototype.handleAddMoreTechProfiles = function() {
App.router.closeModalView();
App.router.openModalView('addtechprofile');
};
AddTechProfile.prototype.showPanel = function(panelID) {
$('.addtechprofile-panel', this.$element).each(function() {
var $this = $(this);
if ($this.hasClass('hidden') === false) {
$this.addClass('hidden');
}
});
$(panelID, this.$element).removeClass('hidden');
};
module.exports = AddTechProfile;
|
import React from 'react';
import { Provider } from 'react-redux';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import store from './store';
// App Components
import Header from './components/template/header/Header';
import Footer from './components/template/footer/Footer';
import MyTaxi from './components/page/myTaxi/MyTaxi';
import Car2Go from './components/page/car2go/Car2Go';
import NotFound from './components/page/pageNotFound/Error404';
// Global CSS styles
import './assets/styles/style.css';
const App = () => (
<Provider store={store}>
<BrowserRouter>
<div>
<Header />
<div className="container">
<Switch>
<Route exact path="/" component={MyTaxi} />
<Route exact path="/car2go" component={Car2Go} />
<Route component={NotFound} />
</Switch>
</div>
<Footer />
</div>
</BrowserRouter>
</Provider>
);
export default App;
|
import Swagger from "swagger-client"
module.exports = function({ configs }) {
return {
fn: {
fetch: function(obj) {
// replace 'undefined' segments in url
obj.url = obj.url.replace(/\/undefined/g, '');
return Swagger.makeHttp(configs.preFetch, configs.postFetch)(obj);
},
buildRequest: Swagger.buildRequest,
execute: Swagger.execute,
resolve: Swagger.resolve,
serializeRes: Swagger.serializeRes,
opId: Swagger.helpers.opId
}
}
}
|
//NBA Eastern Conference Team information and Roster Information
const eastern = [
{
id:1,
teams:[
{
teamName:'Atlanta Hawks',
teamIMG:'https://upload.wikimedia.org/wikipedia/en/thumb/2/24/Atlanta_Hawks_logo.svg/1200px-Atlanta_Hawks_logo.svg.png',
teamRecord:'4-6',
teamConference:'Eastern',
}
],
shopping:[
{
jersey:'https://images.footballfanatics.com/atlanta-hawks/atlanta-hawks-nike-icon-swingman-jersey-trae-young-mens_ss4_p-12042031+u-oyk50a7f6u934cfcyhso+v-dba649179d884c188e4fd07e7082c731.jpg?_hv=1&w=900',
description:'Trae Young Jersey',
price:'$109.99',
}
],
roster:[
{
Playerid:'1',
player:'Trae Young',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4277905.png&h=80&w=110&scale=crop',
},
{
Playerid:'2',
player:'John Collins',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3908845.png&h=80&w=110&scale=crop',
},
{
Playerid:'3',
player:'Clint Capela',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3102529.png&h=80&w=110&scale=crop',
},
{
Playerid:'4',
player:'Bogdan Bogdanovic',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3037789.png&h=80&w=110&scale=crop',
},
{
Playerid:'5',
player:'Deandre Hunter',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4065732.png&h=80&w=110&scale=crop',
},
{
Playerid:'6',
player:'Cam Reddish',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4395627.png&h=80&w=110&scale=crop',
},
{
Playerid:'7',
player:'Kevin Hurter',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4066372.png&h=80&w=110&scale=crop',
},
{
Playerid:'8',
player:'Danilo Gallinari',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3428.png&h=80&w=110&scale=crop',
},
{
Playerid:'9',
player:'Delon Wright',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3064447.png&h=80&w=110&scale=crop',
},
{
Playerid:'10',
player:'Lou Williams',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2799.png&h=80&w=110&scale=crop',
},
{
Playerid:'11',
player:'Onyeka Okongwu',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4431680.png&h=80&w=110&scale=crop',
},
{
Playerid:'12',
player:'Solomon Hill',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2488958.png&h=80&w=110&scale=crop',
},
{
Playerid:'13',
player:'Sharife Cooper',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4432173.png&h=80&w=110&scale=crop',
},
]
},
{
id:2,
teams:[
{
teamName:'Boston Celtics',
teamIMG:'https://upload.wikimedia.org/wikipedia/en/thumb/8/8f/Boston_Celtics.svg/1200px-Boston_Celtics.svg.png',
teamRecord:'4-6',
teamConference:'Eastern Conference',
}
],
shopping:[
{
jersey:'https://images.footballfanatics.com/boston-celtics/boston-celtics-nike-icon-swingman-jersey-jayson-tatum-mens_ss4_p-11904831+u-rls9h59nafc4cayapi5+v-c1f71d1980544afb84393cfc87107d9e.jpg?_hv=1',
description:'Jayson Tatum jersey',
price:'$109.99',
}
],
roster:[
{
Playerid:'1',
player:'Jayson Tatum',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4065648.png&h=80&w=110&scale=crop',
},
{
Playerid:'2',
player:'Jaylen Brown',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3917376.png&h=80&w=110&scale=crop',
},
{
Playerid:'3',
player:'Marcus Smart',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2990992.png&h=80&w=110&scale=crop',
},
{
Playerid:'4',
player:'Al Horford',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3213.png&h=80&w=110&scale=crop',
},
{
Playerid:'5',
player:'Robert Williams',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4066211.png&h=80&w=110&scale=crop',
},
{
Playerid:'6',
player:'Dennis Schroeder',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3032979.png&h=80&w=110&scale=crop',
},
{
Playerid:'7',
player:'Aaron Nesmith',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4396909.png&h=80&w=110&scale=crop',
},
{
Playerid:'8',
player:'Josh Richardson',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2581190.png&h=80&w=110&scale=crop',
},
{
Playerid:'9',
player:'Romeo Langford',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4397008.png&h=80&w=110&scale=crop',
},
{
Playerid:'10',
player:'Grant Williams',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4066218.png&h=80&w=110&scale=crop',
},
{
Playerid:'11',
player:'Enes Kanter',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/6447.png&h=80&w=110&scale=crop',
},
{
Playerid:'12',
player:'Juancho Hernangomez',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4017839.png&h=80&w=110&scale=crop',
},
{
Playerid:'13',
player:'Payton Pritchard',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4066354.png&h=80&w=110&scale=crop',
},
]
},
{
id:3,
teams:[
{
teamName:'Brooklyn Nets',
teamIMG:'https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Brooklyn_Nets_newlogo.svg/1200px-Brooklyn_Nets_newlogo.svg.png',
teamRecord:'7-3',
teamConference:'Eastern Conference',
}
],
shopping:[
{
jersey:'http://jerseysfamily.com/wp-content/uploads/2019/07/Kevin-Durant-7-Brooklyn-Nets-Black-Music-City-Edition-Jersey.jpg',
description:'Kevin Durant Jersey',
price:'$109.99',
}
],
roster:[
{
Playerid:'1',
player:'Kevin Durant',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3202.png&h=80&w=110&scale=crop',
},
{
Playerid:'2',
player:'James Harden',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3992.png&h=80&w=110&scale=crop',
},
{
Playerid:'3',
player:'Kyrie Irving',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/6442.png&h=80&w=110&scale=crop',
},
{
Playerid:'4',
player:'Blake Griffin',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3989.png&h=80&w=110&scale=crop',
},
{
Playerid:'5',
player:'Bruce Brown',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4065670.png&h=80&w=110&scale=crop',
},
{
Playerid:'6',
player:'LaMarcus Aldridge',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2983.png&h=80&w=110&scale=crop',
},
{
Playerid:'7',
player:'Paul Millsap',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3015.png&h=80&w=110&scale=crop',
},
{
Playerid:'8',
player:'Nic Claxton',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4278067.png&h=80&w=110&scale=crop',
},
{
Playerid:'9',
player:'Joe Harris',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2528794.png&h=80&w=110&scale=crop',
},
{
Playerid:'10',
player:'Patty Mills',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4004.png&h=80&w=110&scale=crop',
},
{
Playerid:'11',
player:'Cam Thomas',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4432174.png&h=80&w=110&scale=crop',
},
{
Playerid:'12',
player:'Jevon Carter',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3133635.png&h=80&w=110&scale=crop',
},
{
Playerid:'13',
player:'DeAndre Bembry',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3062667.png&h=80&w=110&scale=crop',
},
]
},
{
id:4,
teams:[
{
teamName:'Charlotte Hornets',
teamIMG:'https://upload.wikimedia.org/wikipedia/en/thumb/c/c4/Charlotte_Hornets_%282014%29.svg/1200px-Charlotte_Hornets_%282014%29.svg.png',
teamRecord:'5-6',
teamConference:'Eastern Conference',
}
],
shopping:[
{
jersey:'http://jerseysfamily.com/wp-content/uploads/2020/12/Charlotte-Hornets-LaMelo-Ball-2-Teal-Icon-2020-NBA-Draft.jpg',
description:'Lamelo Ball Jersey',
price:'$109.99',
}
],
roster:[
{
Playerid:'1',
player:'Lamelo Ball',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4432816.png&h=80&w=110&scale=crop',
},
{
Playerid:'2',
player:'Gordon Hayward',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4249.png&h=80&w=110&scale=crop',
},
{
Playerid:'3',
player:'Terry Rozier',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3074752.png&h=80&w=110&scale=crop',
},
{
Playerid:'4',
player:'Miles Bridges',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4066383.png&h=80&w=110&scale=crop',
},
{
Playerid:'5',
player:'Pj Washigton',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4278078.png&h=80&w=110&scale=crop',
},
{
Playerid:'6',
player:'Kelly Oubre',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3133603.png&h=80&w=110&scale=crop',
},
{
Playerid:'7',
player:'Mason Plumlee',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2488653.png&h=80&w=110&scale=crop',
},
{
Playerid:'8',
player:'Ish Smith',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4305.png&h=80&w=110&scale=crop',
},
{
Playerid:'9',
player:'James Bouknight',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4431712.png&h=80&w=110&scale=crop',
},
{
Playerid:'10',
player:'Kai Jones',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4431699.png&h=80&w=110&scale=crop',
},
{
Playerid:'11',
player:'Cody Martin',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3138161.png&h=80&w=110&scale=crop',
},
{
Playerid:'12',
player:'Jaden Mcdaniels',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4066731.png&h=80&w=110&scale=crop',
},
{
Playerid:'13',
player:'Vernon Carey Jr',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4431669.png&h=80&w=110&scale=crop',
},
]
},
{
id:5,
teams:[
{
teamName:'Chicago Bulls',
teamIMG:'https://upload.wikimedia.org/wikipedia/en/thumb/6/67/Chicago_Bulls_logo.svg/1200px-Chicago_Bulls_logo.svg.png',
teamRecord:'6-3',
teamConference:'Eastern Conference',
}
],
shopping:[
{
jersey:'https://images.footballfanatics.com/FFImage/thumb.aspx?i=/productimages/_3705000/altimages/ff_3705449-61d06ef8e9b25b75fcabalt1_full.jpg&w=900',
description:'Zach LaVine Jersey',
price:'$109.99',
}
],
roster:[
{
Playerid:'1',
player:'Lonzo Ball',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4066421.png&h=80&w=110&scale=crop',
},
{
Playerid:'2',
player:' Zach LaVine',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3064440.png&h=80&w=110&scale=crop',
},
{
Playerid:'3',
player:'Demar DeRozan',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3978.png&h=80&w=110&scale=crop',
},
{
Playerid:'4',
player:'Nikola Vucevic',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/6478.png&h=80&w=110&scale=crop',
},
{
Playerid:'5',
player:'Coby White',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4395651.png&h=80&w=110&scale=crop',
},
{
Playerid:'6',
player:'Patrick Williams',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4431687.png&h=80&w=110&scale=crop',
},
{
Playerid:'7',
player:'Alex Caruso',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2991350.png&h=80&w=110&scale=crop',
},
{
Playerid:'8',
player:'Troy Brown Jr',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4278508.png&h=80&w=110&scale=crop',
},
{
Playerid:'9',
player:'Derrick Jones Jr.',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3936099.png&h=80&w=110&scale=crop',
},
{
Playerid:'10',
player:'Ayo Dosunmu',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4397002.png&h=80&w=110&scale=crop',
},
{
Playerid:'11',
player:'Tony Bradley',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4065673.png&h=80&w=110&scale=crop',
},
{
Playerid:'12',
player:'Javonte Green',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2596112.png&h=80&w=110&scale=crop',
},
{
Playerid:'13',
player:'Matt Thomas',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3059311.png&h=80&w=110&scale=crop',
},
]
},
{
id:6,
teams:[
{
teamName:'Cleveland Cavaliers',
teamIMG:'https://logos-world.net/wp-content/uploads/2020/05/Cleveland-Cavaliers-logo.png',
teamRecord:'6-5',
teamConference:'Eastern Conference',
}
],
shopping:[
{
jersey:'https://fanatics.frgimages.com/FFImage/thumb.aspx?i=/productimages/_3662000/altimages/ff_3662222-afebd191edde08997168alt1_full.jpg&w=900',
description:'Darius Garland Jersey',
price:'$109.99',
}
],
roster:[
{
Playerid:'1',
player:'Darius Garland',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4396907.png&h=80&w=110&scale=crop',
},
{
Playerid:'2',
player:'Colin Sexton',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4277811.png&h=80&w=110&scale=crop',
},
{
Playerid:'3',
player:'Jarret Allen',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4066328.png&h=80&w=110&scale=crop',
},
{
Playerid:'4',
player:'Evan Mobley',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4432158.png&h=80&w=110&scale=crop',
},
{
Playerid:'5',
player:'Lauri Markkanen',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4066336.png&h=80&w=110&scale=crop',
},
{
Playerid:'6',
player:'Kevin Love',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3449.png&h=80&w=110&scale=crop',
},
{
Playerid:'7',
player:'Isaac Okoro',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4432822.png&h=80&w=110&scale=crop',
},
{
Playerid:'8',
player:'Cedi Osman',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3893016.png&h=80&w=110&scale=crop',
},
{
Playerid:'9',
player:'Ricky Rubio',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4011.png&h=80&w=110&scale=crop',
},
{
Playerid:'10',
player:'Denzel Valentine',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2999549.png&h=80&w=110&scale=crop',
},
{
Playerid:'11',
player:'Dean Wade',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3912848.png&h=80&w=110&scale=crop',
},
{
Playerid:'12',
player:'Dylan Windler',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3906786.png&h=80&w=110&scale=crop',
},
{
Playerid:'13',
player:'Tacko Fall',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3904625.png&h=80&w=110&scale=crop',
},
]
},
{
id:7,
teams:[
{
teamName:'Detroit Pistons',
teamIMG:'https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/Pistons_logo17.svg/1200px-Pistons_logo17.svg.png',
teamRecord:'1-8',
teamConference:'Eastern Conference',
}
],
shopping:[
{
jersey:'https://images.footballfanatics.com/detroit-pistons/detroit-pistons-nike-swingman-jersey-blue-cade-cunningham-youth-icon-edition_ss4_p-12083936+u-1fu4pdvh5eudtj9yj3b3+v-2c1c7996262c43a7b1da8f2b199d1072.jpg?_hv=1&w=900',
description:'Cade Cunningham',
price:'$109.99',
}
],
roster:[
{
Playerid:'1',
player:'Jerami Grant',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2991070.png&h=80&w=110&scale=crop',
},
{
Playerid:'2',
player:'Cade Cunnigham',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4432166.png&h=80&w=110&scale=crop',
},
{
Playerid:'3',
player:'Killian Hayes',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4683024.png&h=80&w=110&scale=crop',
},
{
Playerid:'4',
player:'Saddiq Bey',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4397136.png&h=80&w=110&scale=crop',
},
{
Playerid:'5',
player:'Kelly Olynyk',
image:'',
},
{
Playerid:'6',
player:'Josh Jackson',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4066297.png&h=80&w=110&scale=crop',
},
{
Playerid:'7',
player:'Saben Lee',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4278124.png&h=80&w=110&scale=crop',
},
{
Playerid:'8',
player:'Corey Joesph',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/6446.png&h=80&w=110&scale=crop',
},
{
Playerid:'9',
player:'Hamidou Diallo',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4080610.png&h=80&w=110&scale=crop',
},
{
Playerid:'10',
player:'Frank Jackson',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4065651.png&h=80&w=110&scale=crop',
},
{
Playerid:'11',
player:'Isaiah Stewart',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4432810.png&h=80&w=110&scale=crop',
},
{
Playerid:'12',
player:'Rodney McGruder',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2488826.png&h=80&w=110&scale=crop',
},
{
Playerid:'13',
player:'Luka Garza',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4277951.png&h=80&w=110&scale=crop',
},
]
},
{
id:8,
teams:[
{
teamName:'Indiana Pacers',
teamIMG:'https://upload.wikimedia.org/wikipedia/en/thumb/1/1b/Indiana_Pacers.svg/1200px-Indiana_Pacers.svg.png',
teamRecord:'4-7',
teamConference:'Eastern Conference',
}
],
shopping:[
{
jersey:'https://i5.walmartimages.com/asr/1fd574dc-fae5-45a9-9e94-fea234752e46.96073e463e752c4c8bff7edc6b3933e4.jpeg',
description:'Domantas Sabonis Jersey',
price:'$109.99',
}
],
roster:[
{
Playerid:'1',
player:'Malcolm Brogdon',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2566769.png&h=80&w=110&scale=crop',
},
{
Playerid:'2',
player:'Domantas Sabonis',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3155942.png&h=80&w=110&scale=crop',
},
{
Playerid:'3',
player:'Myles Turner',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3133628.png&h=80&w=110&scale=crop',
},
{
Playerid:'4',
player:'Carris Levert',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2991043.png&h=80&w=110&scale=crop',
},
{
Playerid:'5',
player:'Torry Craig',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2528693.png&h=80&w=110&scale=crop',
},
{
Playerid:'6',
player:'Chris Durate',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4592402.png&h=80&w=110&scale=crop',
},
{
Playerid:'7',
player:'Jermey Lamb',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/6603.png&h=80&w=110&scale=crop',
},
{
Playerid:'8',
player:'Tj Warren',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2982334.png&h=80&w=110&scale=crop',
},
{
Playerid:'9',
player:'T.J. McConnell',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2530530.png&h=80&w=110&scale=crop',
},
{
Playerid:'10',
player:'Brad Wanamaker',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/6507.png&h=80&w=110&scale=crop',
},
{
Playerid:'11',
player:'Justin Holiday',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2284101.png&h=80&w=110&scale=crop',
},
{
Playerid:'12',
player:'Oshae Brissett',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4278031.png&h=80&w=110&scale=crop',
},
{
Playerid:'13',
player:'Goga Bitadze',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4348700.png&h=80&w=110&scale=crop',
},
]
},
{
id:9,
teams:[
{
teamName:'Miami Heat',
teamIMG:'https://upload.wikimedia.org/wikipedia/en/thumb/f/fb/Miami_Heat_logo.svg/1200px-Miami_Heat_logo.svg.png',
teamRecord:'7-2',
teamConference:'Eastern Conference',
}
],
shopping:[
{
jersey:'https://images.footballfanatics.com/miami-heat/miami-heat-nike-icon-swingman-jersey-jimmy-butler-mens_ss4_p-12006482+u-qmydmzhxq2sc65qw4h5b+v-6dbd60127047496dacc9835aa25be974.jpg?_hv=1&w=900',
description:'Jimmy Butler Jersey',
price:'$109.99',
}
],
roster:[
{
Playerid:'1',
player:'Jimmy Butler',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/6430.png&h=80&w=110&scale=crop',
},
{
Playerid:'2',
player:'Kyle Lowry',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3012.png&h=80&w=110&scale=crop',
},
{
Playerid:'3',
player:'Bam Adebeyo',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4066261.png&h=80&w=110&scale=crop',
},
{
Playerid:'4',
player:'Duncan Robinson',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3157465.png&h=80&w=110&scale=crop',
},
{
Playerid:'5',
player:'Tyler Herro',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4395725.png&h=80&w=110&scale=crop',
},
{
Playerid:'6',
player:'Markieff Morris',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/6461.png&h=80&w=110&scale=crop',
},
{
Playerid:'7',
player:'Victor Oladipo',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2527963.png&h=80&w=110&scale=crop',
},
{
Playerid:'8',
player:'Pj Tucker',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3033.png&h=80&w=110&scale=crop',
},
{
Playerid:'9',
player:'Dewayne Dedmon',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2580913.png&h=80&w=110&scale=crop',
},
{
Playerid:'10',
player:'Caleb Martin',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3138160.png&h=80&w=110&scale=crop',
},
{
Playerid:'11',
player:'KZ Okpala',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4278521.png&h=80&w=110&scale=crop',
},
{
Playerid:'12',
player:'Gabe Vincent',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3137259.png&h=80&w=110&scale=crop',
},
{
Playerid:'13',
player:'Udonis Haslem',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2184.png&h=80&w=110&scale=crop',
},
]
},
{
id:10,
teams:[
{
teamName:'Milwaukee Bucks',
teamIMG:'https://upload.wikimedia.org/wikipedia/en/thumb/4/4a/Milwaukee_Bucks_logo.svg/1200px-Milwaukee_Bucks_logo.svg.png',
teamRecord:'4-6',
teamConference:'Eastern Conference',
}
],
shopping:[
{
jersey:'https://images.footballfanatics.com/milwaukee-bucks/milwaukee-bucks-jordan-statement-swingman-jersey-giannis-antetokounmpo-mens_ss4_p-12041596+u-4pvjeq8484olpxm2z7rk+v-faaf6f9ab0f3423d8e4a7f84fa847315.jpg?_hv=1&w=900',
description:'Giannis Antetokounmpo Jersey',
price:'$109.99',
}
],
roster:[
{
Playerid:'1',
player:'Giannis Antetokounmpo',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3032977.png&h=80&w=110&scale=crop',
},
{
Playerid:'2',
player:'Khris Middleton',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/6609.png&h=80&w=110&scale=crop',
},
{
Playerid:'3',
player:'Jrue Holiday',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3995.png&h=80&w=110&scale=crop',
},
{
Playerid:'4',
player:'Bobby Portis',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3064482.png&h=80&w=110&scale=crop',
},
{
Playerid:'5',
player:'Brook Lopez',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3448.png&h=80&w=110&scale=crop',
},
{
Playerid:'6',
player:'Pat Connaughton',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2578239.png&h=80&w=110&scale=crop',
},
{
Playerid:'7',
player:'George Hill',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3438.png&h=80&w=110&scale=crop',
},
{
Playerid:'8',
player:'Donte DiVincenzo',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3934673.png&h=80&w=110&scale=crop',
},
{
Playerid:'9',
player:'Jordan Nwora',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4277883.png&h=80&w=110&scale=crop',
},
{
Playerid:'10',
player:'Grayson Allen',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3135045.png&h=80&w=110&scale=crop',
},
{
Playerid:'11',
player:'Rodney Hood',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2581177.png&h=80&w=110&scale=crop',
},
{
Playerid:'12',
player:'Semi Ojeleye',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3056602.png&h=80&w=110&scale=crop',
},
{
Playerid:'13',
player:'Thanasis Antetokounmpo',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3102533.png&h=80&w=110&scale=crop',
},
]
},
{
id:11,
teams:[
{
teamName:'New York Knicks',
teamIMG:'https://upload.wikimedia.org/wikipedia/en/thumb/2/25/New_York_Knicks_logo.svg/1200px-New_York_Knicks_logo.svg.png',
teamRecord:'6-4',
teamConference:'Eastern Conference',
}
],
shopping:[
{
jersey:'https://fanatics.frgimages.com/FFImage/thumb.aspx?i=/productimages/_3774000/altimages/ff_3774144-af7107a71a25f41977acalt1_full.jpg&w=900',
description:'Julius Randle',
price:'$109.99',
}
],
roster:[
{
Playerid:'1',
player:'Julius Randle',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3064514.png&h=80&w=110&scale=crop',
},
{
Playerid:'2',
player:'Rj Barret',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4395625.png&h=80&w=110&scale=crop',
},
{
Playerid:'3',
player:'Kemba Walker',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/6479.png&h=80&w=110&scale=crop',
},
{
Playerid:'4',
player:'Derrick Rose',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3456.png&h=80&w=110&scale=crop',
},
{
Playerid:'5',
player:'Evan Fornier',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/6588.png&h=80&w=110&scale=crop',
},
{
Playerid:'6',
player:'Mitchell Robinson',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4351852.png&h=80&w=110&scale=crop',
},
{
Playerid:'7',
player:'Obi Toppin',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4278355.png&h=80&w=110&scale=crop',
},
{
Playerid:'8',
player:'Immanuel Quickley',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4395724.png&h=80&w=110&scale=crop',
},
{
Playerid:'9',
player:'Nerlens Noel',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2991280.png&h=80&w=110&scale=crop',
},
{
Playerid:'10',
player:'Taj Gibson',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3986.png&h=80&w=110&scale=crop',
},
{
Playerid:'11',
player:'Kevin Knox II',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4278075.png&h=80&w=110&scale=crop',
},
{
Playerid:'12',
player:'Alec Burkes',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/6429.png&h=80&w=110&scale=crop',
},
{
Playerid:'13',
player:'Quentin Grimes',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4397014.png&h=80&w=110&scale=crop',
},
]
},
{
id:12,
teams:[
{
teamName:'Orlando Magic',
teamIMG:'https://logos-world.net/wp-content/uploads/2020/05/Orlando-Magic-logo.png',
teamRecord:'3-8',
teamConference:'Eastern Conference',
}
],
shopping:[
{
jersey:'https://images.footballfanatics.com/orlando-magic/orlando-magic-nike-icon-swingman-jersey-cole-anthony-mens_ss4_p-12049234+u-h3tbpkt28ml4yhebwki8+v-e037c833ea3a43219569afc9c75adfac.jpg?_hv=1',
description:'Cole Anthony Jersey',
price:'$109.99',
}
],
roster:[
{
Playerid:'1',
player:'Cole Anthony',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4432809.png&h=80&w=110&scale=crop',
},
{
Playerid:'2',
player:'Jalen Suggs',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4432165.png&h=80&w=110&scale=crop',
},
{
Playerid:'3',
player:'Markelle Fultz',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4066636.png&h=80&w=110&scale=crop',
},
{
Playerid:'4',
player:'Johnathan Issac',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4065654.png&h=80&w=110&scale=crop',
},
{
Playerid:'5',
player:'Wendall Carter Jr',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4277847.png&h=80&w=110&scale=crop',
},
{
Playerid:'6',
player:'Mo Bamba',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4277919.png&h=80&w=110&scale=crop',
},
{
Playerid:'7',
player:'Franz Wagner',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4065654.png&h=80&w=110&scale=crop',
},
{
Playerid:'8',
player:'Rj Hampton',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4590530.png&h=80&w=110&scale=crop',
},
{
Playerid:'9',
player:'Gary Harris',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2999547.png&h=80&w=110&scale=crop',
},
{
Playerid:'10',
player:'Terrance Ross',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/6619.png&h=80&w=110&scale=crop',
},
{
Playerid:'11',
player:'Micheal Carter Williams',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2596108.png&h=80&w=110&scale=crop',
},
{
Playerid:'12',
player:'Robin Lopez',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3447.png&h=80&w=110&scale=crop',
},
{
Playerid:'13',
player:'Chuma Okeke',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4278052.png&h=80&w=110&scale=crop',
},
]
},
{
id:13,
teams:[
{
teamName:'Philadelphia 76ers',
teamIMG:'https://s.yimg.com/cv/apiv2/default/nba/20181217/500x500/76ers_wbg.png',
teamRecord:'8-3',
teamConference:'Eastern Conference',
}
],
shopping:[
{
jersey:'https://images.footballfanatics.com/FFImage/thumb.aspx?i=/productimages/_3378000/ff_3378498-e9470495f3f7467f41ff_full.jpg',
description:'Joel Embiid',
price:'$109.99',
}
],
roster:[
{
Playerid:'1',
player:'Joel Embiid',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3059318.png&h=80&w=110&scale=crop',
},
{
Playerid:'2',
player:'Ben Simmons',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3907387.png&h=80&w=110&scale=crop',
},
{
Playerid:'3',
player:'Danny Green',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3988.png&h=80&w=110&scale=crop',
},
{
Playerid:'4',
player:'Tobias Harris',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/6440.png&h=80&w=110&scale=crop',
},
{
Playerid:'5',
player:'Andre Drummond',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/6585.png&h=80&w=110&scale=crop',
},
{
Playerid:'6',
player:'Furkan Korkmaz',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3929325.png&h=80&w=110&scale=crop',
},
{
Playerid:'7',
player:'Seth Curry',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2326307.png&h=80&w=110&scale=crop',
},
{
Playerid:'8',
player:'Tyrese Maxey',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4431678.png&h=80&w=110&scale=crop',
},
{
Playerid:'9',
player:'Shake Milton',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3915195.png&h=80&w=110&scale=crop',
},
{
Playerid:'10',
player:'Matisse Thybulle',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3929325.png&h=80&w=110&scale=crop',
},
{
Playerid:'11',
player:'Georges Niang',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2990969.png&h=80&w=110&scale=crop',
},
{
Playerid:'12',
player:'Jaden Springer',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4432164.png&h=80&w=110&scale=crop',
},
{
Playerid:'13',
player:'Isaiah Joe',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/6440.png&h=80&w=110&scale=crop',
},
]
},
{
id:14,
teams:[
{
teamName:'Toronto Raptors',
teamIMG:'https://upload.wikimedia.org/wikipedia/en/thumb/3/36/Toronto_Raptors_logo.svg/1200px-Toronto_Raptors_logo.svg.png',
teamRecord:'6-5',
teamConference:'Eastern Conference',
}
],
shopping:[
{
jersey:'https://images.footballfanatics.com/toronto-raptors/toronto-raptors-nike-swingman-jersey-red-scottie-barnes-youth-icon-edition_ss4_p-12083916+u-8uentjp4vq6pcbimnm8i+v-ed9d2de407f942a9b50f3ffc96bb3185.jpg?_hv=1',
description:'Scottie Barnes',
price:'$109.99',
}
],
roster:[
{
Playerid:'1',
player:'Pascal Siakam',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4277843.png&h=80&w=110&scale=crop',
},
{
Playerid:'2',
player:'Scottie Barnes',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4433134.png&h=80&w=110&scale=crop',
},
{
Playerid:'3',
player:'Fred VanVleet',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2991230.png&h=80&w=110&scale=crop',
},
{
Playerid:'4',
player:'Gary Trent Jr',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4277843.png&h=80&w=110&scale=crop',
},
{
Playerid:'5',
player:'Goran Dragic',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3423.png&h=80&w=110&scale=crop',
},
{
Playerid:'6',
player:'Chris Boucher',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3948153.png&h=80&w=110&scale=crop',
},
{
Playerid:'7',
player:'OG Annunoby',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3934719.png&h=80&w=110&scale=crop',
},
{
Playerid:'8',
player:'Precious Achiuwa',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4431679.png&h=80&w=110&scale=crop',
},
{
Playerid:'9',
player:'Malachi Flynn',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4066668.png&h=80&w=110&scale=crop',
},
{
Playerid:'10',
player:'Svi Mykhailiuk',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3133602.png&h=80&w=110&scale=crop',
},
{
Playerid:'11',
player:'Isaac Bonga',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4348697.png&h=80&w=110&scale=crop',
},
{
Playerid:'12',
player:'Sam Dekker',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2991184.png&h=80&w=110&scale=crop',
},
{
Playerid:'13',
player:'Kem Birch',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2578240.png&h=80&w=110&scale=crop',
},
]
},
{
id:15,
teams:[
{
teamName:'Washington wizards',
teamIMG:'https://upload.wikimedia.org/wikipedia/en/thumb/0/02/Washington_Wizards_logo.svg/1200px-Washington_Wizards_logo.svg.png',
teamRecord:'7-3',
teamConference:'Eastern Conference',
}
],
shopping:[
{
jersey:'https://images.footballfanatics.com/washington-wizards/washington-wizards-jordan-statement-swingman-jersey-bradley-beal-mens_ss4_p-12041655+u-pakt5ebjhq502bcg6au0+v-21d1a11986ed46aa81ec39e080e81365.jpg?_hv=1',
description:'Bradley Beal Jersey',
price:'$109.99',
}
],
roster:[
{
Playerid:'1',
player:'Bradley Beal',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/6580.png&h=80&w=110&scale=crop',
},
{
Playerid:'2',
player:'Spencer Dinwiddie',
image:'',
},
{
Playerid:'3',
player:'Kyle Kuzma',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3134907.png&h=80&w=110&scale=crop',
},
{
Playerid:'4',
player:'Montrez Harrel',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2991055.png&h=80&w=110&scale=crop',
},
{
Playerid:'5',
player:'Rui Hachimura',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4066648.png&h=80&w=110&scale=crop',
},
{
Playerid:'6',
player:'Kentavious Caldwell-Pope',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2581018.png&h=80&w=110&scale=crop',
},
{
Playerid:'7',
player:'Daniel Gafford',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4278049.png&h=80&w=110&scale=crop',
},
{
Playerid:'8',
player:'Aaron Holiday',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3922230.png&h=80&w=110&scale=crop',
},
{
Playerid:'9',
player:'Davis Bertans',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/6426.png&h=80&w=110&scale=crop',
},
{
Playerid:'10',
player:'Thomas Bryant',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/3934723.png&h=80&w=110&scale=crop',
},
{
Playerid:'11',
player:'Raul Neto',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2968361.png&h=80&w=110&scale=crop',
},
{
Playerid:'12',
player:'Deni Avdija',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/4683021.png&h=80&w=110&scale=crop',
},
{
Playerid:'13',
player:'Anthony Gill',
image:'https://a.espncdn.com/combiner/i?img=/i/headshots/nba/players/full/2581184.png&h=80&w=110&scale=crop',
},
]
},
]
module.exports = { eastern }
|
function addCode() {
document.getElementById("add_to_me").innerHTML = 'This demo DIV block was inserted into the page using JavaScript.';
}
|
(function (window) {
window.__env = window.__env || {};
// Base url
window.__env.baseUrl = '@@baseUrl';
// context will be prepended to policy2-admin relative paths
window.__env.context = '/policy2-admin';
// relative path to logout
window.__env.logoutPath = '/logout';
// relative path to session time check
window.__env.sessionTimeCheck = '/api/session/timecheck';
// relative path to session keep alive
window.__env.sessionKeepAlive = '/api/session/keepalive';
// relative path to session keep alive
window.__env.sessionTimedOut = '/sessionTimedOut';
// Time in milliseconds before the session expires to open the dialog
window.__env.sessionWarnBefore = '@@sessionWarnBefore';
// Whether or not to enable debug mode
// Setting this to false will disable console output
window.__env.enableDebug = true;
}(this));
|
/*
* allTests.js by Aaron Becker
* All unit tests for CarLOS; uses Mocha+Chai
*
* Dedicated to Marc Perkel
*
*/
const expect = require('chai').expect;
const events = require("events");
const timerModule = require("../drivers/trackTimers&Controllers.js");
describe("basic", function() {
it('does aaron know how to use mocha?', function(){})
})
describe("#trackTimerModule", function() {
context("basic tests", function() {
var trackTimer = timerModule.trackTimer;
it("should return instance of eventEmitter on init", function() {
expect(trackTimer.init()).to.be.instanceOf(events);
})
it("should return instance of eventEmitter on reset", function() {
expect(trackTimer.reset(0.001)).to.be.instanceOf(events);
})
})
context("event-driven tests", function() {
var trackTimer = timerModule.trackTimer;
it("should return begin event", function(done) {
trackTimer.init().once('trackBegan', () => {done()})
trackTimer.reset(0.01);
})
it("should return end event after 0.1s", function(done) {
trackTimer.init();
trackTimer.reset(0.01).once('trackEnded', () => {done()})
})
it("should return pause event", function(done) {
this.slow(210);
trackTimer.init();
trackTimer.reset(0.2).once("trackPaused", () => setTimeout( () => {done()},100)); //give time for rest of tests to pass
setTimeout( () => {
trackTimer.pause();
expect(trackTimer.currentPlayingTrackDuration).to.be.equal(0.2);
expect(trackTimer.currentPlayingTrackPlayed).to.be.above(0.09);
expect(trackTimer.currentPlayingTrackPlayed).to.be.below(0.21);
},100);
})
it("should handle resume event", function(done) {
this.slow(270);
trackTimer.init();
trackTimer.reset(0.3).once("trackResumed", () => setTimeout( () => {done()},100)); //give time for rest of tests
setTimeout( () => {
trackTimer.pause();
},100);
setTimeout( () => {
trackTimer.resume();
},150);
setTimeout( () => {
expect(trackTimer.currentPlayingTrackDuration).to.be.equal(0.3);
expect(trackTimer.currentPlayingTrackPlayed).to.be.above(0.09);
expect(trackTimer.currentPlayingTrackPlayed).to.be.below(0.31);
},260)
});
})
})
describe("#interactTimerModule", function() {
context("basic tests", function() {
var interactTimer = timerModule.interactTimer;
it("should return instance of eventEmitter", function() {
expect(interactTimer.init()).to.be.instanceOf(events);
})
it("should have time delay of 2 without configuration", function() {
expect(interactTimer.timeDelay).to.equal(2);
})
it("should have time delay of 3 after configuration", function(done) {
interactTimer.init(3);
expect(interactTimer.timeDelay).to.equal(3);
done();
})
})
context("event-driven tests", function() {
var interactTimer = timerModule.interactTimer;
it("should return instance of eventEmitter on init", function() {
expect(interactTimer.init()).to.be.instanceOf(events);
})
it("should return instance of eventEmitter on reset", function() {
expect(interactTimer.reset()).to.be.instanceOf(events);
})
it("should return canInteract based on whether timer has expired", function(done) {
this.slow(110);
interactTimer.init(0.1);
expect(interactTimer.canInteract()).to.be.equal(true);
interactTimer.reset();
expect(interactTimer.canInteract()).to.be.equal(false);
setTimeout( () => {
expect(interactTimer.canInteract()).to.be.equal(true);
done();
},105);
})
it("should handle cannotInteract event", function(done) {
this.slow(110);
interactTimer.init(0.1).once("cannotInteract", () => done())
interactTimer.reset(); //reset before previous timeout expired
})
it("should handle canInteract event", function(done) {
this.slow(110);
interactTimer.init(0.1).once("canInteract", () => done())
interactTimer.reset(); //reset before previous timeout expired
})
})
})
describe("#trackController", function() {
context("basic tests", function() {
it("should control tracks")
})
})
|
import React, { useState, useContext, useEffect } from 'react';
import { Link } from 'react-router-dom';
import AlertContext from '../../context/alerts/alertContext';
import AuthContext from '../../context/auth/authContext';
const Login = (props) => {
// Extract values from context
const alertContext = useContext(AlertContext);
const { alert, showAlert } = alertContext;
// Extract values from Auth context
const authContext = useContext(AuthContext);
const { login, message, authenticated } = authContext;
// In case of password or user doesn't exist reload component
useEffect(() => {
if (authenticated) {
props.history.push('/projects');
}
if (message) {
showAlert(message.msg, message.category);
}
// eslint-disable-next-line
}, [message, authenticated, props.history]);
// Stae for Login
const [user, setUser] = useState({
email: '',
password: '',
});
// Extract data from user
const { email, password } = user;
const onChangeLogin = (e) => {
setUser({
...user,
[e.target.name]: e.target.value,
});
};
// User Login
const onSubmitForm = (e) => {
e.preventDefault();
// Validate empty fields
if (email.trim() === '' || password.trim() === '') {
showAlert('Todos los campos son obligatorios', 'alerta-error');
}
// Pass to action
login({ email, password });
};
return (
<div className="form-usuario">
{alert ? <div className={`alerta ${alert.category}`}>{alert.msg}</div> : null}
<div className="contenedor-form sombra-dark">
<h1>Iniciar Sesión</h1>
<form onSubmit={onSubmitForm}>
<div className="campo-form">
<label htmlFor="email">Email</label>
<input
type="email"
id="email"
name="email"
placeholder="Tu Email"
value={email}
onChange={onChangeLogin}
></input>
</div>
<div className="campo-form">
<label htmlFor="email">Password</label>
<input
type="password"
id="password"
name="password"
value={password}
placeholder="Tu Password"
onChange={onChangeLogin}
></input>
</div>
<div className="campo-form">
<input type="submit" className="btn btn-primario btn-block" value="Iniciar Sesión"></input>
</div>
</form>
<Link className="enlace-cuenta" to={'/new-account'}>
Obtener una cuenta
</Link>
</div>
</div>
);
};
export default Login;
|
console.log('Hellow!!#1');
$(document).ready(function(){
console.log('Hellow!!');
});
|
/**
* CostCenter holds CostCenter specific js logic
*/
var CostCenter = {};
/**
* init CostCenter specific js
*/
CostCenter.init = function(){
CostCenter.onAddBuyerToCostCenter();
CostCenter.onAddApproverToCostCenter();
}
/**
* Modal dialog to add a buyer to the cost center
*/
CostCenter.onAddBuyerToCostCenter = function(){
$(document).on('click', '.open-general-costcenter-modal', function(event){
event.preventDefault();
var button = $(this);
var url = $(this).attr('data-url');
var modal = $('#general-costcenter-modal');
$(modal).modal('hide');
$.ajax({
url : url,
success : function(data){
$(modal).find('.modal-body').html(data);
$(modal).find('.modal-title').html(button.attr('data-quick-title'));
$(modal).modal('show');
}
});
});
}
/**
* Modal dialog to add a approver to the cost center
*/
CostCenter.onAddApproverToCostCenter = function(){
$(document).on('click', '.open-general-costcenter-modal', function(event){
event.preventDefault();
var button = $(this);
var url = $(this).attr('data-url');
var modal = $('#general-costcenter-modal');
$(modal).modal('hide');
$.ajax({
url : url,
success : function(data){
$(modal).find('.modal-body').html(data);
$(modal).find('.modal-title').html(button.attr('data-quick-title'));
$(modal).modal('show');
}
});
});
}
/*
* init CostCenter specific js
*/
$(function(){
CostCenter.init();
});
/**
* Modal dialog to create a new cost center
*/
$(document).on('click', '.open-costcenter-modal', function(event){
event.preventDefault();
var button = $(this);
var url;
if ($(this).attr('href')) {
url = $(this).attr('href');
}
if ($(this).attr('data-url')) {
url = $(this).attr('data-url');
}
var modal = $('#general-costcenter-modal');
$(modal).modal('hide');
$.ajax({
url : url,
success : function(data){
$(modal).find('.modal-body').html(data);
$(modal).find('.modal-title').html(button.attr('data-quick-title'));
$(modal).modal('show');
var form = $(modal).find('form');
form.bootstrapValidator();
}
});
});
|
var Test = function(name, res) {
this.name = name;
this.answer = res == 0 ? "Failed" : "Passed";
};
var TestRunner = function(clazz) {
var results = [];
for (property in clazz) {
if (property.substring(0, 4) == "test" ) {
results.push(new Test(property, clazz[property]()));
}
}
return results;
};
|
const globby = require("globby");
const fs = require("fs-extra");
const parsePath = require("parse-filepath");
const Template = require("./Template");
const TemplatePath = require("./TemplatePath");
const TemplateMap = require("./TemplateMap");
const TemplateRender = require("./TemplateRender");
const TemplatePassthrough = require("./TemplatePassthrough");
const EleventyError = require("./EleventyError");
const Pagination = require("./Plugins/Pagination");
const TemplateGlob = require("./TemplateGlob");
const pkg = require("../package.json");
const eleventyConfig = require("./EleventyConfig");
const config = require("./Config");
const debug = require("debug")("Eleventy:TemplateWriter");
function TemplateWriter(inputPath, outputDir, extensions, templateData) {
this.config = config.getConfig();
this.input = inputPath;
this.inputDir = this._getInputPathDir(inputPath);
this.templateExtensions = extensions;
this.outputDir = outputDir;
this.templateData = templateData;
this.isVerbose = true;
this.writeCount = 0;
this.includesDir = this.inputDir + "/" + this.config.dir.includes;
// Duplicated with TemplateData.getDataDir();
this.dataDir = this.inputDir + "/" + this.config.dir.data;
// Input was a directory
if (this.input === this.inputDir) {
this.rawFiles = TemplateGlob.map(
this.templateExtensions.map(
function(extension) {
return this.inputDir + "/**/*." + extension;
}.bind(this)
)
);
} else {
this.rawFiles = TemplateGlob.map([inputPath]);
}
this.watchedFiles = this.addIgnores(this.inputDir, this.rawFiles);
this.files = this.addWritingIgnores(this.inputDir, this.watchedFiles);
this.templateMap;
}
TemplateWriter.prototype.restart = function() {
this.writeCount = 0;
debug("Resetting writeCount to 0");
};
TemplateWriter.prototype.getIncludesDir = function() {
return this.includesDir;
};
TemplateWriter.prototype.getDataDir = function() {
return this.dataDir;
};
TemplateWriter.prototype._getInputPathDir = function(inputPath) {
// Input points to a file
if (!fs.statSync(inputPath).isDirectory()) {
return parsePath(inputPath).dir;
}
// Input is a dir
if (inputPath) {
return inputPath;
}
return ".";
};
TemplateWriter.prototype.getRawFiles = function() {
return this.rawFiles;
};
TemplateWriter.prototype.getWatchedIgnores = function() {
return this.addIgnores(this.inputDir, []).map(ignore =>
TemplatePath.stripLeadingDotSlash(ignore.substr(1))
);
};
TemplateWriter.prototype.getFiles = function() {
return this.files;
};
TemplateWriter.getFileIgnores = function(ignoreFile) {
let dir = parsePath(ignoreFile).dir || ".";
let ignorePath = TemplatePath.normalize(ignoreFile);
let ignoreContent;
try {
ignoreContent = fs.readFileSync(ignorePath, "utf-8");
} catch (e) {
ignoreContent = "";
}
let ignores = [];
if (ignoreContent) {
ignores = ignoreContent
.split("\n")
.map(line => {
return line.trim();
})
.filter(line => {
// empty lines or comments get filtered out
return line.length > 0 && line.charAt(0) !== "#";
})
.map(line => {
let path = TemplateGlob.normalizePath(dir, "/", line);
debug(`${ignoreFile} ignoring: ${path}`);
try {
let stat = fs.statSync(path);
if (stat.isDirectory()) {
return "!" + path + "/**";
}
return "!" + path;
} catch (e) {
return "!" + path;
}
});
}
return ignores;
};
TemplateWriter.prototype.addIgnores = function(inputDir, files) {
files = files.concat(
TemplateWriter.getFileIgnores(inputDir + "/.eleventyignore")
);
files = files.concat(TemplateWriter.getFileIgnores(".gitignore"));
files = files.concat(TemplateGlob.map("!" + this.outputDir + "/**"));
return files;
};
TemplateWriter.prototype.addWritingIgnores = function(inputDir, files) {
if (this.config.dir.includes) {
files = files.concat(TemplateGlob.map("!" + this.includesDir + "/**"));
}
if (this.config.dir.data && this.config.dir.data !== ".") {
files = files.concat(TemplateGlob.map("!" + this.dataDir + "/**"));
}
return files;
};
TemplateWriter.prototype._getAllPaths = async function() {
// Note the gitignore: true option for globby is _really slow_
return globby(this.files); //, { gitignore: true });
};
TemplateWriter.prototype._getTemplate = function(path) {
let tmpl = new Template(
path,
this.inputDir,
this.outputDir,
this.templateData
);
tmpl.setIsVerbose(this.isVerbose);
/*
* Sample filter: arg str, return pretty HTML string
* function(str) {
* return pretty(str, { ocd: true });
* }
*/
for (let filterName in this.config.filters) {
let filter = this.config.filters[filterName];
if (typeof filter === "function") {
tmpl.addFilter(filter);
}
}
let writer = this;
tmpl.addPlugin("pagination", async function(data) {
let paging = new Pagination(data);
paging.setTemplate(this);
await paging.write();
writer.writeCount += paging.getWriteCount();
if (paging.cancel()) {
return false;
}
});
return tmpl;
};
TemplateWriter.prototype._copyPassthroughs = async function(paths) {
if (!this.config.passthroughFileCopy) {
debug("`passthroughFileCopy` is disabled in config, bypassing.");
return;
}
for (let path of paths) {
if (!TemplateRender.hasEngine(path)) {
let pass = new TemplatePassthrough(path, this.outputDir);
try {
await pass.write();
} catch (e) {
throw EleventyError.make(
new Error(`Having trouble copying: ${path}`),
e
);
}
}
}
};
TemplateWriter.prototype._createTemplateMap = async function(paths) {
this.templateMap = new TemplateMap();
for (let path of paths) {
if (TemplateRender.hasEngine(path)) {
await this.templateMap.add(this._getTemplate(path));
debug(`Template for ${path} added to map.`);
}
}
await this.templateMap.cache();
return this.templateMap;
};
TemplateWriter.prototype._writeTemplate = async function(mapEntry) {
let outputPath = mapEntry.outputPath;
let data = mapEntry.data;
let tmpl = mapEntry.template;
try {
await tmpl.writeWithData(outputPath, data);
} catch (e) {
throw EleventyError.make(
new Error(`Having trouble writing template: ${outputPath}`),
e
);
}
this.writeCount += tmpl.getWriteCount();
return tmpl;
};
TemplateWriter.prototype.write = async function() {
debug("Searching for: %O", this.files);
let paths = await this._getAllPaths();
debug("Found: %o", paths);
await this._copyPassthroughs(paths);
await this._createTemplateMap(paths);
for (let mapEntry of this.templateMap.getMap()) {
await this._writeTemplate(mapEntry);
}
eleventyConfig.emit(
"alldata",
this.templateMap.getCollection().getAllSorted()
);
debug("`alldata` event triggered.");
};
TemplateWriter.prototype.setVerboseOutput = function(isVerbose) {
this.isVerbose = isVerbose;
};
TemplateWriter.prototype.getWriteCount = function() {
return this.writeCount;
};
module.exports = TemplateWriter;
|
(function () {
"use strict";
angular.module('omdb', ['frontmovies'])
.factory('omdbService', function ($http, $q) {
var movieData = {"Title":"Star Wars","Year":"1983","Rated":"N/A","Released":"01 May 1983","Runtime":"N/A","Genre":"Action, Adventure, Sci-Fi","Director":"N/A","Writer":"N/A","Actors":"Harrison Ford, Alec Guinness, Mark Hamill, James Earl Jones","Plot":"N/A","Language":"English","Country":"USA","Awards":"N/A","Poster":"N/A","Metascore":"N/A","imdbRating":"7.8","imdbVotes":"349","imdbID":"tt0251413","Type":"game","Response":"True"};
var movieDataById = {"Title":"Star Wars","Year":"1983","Rated":"N/A","Released":"01 May 1983","Runtime":"N/A","Genre":"Action, Adventure, Sci-Fi","Director":"N/A","Writer":"N/A","Actors":"Harrison Ford, Alec Guinness, Mark Hamill, James Earl Jones","Plot":"N/A","Language":"English","Country":"USA","Awards":"N/A","Poster":"N/A","Metascore":"N/A","imdbRating":"7.8","imdbVotes":"349","imdbID":"tt0251413","Type":"game","Response":"True"};
var baseUrl = 'http://www.omdbapi.com/?v=1&';
return {
search: function (query) {
var myPromise = $q.defer();
$http.get(baseUrl + 's=' + encodeURIComponent(query))
.success(function (data) {
myPromise.resolve(data);
});
return myPromise.promise;
},
searchById: function (id) {
var myPromise = $q.defer();
$http.get(baseUrl + 'i=' + id)
.success(function (data) {
myPromise.resolve(data);
});
return myPromise.promise;
}
}
});
}());
|
/**
* Created by alucas on 12/1/17.
*/
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import mui from 'material-ui'
import * as homeActions from '../../actions/homeActions';
import PdfViewer, {PDF} from './PdfViewer';
import { Link } from 'react-router';
class Documentation extends Component {
static propTypes = {
location: React.PropTypes.object.isRequired,
};
static contextTypes = {
history: PropTypes.object.isRequired
};
getStyles() {
return {
root: {
paddingTop: 64
}
}
}
componentDidMount() {
}
constructor(props) {
super(props);
}
render() {
let styles = this.getStyles();
return (
<div style={styles.root}>
<h2>Documentation</h2>
<PDF src={'https://cdn.rawgit.com/andresin87/ProgrammingSudoku/94b7a191/docs/Programming%20Sudoku%20(2006)%20%20Wei-Meng%20Lee.pdf'}>
<PdfViewer />
</PDF>
</div>
);
}
}
function mapStateToProps(state) {
return {};
}
export default connect(
mapStateToProps
)(Documentation);
|
"use strict";
const format = require("../utils/format");
function apply(api) {
Object.keys(api).forEach((className) => {
if (/^[A-Z]\w+$/.test(className) && typeof api[className] === "function") {
const klass = api[className];
Object.getOwnPropertyNames(klass.prototype).forEach((methodName) => {
const desc = Object.getOwnPropertyDescriptor(klass.prototype, methodName);
if (typeof desc.get === "function" && typeof desc.set === "undefined") {
Object.defineProperty(klass.prototype, methodName, Object.assign(desc, { set: readonly(className, methodName) }));
}
});
}
});
}
function readonly(className, methodName) {
return function() {
const klassName = (this._ && this._.className) || className;
throw new TypeError(format(`
Faild to set the '${ methodName }' property on '${ klassName }'.
The ${ methodName } is readonly, but attempt to set a value.
`));
};
}
module.exports = { apply };
|
import {types} from '../types/types'
import {db} from '../firebase/firebaseConfig'
export const registroUsuarios=(id,nombre,email,telefono)=>{
return async (dispatch)=>{
const nuevoUsuario={
id: id,
nombre:nombre,
email:email,
telefono: telefono
}
await db.collection('/Usuario').add(nuevoUsuario);
console.log(id,nombre, email,telefono)
dispatch(registro(id,nombre, email,telefono));
}
}
export const registro = (id,nombre, email,telefono)=>{
return{
type: types.Registrar,
payload:{
id,
nombre,
email,
telefono}
}
}
|
const AWSEmulator = require('./aws-emulator.js')
module.exports = AWSEmulator
|
import React, { Component } from 'react';
import styles from './Layout.module.css';
import * as actionTypes from '../../store/actions';
import { connect } from "react-redux";
class Layout extends Component {
render() {
return (
<React.Fragment>
{/* HEADER */}
<main className={styles.Content}>
{this.props.children}
</main>
</React.Fragment>
)
}
}
const mapStateToProps = state => {
return {
dummyProp: state.dummyProp,
token: state.token
};
}
const mapDispatchToProps = dispatch => {
return {
dummyAction: () => dispatch({type: actionTypes.DUMMY_ACTION}),
dummyWithPayloadAction: (token) => dispatch({type: actionTypes.DUMMY_ACTION_WITH_PAYLOAD, token}),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Layout);
|
import React from "react";
const Product = ({ products, selectedProduct, history }) => {
const handlePurchase = (prod) => () => {
console.log(prod)
selectedProduct(prod);
history.push("/checkout");
};
return products.map((prod) => {
return (
<div className="product" key={prod.id}>
<section>
<h2>{prod.name}</h2>
<p>{prod.desc}</p>
<h3>{"$" + prod.price}</h3>
<button type="button" onClick={handlePurchase(prod)}>
PURCHASE
</button>
</section>
<img src={prod.img} alt={prod.name} />
</div>
);
});
};
export default Product;
|
const kwh = 0.05;
let consumo = 280 * kwh
console.log("O valor a ser pago de consumo é R$ " + consumo);
let consumoDesconto = consumo * 0.15;
consumo = consumo - consumoDesconto;
console.log("O valor a ser pago de consumo com desconto é R$ " + consumo);
|
OC.L10N.register(
"lib",
{
"Unknown filetype" : "Berkas ora jelas",
"Invalid image" : "Dudu gambar"
},
"nplurals=1; plural=0;");
|
function solve(speed, zoneInput)
{
let kmh=Number(speed);
let zone=zoneInput;
let speedLimit=0;
let output='';
if (zone=='motorway')
{
speedLimit=130;
}
else if (zone=='interstate')
{
speedLimit=90;
}
else if (zone=='city')
{
speedLimit=50;
}
else if (zone=='residential')
{
speedLimit=20;
}
if (kmh-speedLimit<=0)
{
output=`Driving ${kmh} km/h in a ${speedLimit} zone`;
}
else
{
let status='';
if (kmh-speedLimit<=20)
{
status='speeding';
}
else if(kmh - speedLimit <=40)
{
status=`excessive speeding`;
}
else
{
status='reckless driving';
}
output=`The speed is ${kmh-speedLimit} km/h faster than the allowed speed of ${speedLimit} - ${status}`
}
console.log(output);
}
solve(40, 'city');
solve(120, 'interstate')
|
import React, { useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { UserInfoContainer } from "./UserInfoContainer";
import { PetContainer } from "./PetContainer";
import { Divider, Icon, Modal } from "semantic-ui-react";
import { Link } from "react-router-dom";
import { AddTaskForm } from "./AddTaskForm";
import { AddApptForm } from "./AddApptForm";
import { AddPetForm } from "./AddPetForm";
import { BACKEND_HOST } from "./ip";
export function UserHomePage() {
const dispatch = useDispatch();
const user = useSelector(state => state.currentUser);
const modal = useSelector(state => state.modal);
const showAddPetForm = size => {
dispatch({ type: "CHANGE_MODAL", key: "display", payload: "addpetform" });
dispatch({ type: "CHANGE_MODAL", key: "size", payload: size });
dispatch({ type: "CHANGE_MODAL", key: "open", payload: true });
};
const closeModal = () => {
dispatch({ type: "CHANGE_MODAL", key: "open", payload: false });
};
useEffect(() => {
if (localStorage.token != null) {
fetch(`http://${BACKEND_HOST}/get_user`, {
headers: {
Authorization: `Bearer ${localStorage.token}`
}
})
.then(response => response.json())
.then(response => dispatch({ type: "STORE_CURRENT_USER", payload: response }));
} else {
console.log("cannot find token");
}
}, [dispatch]);
if (user === null) return <h1>Loading</h1>;
return (
<div className='background1' style={{ height: "100vh" }}>
<div style={{ padding: "2%", fontFamily: "Montserrat" }}>
<Link className='ui right floated teal button' to='/' onClick={() => localStorage.clear()}>
Log Out
</Link>
</div>
<div style={{ margin: "auto", paddingTop: "5%" }}>
<UserInfoContainer />
<Divider horizontal>
<div className='ui teal button' onClick={() => showAddPetForm("mini")}>
<Icon name='plus' />
<span>ADD PET</span>
</div>
</Divider>
{user.user.pets.map(pet => (
<PetContainer pet={pet} />
))}
</div>
<Modal size={modal.size} open={modal.open} onClose={() => closeModal()}>
{modal.display === "apptform" || modal.display === "taskform" ? (
<Modal.Header>{modal.display === "apptform" ? "Request an Appointment" : "Send a Message"}</Modal.Header>
) : (
<Modal.Header>Add a pet</Modal.Header>
)}
{modal.display === "apptform" || modal.display === "taskform" ? (
<Modal.Content>{modal.display === "apptform" ? <AddApptForm /> : <AddTaskForm />}</Modal.Content>
) : (
<Modal.Content>
<AddPetForm />
</Modal.Content>
)}
</Modal>
</div>
);
}
|
import { jsonp } from "common/js/jsonp";
import { commonParams, options } from "api/config";
import axios from 'axios';
export function getRank() {
let url='https://c.y.qq.com/v8/fcg-bin/fcg_myqq_toplist.fcg'
let data=Object.assign({}, commonParams, {
notice: 0,
platform: 'h5',
needNewCode: 1
})
return jsonp(url, data, options)
}
export function getTopList(topid) {
let url='https://c.y.qq.com/v8/fcg-bin/fcg_v8_toplist_cp.fcg'
let data=Object.assign({}, commonParams, {
notice: 0,
platform: 'h5',
needNewCode: 1,
tpl: 3,
page: 'detail',
type: 'top',
topid
})
return jsonp(url, data, options)
}
|
import React, { Component } from 'react';
import './index.css';
import api from '../../http/api.js';
import Articlebox from '../../components/articlebox'
import Loadmore from '../../components/loadmore';
import Loading from '../../components/loading';
class Liketop extends Component {
constructor(props) {
super(props);
this.state = {
config:{page:1,order:'likeCount'},
data:[],
ismore:true,
initing:true
}
}
componentDidMount(){
this.getData(this.state.config);
}
componentWillUnmount(){
// 卸载异步操作设置状态
this.setState = (state, callback) => {
return;
}
}
getData(config, callback){
api.serchpage(config)
.then(res=>res.json())
.then(data=>{
callback && callback();
if (data.status === 1){
this.setState({
data:[...this.state.data, ...data.data],
config:{...this.state.config, page:this.state.config.page+1},
ismore:data.data.length>=10,
initing:false
});
}
})
.catch(error=>{
callback && callback();
});
}
loadMore = (callback)=>{
this.getData(this.state.config, callback);
};
render() {
return (
this.state.initing?
<Loading/>
:
<div className='like-top-box'>
{
this.state.data.map((value, index)=>{
return (
<div key={value.id} className='like-top-one'>
<span>{index+1}</span>
<Articlebox
data={value}
history={this.props.history}
/>
</div>
)
})
}
<Loadmore isMore={this.state.ismore} loadMore={this.loadMore}/>
</div>
)
}
}
export default Liketop;
|
class Game extends React.Component {
constructor(props) {
super(props);
this.state = {
game: Object.assign({}, game_init),
board: JSON.parse(JSON.stringify(board_init)), // Deep clone,
};
this.initGame = this.initGame.bind(this);
this.resetGame = this.resetGame.bind(this);
this.startGame = this.startGame.bind(this);
this.rollDice = this.rollDice.bind(this);
this.play = this.play.bind(this);
this.assignPlayer = this.assignPlayer.bind(this);
this.unAssignPlayer = this.unAssignPlayer.bind(this);
}
initGame() {
let game = Object.assign({}, this.state.game);
this.setState({
game: {
...game,
game_state: 1
}
});
}
resetGame() {
this.setState({
game: Object.assign({}, game_init),
board: JSON.parse(JSON.stringify(board_init)) // Deep clone
});
}
startGame() {
let game = this.state.game;
this.setState({
game: {
...game,
game_state: 2,
active_player: 0
}
});
}
assignPlayer(player, color) {
const game = this.state.game;
const players = [...game.players];
players.push({ color, type: player });
this.setState({
game: {
...game,
players
}
});
}
unAssignPlayer(color) {
const game = this.state.game;
const players = game.players.filter(p => p.color !== color);
this.setState({
game: {
...game,
players
}
});
}
nextPlayer(player) {
return (player + 1) % this.state.game.players.length;
}
nextPosition(curr_pos, dice_roll, home_turn, finish) {
let next_pos = -1;
if (curr_pos > 200) {
next_pos = curr_pos;
} else if (curr_pos >= 100) {
// special handling for 151
let cpos = curr_pos === 151 ? curr_pos - 52 : curr_pos;
next_pos = cpos + dice_roll;
next_pos = next_pos <= finish ? next_pos : curr_pos;
} else {
next_pos = (curr_pos + dice_roll) % 52;
// Check for home run
if (curr_pos <= home_turn && home_turn < curr_pos + dice_roll) {
next_pos = next_pos + 100;
}
}
return next_pos;
}
rollDice(player_idx) {
const board = JSON.parse(JSON.stringify(this.state.board));
let game = Object.assign({}, this.state.game);
let canPlay = false;
const player = game.players[player_idx].color;
// Dice Roll
const dice_roll = Math.floor(Math.random() * 6 + 1);
// const dice_roll = parseInt(document.getElementById("dice").value);
// Calculate status and next position for player coins
for (const coin in board[player]) {
const curr_position = board[player][coin].pos;
// Ignore coins who have finished
if (curr_position === board_metadata[player].finish) {
continue;
}
// Compute next position
const next_position = this.nextPosition(
curr_position,
dice_roll,
board_metadata[player].turn,
board_metadata[player].finish
);
// On dice roll outcome 6
if (dice_roll == 6) {
// Activate jailed coins
if (curr_position > 200) {
canPlay = true;
board[player][coin].status = 1;
board[player][coin].next_pos = board_metadata[player].start;
}
// Activate board coins
else if (curr_position < 52) {
canPlay = true;
board[player][coin].status = 1;
board[player][coin].next_pos = next_position;
}
}
// Other dice roll outcomes
else {
if (next_position != curr_position) {
canPlay = true;
board[player][coin].status = 1;
board[player][coin].next_pos = next_position;
}
}
}
if (canPlay) {
game = {
...game,
board_active: true,
active_player: player_idx,
dice_roll,
prev_player: undefined,
prev_roll: undefined
};
} else {
const next_player_idx = this.nextPlayer(player_idx);
game = {
...game,
board_active: false,
active_player: next_player_idx,
dice_roll: -1,
prev_player: player_idx,
prev_roll: dice_roll
};
}
this.setState({
game,
board
});
}
play(player_idx, coin, dice_roll) {
let game = Object.assign({}, this.state.game);
const board = JSON.parse(JSON.stringify(this.state.board));
const coin_position_map = getPositionMap(board);
const player = game.players[player_idx].color;
const player_next_pos = board[player][coin].next_pos;
let playAgain = false;
let gaveOver = false;
// Handle next_pos having existing player
if (!safe_cells.includes(player_next_pos)) {
// Fetching existing_player, if any, from next_pos
const existing_player = coin_position_map[player_next_pos]
? coin_position_map[player_next_pos][0]
: undefined;
// Handle next_pos has another coin of different player, send coin to jail
if (existing_player && existing_player.player != player) {
const jail_position =
board[existing_player.player][existing_player.coin].jail_pos;
board[existing_player.player][existing_player.coin].pos = jail_position;
board[existing_player.player][
existing_player.coin
].next_pos = jail_position;
playAgain = true;
}
}
// Handle next_pos is home/finish
if (player_next_pos === board_metadata[player].finish) {
board[player][coin].pos = player_next_pos;
board[player][coin].status = 2;
// Check game over condition
if (Object.values(board[player]).every(coin => coin.status === 2)) {
gaveOver = true;
} else {
playAgain = true;
}
} else {
// Move the active coin
if (board[player][coin].status === 1) {
board[player][coin].pos = player_next_pos;
}
// Remove active status of other coins for player
for (const coin in board[player]) {
if (board[player][coin].status === 1) {
board[player][coin].status = 0;
}
}
}
if (gaveOver) {
game = {
...game,
game_state: 3,
board_active: false,
active_player: player_idx,
dice_roll: -1
};
}
// Player rolls again
else if (playAgain || dice_roll == 6) {
game = {
...game,
board_active: false,
active_player: player_idx,
dice_roll: -1
};
}
// Next player's turn
else {
const next_player_idx = this.nextPlayer(player_idx);
game = {
...game,
board_active: false,
active_player: next_player_idx,
dice_roll: -1
};
}
this.setState({
game,
board
});
}
componentDidUpdate() {
// Set up bot play
if (isBotsTurn(this.state.game)) {
botPlay(this.state.game, this.state.board);
}
}
render() {
const game = [];
game.push(
<Board
key="board"
board={this.state.board}
game={this.state.game}
initGame={this.initGame}
resetGame={this.resetGame}
coinClickHandler={this.play}
diceClickHandler={this.rollDice}
/>
);
if (this.state.game.game_state === 1) {
game.push(
<DraggableAssignBox
key="assignmentbox"
game={this.state.game}
startClickHandler={this.startGame}
assignPlayer={this.assignPlayer}
unAssignPlayer={this.unAssignPlayer}
/>
);
}
return <div className="game-container">{game}</div>;
}
}
ReactDOM.render(<Game />, document.getElementById("root"));
|
module.exports = function(grunt) {
'use strict';
var config = require('../task');
grunt.config('imageoptim', {
images: {
options: {
jpegMini: false,
imageAlpha: true,
quitAfter: true
},
src: config.imagemin
}
});
grunt.loadNpmTasks('grunt-imageoptim');
};
|
/**
* Created by zhangfan on 17-4-11.
*/
import React, {Component, PureComponent} from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Navigator
} from 'react-native';
class ModuleRoot extends PureComponent {
state = {
viewList: []
};
sequence = 0;
render() {
return (
<View style={{position: "absolute", left: 0, right: 0, top: 0, bottom: 0}}>
{this.state.viewList.map(this.renderItem)}
</View>
)
}
renderItem = (it) =>
<View style={{position: "absolute", left: 0, right: 0, top: 0, bottom: 0}} key={it.id}>
{it.component}
</View>;
insertModule = (moduleView) => {
let moduleBean = new ModuleBean();
moduleView.props.dismissCallback(() => {
let index = this.state.viewList.indexOf(moduleBean);
if (index > -1) {
this.state.viewList.splice(index, 1);
// this.setState({})
this.forceUpdate();
}
});
moduleBean.id = this.sequence++;
moduleBean.component = moduleView;
this.state.viewList.push(moduleBean);
// this.setState({})
this.forceUpdate();
}
componentWillMount() {
this.props.handlerInsertModule(this.insertModule);
};
}
class ModuleBean {
id = 0;
component = null;
}
export default ModuleRoot
|
import React from 'react';
import Button from '../components/Button';
import PageHeader from '../components/PageHeader';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import { signIn } from '../redux/actions';
class SignInPage extends React.Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: ''
};
this.onFieldChange = this.onFieldChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
render() {
return (
<div className="content__centered">
<PageHeader title="Logowanie" />
<form className="form form--signin" onSubmit={this.onSubmit}>
<label htmlFor="email" className="form__label">Adres email</label>
<input type="email" id="email" className="input input--dark"
placeholder="Adres email" onChange={this.onFieldChange} required />
<label htmlFor="password" className="form__label">Hasło</label>
<input type="password" id="password" className="input input--dark"
placeholder="Hasło" onChange={this.onFieldChange} required />
<Button text="Zaloguj się" submit />
</form>
</div>
);
}
onFieldChange(event) {
this.setState({
[event.target.id]: event.target.value
})
}
onSubmit(event) {
event.preventDefault();
this.props.onSignIn(this.state.email, this.state.password);
}
}
const mapDispatchToProps = dispatch => ({
onSignIn: (email, password) => dispatch(signIn(email, password))
});
export default withRouter(
connect(null, mapDispatchToProps)(SignInPage)
);
|
/**
* Created by diakabanab on 10/23/2016.
*/
define(function() {
/**
* Maps the points of the notes on the circle
* @param theta
* @param radius
* @returns {{x: number, y: number}}
*/
function toCartesian(theta, radius) {
return {
x: radius * Math.cos(theta),
y: radius * Math.sin(theta)
};
}
var innerRadius = 0.66;
var majorOrder = ["C", "G", "D", "A", "E", "B", "F#", "C#", "G#", "A#", "F"];
var minorOrder = ["A", "E", "B", "F#", "C#", "G#", "D#", "A#", "F", "C", "G", "D"];
var majorCoordinates = {};
var minorCoordinates = {};
var threshold = 0.01;
// draws major slices first
var arcSize = Math.PI * 2 / majorOrder.length;
var startAngle = 0 - arcSize / 2 - Math.PI / 2;
for (var i = 0; i < majorOrder.length; i++) {
var coordinates = {
startAngle : startAngle - threshold,
endAngle : startAngle + arcSize + threshold,
innerRadius : innerRadius,
outerRadius : 1
};
coordinates.center = toCartesian((coordinates.endAngle + coordinates.startAngle) / 2,
(coordinates.outerRadius + coordinates.innerRadius) / 2);
majorCoordinates[majorOrder[i]] = coordinates;
startAngle += arcSize;
}
// onto the minor slices
for (var j = 0; j < minorOrder; j++) {
var minorCoords = {
startAngle : startAngle - threshold,
endAngle : startAngle + arcSize + threshold,
innerRadius : 0,
outerRadius : innerRadius
};
minorCoords.center = toCartesian((minorCoords.endAngle + coordinates.startAngle) / 2,
(minorCoords.outerRadius * 3) / 4);
minorCoordinates[minorOrder[j]] = minorCoords;
startAngle += arcSize;
}
return {
major : majorCoordinates,
minor : minorCoordinates,
majorOrder : majorOrder,
minorOrder : minorOrder,
innerRadius : innerRadius
};
});
|
/**
* Created by a689638 on 2/3/2016.
*/
(function () {
'use strict';
angular.module('routerApp').controller('ArchetypeOneController', ['DriveFileService', 'FileStructureService', 'CurrentEntity',
function (DriveFileService, FileStructureService, CurrentEntity) {
var vm = this;
CurrentEntity.entity.arch = {
name: "",
about: "Holds the data for the stuff",
tags: ["fnd"],
displayField: "Name",
data: [{
name: "Name"
}, {
name: "Characteristics",
type: "array-val",
data: [{
name: "int"
}, {
name: "char"
}, {
name: "float"
}, {
name: "string"
}]
}, {
name: "Skills",
type: "array-val",
data: [{
name: "skill1"
}, {
name: "skill2"
}, {
name: "skill3"
}]
}, {
name: "Items",
type: "array-arch"
}],
mainView: [{
data: "Name",
view: "single-string"
}, {
data: "Characteristics",
view: "int-row"
}, {
data: "Skills",
view: "int-list"
}, {
data: "Items",
view: "link-list"
}]
};
CurrentEntity.entity.data = [
"name goes here"
, [6, 7, 8, 9]
, [1, 2, 3], [{
link: "354jnkwj5nkjsdfn43",
name: "Item1"
}, {
link: "12j43k3sdfnjn5d54n",
name: "Item2"
}]];
vm.editing = CurrentEntity.entity.editing;
vm.d = CurrentEntity.entity.data;
vm.arch = CurrentEntity.entity.arch;
vm.editOptions = getEditOptions();
vm.editSubOptions = getEditSubOptions();
vm.getIndexBySubName = function (name, subName) {
var dd = _.findIndex(CurrentEntity.entity.arch.data, function (it) {
return it.name == name;
});
var arr = CurrentEntity.entity.arch.data[dd].data;
return _.findIndex(arr, function (it) {
return it.name == subName;
})
};
vm.getIndexByName = function (name) {
return _.findIndex(vm.arch.data, function (it) {
return it.name == name;
});
};
vm.selectSearchType = function (op) {
vm.searchType = op;
};
vm.addOneToSmall = function (index){
console.log("add one to", index)
};
function getEditOptions() {
var deflt = function (index) {
return true;
};
var swap = function (arr, index, indexTo) {
var temp = arr[index];
arr[index] = arr[indexTo];
arr[indexTo] = temp;
};
return [
{
icon: "keyboard_arrow_down",
callback: function (index) {
swap(CurrentEntity.entity.arch.data, index, index + 1);
swap(CurrentEntity.entity.arch.mainView, index, index + 1);
swap(CurrentEntity.entity.data, index, index + 1);
console.log("index move down", index);
},
show: function (index) {
return index < vm.arch.data.length - 1;
}
}, {
icon: "keyboard_arrow_up",
callback: function (index) {
swap(CurrentEntity.entity.arch.data, index, index - 1);
swap(CurrentEntity.entity.arch.mainView, index, index - 1);
swap(CurrentEntity.entity.data, index, index - 1);
console.log("index move up", index);
},
show: function (index) {
return index > 0;
}
},
{
icon: "mode_edit",
callback: function (index) {
console.log("edit", index);
},
show: function () {
return false
}
},
{
icon: "delete",
callback: function (index) {
CurrentEntity.entity.arch.data.splice(index, 1);
CurrentEntity.entity.arch.mainView.splice(index, 1);
CurrentEntity.entity.data.splice(index, 1);
console.log("delete", index);
},
show: deflt
}
]
}
function getEditSubOptions() {
var deflt = function (index) {
return true;
};
var swap = function (arr, index, indexTo) {
var temp = arr[index];
arr[index] = arr[indexTo];
arr[indexTo] = temp;
};
return [
{
icon: "keyboard_arrow_down",
callback: function (mainIndex, index) {
swap(CurrentEntity.entity.arch.data[mainIndex].data, index, index + 1);
console.log("index move down", index);
},
show: function (index) {
return index < vm.arch.data.length - 1;
}
}, {
icon: "keyboard_arrow_up",
callback: function (mainIndex, index) {
swap(CurrentEntity.entity.arch.data[mainIndex].data, index, index - 1);
console.log("index move up", index);
},
show: function (index) {
return index > 0;
}
},
{
icon: "mode_edit",
callback: function (mainIndex, index) {
console.log("edit", index);
},
show: function (index) {
return false
}
},
{
icon: "delete",
callback: function (mainIndex, index) {
CurrentEntity.entity.arch.data[mainIndex].data.splice(index, 1);
console.log("delete", index);
},
show: deflt
}
]
}
}]);
})();
|
// send-bytes.js
var dgram = require('dgram');
var optparse = require('optparse');
var D_PORT = 33333;
var D_ADDR = 'aaaa::0205:0c2a:8c35:8a06';
var S_PORT = 1111;
var S_ADDR = undefined;
var FRZ_PROTO = require('./frz-proto.js');
var FUNCS = require('./sensor-block-proto.js');
// debug log
var dlog = function(s) { console.log(" DEB >>> "+s); }
var errlog = function(s) { console.log("ERROR >>> "+s); }
//var message = new Buffer('My KungFu is Good!');
var client = dgram.createSocket('udp6');
var switches = [
[ '-h', '--help', 'Help info'],
[ '-s', '--sourceaddr [addr]', 'Source address'],
[ '-d', '--destaddr [addr]', 'Destination address'],
[ '-sp', '--sourceport [port]', 'Source port'],
[ '-dp', '--destport [port]', 'Destination port'],
[ '-exec', '--execute [funcname]', 'Execute a function for data' ],
['-r', '--reset', 'Send reset flag.'],
['-l', '--listen', 'Listen only.']
]
var exec_func = null;
var exec_func_name = null;
var parser = new optparse.OptionParser(switches);
var needs_reset = false;
var listen_only = false;
// ------------ options -----------------
parser.on('help',function() {
console.log("Help...");
});
parser.on('sourceaddr',function(name,value){
S_ADDR = value;
});
parser.on('destaddr',function(name,value){
D_ADDR = value;
});
parser.on('sourceport',function(name,value){
S_PORT = parseInt(value);
});
parser.on('destport',function(name,value){
D_PORT = parseInt(value);
console.log("D_PORT = " + D_PORT);
});
parser.on('reset',function(name,value){
needs_reset = true;
});
parser.on('listen',function(name,value){
listen_only = true;
});
parser.on('execute', function(name,value) {
if(!FUNCS[value]) {
console.log("Unknown function!");
process.exit(1);
} else {
exec_func_name = value;
exec_func = FUNCS[exec_func_name];
}
});
//var outBytesStr = [];
var outBuffer = new Buffer(60);
var sendBytes = 0;
var commaString = undefined;
var reset_flag = false;
parser.on(2, function(value) {
console.log('nums: ' + value);
commaString = value.split(',');
});
// // Parse command line arguments
parser.parse(process.argv);
if(exec_func) {
console.log("Using function " + exec_func_name + " for data gen.");
var output = null;
console.log(" EXEC: " + exec_func_name + "("+commaString+") ...");
output = exec_func.apply(undefined,commaString);
if(!output) {
console.log(" function failed. Returned null. Check your parameters");
process.exit(1);
}
sendBytes = output.totalbytes;
outBuffer = output.buffer;
// data
} else {
if(commaString) {
for(var n=0;n<commaString.length;n++) {
console.log(commaString[n]);
if(commaString[n] > 255) {
console.log("ERROR: a number was larger than a byte!");
return;
} else {
outBuffer.writeUInt8(parseInt(commaString[n]),n);
}
}
sendBytes = commaString.length;
} else
sendBytes = 0;
}
var stringifyBytes = function(buf,N) {
var str = "[";
for(var n=0;n<N;n++) {
if(n>0)
str+=',';
str += '0x' + buf.readUInt8(n).toString(16);
}
str += ']';
return str;
}
var str = stringifyBytes(outBuffer,sendBytes);
if(sendBytes > 0)
console.log("Will send " + sendBytes + " bytes. " + str);
// ---------------------------------------
if(1) {
console.log( " SRC->DEST = " + S_ADDR + ":" + S_PORT + " --> " + D_ADDR + ":" + D_PORT);
// finalSendBytes = sendBytes + FRZ_PROTO.FRZ_HEADER_SIZE;
// if(finalSendBytes > FRZ_PROTO.MAX_PACK_SIZE)
// console.log("WARNING: will be multiple packets. " + (finalSendBytes/FRZ_PROTO.MAX_PACK_SIZE)+1 + " packets needed.");
var totalsent = 0;
var totalpacks = 0;
var packnumber = 0;
totalpacks = Math.floor(sendBytes / FRZ_PROTO.MAX_FRZ_PAYLOAD);
if((sendBytes % FRZ_PROTO.MAX_FRZ_PAYLOAD) > 0)
totalpacks++;
if(totalpacks>1)
console.log("WARNING: will be multiple packets. " + totalpacks + " packets needed.");
var flags = 0;
// setup header
// if reset only op:
if(reset_flag && (!sendBytes)) {
flags |= FRZ_PROTO.FRZ_FLAG_RESET;
}
function dec2hex(i) {
return (i+0x10000).toString(16).substr(-4).toUpperCase();
}
var processInbound = function(buf, rinfo) {
if(rinfo.size < FRZ_PROTO.FRZ_HEADER_SIZE) {
errlog("Tiny packet. ?? " + rinfo.size);
return;
}
if(rinfo.size == FRZ_PROTO.FRZ_HEADER_SIZE) {
dlog("Recv header only.");
}
if(FRZ_PROTO.GET_FRZ_FLAGS(buf) & FRZ_PROTO.FRZ_FLAG_ACK)
dlog("Recv ACK. Ok.");
if(rinfo.size > FRZ_PROTO.FRZ_HEADER_SIZE) {
dlog( "Buffer was: " + stringifyBytes(buf,rinfo.size));
var offset = FRZ_PROTO.FRZ_HEADER_SIZE;
var category = buf.readUInt16LE( offset );
switch(category) {
case FRZ_PROTO.CATEGORY.ASYNC_PUSH:
dlog("Have an ASYNC_PUSH.");
offset += 2;
var eventcode = buf.readUInt16LE( offset );
var str_code = '0x' + dec2hex(eventcode);
dlog("Event code: " + str_code);
var func_name = FUNCS.EVENTHANDLERS[str_code];
if(func_name) {
dlog("Found handler: " + func_name);
var func = FUNCS[func_name];
if(!func) {
errlog("No function named: " + func_name + " in test function file.");
} else {
var payloadonly = buf.slice(FRZ_PROTO.FRZ_HEADER_SIZE);
var results = func.call(undefined,{ buf: payloadonly, size: rinfo.size - FRZ_PROTO.FRZ_HEADER_SIZE, rinfo: rinfo });
if(results !== undefined) {
dlog(" Results of func: " + JSON.stringify(results));
} else
dlog(" No results.");
}
} else {
errlog("Can't find a corresponding function name for this eventcode.");
}
break;
default:
dlog("Protocol category - Unimplemented: " + category + " " + dec2hex(category));
}
console.log(" ---------------------------- ");
}
}
client.bind(S_PORT,S_ADDR);
client.on('listening', function() {
dlog(" ---- ready for response");
});
client.on('message', function(msg, rinfo) { // msg is a Buffer
dlog(" >> data from " + rinfo.address + ":" + rinfo.port);
dlog(" >> rinfo = " + JSON.stringify(rinfo));
processInbound(msg,rinfo);
});
client.on('error', function(err) {
console.log(" Socket error -> OOPS: " + e.message + " --> " + e.stack);
});
var looping = false;
var sendPack = function(buffer,totalsize,maxsendsize, d_addr, d_port, s_addr, s_port, flags) {
var sendsize = 0;
if(totalsent < totalsize) {
sendsize = totalsize - totalsent;
if(sendsize > maxsendsize)
sendsize = maxsendsize;
} else {
// send a header only?
sendsize = 0;
if(!flags) {
console.log("sendPack: send what???");
return;
}
}
console.log("sendsize " + sendsize);
console.log("packs: " + (packnumber+1) + "/" + totalpacks);
var sendBuffer = new Buffer(sendsize + FRZ_PROTO.FRZ_HEADER_SIZE);
sendBuffer.fill(0); // zero it out
if(sendsize)
outBuffer.copy(sendBuffer,FRZ_PROTO.FRZ_HEADER_SIZE,totalsent,sendsize); // copy the byte buffer into our final send buffer, leave room for header
FRZ_PROTO.SET_FRZ_FLAGS(sendBuffer,flags); // set any passed in flags
if(packnumber == 0) { // the first packet gets the total number of packets
FRZ_PROTO.SET_FRZ_OPTIONAL(sendBuffer, totalpacks); // set any passed in flags
FRZ_PROTO.SET_FRZ_FLAGS(sendBuffer, FRZ_PROTO.GET_FRZ_FLAGS(sendBuffer) | FRZ_PROTO.FRZ_FLAG_FIRST);
if(needs_reset)
FRZ_PROTO.SET_FRZ_FLAGS(sendBuffer,FRZ_PROTO.GET_FRZ_FLAGS(sendBuffer) | FRZ_PROTO.FRZ_FLAG_RESET); // set any passed in flags
}
if((packnumber+1) == totalpacks) {
FRZ_PROTO.SET_FRZ_FLAGS(sendBuffer,FRZ_PROTO.GET_FRZ_FLAGS(sendBuffer) | FRZ_PROTO.FRZ_FLAG_LAST);
}
FRZ_PROTO.SET_FRZ_SEQ_ID(sendBuffer,packnumber);
console.log("attempting send pack "+packnumber+"... (" + sendsize + " data bytes, "+(sendsize + FRZ_PROTO.FRZ_HEADER_SIZE)+" total bytes)");
//console.log("sendBuffer: " + JSON.stringify(sendBuffer));
client.send(sendBuffer, 0, sendsize + FRZ_PROTO.FRZ_HEADER_SIZE, d_port, d_addr, function(err, bytes) {
if (err)
console.log(" OOPS: " + err.message + " --> " + err.stack);
else {
console.log('UDP message sent to ' + d_addr +':'+ d_port + " ... " + bytes + " bytes sent.");
// why is 'bytes' always undefined???!!
// totalsent += bytes;
packnumber++;
totalsent += sendsize; // bytes is not returning so we do this HACK HACK HACK
if(totalsent < sendsize) {
if(totalsent == 0) {
if(looping == true)
process.exit(1);
looping = true;
}
setImmediate(sendPack, buffer,totalsize,maxsendsize, d_addr, d_port, s_addr, s_port, flags);
}
}
});
}
if(!listen_only)
sendPack(outBuffer,sendBytes,FRZ_PROTO.MAX_PACK_SIZE,D_ADDR,D_PORT,S_ADDR,S_PORT,flags);
else
console.log("Listen only. Waiting...");
}
// try {
// sendNWait(finalSendBuffer,finalSendBytes,FRZ_PROTO.MAX_PACK_SIZE,D_ADDR,D_PORT,S_ADDR,S_PORT);
// } catch (e) {
// console.log(" OOPS: " + e.message + " --> " + e.stack);
// }
|
const { JsonWebTokenError } = require("jsonwebtoken")
const {JWT_SECRET}=require('../keys')
const jwt= require('jsonwebtoken')
const mongoose= require('mongoose')
const User = mongoose.model('User')
module.exports=(req,res,next)=>{
const {authorization} =req.headers
console.log(req.headers);
if(!authorization){
res.status(401).json({error:"you must be loggin "})
}
const token = authorization.replace("Bearerr ","")
console.log(token);
jwt.verify(token,JWT_SECRET,(err,payloadJWT)=>{
if(err){
res.status(402).json({error:"You must be loggggggin"})
}
console.log(payloadJWT);
const {_id} =payloadJWT
User.findById(_id).then(userdata=>{
req.user=userdata;
})
next()
})
}
|
define(function(require) {
'use strict'
var app = require('app'),
hist = require('modules/history'),
events = require('modules/events'),
header = require('partials/header'),
af = require('modules/animation-frame');
var self = {
init: function() {
this.reset();
this.initEvents();
hist.register('treaty-read', this);
af.add('treaty-scroll', function() {
self.scroll.update();
})
},
reset: function() {
this.startPos = {
x: 0,
y: 0
};
this.currentPos = {
x: 0,
y: 0
};
this.scrollPos = 0;
this.touchId = 0;
this.touching = false;
$('.treaty-read .scroll').attr('style', '');
$('.treaty-read .transition').removeClass('transition transition2');
},
initEvents: function() {
var $scroll = $('.scroll');
var moving = false;
var startMove;
events.register('treaty-read', '.scroll-outer', 'touchstart', function(e) {
var x = e.originalEvent.changedTouches[0].clientX;
var y = e.originalEvent.changedTouches[0].clientY;
if (self.touching) return
self.touching = true;
self.touchId = e.originalEvent.changedTouches[0].identifier;
$('.treaty-read .transition').removeClass('transition transition2');
self.startPos = {
x: x,
y: y
};
})
events.register('treaty-read', '.scroll-outer', 'touchmove', function(e) {
e.preventDefault();
for (var i = 0; i < e.originalEvent.changedTouches.length; i++) {
if (e.originalEvent.changedTouches[i].identifier !== self.touchId) continue;
var x = e.originalEvent.changedTouches[i].clientX;
var y = e.originalEvent.changedTouches[i].clientY;
var moveY = self.currentPos.y + (self.startPos.y - y);
if (moveY < 0) {
moveY = moveY - (moveY / 1.5);
} else if (moveY > self.scrollHeight - self.scrollInnerHeight) {
var val = moveY - (self.scrollHeight - self.scrollInnerHeight);
moveY = moveY - (val / 1.5);
}
$scroll.css({
'-webkit-transform': 'translate3d(0,' + moveY * -1 + 'px,0)'
});
}
})
events.register('treaty-read', '.scroll-outer', 'touchend', function(e) {
for (var i = 0; i < e.originalEvent.changedTouches.length; i++) {
if (e.originalEvent.changedTouches[i].identifier !== self.touchId) continue;
self.touching = false;
var x = e.originalEvent.changedTouches[i].clientX;
var y = e.originalEvent.changedTouches[i].clientY;
var currentEnd = self.currentPos.y + (self.startPos.y - y);
self.currentPos.y = Math.min(self.scrollHeight - self.scrollInnerHeight, Math.max(0, currentEnd));
if (currentEnd < 0 || currentEnd > self.scrollHeight - self.scrollInnerHeight) {
$scroll.addClass('transition').css({
'-webkit-transform': 'translate3d(0,-' + self.currentPos.y + 'px,0)'
});
}
}
})
events.register('treaty-read', '[data-footnote]', 'touchstart', function(e) {
e.preventDefault();
e.stopPropagation();
moving = false;
var y = e.originalEvent.changedTouches[0].clientY;
startMove = y;
});
events.register('treaty-read', '[data-footnote]', 'touchend', function(e, el) {
if (moving) return;
e.preventDefault();
e.stopPropagation();
var copy = $(el).attr('data-footnote');
$('.footnote .message').html(copy);
setTimeout(function() {
$('.footnote').css({
top: 0,
opacity: 1
})
}, 100);
});
events.register('treaty-read', '[data-footnote]', 'touchmove', function(e, el) {
e.preventDefault();
e.stopPropagation();
var y = e.originalEvent.changedTouches[0].clientY;
if (Math.abs(startMove - y) > 10) moving = true;
});
events.register('treaty-read', '.footnote', 'touchstart', function(e, el) {
e.preventDefault();
e.stopPropagation();
moving = false;
$('.footnote').css({
opacity: 0
})
setTimeout(function() {
$('.footnote').css({
top: '-100%'
})
}, 700);
});
events.register('treaty-read', '.footnote', 'touchmove touchend', function(e, el) {
e.preventDefault();
e.stopPropagation();
});
events.register('treaty-read', '.arrow', 'touchmove', function(e, el) {
e.preventDefault();
e.stopPropagation();
});
events.register('treaty-read', '.arrow', 'touchend', function(e, el) {
e.preventDefault();
e.stopPropagation();
$(el).css('background-color', 'black');
af.stop('treaty-scroll');
});
events.register('treaty-read', '.arrow', 'touchstart', function(e, el) {
e.preventDefault();
e.stopPropagation();
$(el).css('background-color', '#00632c');
$('.treaty-read .transition').removeClass('transition transition2');
self.scroll.startTime = new Date().getTime();
self.scroll.dir = $(el).hasClass('up') ? -1 : 1;
af.start('treaty-scroll');
});
},
scroll: {
dir: 1,
$scroll: $('.treaty-read .scroll'),
startTime: 0,
update: function() {
var max = 12;
var slowPoint = 60;
if (self.currentPos.y < slowPoint) max = 1 + 11 / slowPoint * self.currentPos.y;
if (self.currentPos.y > self.scrollHeight - self.scrollInnerHeight - slowPoint) {
max = 12 - 11 / slowPoint * (self.currentPos.y - (self.scrollHeight - self.scrollInnerHeight - slowPoint));
}
var speed = Math.max(1, Math.min(max, (new Date().getTime() - this.startTime) / 100));
self.currentPos.y += this.dir * speed;
self.currentPos.y = Math.min(self.scrollHeight - self.scrollInnerHeight, Math.max(self.currentPos.y, 0));
this.$scroll.css({
'-webkit-transform': 'translate3d(0,' + self.currentPos.y * -1 + 'px,0)'
});
},
},
load: function() {
self.scrollHeight = $('.treaty-read .scroll').height();
self.scrollInnerHeight = $('.treaty-read .scroll-inner').height();
},
dump: function() {
var $el = $('.treaty-read');
$el.attr('style', '');
$('.treaty-read .button').removeClass('active');
this.reset();
},
in : function() {
return new Promise(function(success) {
var $el = $('.treaty-read');
$el.css({
display: 'block'
})
setTimeout(function() {
$el.css({
opacity: 1
})
header.change.treaty('read');
}, 100);
setTimeout(function() {
success();
}, 1200);
})
},
out: function() {
return new Promise(function(success) {
var $el = $('.treaty-read');
// $el.removeClass('hide');
$el.css({
opacity: 0
})
setTimeout(function() {
$el.css({
display: 'none'
})
success();
}, 1200);
})
}
};
return self;
});
|
var dep1 = require('./dep1');
var dep2 = require('./dep2');
var dep3 = require('./dep3');
dep1.exec();
dep2.exec();
dep3.exec();
window.no = 'yes';
|
export { default } from './FilmCard';
|
function bindFullPageEvents() {
//
document.addEventListener("turbolinks:click", function() {
$('*[data-toggle = "tooltip"]').tooltip('hide');
})
$(document).on('change', '.onchange.persisted', function(e) {
$(this).collectedSubmit();
e.preventDefault();
return(false);
});
$(document).on('click', '.onclick.persisted', function(e) {
$(this).collectedSubmit();
e.preventDefault();
return(false);
});
$(document).tooltip({
selector: '[data-toggle="tooltip"]',
container: 'body', placement: function(context, source) {
var position = $(source).position().left;
var window_width = $(window).width();
if (position > window_width/2 ) return "left";
return "right";
}
});
$(document).on('dblclick', '.double-click', function(e) {
$(this).collectedSubmit( { url: $(this).data("doubleclick").url, collect: $(this).data("doubleclick").collect } );
e.preventDefault();
return(false);
});
$(document).on('click', '.row-click', function(e) {
var url = $(this).data('url');
if ( $(this).hasClass('remote') ) {
$.getScript(url);
} else {
Turbolinks.visit(url);
}
if ( $(this).hasClass('activate') ) {
$(this).addClass('active').siblings().removeClass('active');
}
e.preventDefault();
return(false);
});
$(document).off('click', '.remote-tab').on('click', '.remote-tab', function(e) {
var ref = $(this).attr("href");
var url = $(this).data("url");
var tabContainer = $(this).closest('.nav').next('.tab-content');
var tabContent = tabContainer.find(ref);
if (tabContent.length) {
if ( tabContent.html().trim().length == 0) {
$.getScript(url, function() {
// tabContainer.initialiseNewContent({ doFullHeight: false });
});
} else {
// Resize full heights inside tabs on tab change
}
$(this).tab('show');
}
e.preventDefault();
return(false);
});
$(document).on('shown.bs.tab', function(event) {
$('.full-height').fullHeight();
var s = event.target.href.match(/#[^#]*$/);
if (s) {
window.history.replaceState(history.state, "", s);
}
});
// reset fullheights when modals closes
$(document).on('hidden.bs.modal', function(e) {
$('#Modal').html('<div class="modal-dialog" role="document"><div class="modal-content"><div class="text-center"><i class="fontello icon-4x icon-spin4 icon-spin-cw"></i></div><div></div></div></div>');
$('.full-height').fullHeight();
});
// set input to first input field when modal shows
$(document).on('shown.bs.modal', function(e) {
var focalPoint=$(e.target);
setTimeout( function() {
focalPoint.firstFocus();
}, 500);
});
$(document).on('show.bs.modal', function(e) {
var a = $(e.relatedTarget)
var dest = a.attr("href");
$.getScript(dest, function() { });
});
$(document).on('click', '.reset-input', function(e) {
$($(this).data('target')).val('');
return(false);
});
window.onscroll = function() {
$('.infinite-scroll.no-full-height').performScroll(true);
}
};
function fetchActiveTab() {
if ( $('ul#tabs').length == 0 ) return;
var hashBit = window.location.hash;
if (hashBit) {
var tab = $('ul#tabs li a[href="'+ hashBit + '"]');
if (tab.length > 0 ) {
$('ul#tabs li a').removeClass("active");
tab.click();
return;
}
}
var default_tab = $('ul#tabs li a.default');
if (default_tab.length > 0)
setTimeout( function() { $('ul#tabs li a.default').click(); }, 100 );
else if ( $('ul#tabs li a.active').length == 0 ) { $('ul#tabs li a:first').click(); };
}
function everyPageSetup() {
fetchActiveTab();
$('html').initialiseNewContent( { "doFullHeight": true } );
};
bindFullPageEvents();
$(document).on('turbolinks:load', everyPageSetup);
$(window).resize( function() { $('.full-height').fullHeight(); });
|
'use strict';
var serializeError = require('serialize-error');
var logger;
logger = require('../logger').getLogger('util/uncaughtExceptionHandler', function(newLogger) {
logger = newLogger;
});
var instanaNodeJsCore = require('@instana/core');
var tracing = instanaNodeJsCore.tracing;
var spanBuffer = tracing.spanBuffer;
var stackTraceUtil = instanaNodeJsCore.util.stackTrace;
var downstreamConnection = null;
var processIdentityProvider = null;
var uncaughtExceptionEventName = 'uncaughtException';
var unhandledRejectionEventName = 'unhandledRejection';
var unhandledRejectionDeprecationWarningHasBeenEmitted = false;
var stackTraceLength = 10;
var config;
// see
// https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode /
// https://github.com/nodejs/node/pull/26599
var unhandledRejectionsMode = 'warn/default';
for (var i = 0; i < process.execArgv.length; i++) {
if (process.execArgv[i] === '--unhandled-rejections=none') {
unhandledRejectionsMode = 'none';
} else if (process.execArgv[i] === '--unhandled-rejections=strict') {
unhandledRejectionsMode = 'strict';
}
}
exports.init = function(_config, _downstreamConnection, _processIdentityProvider) {
config = _config;
downstreamConnection = _downstreamConnection;
processIdentityProvider = _processIdentityProvider;
if (config.reportUncaughtException) {
if (!processIdentityProvider) {
logger.warn('Reporting uncaught exceptions is enabled, but no process identity provider is available.');
} else if (typeof processIdentityProvider.getEntityId !== 'function') {
logger.warn(
'Reporting uncaught exceptions is enabled, but the process identity provider does not support ' +
'retrieving an entity ID.'
);
}
}
};
exports.activate = function() {
activateUncaughtExceptionHandling();
activateUnhandledPromiseRejectionHandling();
};
function activateUncaughtExceptionHandling() {
if (config.reportUncaughtException) {
process.once(uncaughtExceptionEventName, onUncaughtException);
try {
if (require.resolve('netlinkwrapper')) {
logger.info('Reporting uncaught exceptions is enabled.');
if (process.version === 'v12.6.0') {
logger.warn(
'You are running Node.js v12.6.0 and have enabled reporting uncaught exceptions. To enable this feature, ' +
'@instana/collector will register an uncaughtException handler. Due to a bug in Node.js v12.6.0, the ' +
'original stack trace will get lost when this process is terminated with an uncaught exception. ' +
'Instana recommends to use a different Node.js version (<= v12.5.0 or >= v12.6.1). See ' +
'https://github.com/nodejs/node/issues/28550 for details.'
);
}
} else {
// This should actually not happen as require.resolve should either return a resolved filename or throw an
// exception.
logger.warn(
'Reporting uncaught exceptions is enabled, but netlinkwrapper could not be loaded ' +
"(require.resolve('netlinkwrapper') returned a falsy value). Uncaught exceptions will " +
'not be reported to Instana for this application. This typically occurs when native addons could not be ' +
'compiled during module installation (npm install/yarn). See the instructions to learn more about the ' +
'requirements of the collector: ' +
'https://www.instana.com/docs/ecosystem/node-js/installation/#native-addons'
);
}
} catch (notResolved) {
// This happens if netlinkwrapper is not available (it is an optional dependency).
logger.warn(
'Reporting uncaught exceptions is enabled, but netlinkwrapper could not be loaded. Uncaught exceptions will ' +
'not be reported to Instana for this application. This typically occurs when native addons could not be ' +
'compiled during module installation (npm install/yarn). See the instructions to learn more about the ' +
'requirements of the collector: ' +
'https://www.instana.com/docs/ecosystem/node-js/installation/#native-addons'
);
}
} else {
logger.info('Reporting uncaught exceptions is disabled.');
}
}
exports.deactivate = function() {
process.removeListener(uncaughtExceptionEventName, onUncaughtException);
process.removeListener(unhandledRejectionEventName, onUnhandledRejection);
};
function onUncaughtException(uncaughtError) {
// because of the way Error.prepareStackTrace works and how error.stack is only created once and then cached it is
// important to create the JSON formatted stack trace first, before anything else accesses error.stack.
var jsonStackTrace = stackTraceUtil.getStackTraceAsJson(stackTraceLength, uncaughtError);
finishCurrentSpanAndReportEvent(uncaughtError, jsonStackTrace);
logAndRethrow(uncaughtError);
}
function finishCurrentSpanAndReportEvent(uncaughtError, jsonStackTrace) {
var spans = finishCurrentSpan(jsonStackTrace);
var eventPayload = createEventForUncaughtException(uncaughtError);
downstreamConnection.reportUncaughtExceptionToAgentSync(eventPayload, spans);
}
function createEventForUncaughtException(uncaughtError) {
return createEvent(uncaughtError, 'A Node.js process terminated abnormally due to an uncaught exception.', 10);
}
function finishCurrentSpan(jsonStackTrace) {
var cls = tracing.getCls();
if (!cls) {
return [];
}
var currentSpan = cls.getCurrentSpan();
if (!currentSpan) {
return [];
}
currentSpan.ec = 1;
currentSpan.d = Date.now() - currentSpan.ts;
currentSpan.stack = jsonStackTrace;
currentSpan.transmit();
return spanBuffer.getAndResetSpans();
}
function logAndRethrow(err) {
// Remove all listeners now, so the final throw err won't trigger other registered listeners a second time.
var registeredListeners = process.listeners(uncaughtExceptionEventName);
if (registeredListeners) {
registeredListeners.forEach(function(listener) {
process.removeListener(uncaughtExceptionEventName, listener);
});
}
// prettier-ignore
// eslint-disable-next-line max-len
logger.error('The Instana Node.js collector caught an otherwise uncaught exception to generate a respective Instana event for you. Instana will now rethrow the error to terminate this process, otherwise the application would be left in an inconsistent state, see https://nodejs.org/api/process.html#process_warning_using_uncaughtexception_correctly. The next line on stderr will look as if Instana crashed your application, but actually the original error came from your application code, not from Instana. Since we rethrow the original error, you should see its stacktrace below (depening on how you operate your application and how logging is configured.)');
// Rethrow the original error (after notifying the agent) to trigger the process to finally terminate - Node won't
// run this handler again since it (a) has been registered with `once` and (b) we removed all handlers for
// uncaughtException anyway.
throw err;
}
function activateUnhandledPromiseRejectionHandling() {
if (config.reportUnhandledPromiseRejections) {
if (unhandledRejectionsMode === 'strict') {
logger.warn(
'Node.js has been started with --unhandled-rejections=strict, therefore reporting unhandled promise ' +
'rejections will not be enabled.'
);
return;
}
process.on(unhandledRejectionEventName, onUnhandledRejection);
logger.info('Reporting unhandled promise rejections is enabled.');
} else {
logger.info('Reporting unhandled promise rejections is disabled.');
}
}
function onUnhandledRejection(reason) {
if (unhandledRejectionsMode !== 'none') {
// Best effort to emit the same log messages that Node.js does by default (when no handler for the
// unhandledRejection event is installed.
// eslint-disable-next-line no-console
console.warn('UnhandledPromiseRejectionWarning:', reason);
// eslint-disable-next-line no-console
console.warn(
'UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing ' +
'inside of an async function without a catch block, or by rejecting a promise which was not handled with ' +
'.catch().'
);
if (!unhandledRejectionDeprecationWarningHasBeenEmitted) {
// eslint-disable-next-line no-console
console.warn(
'[DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise ' +
'rejections that are not handled will terminate the Node.js process with a non-zero exit code.'
);
unhandledRejectionDeprecationWarningHasBeenEmitted = true;
}
}
downstreamConnection.sendEvent(createEventForUnhandledRejection(reason), function(error) {
if (error) {
logger.error('Error received while trying to send event to agent: %s', error.message);
}
});
}
function createEventForUnhandledRejection(reason) {
return createEvent(reason, 'An unhandled promise rejection occured in a Node.js process.', 5);
}
function createEvent(error, title, severity) {
var eventText = errorToMarkdown(error);
return {
title: title,
text: eventText,
plugin: 'com.instana.forge.infrastructure.runtime.nodejs.NodeJsRuntimePlatform',
id:
processIdentityProvider && typeof processIdentityProvider.getEntityId === 'function'
? processIdentityProvider.getEntityId()
: undefined,
timestamp: Date.now(),
duration: 1,
severity: severity
};
}
function errorToMarkdown(error) {
var serializedError = serializeError(error);
if (serializedError.name && serializedError.message && typeof serializedError.stack === 'string') {
// prettier-ignore
return (
'### ' + serializedError.name + '\n\n' +
'#### Message: \n\n' + serializedError.message + '\n\n' +
'#### Stack:\n\n' + stackTraceToMarkdown(serializedError.stack)
);
} else {
return JSON.stringify(serializedError);
}
}
function stackTraceToMarkdown(stackTrace) {
var formatted = '';
var callSites = stackTrace.split('\n');
callSites.forEach(function(callSite) {
formatted = formatted + '* `' + callSite.trim() + '`\n';
});
return formatted;
}
|
'use strict';
/**
* Alidayu client for Node.js 阿里大鱼短信服务Node.js客户端
*
* @author Zongmin Lei <leizongmin@gmail.com>
*/
const utils = require('lei-utils');
const request = require('request');
class AliDaYu {
constructor(options) {
options = options || {};
this._options = {};
this._options.gw = 'http://gw.api.taobao.com/router/rest';
this._options.v = '2.0';
this._options.format = 'json';
this._options.sign_method = 'md5';
for (const key in options) {
this._options[key] = options[key];
}
}
_commonArgs(params) {
params = params || {};
params.app_key = this._options.app_key;
params.v = this._options.v;
params.sign_method = this._options.sign_method;
params.format = this._options.format;
params.timestamp = utils.date('Y-m-d H:i:s');
return params;
}
_sign(params) {
params = this._commonArgs(params);
const keys = Object.keys(params).sort();
const signString = keys.map(function (k) {
return k + params[k];
}).join('');
const str = this._options.secret + signString + this._options.secret;
return utils.md5(str).toUpperCase();
}
_formatArgs(params) {
for (const i in params) {
if (typeof params[i] === 'object') {
params[i] = JSON.stringify(params[i]);
}
}
return params;
}
_request(params, callback) {
params = this._formatArgs(params);
params.sign = this._sign(params);
const body = Object.keys(params).map(function (k) {
return k + '=' + params[k];
}).join('&');
request.post(this._options.gw, {
form: params,
}, function (err, res, body) {
if (err) return callback(err);
let data;
try {
data = JSON.parse(body.toString());
} catch (err) {
return callback(err, body);
}
if (data.error_response) {
callback(data.error_response, data);
} else {
callback(null, data);
}
});
}
/**
* 发送短信
*
* @param {Object} params
* @param {Function} callback
*
* @example:
* ```
* sms({
* sms_free_sign_name: '登录验证',
* sms_param: {
* code: '1234',
* product: '一登',
* },
* rec_num: '13800138000',
* sms_template_code: 'SMS_4045620',
* }, callback);
* ```
*/
sms(params, callback) {
params = params || {};
params.method = 'alibaba.aliqin.fc.sms.num.send';
params.sms_type = 'normal';
callback = callback || createPromiseCallback();
this._request(params, callback);
return callback.promise;
}
}
function createPromiseCallback() {
const callback = (err, ret) => {
if (err) {
callback.reject(err);
} else {
callback.resolve(ret);
}
};
callback.promise = new Promise((resolve, reject) => {
callback.resolve = resolve;
callback.reject = reject;
});
return callback;
}
module.exports = AliDaYu;
|
export {default} from './SelfAssessmentPanel';
|
import React, { Component } from 'react'
import "./style.css"
class CardNota extends Component {
render() {
return (
<section className="card-nota">
<header><h2>Título</h2></header>
<p>Conteúdo</p>
</section>
);
}
}
export default CardNota;
|
slide[MODULEID].umg_transition_caption_do = function(index)
{
if (!this.captionHeight)
{
this.captionHeight = this.umg_caption.height() + this.umg_caption.css("padding-top").replace("px", "")*1+this.umg_caption.css("padding-bottom").replace("px", "")*1;
this.captionTop = this.umg_caption.position().top;
this.captionTopNew = this.captionTop + this.captionHeight;
}
var caller = this;
this.umg_caption.animate({height:0, top:caller.captionTopNew},"fast", function(){
caller.updateCaption(index);
caller.umg_caption.animate({height:caller.captionHeight, top:caller.captionTop},"fast");
});
}
|
//阻止預設送出表單
var liIndex = 0;
$(document).ready(function () {
$("#list-items").html(localStorage.getItem("listItems"));
$(".add-items").submit(function (event) {
event.preventDefault();
var item = $("#todo-list-item").val();
//將表單列印出,歸零
if (item) {
liIndex +=1;
$("#list-items").append(
`<li><input class='checkbox' type='checkbox' id='${liIndex}'><label for='${liIndex}'>${item}
</label><a class='remove'>x</a></li>`
);
localStorage.setItem("listItems", $("#list-items").html());
$("#todo-list-item").val("");
}
});
$(document).on("change", ".checkbox", function () {
if ($(this).attr("checked")) {
$(this).removeAttr("checked");
} else {
$(this).attr("checked", "checked");
}
$(this).parent().toggleClass("checked");
localStorage.setItem("listItems", $("#list-items").html());
});
$(document).on("click", ".remove", function () {
$(this).parent().remove();
localStorage.setItem("listItems", $("#list-items").html());
});
});
|
/**
* this file will be loaded before server started
* you can define global functions used in controllers, models, templates
*/
/**
* use global.xxx to define global functions
*
* global.fn1 = function(){
*
* }
*/
global.uri2Query = (uri) => {
console.log(uri);
var arr = uri.split(/\&/g);
var r = {};
arr.forEach((item) => {
var a = item.split('=');
r[a[0]] = a[1];
});
return r;
};
|
angular
.module('players')
.component('playersComponent', {
templateUrl: 'players/players.template.html',
controller: ['$scope', '$http', function PlayersComponent($scope, $http) {
this.$onInit = function () {
$http.get('http://localhost:3000/player')
.then((res) => {
const { players } = res.data;
$scope.players = players;
})
}
}],
controllerAs: '$ctrl'
})
|
/**
* Date Author Des
*----------------------------------------------
* 2019/12/20 gongtiexin 服务详情
* */
import React, { Component } from 'react';
import { inject, observer } from 'mobx-react';
import qs from 'query-string';
import {
Descriptions,
Divider,
Form,
Input,
Modal,
Popconfirm,
Table,
Radio,
Row,
Col,
Icon,
} from 'antd';
import PropTypes from 'prop-types';
const CollectionCreateForm = Form.create({ name: 'form_in_modal' })(
class extends React.Component {
render() {
const { visible, onCancel, onCreate, form, instance } = this.props;
const { getFieldDecorator } = form;
return (
<Modal visible={visible} title="修改实例" onCancel={onCancel} onOk={onCreate} width={900}>
<Form layout="vertical">
<Row gutter={24}>
<Col span={12}>
<Form.Item label="IP">
{getFieldDecorator('ip', {
initialValue: instance?.ip,
rules: [{ required: true, message: '请输入IP!' }],
})(<Input />)}
</Form.Item>
<Form.Item label="端口">
{getFieldDecorator('port', {
initialValue: instance?.port,
rules: [{ required: true, message: '请输入端口!' }],
})(<Input />)}
</Form.Item>
<Form.Item label="权重">
{getFieldDecorator('weight', {
initialValue: instance?.weight,
rules: [{ required: true, message: '请输入权重!' }],
})(<Input />)}
</Form.Item>
<Form.Item label="元数据">
{getFieldDecorator('metadata', {
initialValue: JSON.stringify(instance?.metadata),
rules: [{ required: true, message: '请输入元数据!' }],
})(<Input />)}
</Form.Item>
<Form.Item label="健康状态">
{getFieldDecorator('healthy', {
initialValue: instance?.healthy,
})(
<Radio.Group>
<Radio value>健康</Radio>
<Radio value={false}>不健康</Radio>
</Radio.Group>,
)}
</Form.Item>
<Form.Item label="禁用/启用">
{getFieldDecorator('enabled', {
initialValue: instance?.enabled,
})(
<Radio.Group>
<Radio value>启用</Radio>
<Radio value={false}>禁用</Radio>
</Radio.Group>,
)}
</Form.Item>
</Col>
<Col span={12}>
<Form.Item label="healthyCheckMethod">
{getFieldDecorator('healthyCheckMethod', {
initialValue: instance?.healthyCheckMethod,
rules: [{ required: true, message: '请输入 healthyCheckMethod !' }],
})(<Input />)}
</Form.Item>
<Form.Item label="healthyCheckInterval">
{getFieldDecorator('healthyCheckInterval', {
initialValue: instance?.healthyCheckInterval,
rules: [{ required: true, message: '请输入 healthyCheckInterval !' }],
})(<Input />)}
</Form.Item>
<Form.Item label="unhealthyCheckCount">
{getFieldDecorator('unhealthyCheckCount', {
initialValue: instance?.unhealthyCheckCount,
rules: [{ required: true, message: '请输入 unhealthyCheckCount !' }],
})(<Input />)}
</Form.Item>
<Form.Item label="protocol">
{getFieldDecorator('protocol', {
initialValue: instance?.protocol,
rules: [{ required: true, message: '请输入 protocol !' }],
})(<Input />)}
</Form.Item>
<Form.Item label="useTls">
{getFieldDecorator('useTls', {
initialValue: instance?.useTls,
rules: [{ required: true, message: '请输入 useTls !' }],
})(<Input />)}
</Form.Item>
<Form.Item label="httpPath">
{getFieldDecorator('httpPath', {
initialValue: instance?.httpPath,
})(<Input />)}
</Form.Item>
</Col>
</Row>
</Form>
</Modal>
);
}
},
);
@inject(({ store: { serviceStore, namespaceStore } }) => ({ serviceStore, namespaceStore }))
@observer
export default class Detail extends Component {
static propTypes = {
serviceStore: PropTypes.object.isRequired,
};
formRef = React.createRef();
state = {
visible: false,
loading: false,
instance: null,
};
componentDidMount() {
this.fetchData();
}
componentWillUnmount() {
this.props.serviceStore.setService();
}
fetchData = () => {
this.setState({ loading: true });
this.props.serviceStore
.getService(qs.parse(window.location.search))
.finally(() => this.setState({ loading: false }));
};
showModal = instance => () => {
this.setState({ visible: true, instance });
};
handleCancel = () => {
this.setState({ visible: false, instance: null });
this.formRef.current.props.form.resetFields();
};
handleUpdate = () => {
const { form } = this.formRef.current.props;
const { instance } = this.state;
const {
serviceStore: { service },
} = this.props;
form.validateFields((err, values) => {
if (err) {
return;
}
console.log('Received values of form: ', values);
this.props.serviceStore
.updateInstance({
namespace: service.namespace,
serviceName: service.serviceName,
instanceId: instance.instanceId,
...values,
metadata: JSON.parse(values.metadata),
})
.then(() => {
this.fetchData();
this.handleCancel();
});
});
};
handleDeleteInstance = instance => () => {
this.props.serviceStore.deleteInstance(instance).then(this.fetchData);
};
render() {
const {
serviceStore: { service },
} = this.props;
const { loading, visible, instance } = this.state;
const columns = [
{
title: 'IP',
dataIndex: 'ip',
key: 'ip',
},
{
title: '端口',
dataIndex: 'port',
key: 'port',
},
{
title: '临时实例',
dataIndex: 'ephemeral',
key: 'ephemeral',
render: text => <span>{text ? <Icon type="check" /> : <Icon type="close" />}</span>,
},
{
title: '权重',
dataIndex: 'weight',
key: 'weight',
},
{
title: '健康状态',
dataIndex: 'healthy',
key: 'healthy',
render: text =>
text ? (
<Icon style={{ color: '#87d068' }} type="smile" />
) : (
<Icon type="frown" style={{ color: '#f50' }} />
),
},
{
title: '元数据',
dataIndex: 'metadata',
key: 'metadata',
render: text => <span>{JSON.stringify(text)}</span>,
width: '30%',
},
{
title: '操作',
dataIndex: 'action',
key: 'action',
width: '10%',
render: (text, record) => (
<span>
<a onClick={this.showModal(record)} href="#">
修改
</a>
<Divider type="vertical" />
<Popconfirm
title="确定要删除该实例吗?"
onConfirm={this.handleDeleteInstance({
namespace: service.namespace,
serviceName: service.serviceName,
instanceId: record.instanceId,
})}
okText="确认"
cancelText="取消"
>
<a href="#">删除</a>
</Popconfirm>
</span>
),
},
];
return (
<div>
<Descriptions>
<Descriptions.Item label="服务名称">{service.serviceName}</Descriptions.Item>
<Descriptions.Item label="命名空间">{service.namespace}</Descriptions.Item>
<Descriptions.Item label="分组">{service.groupName}</Descriptions.Item>
<Descriptions.Item label="实例">
<Table
loading={loading}
style={{ marginTop: 16 }}
bordered
dataSource={service.instances}
columns={columns}
pagination={false}
rowKey="instanceId"
/>
</Descriptions.Item>
</Descriptions>
<CollectionCreateForm
instance={instance}
wrappedComponentRef={this.formRef}
visible={visible}
onCancel={this.handleCancel}
onCreate={this.handleUpdate}
/>
</div>
);
}
}
|
import React from "react"
import ReactDOM from "react-dom"
import axios from "axios"
window.axios = axios;
import store from "./store/store.js"
import { Provider } from "react-redux"
import { HashRouter as Router , Route , Link ,Redirect} from "react-router-dom"
import ReactCSSTransitionGroup from 'react-addons-css-transition-group'; // ES6
import Home from "./page/home.jsx"
import Show from "./page/show.jsx"
import More from "./page/more.jsx"
import Klogin from "./page/Klogin.jsx"
import Kreg from "./page/Kreg.jsx"
import Kuser from "./page/Kuser.jsx"
import Kfollow from "./page/Kfollow.jsx"
import Kuserissue from "./page/Kuserissue.jsx"
import All from "./components/home-child/all.jsx"
import "./css/muse-ui.scss"
//console.log(window.location.hash)
//重定向
if(window.location.hash=="#/"||window.location.hash=="") window.location.hash = "#/home/all"
ReactDOM.render(
<Provider store={store}>
<Router>
<div>
{/*<Redirect exact path="/" to="home"/>*/}
<Route path="/home" component = {Home}></Route>
<Route path="/show" component = {Show}></Route>
<Route path="/more" component = {More}></Route>
<Route path="/login" component = {Klogin}></Route>
<Route path="/reg" component = {Kreg}></Route>
<Route exact path="/user" component = {Kuser}></Route>
<Route exact path="/user/follow" component = {Kfollow}></Route>
<Route exact path="/user/userissue:id" component = {Kuserissue}></Route>
</div>
</Router>
</Provider>,document.querySelector("#demo")
)
|
import React from 'react';
import { Form } from 'react-bootstrap';
function handleSourceChevron() {
document.querySelector('.source-chev').classList.toggle('fa-chevron-down');
document.querySelector('.source-chev').classList.toggle('fa-chevron-up');
}
function handleNYT() {
let a, nyt, i;
a = document.querySelectorAll('.article');
for (i = 0; i < a.length; i++) {
a[i].style.display = 'none';
}
nyt = document.querySelectorAll('.nyt');
for (i = 0; i < nyt.length; i++) {
nyt[i].style.display = 'block';
}
}
function handleFox() {
let a, fox, i;
a = document.querySelectorAll('.article');
for (i = 0; i < a.length; i++) {
a[i].style.display = 'none';
}
fox = document.querySelectorAll('.fox');
for (i = 0; i < fox.length; i++) {
fox[i].style.display = 'block';
}
}
function handleWPost() {
let a, wp, i;
a = document.querySelectorAll('.article');
for (i = 0; i < a.length; i++) {
a[i].style.display = 'none';
}
wp = document.querySelectorAll('.wpost');
for (i = 0; i < wp.length; i++) {
wp[i].style.display = 'block';
}
}
function handleBBC() {
let a, bbc, i;
a = document.querySelectorAll('.article');
for (i = 0; i < a.length; i++) {
a[i].style.display = 'none';
}
bbc = document.querySelectorAll('.bbc');
for (i = 0; i < bbc.length; i++) {
bbc[i].style.display = 'block';
}
}
function handleAlJazeera() {
let a, aj, i;
a = document.querySelectorAll('.article');
for (i = 0; i < a.length; i++) {
a[i].style.display = 'none';
}
aj = document.querySelectorAll('.al-jazeera');
for (i = 0; i < aj.length; i++) {
aj[i].style.display = 'block';
}
}
function handleLATimes() {
let a, la, i;
a = document.querySelectorAll('.article');
for (i = 0; i < a.length; i++) {
a[i].style.display = 'none';
}
la = document.querySelectorAll('.la-times');
for (i = 0; i < la.length; i++) {
la[i].style.display = 'block';
}
}
function handleHuff() {
let a, hp, i;
a = document.querySelectorAll('.article');
for (i = 0; i < a.length; i++) {
a[i].style.display = 'none';
}
hp = document.querySelectorAll('.huff');
for (i = 0; i < hp.length; i++) {
hp[i].style.display = 'block';
}
}
function handleBlaze() {
let a, b, i;
a = document.querySelectorAll('.article');
for (i = 0; i < a.length; i++) {
a[i].style.display = 'none';
}
b = document.querySelectorAll('.blaze');
for (i = 0; i < b.length; i++) {
b[i].style.display = 'block';
}
}
function handleCNN() {
let a, cnn, i;
a = document.querySelectorAll('.article');
for (i = 0; i < a.length; i++) {
a[i].style.display = 'none';
}
cnn = document.querySelectorAll('.cnn');
for (i = 0; i < cnn.length; i++) {
cnn[i].style.display = 'block';
}
}
function handleMySources() {
let a, my, i;
a = document.querySelectorAll('.article');
for (i = 0; i < a.length; i++) {
a[i].style.display = 'none';
}
my = document.querySelectorAll('.my-sources');
for (i = 0; i < my.length; i++) {
my[i].style.display = 'block';
}
}
function handleSelectAll() {
let all, i;
all = document.querySelectorAll('.article');
for (i = 0; i < all.length; i++) {
all[i].style.display = 'block';
}
}
const SearchFilterBar = () => {
return (
<div>
<h2>Filter by:</h2>
<div>
<a
onClick={handleSourceChevron}
id='source-topic'
href='#demo'
data-toggle='collapse'
>
<i class='source-chev fas fa-chevron-down'></i> SOURCE
</a>
<div
style={{ marginTop: '10px', marginLeft: '20px' }}
// id='demo'
className='collapse'
>
<Form>
{['radio'].map((type) => (
<div key={`custom-${type}`} className='mb-3'>
<Form.Check
onClick={handleNYT}
custom
type='radio'
label='New York Times'
name='formHorizontalRadios'
id='formHorizontalRadios1'
className='filter-dropdown-text'
// className={`custom-${type}`}
/>
<Form.Check
onClick={handleFox}
custom
type='radio'
label='Fox News'
name='formHorizontalRadios'
id='formHorizontalRadios2'
className='filter-dropdown-text'
// className={`custom-${type}`}
/>
<Form.Check
onClick={handleWPost}
custom
type='radio'
label='Washington Post'
name='formHorizontalRadios'
id='formHorizontalRadios3'
className='filter-dropdown-text'
// className={`custom-${type}`}
/>
<Form.Check
onClick={handleBBC}
custom
type='radio'
label='BBC'
name='formHorizontalRadios'
id='formHorizontalRadios4'
className='filter-dropdown-text'
// className={`custom-${type}`}
/>
<Form.Check
onClick={handleAlJazeera}
custom
type='radio'
label='Al Jazeera'
name='formHorizontalRadios'
id='formHorizontalRadios5'
className='filter-dropdown-text'
// className={`custom-${type}`}
/>
<Form.Check
onClick={handleLATimes}
custom
type='radio'
label='LA Times'
name='formHorizontalRadios'
id='formHorizontalRadios6'
className='filter-dropdown-text'
// className={`custom-${type}`}
/>
<Form.Check
onClick={handleHuff}
custom
type='radio'
label='Huffington Post'
name='formHorizontalRadios'
id='formHorizontalRadios7'
className='filter-dropdown-text'
// className={`custom-${type}`}
/>
<Form.Check
onClick={handleBlaze}
custom
type='radio'
label='The Blaze'
name='formHorizontalRadios'
id='formHorizontalRadios8'
className='filter-dropdown-text'
// className={`custom-${type}`}
/>
<Form.Check
onClick={handleCNN}
custom
type='radio'
label='CNN'
name='formHorizontalRadios'
id='formHorizontalRadios9'
className='filter-dropdown-text'
// className={`custom-${type}`}
/>
<Form.Check
onClick={handleMySources}
custom
type='radio'
label='My Sources'
name='formHorizontalRadios'
id='formHorizontalRadios10'
className='filter-dropdown-text'
// className={`custom-${type}`}
/>
<Form.Check
onClick={handleSelectAll}
custom
type='radio'
label='Select All'
name='formHorizontalRadios'
id='formHorizontalRadios11'
className='filter-dropdown-text'
// className={`custom-${type}`}
/>
</div>
))}
</Form>
</div>
</div>
{/* <Row className='justify-content-md-center'>
<Col xs lg='9'>
<h3>Healthcare</h3>
<hr />
<p>
Show me:{' '}
<Button variant='primary' defaultChecked>
All
</Button>{' '}
<Button variant='outline-primary'>News</Button>{' '}
<Button variant='outline-primary'>Opinions</Button>{' '}
<Button variant='outline-primary'>Solutions</Button>
</p>
<p>
Filter By:{' '}
<Button variant='primary' defaultChecked>
All
</Button>{' '}
<Button variant='outline-primary'>Slant</Button>{' '}
<Button variant='outline-primary'>Source</Button>{' '}
<Button variant='outline-primary'>Topic</Button>
</p>
<p>
<DropdownButton
id='dropdown-basic-button'
title='All'
variant='outline-primary'
></DropdownButton>
<Button variant='outline-primary' defaultChecked>
All
</Button>{' '}
<Button variant='outline-primary'>Liberal</Button>{' '}
<Button variant='outline-primary'>Moderate</Button>{' '}
<Button variant='outline-primary'>Conservative</Button>{' '}
</p>
<p>
<Button variant='outline-primary'>Governance</Button>{' '}
<Button variant='outline-primary'>Economy</Button>{' '}
<Button variant='outline-primary'>Freigh Policy & Defence</Button>{' '}
<Button variant='outline-primary'>Healthcare</Button>{' '}
<Button variant='outline-primary'>Justice & Public Safety</Button>{' '}
<Button variant='outline-primary'>Infrastructure</Button>{' '}
<Button variant='outline-primary'>
Cllimate,Science, & Tech
</Button>{' '}
<InputGroup className='mb-3'></InputGroup>
</p>
</Col>
<Col xs lg='3'>
<div className='mb-2'>
<Button variant='primary' size='lg'>
ONC NEWSLETTERS
</Button>
</div>
<div className='mb-2'>
<Button variant='primary' size='lg'>
ONC WEBISODES
</Button>
</div>
<div className='mb-2'>
<Button variant='primary' size='lg'>
ONC PODCASTS
</Button>
</div>
</Col>
</Row>
*/}
</div>
);
};
export default SearchFilterBar;
|
const { BaseModel } = require('../base.model')
class Provinces extends BaseModel{
static get tableName(){
return 'support.provinces'
}
static get idColumn(){
return 'id_province'
}
static get relationMappings(){
return{
users:{
relation: BaseModel.HasManyRelation,
modelClass: BaseModel.modelPaths + '/pengguna/users.model',
join: {
from: 'support.provinces.id_pronvince',
to: 'pengguna.users.province_id'
}
},
regencies:{
relation: BaseModel.HasManyRelation,
modelClass: BaseModel.modelPaths + '/support/regencies.model',
join:{
from: 'support.provinces.id_province',
to: 'support.regencies.province_id'
}
}
}
}
}
module.exports = Provinces
|
var db = require('../mongoCollections')
var OriginMenu_DB = db.collection_originMenu()
var Menu_DB = db.collection_menu()
var Restaurant_DB = db.collection_restaurant()
var schedule = require('node-schedule');
module.exports = {
getMenuList: function(req, res){
Restaurant_DB.findById(req.query.restaurant_id, (err, restaurant)=>{
Menu_DB.find({
'_id': { $in: restaurant.menuidList }
}, function(err, menuList){
res.json(menuList);
});
})
},
createMenu: function(req, res){
OriginMenu_DB.findById(req.body.originMenu_id, function(err, originMenu){
Restaurant_DB.findById(originMenu.restaurant_id, function(err2, restaurant){
const today = new Date()
var result_start = new Date(req.body.start_year, req.body.start_month-1, req.body.start_date, req.body.start_hour, req.body.start_min)
var result_end = new Date(req.body.end_year, req.body.end_month-1, req.body.end_date, req.body.end_hour, req.body.end_min)
var startDateObj = new Date(result_start.getTime() + (3600000*9))
var endDateObj = new Date(result_end.getTime() + (3600000*9))
var newMenu = new Menu_DB({
token: restaurant.token,
originMenu : originMenu,
restaurantTitle : restaurant.title,
title : originMenu.title,
type : originMenu.type,
location : restaurant.location,
address : restaurant.address,
picture : req.body.picture,
discount : req.body.discount,
quantity : req.body.quantity,
method : req.body.method,
startDateObject : startDateObj,
endDateObject : endDateObj,
startTimeInt : parseInt(result_start.toTimeString().substr(0,5).replace(":", "")),
endTimeInt : parseInt(result_end.toTimeString().substr(0,5).replace(":", ""))
})
newMenu.save(function(err3, menu){
restaurant.menuidList.push(menu._id)
restaurant.save(function(err4, updatedRestaurant){
//menu end : 메뉴 삭제 / 가게 메뉴id리스트 pop
var destroyJob = schedule.scheduleJob(
`* ${req.body.end_min} ${req.body.end_hour}
${req.body.end_date} ${req.body.end_month} *`, ()=>{
var idx = updatedRestaurant.menuidList.findIndex(function(item) {
return item == String(menu._id)})
if (idx > -1) updatedRestaurant.menuidList.splice(idx, 1)
updatedRestaurant.save(()=>{
Menu_DB.deleteOne({_id: menu._id}, ()=>{
destroyJob.cancel()
})
})
});
res.json(menu)
})
})
})
})
},
updateMenu: function(req, res){
Menu_DB.findById(req.body.menu_id, (err, menu)=>{
var result_start = new Date(req.body.start_year, req.body.start_month-1, req.body.start_date, req.body.start_hour, req.body.start_min)
var result_end = new Date(req.body.end_year, req.body.end_month-1, req.body.end_date, req.body.end_hour, req.body.end_min)
var startDateObj = new Date(result_start.getTime() + (3600000*9))
var endDateObj = new Date(result_end.getTime() + (3600000*9))
menu.picture = req.body.picture,
menu.discount = req.body.discount,
menu.quantity = req.body.quantity,
menu.method = req.body.method,
menu.startDateObject = startDateObj,
menu.endDateObject = endDateObj,
menu.startTimeInt = parseInt(result_start.toTimeString().substr(0,5).replace(":", "")),
menu.endTimeInt = parseInt(result_end.toTimeString().substr(0,5).replace(":", "")),
menu.save((err2, updatedMenu)=>{
Restaurant_DB.findById(updatedMenu.originMenu.restaurant_id, (err3, restaurant)=>{
//menu end : 메뉴 삭제 / 가게 메뉴id리스트 pop
var destroyJob = schedule.scheduleJob(
`* ${req.body.end_min} ${req.body.end_hour}
${req.body.end_date} ${req.body.end_month} *`, ()=>{
var idx = restaurant.menuidList.findIndex(function(item) {
return item == String(updatedMenu._id)})
if (idx > -1) restaurant.menuidList.splice(idx, 1)
restaurant.save(()=>{
Menu_DB.deleteOne({_id: updatedMenu._id}, ()=>{
destroyJob.cancel()
})
})
});
res.json(menu)
})
})
})
},
deleteMenu: function (req, res) {
Menu_DB.findById(req.body.menu_id, (err, menu)=>{
Restaurant_DB.findById(menu.originMenu.restaurant_id, (err2, restaurant)=>{
var idx = restaurant.menuidList.findIndex(function(item) {
return item == String(menu._id)})
if (idx > -1) restaurant.menuidList.splice(idx, 1)
restaurant.save(()=>{
Menu_DB.deleteOne({_id: menu._id}, ()=>{
res.json(restaurant.menuidList)
})
})
})
})
}
}
|
/**
* @fileoverview Extern for mp3 generating library.
*/
/**
* A lame js object that allows access into the rest of the library.
* @constructor
*/
var lamejs = function() {};
/**
* An object responsible for a single run of encoding.
* @param {number} channels The number of channels.
* @param {number} sampleRate The sample rate.
* @param {number} quality The quality of the mp3 (like 128 kbps for instance).
* @constructor
*/
lamejs.Mp3Encoder = function(channels, sampleRate, quality) {};
/**
* Encodes 2 buffers.
* @param {!ArrayBufferView} left The left channel.
* @param {!ArrayBufferView=} opt_right The optional right channel.
* @return {!Int8Array} Encoded mp3 data.
*/
lamejs.Mp3Encoder.prototype.encodeBuffer = function(left, opt_right) {};
/**
* @return {!Int8Array} The rest of the mp3 data needed to generate the file.
*/
lamejs.Mp3Encoder.prototype.flush = function() {};
|
define(['src/util/color'], function (Color) {
return {
getChart(x, y, options) {
options = options || {};
if (x.length !== y.length || y.length === 0) {
throw new Error('Invalid data length');
}
var chart = {
data: [],
axis: [
{
label: options.xLabel || ''
},
{
label: options.yLabel || ''
}
]
};
var species = Object.keys(y[0]);
var colors = Color.getDistinctColors(species.length);
for (var i = 0; i < species.length; i++) {
var data = {};
chart.data.push(data);
// eslint-disable-next-line no-loop-func
data.y = y.map((y) => {
return y[species[i]];
});
if (options.xLog) {
data.x = x.map((v) => -Math.log10(v));
} else {
data.x = x;
}
data.label = species[i];
data.xAxis = 0;
data.yAxis = 1;
data.defaultStyle = {
lineColor: colors[i],
lineWidth: 1
};
}
return chart;
}
};
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.