text
stringlengths 7
3.69M
|
|---|
import {
Steps,
Button,
message,
Modal,
Form,
Switch,
Row,
Col,
Input,
Select,
Number,
notification,
Icon,
} from 'antd';
import React from 'react';
import { connect } from 'dva';
import FormModular from './FormModular';
import TableModular from './TableModular';
import ResultModular from './ResultModular';
const Step = Steps.Step;
@connect(({ guidePage,loading }) => ({
guidePage,
loadingG:
loading.effects['guidePage/getButtonGuideConfig'] ||
loading.effects['guidePage/getButtonGuideData']
}))
@Form.create()
class GuidePage extends React.Component {
state = {
current: 0,
visible: true,
isLoading:false,
};
UNSAFE_componentWillMount = () => {
let params = this.props.tableButton.BUTTON_GUIDE[0];
this.props.dispatch({ type: 'guidePage/detailButtonGuide', payload: { params } });
this.props.dispatch({ type: 'guidePage/getButtonGuideClean' });
};
handleOk = e => {
this.setState({
visible: false,
});
};
handleCancel = e => {
this.props.dispatch({
type: 'guidePage/save',
payload: { cacheFormData: [], cacheSelectData: [] },
});
if(this.formPage){
this.formPage.props.form.resetFields()
}
this.setState({
visible: false,
});
};
next() {
this.formPage.props.form.validateFields((err, values) => {
this.setState({})
if (err) {
return
} else {
const current = this.state.current + 1;
let params = this.props.tableButton.BUTTON_GUIDE[current];
const formData = _.flatten(this.props.guidePage.cacheFormData)
switch (params.BUTTON_GUIDE_TYPE) {
case 'Detail':
this.props.dispatch({ type: 'guidePage/detailButtonGuide', payload: { params } });
break;
case 'EditDetail':
this.props.dispatch({
type: 'guidePage/getGuideBean', payload: {
params,
pageNum: 1,
pageSize: 10,
METHOD_BODY: params.METHOD_BODY,
formData: formData.length ? formData : this.formPage.props.guidePage.guidePageFormData.policyFormFields
}, callback: res => {
if (res.status == 'success') {
this.props.dispatch({ type: 'guidePage/getButtonGuideConfig', payload: { params } });
this.props.dispatch({
type: 'guidePage/getButtonGuideData',
payload: {
params,
pageNum: 1,
pageSize: 10,
METHOD_BODY: params.METHOD_BODY,
// formData: formData.length ? formData : this.formPage.props.guidePage.guidePageFormData.policyFormFields
},
});
}
}
});
break;
case 'Result':
notification.success({ message: 'result page!', duration: 3 });
break;
default:
break;
}
this.setState({ current });
}
})
// return
}
// 点击提交按钮
Submit = () => {
this.setState({
isLoading:true
})
const current = this.state.current + 1;
const cacheFormDataTest = this.props.guidePage.cacheFormData; //被分组了,要处理下
const cacheFormData = [];
cacheFormDataTest.map(item => {
item.map(ii => {
cacheFormData.push(ii);
});
});
const cacheSelectData = this.props.guidePage.cacheSelectData;
let buttonName = this.props.tableButton.FIELD_NAME; //当前按钮名字
this.props.dispatch({
type: 'guidePage/TransactionProcess',
payload: {
params: {
cacheFormData,
cacheSelectData,
ButtonName: buttonName,
},
},
callback: res => {
if (res.status == 'success') {
this.props.dispatch({ type: 'tableTemplate/getPagelist' }); //重新获取列表页数据
this.setState({ current,isLoading:false });
} else {
this.setState({ current,isLoading:false });
}
},
});
this.props.dispatch({
type: 'guidePage/save',
payload: { cacheFormData: [], cacheSelectData: [], cacheTableData: [] },
});
};
prev() {
const current = this.state.current - 1;
let params = this.props.tableButton.BUTTON_GUIDE[current];
switch (params.BUTTON_GUIDE_TYPE) {
case 'Detail':
this.props.dispatch({ type: 'guidePage/detailButtonGuide', payload: { params } });
break;
case 'EditDetail':
this.props.dispatch({ type: 'guidePage/getButtonGuideConfig', payload: { params } });
this.props.dispatch({
type: 'guidePage/getButtonGuideData',
payload: {
params,
pageNum: 1,
pageSize: 10,
},
});
break;
case 'Result':
notification.success({ message: 'result page!', duration: 3 });
break;
default:
break;
}
this.setState({ current });
}
complete = () => {
this.setState({
visible: false,
});
};
//渲染向导页的内容
setStepsContent = (type, data) => {
switch (type) {
case 'Detail': //form表单
const formProps = {
CurrentData: data,
form:this.props.form
};
return <FormModular key={_.now()} store={window.g_app._store} ref={dom => this.formPage = dom} {...formProps} />;
break;
case 'EditDetail': //table页
const tableProps = {
CurrentData: data,
...this.props,
};
return <TableModular {...tableProps} />;
break;
case 'Result': //结果反馈页
const resultProps = {
CurrentData: data,
...this.props,
};
return <ResultModular {...resultProps} />;
break;
default:
break;
}
};
render() {
const { current } = this.state; //当前步骤条数
const pageStructure = this.props.tableButton.BUTTON_GUIDE;
let { guidePageData } = this.props.guidePage;
return (
<Modal
footer={null}
width="80%"
maskClosable={false}
// bodyStyle={{height:'70vh',overflow:'scroll'}}
closable={false}
centered={true}
visible={this.state.visible}
onOk={this.handleOk}
onCancel={this.handleCancel}
>
{/* 步骤条 */}
<Steps current={current} style={{ marginTop: '1rem' }}>
{pageStructure.map(item => (
<Step key={item.ID} title={item.LABEL} />
))}
</Steps>
{/* 显示的内容 */}
{this.props.tableButton.BUTTON_GUIDE[current].BUTTON_GUIDE_TYPE && (
<div className="steps-content" style={{ margin: '1rem 0', width: '100%' }}>
<Row>
{this.setStepsContent(
this.props.tableButton.BUTTON_GUIDE[current].BUTTON_GUIDE_TYPE,
this.props.tableButton.BUTTON_GUIDE[current]
)}
</Row>
</div>
)}
{/* 底部的按钮 */}
<div className="steps-action" style={{ width: '100%', textAlign: 'center' }}>
{current < pageStructure.length - 2 && (
<Button type="primary" onClick={() => this.next()}>
下一步
</Button>
)}
{current === pageStructure.length - 1 && (
<Button type="primary" onClick={() => this.complete()}>
完成
</Button>
)}
{current === pageStructure.length - 2 && (
<Button type="primary" onClick={() => this.Submit()}>
提交<Icon style={{display:this.state.isLoading ? 'null' : 'none'}} type="loading" />
</Button>
)}
{/* {
current > 0 && current === pageStructure.length - 2
&& (
<Button style={{ marginLeft: 8 }} onClick={() => this.prev()}>
上一步
</Button>
)
} */}
{current < pageStructure.length - 1 && (
<Button style={{ marginLeft: 8 }} type="primary" onClick={() => this.handleCancel()}>
关闭
</Button>
)}
</div>
</Modal>
);
}
}
export default GuidePage
|
import React from 'react';
import { StackNavigator } from 'react-navigation';
import { WelcomeScreen } from './WelcomeScreen';
import { ActivitiesScreen } from './Activities/ActivitiesScreen'
const App = StackNavigator({
Home: {
screen: WelcomeScreen,
},
Activities: {
screen: ActivitiesScreen,
},
});
export default App;
|
"use strict";
const Sandwich = require("./sandwich.js");
const data = require("./data.js");
const buildDom = (ingredients, categories) => {
categories.forEach((category) =>{
const div = createCategoryDiv(category);
addCategoryDivEventListener(div);
ingredients.forEach((ingredient) => {
if (category.id === ingredient.categoryId) {
createOption(ingredient, div);
}
});
});
};
const createCategoryDiv = (category) => {
const newDiv = document.createElement("div");
newDiv.setAttribute("id", `${category.name}-container`);
newDiv.innerText = `${category.name} Options`;
document.getElementById("order-container").appendChild(newDiv);
let selectType = category.isMultiSelect ? "checkbox" : "radio";
newDiv.innerHTML += `<div class=${selectType}><label><input type="${selectType}" name="${category.name}-${selectType}" value="None">None</label></div>`; //add none option for each category
return newDiv;
};
const addCategoryDivEventListener = (element) => {
const totalCostHTML = document.getElementById("total-cost");
element.addEventListener("change", (e) => {
if (e.target.type === "radio") {
clearSiblingRadios(e.target);
Sandwich.addIngredient(e.target.value);
totalCostHTML.innerHTML = Sandwich.getSandwichPrice();
addSelectedCategories();
}
else if (e.target.checked === true) {
(e.target.value === "None") ? clearSiblingCheckboxes(e.target) : clearNoneCheckbox(e.target);
Sandwich.addIngredient(e.target.value);
totalCostHTML.innerHTML = Sandwich.getSandwichPrice();
addSelectedCategories();
} else {
Sandwich.removeIngredient(e.target.value);
totalCostHTML.innerHTML = Sandwich.getSandwichPrice();
addSelectedCategories();
}
});
};
const createOption = (ingredient, parentElement) => {
let cls; let nm;
if (ingredient.isMultiSelect) {
cls = "checkbox";
nm = `${ingredient.categoryName}-checkbox`;
} else {
cls = "radio";
nm = `${ingredient.categoryName}-radio`;
}
let newDiv = document.createElement("div");
newDiv.setAttribute("class", cls);
parentElement.appendChild(newDiv);
let newLabel = document.createElement("label");
newLabel.innerHTML = `<input type=${cls} name=${nm} value="${ingredient.name}">${ingredient.name} - $${ingredient.price.toFixed(2)}`;
newDiv.appendChild(newLabel);
};
const addSelectedCategories = () => {
let categories = Sandwich.listUniqueCategorySelections();
const finalOrderContainer = document.getElementById("selections-container");
finalOrderContainer.innerHTML = "";
categories.forEach((category) => {
let newDiv = document.createElement("div");
newDiv.setAttribute("class", `selected-category-container`);
newDiv.setAttribute("id", `selected-${category}`);
newDiv.innerHTML = `${category}`;
finalOrderContainer.appendChild(newDiv);
});
addSelectionsToCategories();
};
const addSelectionsToCategories = () => {
const finalOrderContainer = document.getElementById("selections-container");
let selectedIngredients = Sandwich.getSelectedIngredients();
let categoryDivs = finalOrderContainer.childNodes;
for (let div of categoryDivs) {
let categoryName = div.id.split("-")[1];
selectedIngredients.forEach((ingredient) => {
if (categoryName === ingredient.categoryName) {
div.innerHTML += `<p>${ingredient.name}</p>`;
}
});
}
};
const clearSiblingRadios = (selectedOption) => {
let sameNamedOptions = document.getElementsByName(selectedOption.name);
sameNamedOptions.forEach((option) => {
if (option.checked === false) {
Sandwich.removeIngredient(option.value);
}
});
};
const clearSiblingCheckboxes = (selectedOption) => {
let sameNamedOptions = document.getElementsByName(selectedOption.name);
sameNamedOptions.forEach((option) => {
if (option.value !== selectedOption.value) {
Sandwich.removeIngredient(option.value);
option.checked = false;
}
});
};
const clearNoneCheckbox = (selectedOption) => {
let sameNamedOptions = document.getElementsByName(selectedOption.name);
sameNamedOptions.forEach((option) => {
if (option.value === "None") {
Sandwich.removeIngredient(option.value);
option.checked = false;
}
});
};
module.exports = buildDom;
|
import React from 'react'
import { ThemeProvider } from 'emotion-theming'
import { Theme } from '../src/config'
const theme1 = new Theme()
const withThemeProvider = storyFn => (
<ThemeProvider theme={theme1}>
{storyFn()}
</ThemeProvider>
)
export default withThemeProvider
|
import React from 'react';
import _ from 'lodash';
import { getSchemaFromView } from '../../Store/View';
import Store from '../../Store/Store';
import ItemFrame from '../ItemFrame';
import DataTypes from '../DataTypes';
class NewEditor extends React.Component {
onSubmit() {
this.props.dispatch(Store.actions.save(this.props.schema));
this.props.dispatch(Store.actions.close());
}
render() {
const schema = getSchemaFromView(this.props.schema, this.props.microcastle, this.props.view);
const editorComponents = _.values(_.mapValues(schema.attributes, (columnOptions, columnName) => {
const ColumnComponent = DataTypes.stringToComponent(columnOptions.type);
return (
<ItemFrame title={columnOptions.name || columnName} key={columnName}>
<ColumnComponent view={this.props.view.set('attribute', columnName)}
schema={this.props.schema} />
</ItemFrame>
);
}));
return <div>
{editorComponents}
</div>;
}
}
export default NewEditor;
|
import React from 'react';
function PeopleLeft() {
return(
<div className='peopleList-left-me'>
<div className="cleaner"></div>
<div className="peopleList-left-me-body">
<h2 className="peopleList-left-me-title">
Çevrimiçi - 0
</h2>
<div className="peopleList-left-me-persons">
<a className="peopleList-left-me-person" href="/channels/@me">
<div className="peopleList-left-me-person_profile">
<div className="peopleList-left-me-person-avatar">
<svg width="32" height="32" viewBox="0 0 32 32">
<foreignObject x="0" y="0" width="32" height="32">
<img
className="avatar-img"
src="https://cdn.discordapp.com/avatars/364095318658121729/64c9b3a2111c69340537515f04613322.png?size=256"
/>
</foreignObject>
<svg width="16" height="16" viewBox="0 0 23 23" x="19" y="19">
<circle cx="11.5" cy="11.5" r="11.5" fill="#2F3136" />
</svg>
<svg width="10" height="10" viewBox="0 0 23 23" x="22" y="22">
<circle cx="11.5" cy="11.5" r="11.5" fill="#399F58" />
</svg>
</svg>
</div>
<div className="peopleList-left-me-person_info">
<div className="peopleList-left-me-person_username">
<span>mehmetnail0</span>
<span className="peopleList-left-me-person_id">#7777</span>
</div>
<div className="peopleList-left-me-person_status">Çevrimiçi</div>
</div>
</div>
<div className="peopleList-left-me-icons">
<div className="peopleList-left-me-icon">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path fill="currentColor" d="M4.79805 3C3.80445 3 2.99805 3.8055 2.99805 4.8V15.6C2.99805 16.5936 3.80445 17.4 4.79805 17.4H7.49805V21L11.098 17.4H19.198C20.1925 17.4 20.998 16.5936 20.998 15.6V4.8C20.998 3.8055 20.1925 3 19.198 3H4.79805Z"></path></svg>
</div>
<div className="peopleList-left-me-icon">
<svg width="20" height="20" viewBox="0 0 24 24"><g fill="none" fillRule="evenodd"><path d="M24 0v24H0V0z"></path><path fill="currentColor" d="M12 16c1.1045695 0 2 .8954305 2 2s-.8954305 2-2 2-2-.8954305-2-2 .8954305-2 2-2zm0-6c1.1045695 0 2 .8954305 2 2s-.8954305 2-2 2-2-.8954305-2-2 .8954305-2 2-2zm0-6c1.1045695 0 2 .8954305 2 2s-.8954305 2-2 2-2-.8954305-2-2 .8954305-2 2-2z"></path></g></svg>
</div>
</div>
</a>
</div>
</div>
</div>
);
}
export default PeopleLeft;
|
import React, { Component } from 'react';
import OrderViewRow from './OrderViewRow';
export class OrderView extends Component {
render() {
return (
<main className="main-page" style={{margin: "auto", width: "85%"}}>
<h3>Order History</h3>
<table>
<thead>
<tr>
<th>Order Number</th>
<th>Total</th>
<th>Order Date</th>
<th></th>
</tr>
</thead>
<OrderViewRow />
</table>
</main>
);
}
}
export default OrderView;
|
'use strict';
const IMAGES = [
//wheat
'https://i.imgur.com/K8swhvR.jpg',
//sparse wheat
'https://i.imgur.com/voaoCxd.jpg'
];
const GRID_HEIGHT = 400; //in the unit pixels
const GRID_WIDTH = 400;
const GRID_CELL_SIZE = 40; //try to make it divide with no remainders
const GRID_EMPTY = [244, 86, 66]; //color of the grid when it's empty
const RESOURCES = {
money: '💰', //http://getemoji.com/
corn: '🌽',
milk: '🍼'
};
const STATE = {
resources: {
money: 100,
corn: 0,
milk: 0
},
cashPerCrop: 10,
investment: 0
};
class Corn extends Item { //convention in every programming language that classes are Capitalized
init(){
this.quantity = 3;
}
get cost(){
return {
money: 20,
corn: 1,
milk: 0
}
}
get info () {
return `This is some nice corn ${this.quantity}`
}
get image () {
if (this.quantity <3) {
return 'voaoCxd.jpg' //sparse wheat
} else {
return 'K8swhvR.jpg' //wheat
}
}
onClick () {
this.quantity -= 1;
STATE.resources.money += Math.round(STATE.cashPerCrop * Math.random());
if (this.quantity <= 0) {
this.destroy ();
showMessage('You ran out of corn!');
}
}
}
var tractorBonus = new Bonus('Powerful Tractor', {
money: 50
}, function() {
STATE.cashPerCrop += 5;
})
var investmentPortfolio = new Bonus('Investment Portfolio', {
money: 100
}, function(){
STATE.investment += 0.1;
})
function init() {
var corn = new Corn();
GAME.grid.place(corn, 0, 0);
var menu = new Menu('Farm Mall', [
new Button('Buy Corn', tryBuy(Corn)),
new Button('Upgrade Tractor', tryBuy(tractorBonus)),
new Button('Open Roth IRA', tryBuy(investmentPortfolio))
])
defineHarvester('trees', function() {
return 1 * STATE.resources.money;
}, 2000); //milliseconds
//investment
defineHarvester('money', function() {
return Math.round(STATE.investment * STATE.resources.money);
}, 1000);
//taxes
defineHarvester('money', function() {
return -Math.round(STATE.resources.money * 0.3)
}, 10000);
//random events such as frost
every(5000, function(){
if (Math.random() < 0.05) {
var frost = new Event('Early Frost', 'The frost came early and messed up your crops, that sucks',
[
new Action('DEFROST', function() {
STATE.resources.money -= 10;
}),
new Action('Do nothing', function() {
STATE.cashPerCrop -= 5;
schedule(10000, function() {
STATE.cashPerCrop += 5;
showMessage('Spring is Here!')
})
})
])
}
});
}
function main() {
background (106, 152, 221);
}
|
const knex = require('knex');
const cache = require('../notificationsCache')
const config = require('../knexfile.js');
// we must select the development object from our knexfile
const db = knex(config.development);
module.exports = async ({name, description, project_id}) => {
console.log('postResources invoked')
try {
const [id] = await db('resources').insert({name, description})
const newResource = await db('resources')
.select('*')
.where({ id })
await db('proj_to_resource').insert(
{
project_id,
resource_id: id
}
)
cache.setResources(newResource[0])
return newResource
} catch (e) {
console.log(e)
return e
}
}
|
export {version} from "./build/package";
export * from "d3-selection"
export * from "d3-selection-multi"
export * from "d3-transition"
export * from "d3-array"
export * from "d3-collection"
export * from "d3-ease";
export * from "d3-color"
export * from "d3-format"
export * from "d3-interpolate"
export * from "d3-scale"
export * from "d3-shape"
|
export const fetchScores = () => (
$.ajax({
method: 'GET',
url: '/api/scores'
})
);
export const createScore = score => (
$.ajax({
method: 'POST',
url: '/api/scores',
data: score
})
);
export const updateScore = score => (
$.ajax({
method: 'PUT',
url: `/api/scores/${score.score.id}`,
data: score
})
);
|
var http = require('http');
var url = require('url');
var server = http.createServer(function(request,response){
var pathname = url.parse(request.url).pathname;
if(pathname === '/'){
response.writeHead(200,{"Content-type" : "text/html"});
response.end("Home Page\n");
}else if(pathname === '/about'){
response.writeHead(200,{"Content-type" : "text/html"});
response.end("About Us");
}else if(pathname === '/redirect'){
response.writeHead(301,{"Location" : "/"});
response.end();
}else{
response.writeHead(404,{"Content-type" : "text/html"});
response.end("Page not found");
}
});
server.listen(3000,"localhost");
console.log("Server running on localhost on port 3000");
|
import express from 'express';
import * as raiderCtrl from '../controllers/raider.controller';
import isAuthenticated from '../middlewares/authenticate';
import validate from '../config/joi.validate';
import schema from '../utils/validator';
const router = express.Router();
/**
* @swagger
* tags:
* - name: raider
* description: Raider operations
*/
router.route('/add')
/**
* @swagger
* /raider/add:
* put:
* tags:
* - raider
* summary: "Create a new Raider"
* security:
* - Bearer: []
* operationId: add
* consumes:
* - application/json
* produces:
* - application/json
* parameters:
* - name: body
* in: body
* description: Created raider object
* required: true
* schema:
* $ref: "#/definitions/raider"
* responses:
* 200:
* description: OK
* schema:
* $ref: "#/definitions/Raider"
* 403:
* description: Third Level Project not found
* schema:
* $ref: '#/definitions/Error'
*/
.put(validate(schema.Raider), (req, res) => {
raiderCtrl.SaveRaider(req, res);
});
router.route('/upload_image/:id')
.post(validate(schema.CheckId), (req, res) => {
raiderCtrl.UploadRaiderImage(req, res);
});
router.route('/download_image/:id')
.get(validate(schema.CheckId), (req, res) => {
raiderCtrl.DownloadRaiderImage(req, res);
});
router.route('/get_by_id/:id')
/**
* @swagger
* /raider/get_by_id/{id}:
* get:
* tags:
* - raider
* summary: Get Raider by Id
* operationId: getById
* consumes:
* - application/json
* produces:
* - application/json
* parameters:
* - name: id
* in: path
* description: id of raider that needs to be fetched
* required: true
* type: integer
* responses:
* 200:
* description: OK
* schema:
* $ref: "#/definitions/Raider"
* 404:
* description: Raider not found
* schema:
* $ref: '#/definitions/Error'
*/
.get(validate(schema.CheckId), (req, res) => {
raiderCtrl.GetRaiderById(req, res);
});
router.route('/modify')
/**
* @swagger
* /raider/modify:
* put:
* tags:
* - raider
* summary: "Modify Raider By Id"
* security:
* - Bearer: []
* operationId: modify
* consumes:
* - application/json
* produces:
* - application/json
* parameters:
* - name: body
* in: body
* description: Updated Raider object
* required: true
* schema:
* $ref: "#/definitions/Raider"
* responses:
* 200:
* description: OK
* schema:
* $ref: "#/definitions/Raider"
* 400:
* description: Invalid Raider
*/
.put(validate(schema.Raider), (req, res) => {
raiderCtrl.SaveRaider(req, res);
});
router.route('/increase/:id')
.put(validate(schema.CheckId), (req, res) => {
raiderCtrl.Increase(req, res);
});
router.route('/get/featured')
.get((req, res) => {
raiderCtrl.GetFeatured(req, res);
});
router.route('/change_status/:id')
/**
* @swagger
* /raider/change_status/{id}:
* put:
* tags:
* - raider
* summary: Change Raider Status
* operationId: changeStatus
* consumes:
* - application/json
* produces:
* - application/json
* parameters:
* - name: id
* in: path
* description: id of raider that needs to be fetched
* required: true
* type: integer
* responses:
* 200:
* description: OK
* schema:
* $ref: "#/definitions/Raider"
* 404:
* description: Raider not found
* schema:
* $ref: '#/definitions/Error'
*/
.put(validate(schema.CheckId), (req, res) => {
raiderCtrl.ChangeStatus(req, res);
});
router.route('/get/loadmore')
.get(validate(schema.CheckLoadMore), (req, res) => {
raiderCtrl.LoadMore(req, res);
});
router.route('/get')
/**
* @swagger
* /raider/get:
* get:
* tags:
* - raider
* summary: "List all raiders"
* operationId: get
* consumes:
* - application/json
* produces:
* - application/json
* parameters: []
* responses:
* 200:
* description: OK
* schema:
* type: object
*/
.get((req, res) => {
raiderCtrl.GetRaiders(req, res);
});
router.route('/delete/:id')
/**
* @swagger
* /raider/delete/{id}:
* delete:
* tags:
* - raider
* summary: Delete the raider by Id
* security:
* - Bearer: []
* operationId: delete
* produces:
* - application/json
* parameters:
* - name: id
* in: path
* description: id of raider that needs to be deleted
* required: true
* type: integer
* responses:
* 200:
* description: OK
* 400:
* description: "Invalid ID"
*/
.delete((req, res) => {
raiderCtrl.DeleteRaider(req, res);
});
router.route('/search/')
/**
* @swagger
* /raider/search/{text}:
* get:
* tags:
* - raider
* summary: "Search Raiders"
* operationId: search
* consumes:
* - application/json
* produces:
* - application/json
* parameters: []
* responses:
* 200:
* description: OK
* schema:
* type: object
*/
.get(validate(schema.CheckText), (req, res) => {
raiderCtrl.Search(req, res);
});
export default router;
|
import React, { PropTypes } from 'react';
// import s from './Wait.css';
import config from '../../config/config.json';
/*
*
* TODO :
*
*/
class Wait extends React.Component {
static propTypes = {
cocktail: PropTypes.object,
setRecipe: PropTypes.func,
incrStep: PropTypes.func,
};
constructor(props) {
super(props);
this.state = {
message: '',
seconds: 0,
};
}
componentDidMount() {
console.log('mount Wait');
console.log(this.props.cocktail);
console.log(config);
this.buildPython();
}
/*
getUserInformations() {
}
getNameDrink() {
}
*/
buildPython() {
const cocktail = this.props.cocktail;
console.log(config.drinks);
console.log(cocktail.drinks[0]);
console.log(cocktail.drinks[1]);
const drink1 = [];
const drink2 = [];
const gpio1 = config.drinks[cocktail.drinks[0].name.toLowerCase()];
const second1 = (cocktail.drinks[0].type.toLowerCase() === 'soft') ? '20' : '5';
const type1 = cocktail.drinks[0].type.toLowerCase();
const gpio2 = config.drinks[cocktail.drinks[1].name.toLowerCase()];
const second2 = (cocktail.drinks[1].type.toLowerCase() === 'soft') ? '20' : '5';
const type2 = cocktail.drinks[1].type.toLowerCase();
if (gpio1 && second1 && gpio2 && second2) {
drink1.push(gpio1, second1, type1);
drink2.push(gpio2, second2, type2);
const serve = {};
serve.drink1 = drink1;
serve.drink2 = drink2;
console.log('Server: ');
console.log(serve);
this.props.setRecipe(serve);
this.props.incrStep();
} else {
// DISPLAY MESSAGE
console.log('NOT OK');
}
}
render() {
return (
<div>
<p>Step 1 : Wait</p>
<p>Hello, wait to get your {this.props.cocktail.name}</p>
</div>
);
}
}
export default Wait;
|
Polymer(
{
iconChanged: function () {
this.icon = 'square-editor:code-block';
},
labelChanged: function () {
this.label = 'Code';
}
}
);
|
var searchData=
[
['projet_20atelier_20c_2b_2b',['Projet atelier C++',['../index.html',1,'']]]
];
|
const logger = require("@threadws/logger");
class AppError extends Error {
constructor(obj) {
super(obj.message);
this.name = this.constructor.name;
this.statusCode = obj.code || 500;
this.details = obj.details || false;
Error.captureStackTrace(this, this.constructor);
logger.info(obj.message, {
detail: { ...obj.details, code: obj.code, stack: obj.stack }
});
}
}
module.exports = AppError;
|
var cssBody =
'html, body, #root-container-editor {' +
' color: $dropback-text-color;' +
'}' +
'.lp-editor,' +
'.primary-toolbar,' +
'.editor-divider {' +
' background-color: $primary-color;' +
'}' +
'.editor-header{' +
' background-color: $secondary-color;' +
'}' +
'.tab-bar{' +
' background-color: $secondary-color;' +
'}' +
'.builder-header,' +
'.widget-panel,' +
'.footer-controls{' +
' background-color: $secondary-alt-color;' +
'}' +
'.editor-header-button,' +
'.editor-header-button-label,' +
'.editor-header-dropdown,' +
'.editor-header-dropdown-label{' +
' border-color: $primary-color;' +
' background-color: $secondary-color;' +
' color: $primary-alt-text-color;' +
'}' +
'.content-tree-node-wrapper{' +
' color: $primary-alt-text-color;' +
'}' +
'.editor-content-tree,' +
'.content-tree-node,' +
'.content-tree-node-visibility-state,' +
'.options-panel-view-pane,' +
'.collapsible-panel,' +
'.options-panel-title {' +
' border-color: $tertiary-alt-color;' +
'}' +
'.content-tree-node-visibility-state.visible:after{' +
' background: $primary-element-color;' +
'}' +
'.content-tree-node-visibility-state.lp-hidden:after{' +
' background: $theme-accents;' +
'}' +
'.content-tree-node-visibility-state:hover:after{' +
' background: $tertiary-color;' +
'}' +
'.content-tree-visibility-toggle,' +
'.settings-bar-dropdown-label:after{' +
' background-image: url(\'data:image/svg+xml; utf8, <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 50 50"><path fill="#{$primary-element-color}" d="M7,8h37c3,0,5,3,3,6L28,40c-1,2-5,2-6,0L4,14C2,11,4,8,7,8z"/></svg>\');' +
'}' +
'.name-edit{' +
' background: $primary-element-color;' +
' color: $highlight-text-color;' +
' border-color: $theme-highlight;' +
'}' +
'.selected-element-highlight .content-tree-visibility-toggle{' +
' background-image: url(\'data:image/svg+xml; utf8, <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 50 50"><path fill="#{$theme-highlight}" d="M7,8h37c3,0,5,3,3,6L28,40c-1,2-5,2-6,0L4,14C2,11,4,8,7,8z"/></svg>\');' +
'}' +
'.selected-element-highlight,' +
'.selected-element-highlight:before{' +
' background: $primary-element-color;' +
' color: $highlight-text-color;' +
'}' +
'.footer-control-button{' +
' color: $primary-text-color;' +
' border-color: transparent;' +
'}' +
'.footer-control-button.active{' +
' color: $theme-highlight;' +
' border-color: $theme-highlight;' +
'}' +
'.footer-control-button-count{' +
' color: $theme-highlight;' +
'}' +
'.page-content-panel,' +
'.editor-info-panel{' +
' background: $primary-alt-color;' +
'}' +
'.options-pane a{' +
' color: $primary-text-color;' +
'}' +
'.disabled .editor-header-button-label{' +
' color: $disabled-text-color;' +
'}' +
'.action-button:not(.disabled),' +
'.action-button:not(.disabled) .editor-header-button-label,' +
'.action-button:not(.disabled) .editor-header-dropdown-label{' +
' background-color: $highlights;' +
' color: $highlights-secondary;' +
'}' +
'.action-button.disabled{' +
' color: $highlights-secondary;' +
'}' +
'.tool-button{' +
' color: $primary-text-color;' +
'}' +
'.tab-bar-tab {' +
' color: $primary-text-color;' +
' border-color: $theme-accents;' +
'}' +
'.tab-bar-tab.on {' +
' color: $theme-highlight;' +
' border-color: $theme-highlight;' +
'}' +
'.tab-button{' +
' color: $theme-highlight;' +
'}' +
'.tab-bar-tab.dsbl{' +
' color: $disabled-text-color;' +
' border-color: $disabled-element-color;' +
'}' +
'.tab-bar-dropdown{' +
' background: $primary-color;' +
'}' +
'.options-panel-title{' +
' color: $theme-highlight;' +
'}' +
'.editor-divider-handle{' +
' background-color: darken($secondary-color, 10%);' +
'}' +
'.editor-divider-handle-left:after{' +
' border-right-color: $theme-highlight;' +
'}' +
'.editor-divider-handle-right:after{' +
' border-left-color: $theme-highlight;' +
'}' +
'#page-content-panel h1 {' +
' background-color: $secondary-color;' +
' color: $primary-alt-text-color;' +
'}' +
'.embed-ico-eye path{' +
' fill: $primary-element-color;' +
'}' +
'.selected-element-highlight .embed-ico-eye path{' +
' fill: $highlight-text-color;' +
'}' +
'.help-button{' +
' background-color: $primary-element-color;' +
' color: $primary-color;' +
' font-weight: bold;' +
'}' +
'.help-button:after{' +
' background-color: $highlights;' +
' color: $highlights-secondary;' +
' font-weight: normal;' +
'}' +
'.help-button:before{' +
' color: $primary-color;' +
'}' +
'a.button{' +
' background-color: $button-primary-color;' +
' color: $button-primary-text-color;' +
'}' +
'a.button.dsbl{' +
' opacity: 0.2;' +
'}' +
'a.button.link{' +
' color: $button-primary-color;' +
'}' +
'.form-elm-label{' +
' color: $dropback-text-color;' +
'}' +
'.form-elm-mini-label{' +
' background: $secondary-color;' +
' color: $dropback-text-color;' +
'}' +
'.form-elm-input-text,' +
'.form-elm-contenteditable{' +
' background: $tertiary-color;' +
' color: $highlight-text-color;' +
'}' +
'.form-elm-input-disabled, .dsbl .form-elm-input-text{' +
' color: $disabled-text-color;' +
'}' +
'.collapsible-panel-title-bar h3{' +
' color: $dropback-text-color;' +
'}' +
'.note{' +
' color: $dropback-text-color;' +
'}' +
'.visibility-toggle{' +
' color: $primary-text-color;' +
'}' +
'.bgPanelAdvanced{' +
' border-color: $tertiary-color;' +
'}' +
'.select2-container .select2-choice{' +
' background-color: $tertiary-color;' +
' color: $highlight-text-color;' +
'}' +
'.select2-drop {' +
' background: $secondary-color;' +
' color: $highlight-text-color;' +
'}' +
'.select2-results .select2-highlighted {' +
' background: $tertiary-color;' +
' color: $highlight-text-color;' +
'}' +
'.select2-container-multi.select2-container-disabled .select2-choices .select2-search-choice, .select2-container.select2-container-disabled .select2-choice {' +
' color: $disabled-text-color;' +
'}' +
'.select2-search input {' +
' color: $highlight-text-color;' +
'}' +
'.select2-no-results{' +
' color: $primary-text-color;' +
'}' +
'.slider .track{' +
' background-color:$secondary-color;' +
'}' +
'.slider .knob {' +
' background-color: $theme-highlight;' +
'}' +
'.modal-panel>.action-bar .btn-blue{' +
' background-color: $modal-highlights-color;' +
' color: $modal-highlight-text-color;' +
'}' +
'.modal-panel>.action-bar .btn-gray{' +
' background-color: $modal-disabled-color;' +
' color: $modal-disabled-text-color;' +
'}' +
'.wgt-color-primary{' +
' fill: $primary-element-color;' +
'}' +
'.wgt-color-secondary{' +
' fill: $secondary-color;' +
'}' +
'.wgt-action-enabled,' +
'.wgt-action-disabled{' +
' fill: transparent;' +
'}' +
'.wgt-action-arrow{' +
' fill: $secondary-color;' +
'}' +
'.widget-button:hover .wgt-bg,' +
'.widget-button:hover .wgt-action-bg{' +
' fill: darken($primary-element-color, 15%);' +
'}' +
'.dnd-ghost .wgt-bg,' +
'.dnd-ghost .wgt-action-bg{' +
' fill: $state-disabled-color;' +
'}' +
'.dnd-ghost .wgt-action-arrow,' +
'.dnd-ghost .wgt-action-enabled{' +
' fill: transparent;' +
'}' +
'.dnd-ghost .wgt-action-disabled{' +
' fill: $secondary-color;' +
'}' +
'.dnd-ghost .init .wgt-bg,' +
'.dnd-ghost .init .wgt-action-bg{' +
' fill: $state-clicked-color;' +
'}' +
'.dnd-ghost .init .wgt-action-disabled,' +
'.dnd-ghost .init .wgt-action-enabled{' +
' fill: transparent;' +
'}' +
'.dnd-ghost .init .wgt-action-arrow{' +
' fill: $secondary-color;' +
'}' +
'.dnd-ghost .ok .wgt-bg,' +
'.dnd-ghost .ok .wgt-action-bg{' +
' fill: $state-enabled-color' +
'}' +
'.dnd-ghost .ok .wgt-action-enabled{' +
' fill: $secondary-color;' +
'}' +
'.dnd-ghost .ok .wgt-action-disabled,' +
'.dnd-ghost .ok .wgt-action-arrow{' +
' fill: transparent;' +
'}' +
'.align-select-pad .button {' +
' background-color: $tertiary-color;' +
'}' +
'.align-select-pad .button.on {' +
' background-color: $highlights;' +
'}' +
'.align-select-pad .button:hover{' +
' background-color: $dropback-text-color;' +
'}' +
'.panel-content .tab-bar{' +
' border-color: $button-primary-color;' +
' background-color: transparent;' +
'}' +
'.panel-content .tab{' +
' background-color: $tertiary-color;' +
' color: $dropback-text-color;' +
'}' +
'.panel-content .tab.on{' +
' background-color: $button-primary-color;' +
' color: $secondary-color;' +
'}' +
'a.layout_button {' +
' background-color: $tertiary-color;' +
'}' +
'a.layout_button.selected{' +
' background-color: $theme-highlight;' +
'}';
|
import React, { useState, useEffect } from 'react';
import Spinner from '../layout/Spinner';
import EditProfile from './EditProfile';
import UserNav from './UserNav';
import AppGrid from '../layout/AppGrid';
import Feed from '../layout/Feed';
import ProfileUserReviews from './ProfileUserReviews';
import ProfileUserList from './ProfileUserList';
import NoFavoritesResultsImage from '../../img/bobslicker.jpg';
import NoWatchListResultsImage from '../../img/homealone.jpg';
import NoReviewsResultsImage from '../../img/jim.jpg';
import Connections from './Connections';
import { updateUser } from '../../actions/users';
import { logout } from '../../actions/auth';
import { getReviews } from '../../actions/review';
import { getUsers } from '../../actions/users';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
const Profile = ({
match,
user,
reviews,
reviewsLoading,
getReviews,
getUsers,
users,
updateUser,
}) => {
const [view, setView] = useState('Reviews');
const { username } = match.params;
useEffect(() => {
window.scrollTo(0, 0);
}, [view]);
useEffect(() => {
getReviews();
getUsers();
}, [getReviews, getUsers, user.name]);
useEffect(() => {
setView('Reviews');
}, [username]);
const profileUserId = () =>
users.find((user) => user.username === username)._id;
const profileUserFollowers = () =>
users.filter((user) => user.friends.some((f) => f._id === profileUserId()));
const profileUserFollowing = () =>
users.filter((user) => user._id === profileUserId())[0].friends;
const toggleFriend = () => {
const profileId = profileUserId();
const { friends } = user;
let updatedUser;
if (friends.filter((friend) => friend._id === profileId).length) {
updatedUser = {
friends: [...friends.filter((friend) => friend._id !== profileId)],
};
} else {
updatedUser = {
friends: [...friends, profileId],
};
}
updateUser(user._id, updatedUser);
};
if (!reviews[0] || !users[0]) {
return <Spinner />;
}
return (
<AppGrid component="profile">
<Feed>
<UserNav
users={users}
user={user}
profileUserId={profileUserId()}
username={username}
toggleFriend={toggleFriend}
followers={profileUserFollowers()}
following={profileUserFollowing()}
view={view}
setView={setView}
/>
{reviewsLoading ? (
<Spinner />
) : (
view === 'Reviews' && (
<ProfileUserReviews
img={NoReviewsResultsImage}
profileUserId={profileUserId}
reviews={reviews}
text={
user._id === profileUserId()
? 'You have not added any reviews'
: `${username} has not added any reviews`
}
/>
)
)}
{view === 'Favorites' && (
<ProfileUserList
userList="favorites"
users={users}
profileUserId={profileUserId}
img={NoFavoritesResultsImage}
text={
user._id === profileUserId()
? 'You have not added any favorites'
: `${username} has not added any favorites`
}
/>
)}
{view === 'Watchlist' && (
<ProfileUserList
userList="watchList"
users={users}
profileUserId={profileUserId}
img={NoWatchListResultsImage}
text={
user._id === profileUserId()
? 'You have not added any movies to your watch list'
: `${username} has no movies on the watch list`
}
/>
)}
{view === 'Edit Profile' && <EditProfile user={user} />}
{(view === 'Followers' || view === 'Following') && (
<Connections
connections={
view === 'Followers'
? profileUserFollowers()
: view === 'Following' && profileUserFollowing()
}
setView={setView}
userId={user._id}
profileUserId={profileUserId()}
username={username}
view={view}
/>
)}
</Feed>
</AppGrid>
);
};
Profile.propTypes = {
user: PropTypes.object.isRequired,
users: PropTypes.array.isRequired,
reviews: PropTypes.array.isRequired,
getReviews: PropTypes.func.isRequired,
reviewsLoading: PropTypes.bool,
getUsers: PropTypes.func.isRequired,
updateUser: PropTypes.func.isRequired,
match: PropTypes.object.isRequired,
};
const mapStateToProps = (state) => ({
user: state.auth.user,
users: state.user.users,
reviews: state.review.reviews,
reviewsLoading: state.review.loading,
});
export default connect(mapStateToProps, {
getReviews,
getUsers,
updateUser,
logout,
})(Profile);
|
import React from "react";
import {connect} from "react-redux";
import {removeItem, addQuantity, subtractQuantity} from "../actions/cartActions";
import Recipe from "../Recipe";
class Cart extends React.Component {
handleRemove = (removedItems) => {
this.props.removeItem(removedItems);
};
handleAddQuantity = (addQuantityItem) => {
this.props.addQuantity(addQuantityItem);
};
handleSubtractQuantity = (subtractQuantityItem) => {
this.props.subtractQuantity(subtractQuantityItem);
};
render() {
// const addedItemsTemp = this.props.addedItems ? {...this.props.addedItems} : {};
// const addedItemsTemp = this.props.items.addedItems ? this.props.items.addedItems : {};
// console.log('addedItems:', this.props.addedItems);
// if (addedItemsTemp.length > 0 ) {
let addedItems = this.props.items.addedItems.map(item => {
// console.log('item:', item);
return (
<li className="list-group-item" key={item.id}>
<div className="item-img">
<img src={item.img} alt={item.img}/>
</div>
<div className="item-desc">
<span className="item-title">{item.title}</span>
<p>{item.description}</p>
<p><b>price: {item.price}</b></p>
<p><b>Quantity: {item.quantity} </b></p>
</div>
<button onClick={() => {this.handleAddQuantity(item)}}>add</button>
<button onClick={() => {this.handleSubtractQuantity(item)}}>sub</button>
<button onClick={() => {this.handleRemove(item)}}>Remove</button>
</li>
)
});
return (
<div className="container">
<div className="cart">
<h5>You have ordered:</h5>
<ul className="list-group">
{addedItems}
</ul>
</div>
<Recipe/>
</div>
)
}
}
const mapStateToProps = (state) => {
// console.log("Cart.js");
// console.log('cart state:', state);
return {
items: state.cart,
// addedItems: state.cart.addedItems
}
};
const mapDispatchToProps = (dispatch) => {
return {
removeItem: removedItems => {
dispatch(removeItem(removedItems))
},
addQuantity: addQuantityItem => {
dispatch(addQuantity(addQuantityItem))
},
subtractQuantity: subtractQuantityItem => {
dispatch(subtractQuantity(subtractQuantityItem))
}
}
};
export default connect(mapStateToProps, mapDispatchToProps)(Cart);
|
import React from 'react';
//let items = [];
const Todo = (props) => {
return (
<>
{props.todos.map(todo => {
return props.showCompleted === todo.completed ? (
<p key={"todo-" + todo.id}>{todo.title}</p>
) : (
undefined
);
})}
</>
);
// if(props.showCompleted)
// {
// props.todos.forEach(todo => {
// if(todo.completed === true)
// {
// items.push(todo.title)
// }
// });
// }
// else {
// props.todos.forEach(todo => {
// if(todo.completed === false)
// {
// items.push(todo.title)
// }
// });
// }
// items.forEach((item) => {
// return (
// <div>{ item }</div>
// )
// });
}
export default Todo;
|
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground')
.then(()=> console.log('Connected to Mongodb'))
.catch(err => console.error('couldnt connect',err ));
const courseSchema = new mongoose.Schema({
name: String,
author: String,
tags: [String],
date: {type:Date, default: Date.now },
isPubished: Boolean,
});
const Course = mongoose.model('Course', courseSchema);
async function createCourse(){
const course =new Course({
name: 'ANgular Course',
author: 'me',
tags: ['Angular', 'frontend'],
isPublished: true,
});
const result = await course.save();
console.log(result);
}
function getCourses(){
Course.find()
.limit(10)
.sort({name: 1})
.select({name:1, author:1})
.then(courses => console.log(courses))
.catch(err => console.log(error));
}
getCourses();
|
var CONST_VALUES = require('./const.js');
var tools = require('./tools.js');
function listeAnimauxNow(liste, start, end) {
var animaux = "";
for (i = start; i < end; i++) {
if (liste[i].période === "Toute l'année" || tools.isActualM(liste[i].période)) {
if (liste[i].heure === "Toute la journée" || tools.isActualH(liste[i].heure)) {
animaux += afficheAnimal(liste[i]);
}
}
}
return animaux;
}
function afficheAnimal(animalJSON) {
var animal = "";
animal += "Nom: " + animalJSON.nom + "\n";
animal += "Période: " + animalJSON.période + "\n";
animal += "Heure: " + animalJSON.heure + "\n";
animal += "Lieu: " + animalJSON.lieu + "\n";
animal += "Prix: " + animalJSON.prix + " clochettes \n";
if (animalJSON.taille) {
animal += "Taille: " + animalJSON.taille + "\n";
}
if (animalJSON.rareté) {
animal += "Rareté: " + animalJSON.rareté + "\n";
}
animal += "\n";
return animal;
}
module.exports = {listeAnimauxNow, afficheAnimal};
|
var AnalyticsFilter = require('./lib/AnalyticsFilter');
module.exports = {
name: 'ember-google-analytics',
treeForVendor: function(tree) {
return new AnalyticsFilter(tree, this.options);
},
config: function(env, baseConfig) {
if (!env) {
return;
}
this.options = baseConfig['ember-google-analytics'] || {};
},
included: function(app) {
this._super.included(app);
if (this.options.trackingId) {
app.import(this.options.localStorage ? 'vendor/google-analytics-local-storage.js' : 'vendor/google-analytics.js');
}
}
};
|
export default {
/*
** Nuxt target
** See https://nuxtjs.org/api/configuration-target
*/
target: 'server',
/*
** Headers of the page
** See https://nuxtjs.org/api/configuration-head
*/
head: {
htmlAttrs: {
lang: 'en',
},
title: 'Jay Codes',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{
hid: 'description',
name: 'description',
content:
'An aspiring Web Dev and Bot Dev. Also, spend time helping others.',
},
],
link: [
{
rel: 'icon',
type: 'image/x-icon',
href:
'https://media.discordapp.net/attachments/854927794571575316/864610625149730856/rect4s0ff24.png',
},
],
noscript: [{ innerHTML: 'This website requires JavaScript.' }],
},
/*
** Global CSS
*/
css: ['~/assets/scss/main.scss', 'boxicons/css/boxicons.min.css'],
/*
** Plugins to load before mounting the App
** https://nuxtjs.org/guide/plugins
*/
plugins: [],
/*
** Auto import components
** See https://nuxtjs.org/api/configuration-components
*/
components: true,
/*
** Nuxt.js dev-modules
*/
buildModules: [
// Doc: https://github.com/nuxt-community/eslint-module
'@nuxtjs/eslint-module',
],
/*
** Nuxt.js modules
*/
modules: [
// Doc: https://http.nuxtjs.org
'@nuxt/http',
],
http: {
baseURL:
process.env.NODE_ENV === 'production' ? 'https://www.jayson.codes' : '',
},
/*
** Server Middleware
*/
serverMiddleware: {
'/api': '~/api',
},
/*
** For deployment you might want to edit host and port
*/
server: {
...(process.env.NODE_ENV !== 'production' && {
port: 10000,
}),
host: process.env.NODE_ENV === 'production' ? '0.0.0.0' : 'localhost',
},
/*
** Build configuration
** See https://nuxtjs.org/api/configuration-build/
*/
build: {},
};
|
import axios from 'axios';
import React, { useState } from 'react';
const PokemonAPI = props => {
const [PokemonList, setPokemonList] = useState([{}])
const [clicked, setClicked] = useState()
const handleClick = () =>{
axios.get("https://pokeapi.co/api/v2/pokemon")
.then(response => {
// return the response.json()
return response.data
})
.then(response => {
// set PokemonList to response.results
setPokemonList(response.results)
}) }
return (
<div>
<button onClick={handleClick}>Fetch Pokemons</button>
<ul>
{PokemonList.filter(pokemon => pokemon.name).map(pokemon =>{
return (
<li>{pokemon.name}</li>
)
})}
</ul>
</div>
);
};
export default PokemonAPI;
|
// ==UserScript==
// @name BiliBili Live Room WebSocket Proxy
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author Shugen
// @include /^https?:\/\/live\.bilibili\.com\//
// @grant none
// ==/UserScript==
(function () {
'use strict';
if (window.DanmakuWebSocket) {
window.__DanmakuWebSocket = window.DanmakuWebSocket;
}
if (!window.BiliBiliOweMe300000 || !Array.isArray(window.BiliBiliOweMe300000)) {
window.BiliBiliOweMe300000 = []
};
Object.defineProperty(window, "DanmakuWebSocket", {
set: function (value) {
var handler = {
construct: function (target, args) {
debugger;
window.latestReceiver = args[0].onReceivedMessage;
args[0].__onReceivedMessage = args[0].onReceivedMessage;
args[0].onReceivedMessage = function () {
//console.log("received Messages:",arguments[0]);
if (!window.BiliBiliOweMe300000 || !Array.isArray(window.BiliBiliOweMe300000)) {
window.BiliBiliOweMe300000 = []
};
if (window.BiliBiliOweMe300000.length > 0) {
for (let i = 0; i < window.BiliBiliOweMe300000.length; i++) {
if (!window.BiliBiliOweMe300000[i](arguments[0])) { return; }
}
}
args[0].__onReceivedMessage.apply(this, arguments)
}
var obj = Object.create(value.prototype);
this.apply(target, obj, args);
return obj;
},
apply: function (target, that, args) {
value.apply(that, args);
}
};
return this.__DanmakuWebSocket = new Proxy(value, handler)
},
get: function () {
return this.__DanmakuWebSocket
}
}
);
})();
|
import React, { useContext } from 'react';
import { GameContext } from '../../../contexts/GameContext';
import GameCell from './GameCell';
const GameGrid = ({ socketHandler }) => {
const { gameState } = useContext(GameContext);
// Handles submitting for Player 1
function handleClick(x, y) {
if (gameState.winner === 0) {
let clickedOwner = gameState.gameData[x][y].owner;
if (clickedOwner === gameState.playerNumber || clickedOwner === 0) {
const playernInputTurn = gameState.playerNumber;
socketHandler.emit('PLAYER_INPUT', {
x,
y,
playerTurn: playernInputTurn,
});
}
}
}
return (
<div className="flex justify-center items-center">
<div>
{gameState.gameData !== null && (
<DrawBoard onClick={handleClick} data={gameState.gameData} />
)}
</div>
</div>
);
};
const DrawBoard = (dataBoard) => {
if (dataBoard.data.length !== 0) {
return (
<>
<div className="flex flex-col text-black mt-8 mb-8">
{dataBoard.data.map((datarow, index) => {
return (
<>
<div key={index} className="flex flex-row">
{datarow.map((dataitem) => {
return (
<div>
<div
className=""
key={dataitem.x * datarow.length + dataitem.y}
onClick={() =>
dataBoard.onClick(dataitem.x, dataitem.y)
}
>
<GameCell dataIndividual={dataitem} />
</div>
</div>
);
})}
</div>
</>
);
})}
</div>
</>
);
}
return <></>;
};
export default GameGrid;
|
import React, { Component } from "react";
class SearchDropdown extends Component {
constructor(props) {
super(props);
}
setSearchOption = (option) => {
console.log("setSearchOption", option);
this.props.setSearchState({
searchOption: option,
});
};
render() {
return (
<div id="search-dropdown">
<select onChange={(e) => this.setSearchOption(e.target.value)}>
<option selected disabled default>
Search Category
</option>
<option value="title">Title</option>
<option value="year">Release Date</option>
<option value="director">Director</option>
<option value="rating">Rating</option>
</select>
</div>
);
}
}
export default SearchDropdown;
|
$(document).ready(function() {
$.ajax({
url: "http://api.npr.org/query?id=1004&apiKey=MDE5MDgxMzU1MDE0MzEwMTc5MzQ0OThkMQ001&output=json",
dataType: 'json'
}).success(function(data) {
var posts = data["list"]["story"];
for (var i=0;i<posts.length;i++) {
console.log(posts[i])
$('#npr').append("<ul><h3>" + posts[i]["title"].$text + "</h3>");
$('#npr').append("<li><a href='" + posts[i]["link"][0].$text + "'>Original Story</a></li></ul>");
}
});
});
|
import { Object3D } from 'three'
import { useRef, useLayoutEffect } from 'react'
import { useFrame } from '@react-three/fiber'
import { useStore, mutation } from '../store'
const o = new Object3D()
export function Skid({ opacity = 0.5, length = 500, size = 0.4 }) {
const ref = useRef()
const { wheels, chassisBody } = useStore((state) => state.raycast)
function setItemAt(obj, i) {
o.position.set(obj.position.x, obj.position.y - 0, obj.position.z)
o.rotation.copy(chassisBody.current.rotation)
o.scale.setScalar(1)
o.updateMatrix()
ref.current.setMatrixAt(i, o.matrix)
ref.current.instanceMatrix.needsUpdate = true
}
let ctrl
let index = 0
useFrame(() => {
ctrl = useStore.getState().controls
if (ctrl.brake && mutation.speed > 10) {
setItemAt(wheels[2].current, index++)
setItemAt(wheels[3].current, index++)
if (index === length) index = 0
}
})
useLayoutEffect(() => void ref.current.geometry.rotateX(-Math.PI / 2), [])
return (
<instancedMesh ref={ref} args={[null, null, length]}>
<planeGeometry args={[size, size * 2]} />
<meshBasicMaterial color="black" transparent opacity={opacity} depthWrite={false} />
</instancedMesh>
)
}
|
'use strict';
const path = require('path'),
os = require('os'),
fs = require('fs-extra'),
glob = require('globby');
const OFFICIALLY_SUPPORTED_MANIFEST_PROPERTIES = [
'dependencies',
'devDependencies'
];
function transformManifest (propertyTransformers, code, manifestContent, includedProperties) {
return includedProperties
.reduce((manifestClean, property) => {
if(!manifestContent[property])
return manifestClean;
const manifestValue = propertyTransformers[property]
? propertyTransformers[property].reduce((cleanProperty, transformer) => transformer(code, cleanProperty), manifestContent[property])
: manifestContent[property];
if(typeof manifestValue === 'object' && !Object.keys(manifestValue).length)
return manifestClean;
manifestClean[property] = manifestValue;
return manifestClean;
}, {})
}
function reorderObjectProperties (code, content) {
return Object.keys(content)
.sort()
.reduce((obj, key) => {
obj[key] = content[key];
return obj;
}, {});
}
function rewriteLocations (code, content) {
var allPackageLocations = glob.sync([
'packages/*',
'packages-shared/*',
//'platform-linked/*', // no package should ever depend on platform-linked, becuase it is a FontoXML core dev tool
'platform/*'
], {
cwd: code.path
});
Object.keys(content).forEach(packageName => {
const activeSourceLocation = allPackageLocations.find(location => path.basename(location) === packageName);
if(activeSourceLocation)
content[packageName] = path.basename(path.resolve(activeSourceLocation, '..')) + '/' + packageName;
});
return content;
}
function formatManifestController (req, res) {
res.caption(`fotno format-manifests`);
res.debug('Looking for fonto-manifest.json files');
const propertyTransformers = {
dependencies: [],
devDependencies: []
};
const code = req.fdt.editorRepository;
if (!code || !code.path) {
throw new Error('Sorry, you must run this command in a Fonto editor instance');
}
const cwd = path.resolve(code.path, req.options.source),
manifests = glob.sync(['**/fonto-manifest.json'], {
cwd: cwd
});
res.debug(`Formatting ${manifests.length} manifest files in "${req.options.source}".`);
if(!req.options['no-reorder']) {
propertyTransformers.dependencies.push(reorderObjectProperties);
propertyTransformers.devDependencies.push(reorderObjectProperties);
} else {
res.debug('Not reordering property names');
}
if(!req.options['no-dep-locations']) {
propertyTransformers.dependencies.push(rewriteLocations);
propertyTransformers.devDependencies.push(rewriteLocations);
} else {
res.debug('Not rewriting dependency locations');
}
req.options['no-clean'] && res.debug('Not cleaning up unsupported manifest properties');
manifests.forEach(manifest => {
const manifestPath = path.join(cwd, manifest);
try {
var manifestContent = require(manifestPath);
} catch (e) {
res.property('Skip', path.basename(path.dirname(manifestPath)), 7, 'error');
res.error(e);
return;
}
let includedProperties =
req.options['no-clean']
? Object.keys(manifestContent)
: OFFICIALLY_SUPPORTED_MANIFEST_PROPERTIES;
if(!req.options['no-reorder'])
includedProperties = includedProperties.sort();
fs.writeFileSync(manifestPath, JSON.stringify(transformManifest(
propertyTransformers,
code,
manifestContent,
includedProperties
), null ,'\t') + os.EOL);
res.property('Rewrote', path.basename(path.dirname(manifestPath)), 7);
});
res.success('Done');
}
module.exports = fotno => {
fotno.registerCommand('format-manifests')
.addAlias('fm')
.setDescription(`Does some basic formatting of manifest files.`)
.setLongDescription([
`- Reorders your manifest properties and dependency names alphabetically.`,
`- Fixes missing or erronous package locations in manifest dependencies (eg. "packages/my-extension")`,
`- Indents everything with tabs instead of anything else`,
`- Leaves a nice newline at the end of your file`
].join('\n'))
.addOption(new fotno.Option('source')
.setDefault('packages', true)
.setDescription('Source directory to look for packages containing a manifest. Defaults to "packages". Setting it to anything different is probably not a good idea.')
)
.addOption('no-clean', 'C', 'Do not clean manifest properties that are not used. If omitted all unofficial manifest properties will be stripped away. Let go of all that weight. You are not your semver info. You are not your fucking khakis. You are the all singing, all dancing crap of the world.')
.addOption('no-reorder', 'R', 'Do not reorder manifest properties and dependencies alphabetically')
.addOption('no-dep-locations', 'L', 'Do not rewrite the (dev) dependencies to point to their locations. You shouldn\'t not have to not use this flag.')
.setController(formatManifestController);
};
|
import React, { useState } from 'react'
import './../content.css';
import ParticlesBg from 'particles-bg'
import {FileTextOutlined ,LinkedinOutlined, GithubOutlined, AppstoreOutlined, PhoneOutlined} from '@ant-design/icons'
import { Row, Col } from 'antd';
import { Button } from 'antd';
import ProfileImage from './image';
import SeeMore from './seemore';
export default function LandingPage(props){
const [seeMore , setSeeMore ] = useState(false);
function OnClickSeeMore(event){
setSeeMore(true)
}
function OnClickSeeMoreCallback(event) {
setSeeMore(false)
}
if (seeMore === true) {
return (
<SeeMore callback={OnClickSeeMoreCallback}/>
)
}else{
return(
<div className="mainview">
<Row>
<Col span={24}>
<img className="profile" alt="profile_pic" src={ProfileImage}/>
</Col>
</Row>
<Row>
<Col span={24}>
<div className="buttons">
<Button className="button" href="https://drive.google.com/file/d/140iZzoTj8Dsi3NueSPd9HAgV62dUpUnm/view?usp=sharing" >
<FileTextOutlined style={{ fontSize: '30px' }}/>
</Button>
<Button className="button" href="https://www.linkedin.com/in/niraj-fonseka-03bab3107/">
<LinkedinOutlined style={{ fontSize: '30px' }}/>
</Button>
<Button className="button" href="https://github.com/Niraj-Fonseka">
<GithubOutlined style={{ fontSize: '30px' }}/>
</Button>
</div>
</Col>
</Row>
<Row>
<Col span={24}>
<div className="morebuttons">
<Button className="button" onClick={OnClickSeeMore}>
<AppstoreOutlined style={{ fontSize: '30px' }}/>
</Button>
<Button className="button" disabled={true}>
<PhoneOutlined style={{ fontSize: '30px' }}/>
</Button>
</div>
</Col>
</Row>
<ParticlesBg type="cobweb" bg={true} color="#bfbfbf" />
</div>
)
}
}
|
import FuzzySearch from 'fuzzy-search';
import path from 'path';
import { directoryContent } from 'src/lib/getContent';
// resolving the path within the API tells the build to include files in the directory
const directoryPath = path.resolve(`./public/content/posts`);
const posts = directoryContent('posts', directoryPath);
export default (req, res) => {
const searcher = new FuzzySearch(
posts,
['frontmatter.title', 'frontmatter.description'],
{
sort: true,
}
);
const results = searcher.search(req.query.q);
const formattedResults = JSON.stringify(results);
res.status(200).json(formattedResults);
};
|
// 今日のスタンプ一覧
exports.createWindow = function(_userData, _diaryData){
Ti.API.debug('[func]winTime.createWindow:');
// 多重クリック防止
var clickEnable = true;
// groupViewの取得
var getGroupView = function(_rowStamp) {
Ti.API.debug('[func]getGroupView:');
var targetView = Ti.UI.createView(style.stampListStampView);
// targetView.stampData = _rowStamp;
var stampImage = Ti.UI.createImageView(style.timeStampImage);
stampImage.image = 'images/icon/' + _rowStamp.stamp + '.png';
targetView.add(stampImage);
return targetView;
};
// stampListTableViewの取得
var getTimeTableView = function() {
Ti.API.debug('[func]getTimeTableView:');
var targetView = Ti.UI.createTableView(style.stampListTableView);
var rowList = [];
if (_diaryData.stampList.length > 0) {
var stampSelectList = model.getStampSelectList();
for (var i=0; i<stampSelectList.length; i++) {
var row = Ti.UI.createTableViewRow(style.stampListTableRow);
var stampGroupView = Ti.UI.createView(style.stampListStampGroupView);
row.add(stampGroupView);
var groupLabel = Ti.UI.createLabel(style.stampListStampGroupLabel);
groupLabel.text = stampSelectList[i].title;
stampGroupView.add(groupLabel);
var groupListView = Ti.UI.createView(style.stampListStampListView);
stampGroupView.add(groupListView);
var targetFlag = false;
for (var j=0; j<_diaryData.stampList.length; j++) {
if (stampSelectList[i].stampList.indexOf(_diaryData.stampList[j].stamp) != -1) {
var groupView = getGroupView(_diaryData.stampList[j]);
groupListView.add(groupView);
targetFlag = true;
}
}
if (targetFlag) {
rowList.push(row);
targetFlag = false;
}
}
}
targetView.setData(rowList);
return targetView;
};
// ビューの更新
var updateTableView = function(updateData) {
Ti.API.debug('[func]updateTableView:');
// スタンプデータの取得 登録時は追加分も含む
var stampList = model.getLocalStampList({
userId: _userData.id,
year: _diaryData.year,
month: _diaryData.month,
day: _diaryData.day
});
if (updateData != null) {
var insertTarget = [];
for (var i=0; i<updateData.stampList.length; i++) {
insertTarget.push(updateData.stampList[i].event);
}
for (var i=0; i<stampList.length; i++) {
if (insertTarget.indexOf(stampList[i].event) != -1) {
stampList[i].insertFlag = true;
}
}
}
_diaryData.stampList = stampList;
// ビューの再作成
if(stampListTableView) {
stampListWin.remove(stampListTableView);
}
stampListTableView = getTimeTableView();
stampListTableView.visible = true;
stampListWin.add(stampListTableView);
// タイトルの表示
dayTitle.text = _diaryData.month + '月' + _diaryData.day + '日(' + _diaryData.weekday.text + ')';
};
// ---------------------------------------------------------------------
var stampListWin = Ti.UI.createWindow(style.stampListWin);
stampListWin.diaryData = _diaryData;
// タイトルの表示
var titleView = Ti.UI.createView(style.stampListTitleView);
stampListWin.titleControl = titleView;
var dayTitle = Ti.UI.createLabel(style.stampListTitleLabel);
titleView.add(dayTitle);
// 戻るボタンの表示
var backButton = Titanium.UI.createButton(style.commonCloseButton);
stampListWin.leftNavButton = backButton;
// ビューの作成
var stampListTableView = null;
updateTableView();
// ---------------------------------------------------------------------
// 戻るボタンをクリック
backButton.addEventListener('click', function(e){
Ti.API.debug('[event]backButton.click:');
// NavigationWindowを使用しているため、navWinを閉じる。
stampListWin.nav.close();
});
return stampListWin;
};
|
var tooltipDocument = document.getElementById("tooltip-document");
var tooltipWrapper = document.getElementById("tooltip-wrapper");
var tooltip = document.getElementById("tooltip");
var tooltipContent = document.getElementById("content");
var hoverArea = document.getElementById('hover-area');
var tooltipObject = {
width: tooltip.offsetWidth,
height: tooltip.offsetHeight,
left: tooltip.offsetLeft,
top: tooltip.offsetTop
};
function getFont(family) {
family = (family || "").replace(/[^A-Za-z]/g, '').toLowerCase();
var sans = 'Helvetica, Arial, "Microsoft YaHei New", "Microsoft Yahei", "微软雅黑", 宋体, SimSun, STXihei, "华文细黑", sans-serif';
var serif = 'Georgia, "Times New Roman", "FangSong", "仿宋", STFangSong, "华文仿宋", serif';
var fonts = {
helvetica : sans,
verdana : "Verdana, Geneva," + sans,
lucida : "Lucida Sans Unicode, Lucida Grande," + sans,
tahoma : "Tahoma, Geneva," + sans,
trebuchet : "Trebuchet MS," + sans,
impact : "Impact, Charcoal, Arial Black," + sans,
comicsans : "Comic Sans MS, Comic Sans, cursive," + sans,
georgia : serif,
palatino : "Palatino Linotype, Book Antiqua, Palatino," + serif,
times : "Times New Roman, Times," + serif,
courier : "Courier New, Courier, monospace, Times," + serif
}
var font = fonts[family] || fonts.helvetica;
return font;
}
function updateTooltipPosition() {
var hor = BannerFlow.settings.ttHorizontalAlign ? BannerFlow.settings.ttHorizontalAlign.toLowerCase() : "";
var ver = BannerFlow.settings.ttVerticalAlign? BannerFlow.settings.ttVerticalAlign.toLowerCase() : "";
if (hor == "left" && ver == "top") {
return {
"origin": "top left",
"position": {
"top": "0",
"left": "0",
"right": "initial",
"bottom": "initial"
},
"transform": "translate(0, 0)",
};
} else if (hor == "left" && ver == "middle") {
return {
"origin": "left center",
"position": {
"top": "50%",
"left": "0",
"right": "inherit",
"bottom": "inherit"
},
"transform": "translate(0, -50%)"
};
} else if (hor == "left" && ver == "bottom") {
return {
"origin": "bottom left",
"position": {
"top": "inherit",
"left": "0",
"right": "inherit",
"bottom": "0"
},
"transform": "translate(0, 0)"
};
} else if (hor == "center" && ver == "top") {
return {
"origin": "top center",
"position": {
"top": "0",
"left": "50%",
"right": "inherit",
"bottom": "inherit"
},
"transform": "translate(-50%, 0)"
};
} else if (hor == "center" && ver == "middle") {
return {
"origin": "left center",
"position": {
"top": "50%",
"left": "50%",
"right": "inherit",
"bottom": "inherit"
},
"transform": "translate(-50%, -50%)"
};
} else if (hor == "center" && ver == "bottom") {
return {
"origin": "bottom center",
"position": {
"top": "inherit",
"left": "50%",
"right": "inherit",
"bottom": "0"
},
"transform": "translate(-50%, 0)"
};
} else if (hor == "right" && ver == "top") {
return {
"origin": "top right",
"position": {
"top": "0",
"left": "inherit",
"right": "0",
"bottom": "inherit"
},
"transform": "translate(0, 0)"
};
} else if (hor == "right" && ver == "middle") {
return {
"origin": "center right",
"position": {
"top": "50%",
"left": "inherit",
"right": "0",
"bottom": "inherit"
},
"transform": "translate(0, -50%)"
};
} else if (hor == "right" && ver == "bottom") {
return {
"origin": "bottom right",
"position": {
"top": "inherit",
"left": "inherit",
"right": "0",
"bottom": "0"
},
"transform": "translate(0, 0)"
};
}
}
function detectArrowPosition(pos) {
var posA = pos % 12;
switch(posA) {
case 0:
return {
"position": {
"top": "inherit",
"left": "50%",
"right": "inherit",
"bottom": "-14px"
},
"transform": "translate(-50%, 0)",
"border": "top"
};
break;
case 1:
return {
"position": {
"top": "inherit",
"left": "inherit",
"right": "5px",
"bottom": "-14px"
},
"transform": "translate(0, 0)",
"border": "top"
};
break;
case 2:
return {
"position": {
"top": "inherit",
"left": "inherit",
"right": "-14px",
"bottom": "5px"
},
"transform": "translate(0, 0)",
"border": "left"
};
break;
case 3:
return {
"position": {
"top": "50%",
"left": "inherit",
"right": "-14px",
"bottom": "inherit"
},
"transform": "translate(0, -50%)",
"border": "left"
};
break;
case 4:
return {
"position": {
"top": "5px",
"left": "inherit",
"right": "-14px",
"bottom": "inherit"
},
"transform": "translate(0, 0)",
"border": "left"
};
break;
case 5:
return {
"position": {
"top": "-14px",
"left": "inherit",
"right": "5px",
"bottom": "inherit"
},
"transform": "translate(0, 0)",
"border": "bottom"
};
break;
case 6:
return {
"position": {
"top": "-14px",
"left": "50%",
"right": "inherit",
"bottom": "inherit"
},
"transform": "translate(-50%, 0)",
"border": "bottom"
};
break;
case 7:
return {
"position": {
"top": "-14px",
"left": "5px",
"right": "inherit",
"bottom": "inherit"
},
"transform": "translate(0, 0)",
"border": "bottom"
}
break;
case 8:
return {
"position": {
"top": "5px",
"left": "-14px",
"right": "inherit",
"bottom": "inherit"
},
"transform": "translate(0, 0)",
"border": "right"
}
break;
case 9:
return {
"position": {
"top": "50%",
"left": "-14px",
"right": "inherit",
"bottom": "inherit"
},
"transform": "translate(0, -50%)",
"border": "right"
}
break;
case 10:
return {
"position": {
"top": "inherit",
"left": "-14px",
"right": "inherit",
"bottom": "5px"
},
"transform": "translate(0, 0)",
"border": "right"
}
break;
case 11:
return {
"position": {
"top": "inherit",
"left": "5px",
"right": "inherit",
"bottom": "-14px"
},
"transform": "translate(0, 0)",
"border": "top"
}
break;
}
}
function addStylesheetRules (rules) {
var styleEl = document.createElement('style'),
styleSheet;
// Append style element to head
document.head.appendChild(styleEl);
// Grab style sheet
styleSheet = styleEl.sheet;
for (var i = 0, rl = rules.length; i < rl; i++) {
var j = 1, rule = rules[i], selector = rules[i][0], propStr = '';
// If the second argument of a rule is an array of arrays, correct our variables.
if (Object.prototype.toString.call(rule[1][0]) === '[object Array]') {
rule = rule[1];
j = 0;
}
for (var pl = rule.length; j < pl; j++) {
var prop = rule[j];
propStr += prop[0] + ':' + prop[1] + (prop[2] ? ' !important' : '') + ';\n';
}
// Insert CSS Rule
styleSheet.insertRule(selector + '{' + propStr + '}', styleSheet.cssRules.length);
}
}
function updateSettingsChanged() {
// Background color
addStylesheetRules([
['#tooltip',
['background', BannerFlow.settings.ttBackground]
],
['#tooltip:after',
['border-top-color', BannerFlow.settings.ttBackground]
]
]);
// Border Color
addStylesheetRules([
['#tooltip',
['border-color', BannerFlow.settings.ttBorderColor]
],
['#tooltip:before',
['border-top-color', BannerFlow.settings.ttBorderColor]
]
]);
// Text Color
tooltipContent.style.color = BannerFlow.settings.ttTextColor;
var ttPos = updateTooltipPosition() ? updateTooltipPosition() : "";
// Size
tooltip.style.transform = "scale("+ ((BannerFlow.settings.ttSize > 0) ? ((BannerFlow.settings.ttSize)/10 + 1) : 1) +")";
tooltip.style.transformOrigin = ttPos.origin;
tooltip.style.webkitTransform = "scale("+ ((BannerFlow.settings.ttSize > 0) ? ((BannerFlow.settings.ttSize)/10 + 1) : 1) +")";
tooltip.style.webkitTransformOrigin = ttPos.origin;
// Position
tooltipWrapper.style.top = ttPos.position.top;
tooltipWrapper.style.left = ttPos.position.left;
tooltipWrapper.style.right = ttPos.position.right;
tooltipWrapper.style.bottom = ttPos.position.bottom;
tooltipWrapper.style.transform = ttPos.transform;
tooltipWrapper.style.webkitTransform = ttPos.transform;
// Arrow Position
addStylesheetRules([
['#tooltip:before, #tooltip:after',
['top', detectArrowPosition(BannerFlow.settings.ttArrowPosition).position.top],
['left', detectArrowPosition(BannerFlow.settings.ttArrowPosition).position.left],
['right', detectArrowPosition(BannerFlow.settings.ttArrowPosition).position.right],
['bottom', detectArrowPosition(BannerFlow.settings.ttArrowPosition).position.bottom],
['transform', detectArrowPosition(BannerFlow.settings.ttArrowPosition).transform],
['-webkit-transform', detectArrowPosition(BannerFlow.settings.ttArrowPosition).transform],
['border-color', 'transparent']
],
['#tooltip:before',
['border-' + detectArrowPosition(BannerFlow.settings.ttArrowPosition).border + '-color', BannerFlow.settings.ttBorderColor]
],
['#tooltip:after',
['border-' + detectArrowPosition(BannerFlow.settings.ttArrowPosition).border + '-color', BannerFlow.settings.ttBackground],
['left', ((detectArrowPosition(BannerFlow.settings.ttArrowPosition).border == "top" || detectArrowPosition(BannerFlow.settings.ttArrowPosition).border == "bottom") && detectArrowPosition(BannerFlow.settings.ttArrowPosition).position.left != 0 && detectArrowPosition(BannerFlow.settings.ttArrowPosition).position.left.indexOf("%") == -1) ? (parseInt(detectArrowPosition(BannerFlow.settings.ttArrowPosition).position.left) - 1 + "px") : detectArrowPosition(BannerFlow.settings.ttArrowPosition).position.left],
['right', ((detectArrowPosition(BannerFlow.settings.ttArrowPosition).border == "top" || detectArrowPosition(BannerFlow.settings.ttArrowPosition).border == "bottom") && detectArrowPosition(BannerFlow.settings.ttArrowPosition).position.right != 0 && detectArrowPosition(BannerFlow.settings.ttArrowPosition).position.right.indexOf("%") == -1) ? (parseInt(detectArrowPosition(BannerFlow.settings.ttArrowPosition).position.right) - 1 + "px") : detectArrowPosition(BannerFlow.settings.ttArrowPosition).position.right],
['top', ((detectArrowPosition(BannerFlow.settings.ttArrowPosition).border == "right" || detectArrowPosition(BannerFlow.settings.ttArrowPosition).border == "left") && detectArrowPosition(BannerFlow.settings.ttArrowPosition).position.top != 0 && detectArrowPosition(BannerFlow.settings.ttArrowPosition).position.top.indexOf("%") == -1) ? (parseInt(detectArrowPosition(BannerFlow.settings.ttArrowPosition).position.top) - 1 + "px") : detectArrowPosition(BannerFlow.settings.ttArrowPosition).position.top],
['bottom', ((detectArrowPosition(BannerFlow.settings.ttArrowPosition).border == "right" || detectArrowPosition(BannerFlow.settings.ttArrowPosition).border == "left") && detectArrowPosition(BannerFlow.settings.ttArrowPosition).position.bottom != 0 && detectArrowPosition(BannerFlow.settings.ttArrowPosition).position.bottom.indexOf("%") == -1) ? (parseInt(detectArrowPosition(BannerFlow.settings.ttArrowPosition).position.bottom) - 1 + "px") : detectArrowPosition(BannerFlow.settings.ttArrowPosition).position.bottom]
]
]);
styleChanged();
updateHoverArea();
// Is Development
tooltipWrapper.style.opacity = BannerFlow.editorMode ? 1 : 0;
// Animation cases
var animationOpt = parseInt(BannerFlow.settings.ttAnimation, 10);
if (!BannerFlow.editorMode) {
switch(animationOpt) {
case 0:
tooltipWrapper.style.opacity = 0;
break;
case 1:
tooltipWrapper.style.opacity = 0;
tooltipWrapper.style.marginTop = "-50px";
break;
case 2:
tooltipWrapper.style.opacity = 0;
tooltipWrapper.style.marginLeft = "-50px";
break;
case 3:
tooltipWrapper.style.opacity = 0;
tooltipWrapper.style.marginLeft = "50px";
break;
case 4:
tooltipWrapper.style.opacity = 0;
tooltipWrapper.style.marginTop = "50px";
break;
default:
tooltipWrapper.style.opacity = 0;
break;
}
}
}
function updateTextChanged() {
var text = (BannerFlow.text || BannerFlow.text == "") ? BannerFlow.text : "Enter text...";
tooltipContent.innerHTML = text;
}
function updateHoverArea() {
if (!BannerFlow.editorMode) {
hoverArea.style.backgroundColor = "transparent";
hoverArea.style.textIndent = "-99999px";
}
var haObject = {
x : BannerFlow.settings.areaX,
y : BannerFlow.settings.areaY,
width : BannerFlow.settings.haWidth,
height : BannerFlow.settings.haHeight
};
hoverArea.style.left = haObject.x + "px";
hoverArea.style.top = haObject.y + "px";
hoverArea.style.width = haObject.width + "px";
hoverArea.style.height = haObject.height + "px";
}
function onMouseOver() {
var animationOpt = parseInt(BannerFlow.settings.ttAnimation, 10);
switch(animationOpt) {
case 0:
tooltipWrapper.style.opacity = 1;
break;
case 1:
tooltipWrapper.style.opacity = 1;
tooltipWrapper.style.marginTop = 0;
break;
case 2:
tooltipWrapper.style.opacity = 1;
tooltipWrapper.style.marginLeft = 0;
break;
case 3:
tooltipWrapper.style.opacity = 1;
tooltipWrapper.style.marginLeft = 0;
break;
case 4:
tooltipWrapper.style.opacity = 1;
tooltipWrapper.style.marginTop = 0;
break;
default:
tooltipWrapper.style.opacity = 1;
break;
}
}
function onMouseOut() {
var animationOpt = parseInt(BannerFlow.settings.ttAnimation, 10);
switch(animationOpt) {
case 0:
tooltipWrapper.style.opacity = 0;
break;
case 1:
tooltipWrapper.style.opacity = 0;
tooltipWrapper.style.marginTop = "-50px";
break;
case 2:
tooltipWrapper.style.opacity = 0;
tooltipWrapper.style.marginLeft = "-50px";
break;
case 3:
tooltipWrapper.style.opacity = 0;
tooltipWrapper.style.marginLeft = "50px";
break;
case 4:
tooltipWrapper.style.opacity = 0;
tooltipWrapper.style.marginTop = "50px";
break;
default:
tooltipWrapper.style.opacity = 0;
break;
}
}
function styleChanged() {
tooltipContent.style.fontFamily = getFont(BannerFlow.settings.fontFamily ? BannerFlow.settings.fontFamily.toLowerCase() : "");
tooltipContent.style.fontSize = BannerFlow.getStyle('font-size', '');
}
BannerFlow.addEventListener(BannerFlow.SETTINGS_CHANGED, updateSettingsChanged);
BannerFlow.addEventListener(BannerFlow.TEXT_CHANGED, updateTextChanged);
BannerFlow.addEventListener(BannerFlow.STYLE_CHANGED, styleChanged)
BannerFlow.addEventListener(BannerFlow.INIT, function() {
hoverArea.addEventListener("mouseover", onMouseOver);
hoverArea.addEventListener("touchstart", onMouseOver);
hoverArea.addEventListener("MSPointerDown", onMouseOver);
hoverArea.addEventListener("MSPointerUp", onMouseOut);
hoverArea.addEventListener("touchend", onMouseOut);
hoverArea.addEventListener("mouseout", onMouseOut);
});
|
const inputs = document.querySelector('form')
let aviso = document.getElementById("terminos").checked;
function sendEmail() {
Email.send({
Host : "smtp.mailtrap.io",
Username : "71e4b9403ab5c0",
Password : "f932ba1e05391f",
To : "divinitebeautyspa@gmail.com",
From : inputs.elements["email"].value,
Subject : "Test email",
Body: inputs.elements["name"].value + " con el correo: "+ inputs.elements["email"].value+ " te envió el siguiente mensaje: "+"<br>" +inputs.elements["message"].value
}).then(message =>{
let p;
if(message!="OK"){
p = document.getElementById('alert');
p.removeAttribute("hidden")
setTimeout(() => {
window.location.reload();
}, 4000);
}else{
console.log(message)
p = document.getElementById('goodAlert')
p.removeAttribute("hidden")
setTimeout(() => {
window.location.reload();
}, 3000);
}
})
}
/*const btn = document.querySelector('button')
const inputs = document.querySelector('form')
btn.addEventListener('click', () => {
Email.send({
Host: "smtp.mailtrap.io",
Username: "71e4b9403ab5c0",
Password: "f932ba1e05391f",
To: "divinitebeautyspa@gmail.com",
From: inputs.elements["email"].value,
Subject: "Contact Us Beauty Spa",
Body: inputs.elements["message"].value + "<br>" + inputs.elements["name"]
}).then(msg => alert("The email was successfully sent"))
})*/
//Código para enviar correos
/*(function () {
emailjs.init("user_nsfB75HsHb3gAeJ6RzBYc");
})();
function sendMail() {
let fullName = document.getElementById("name").value;
let userEmail = document.getElementById("email").value;
let userMessage = document.getElementById("message").value;
var contactParams = {
from_name: fullName,
from_email: userEmail,
message: userMessage,
};
emailjs
.send("service_l8t7c6q", "template_74px0yb", contactParams)
.then(function (res) {});
return true;
}
*/
function envi() {
window.location.reload();
}
|
/*
* abbozza.js
* Copyright 2015 Michael Brinkmeier (mbrinkmeier@uni-osnabrueck.de).
*
* 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
*
* 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.
*/
var Abbozza = {
_mainColor : "#d4daff",
_darkColor : "#b0b0ff",
_hoverColor : "#ffdca8",
_minWorkspaceWidth: 400,
_minContextWidth: 300,
_minContextHeight: 300,
_minMiscHeight: 0,
_modified: false,
_globalSymbols: null,
_blocklyDiv: null,
_workspacePanel: null,
_context : null
}
Abbozza.init = function(toolbox) {
this.makeButtons();
this.setContext(new Terminal());
// Configuration.load();
var toolbox = ToolboxMgr.rebuild("js/abbozza/core/toolbox.xml",true);
Sliders.init();
window.Blockly = Blockly;
console.log("hier");
// this.newSketch();
}
Abbozza.newSketch = function() {
this.clear();
this._globalSymbols = new SymbolDB();
Blockly.mainWorkspace.symbols = this._globalSymbols;
Blockly.Xml.domToWorkspace(Blockly.mainWorkspace, document.getElementById('startBlocks'));
this._modified = false;
}
Abbozza.refit = function() {
Blockly.svgResize(Blockly.mainWorkspace);
if (this._context) this._context.refit();
}
Abbozza.setContext = function(context) {
this._context = context;
this._context.initView(document.getElementById("context_view"));
}
Abbozza.setToolbox = function() {
}
Abbozza.load = function() {
}
Abbozza.save = function() {
}
Abbozza.new = function() {
}
Abbozza.settings = function() {
}
Abbozza.info = function() {
}
Abbozza.step = function() {
}
Abbozza.stop = function() {
if (this._context) this._context.reset();
}
Abbozza.play = function() {
}
Abbozza.clear = function() {
Blockly.mainWorkspace.clear();
}
|
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';
import TodoListComponent from './components/TodoListComponent';
import HeaderComponent from './components/HeaderComponent';
import FooterComponent from './components/FooterComponent';
function App() {
return (
<div>
<Router>
<HeaderComponent/>
<div className="container">
<Switch>
<Route path = "/" exact component = {TodoListComponent}></Route>
<Route path = "/todo" component = {TodoListComponent}></Route>
</Switch>
</div>
<FooterComponent/>
</Router>
</div>
);
}
export default App;
|
$(document).ready(function() {
$('#date').datetimepicker({
format: 'dd/mm/yyyy',
todayBtn: true,
autoclose: true,
todayHighlight: true,
viewSelect: 'day'
});
});
|
import VueRouter from 'vue-router' // eslint-disable-line import/no-extraneous-dependencies
import Vuex from 'vuex' // eslint-disable-line import/no-extraneous-dependencies
import VueI18n from 'vue-i18n'
import ArticlePage from './ArticlePage.vue'
import router from '../../test/router/router'
import commentsApi from '../../services/api/comments'
import chaptersApi from '../../services/api/chapters'
import photosApi from '../../services/api/photos'
import translationsService from '../../services/services/translations'
import ChapterCard from '../ChapterCard/ChapterCard.vue'
import logger from '../../services/services/logger-service'
describe('Component | ArticlePage.vue', () => {
let localVue
let wrapper
let chapters
let photos
let store
const dropboxId = '8'
const title = 'Pierre au pays des'
const commentsFromApi = [{ text: 'comment1' }]
beforeEach(() => {
router.push = jest.fn()
translationsService.getChapterTitle = jest.fn()
translationsService.getChapterTitle.mockReturnValue('My title')
translationsService.getChapterText = jest.fn()
translationsService.getChapterText.mockReturnValue(['one text'])
chapters = [
{
title: '60 : Pierre avec les webf',
imgLink: '../assets/toto.jpg',
text: ['some text'],
},
{
title: '61 : Pierre au Koezio',
imgLink: '/assets/tata.jpg',
text: ['some text'],
},
{
title: '62 : Pierre au Koezio',
imgLink: '/assets/titi.jpg',
text: ['some text'],
},
]
photos = [{ imgLink: 'url/photo1' }, { imgLink: 'url/photo2' }]
photosApi.fetch = jest.fn()
photosApi.fetch.mockResolvedValue(photos)
commentsApi.fetch = jest.fn()
commentsApi.fetch.mockResolvedValue(commentsFromApi)
chaptersApi.fetch = jest.fn()
chaptersApi.fetch.mockResolvedValue({ title, chapters })
localVue = createLocalVue()
localVue.use(Vuex)
localVue.use(VueI18n)
localVue.use(VueRouter)
store = new Vuex.Store({ actions: {}, state: { locale: 'en' } })
})
describe('template', () => {
describe('when chapters are fetched', () => {
beforeEach(() => {
wrapper = shallowMount(ArticlePage, {
localVue,
router,
store,
data: () => ({ dropboxId }),
})
})
it('should match snapshot', () => {
expect(wrapper).toMatchSnapshot()
})
it('should add title when defined', () => {
wrapper = shallowMount(ArticlePage, {
localVue,
router,
store,
data: () => ({ title: 'toto' }),
})
expect(wrapper.find('.article-page__title').text()).toBe('toto')
})
})
describe('when chapters are not fetched', () => {
beforeEach(() => {
chaptersApi.fetch = jest.fn()
chaptersApi.fetch.mockRejectedValue(new Error('error-message'))
logger.error = jest.fn()
wrapper = shallowMount(ArticlePage, {
localVue,
router,
store,
data: () => ({ dropboxId }),
})
})
it('should match snapshot when chapter not fetched', () => {
expect(wrapper).toMatchSnapshot()
})
it('should contain default chapter when chapter not fetched', () => {
expect(wrapper.findComponent(ChapterCard).props().chapter).toEqual({
position: 1,
frTitle: 'Article en cours de chargement',
enTitle: 'Loading article',
imgLink: false,
frText: ['Veuillez patienter quelques secondes'],
enText: ['Please wait just a second'],
})
})
it('should log error when chapter not fetched', () => {
expect(logger.error).toHaveBeenCalledOnceWith('error-message')
})
})
})
describe('mounted', () => {
beforeEach(() => {
chaptersApi.fetch = jest.fn()
chaptersApi.fetch.mockResolvedValue({ title, chapters })
wrapper = shallowMount(ArticlePage, {
localVue,
router,
store,
data: () => ({ dropboxId }),
})
})
it('should call chapters api to fetch chapters', () => {
expect(chaptersApi.fetch).toHaveBeenCalledWith(dropboxId)
})
it('should call photos api to fetch photos', () => {
expect(photosApi.fetch).toHaveBeenCalledWith(dropboxId)
})
it('should save chapters from api in data chapters', () => {
expect(wrapper.vm.chapters).toEqual(chapters)
})
it('should save photos from api in data photos', () => {
expect(wrapper.vm.photos).toEqual(photos)
})
})
describe('methods', () => {
describe('#goToHomePage', () => {
it('should route to next article', () => {
wrapper = shallowMount(ArticlePage, {
localVue, router, data: () => ({ dropboxId }),
})
wrapper.vm.goToHomePage()
expect(router.push).toHaveBeenCalledWith('/')
})
})
describe('#viewNextArticle', () => {
it('should route to next article', () => {
wrapper = shallowMount(ArticlePage, {
localVue, router, data: () => ({ dropboxId }),
})
wrapper.vm.viewNextArticle()
expect(router.push).toHaveBeenCalledWith('/articles/9')
})
})
describe('#viewPreviousArticle', () => {
it('should route to previous article', () => {
wrapper = shallowMount(ArticlePage, { localVue, router, data: () => ({ dropboxId }) })
wrapper.vm.viewPreviousArticle()
expect(router.push).toHaveBeenCalledWith('/articles/7')
})
it('should not route to article id less than 1', () => {
wrapper = shallowMount(ArticlePage, { localVue, router, data: () => ({ dropboxId: 1 }) })
wrapper.vm.viewPreviousArticle()
expect(router.push).not.toHaveBeenCalled()
})
})
})
describe('locales', () => {
const languages = Object.keys(ArticlePage.i18n.messages)
it('contains 2 languages', () => {
expect(languages).toHaveLength(2)
expect(languages).toEqual(['fr', 'en'])
})
describe('each language', () => {
describe('fr', () => {
const locales = Object.keys(ArticlePage.i18n.messages.fr)
it('contains 5 locales', () => {
expect(locales).toHaveLength(5)
expect(locales).toMatchInlineSnapshot(
[
'hereTheGallery',
'goToPreviousArticle',
'goToNextArticle',
'goToHomePage',
'title',
],
`
Array [
"hereTheGallery",
"goToPreviousArticle",
"goToNextArticle",
"goToHomePage",
"title",
]
`,
)
})
})
describe('en', () => {
const locales = Object.keys(ArticlePage.i18n.messages.en)
it('contains 5 locales', () => {
expect(locales).toHaveLength(5)
expect(locales).toMatchInlineSnapshot(
[
'hereTheGallery',
'goToPreviousArticle',
'goToNextArticle',
'goToHomePage',
'title',
],
`
Array [
"hereTheGallery",
"goToPreviousArticle",
"goToNextArticle",
"goToHomePage",
"title",
]
`,
)
})
})
})
})
})
|
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import './App.css';
import Header from './components/Header/Header';
import SimpleSlider from './components/Carousel/Carousel';
import Search from './components/Search/Search';
import MovieList from './components/MovieList/MovieList';
import Login from './pages/Login/Login';
import Home from './pages/Home/Home';
import Signup from './pages/Signup/Signup';
function App() {
return (
<BrowserRouter>
<Switch>
<Route exact path='/' component={Home} />
<Route exact path='/login' component={Login} />
<Route exact path='/signup' component={Signup} />
</Switch>
</BrowserRouter>
);
}
export default App;
|
import React, { Component } from 'react'
import {IndexLink} from 'react-router'
class Login extends Component {
render() {
return(
<div className="loginPage">
<img className="mainLogo" src="http://ubicomp.oulu.fi/wp-content/uploads/2016/03/oulunyliopisto_logo_eng_rgb10.png" />
<br />
<img className="smallLogo" src="https://laturi.oulu.fi/style/logo-multi.png" />
<IndexLink className="toHomePage" to='/home'>Kirjaudu yliopiston tunnuksilla</IndexLink>
<img className="hakaLogin" src="../assets/hakalogin.png" />
</div>
)
}
}
export default Login;
|
'use strict';
module.exports = (sequelize, DataTypes) => {
const Users = sequelize.define('Users', {
ursername: DataTypes.STRING,
password: DataTypes.STRING,
email: DataTypes.STRING,
phone: DataTypes.STRING,
fullname: DataTypes.STRING,
avatarPath: DataTypes.TEXT,
isAdmin: DataTypes.BOOLEAN
}, {});
Users.associate = function(models) {
// associations can be defined here
Users.hasMany(models.Comment,{foreignKey:'UserId'});
Users.hasMany(models.Review,{foreignKey:'UserId'});
};
return Users;
};
|
var fromIndex = 0;
var currentVideoId;
function init() {
loadThumbnails();
bindCloseEvents();
bindKeyboardControls();
bindHoverEvent();
bindBlurEvent();
loadYoutubeApi();
restrictFocusToModal();
if (lastListItemIsInViewport()) {
loadMore();
}
window.onscroll = function() {
if (lastListItemIsInViewport()) {
loadMore();
}
};
}
function getFile(file) {
var request = new XMLHttpRequest();
request.open('GET', file, false);
request.send(null);
if (request.status == 200) {
return request.responseText;
}
};
function isElementInViewport(el) {
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight + el.offsetHeight || document.documentElement.clientHeight + el.offsetHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
function loadThumbnails() {
var listItems = document.querySelectorAll('[data-id]');
for (var i=0, item; item = listItems[i]; i++) {
if (! item.getAttribute('style')) {
item.style.backgroundImage = 'url(https://i.ytimg.com/vi/' + item.getAttribute('data-id') + '/mqdefault.jpg)';
}
}
}
function lastListItemIsInViewport() {
var lastListItem = document.querySelector('.list__vid:last-of-type')
if (isElementInViewport(lastListItem)) {
return true;
}
return false;
}
function loadMore() {
var limitReached = false;
var limit = 10;
for (var i=fromIndex, item; item = videoData[i]; i++) {
if (i < fromIndex + limit && i < Object.keys(videoData).length) {
appendListItem(item.id, item.title);
}
if (fromIndex === 30 && i === 39) {
var listItems = document.querySelectorAll('[data-id]');
var thresholdThumbnail = listItems[listItems.length - 4];
for (var i = 0; i < listItems.length; i++) {
listItems[i].removeEventListener('blur', loadMore, false);
}
window.onscroll = function() { return true; };
limitReached = true;
break;
}
}
if (lastListItemIsInViewport() && !limitReached) {
fromIndex = fromIndex + limit;
loadMore.call();
return true;
}
if (!limitReached) {
bindBlurEvent();
}
fromIndex = fromIndex + limit;
loadThumbnails();
bindHoverEvent();
}
function appendListItem(id, title) {
var parent = document.getElementById('video-list');
var listItem = document.createElement('li');
var link = document.createElement('a');
var heading = document.createElement('h3');
var headingText = document.createTextNode(title);
heading.appendChild(headingText);
listItem.setAttribute('class', 'list__vid');
parent.appendChild(listItem);
link.setAttribute('href', 'https://www.youtube.com/watch?v=' + id);
link.setAttribute('data-id', id);
link.setAttribute('onclick', 'return openModal("' + id + '")');
link.appendChild(heading);
listItem.appendChild(link);
}
function loadYoutubeApi() {
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
function openModal(id) {
var playerElement = document.getElementById('player-container');
var focusedElement = document.getElementById('focused-element');
currentVideoId = id;
playerElement.className = 'player-wrap active';
document.body.className = 'player-open';
focusedElement.focus();
loadPlayer(id);
restrictFocusToModal();
return false;
}
function restrictFocusToModal() {
document.addEventListener('focus', checkModalActive, true);
}
function checkModalActive(e) {
var playerElement = document.getElementById('player-container');
var focusedElement = document.getElementById('focused-element');
if (playerElement.className === 'player-wrap active') {
e.stopPropagation();
focusedElement.focus();
}
}
function loadPlayer(id) {
player = new YT.Player('player', {
height: '100%',
width: '100%',
videoId: id,
events: {
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
function closePlayer(e) {
var playerElement = document.getElementById('player-container');
var videoThumbnail = document.querySelectorAll('[data-id="' + currentVideoId + '"]');
document.removeEventListener('focus', checkModalActive, true);
videoThumbnail[0].focus();
playerElement.className = 'player-wrap';
document.body.className = '';
player.destroy();
e.preventDefault();
}
function bindCloseEvents() {
var closeElements = document.querySelectorAll('[data-close]');
for (var i = 0; i < closeElements.length; i++) {
closeElements[i].addEventListener('click', closePlayer, false);
}
}
function bindHoverEvent() {
// remove focus on hover - mouse wins
var listItems = document.querySelectorAll('[data-id]');
for (var i = 0; i < listItems.length; i++) {
listItems[i].removeEventListener('mouseover', deselectFocus);
listItems[i].addEventListener('mouseover', deselectFocus, false);
}
}
function deselectFocus() {
// with a little catch for an ie9 bug where blurring document switches window focus
if(document.activeElement !== document.body) {
document.activeElement.blur();
}
}
function bindBlurEvent() {
var listItems = document.querySelectorAll('[data-id]');
var thresholdThumbnail = listItems[listItems.length - 4];
// detect when (nearly) the last thumbnail loses focus
// avoids the need to detect tab key press specifically and allows this to work with screen reader focus too
for (var i = 0; i < listItems.length; i++) {
listItems[i].removeEventListener('blur', loadMore, false);
}
thresholdThumbnail.addEventListener('blur', loadMore, false);
}
function bindKeyboardControls() {
document.body.addEventListener('keyup', function(e) {
// escape key closes any open video modals
if (e.keyCode == 27) {
closePlayer(e);
}
});
}
init();
|
var username = process.argv[2];
var password = process.argv[3];
console.log("用户名" + username + "密码" + password);
var info = username + ":" + password;
var infoBuffer = Buffer.from(info,"utf8");
var infoBase64 = infoBuffer.toString("base64");
console.log(infoBase64);
|
/* @flow */
/* eslint no-plusplus: 0 */
/* **********************************************************
* File: utils/Developer/TerminalUtils.js
*
* Brief: Utilities for the mica Terminal
*
* Authors: Craig Cheney
*
* 2017.10.27 CC - Document created
*
********************************************************* */
import { clipboard } from 'electron';
import update from 'immutability-helper';
import terminalCommands from './TerminalCommand';
import type {
terminalParsedObjT, terminalStateT
} from '../../types/developerTypes';
export const delimiters = /\s|\.|\(|\)|"|'|;|:|!/;
export const cmdLineStart = '> ';
export const valueLineStart = ' ';
export const lineEnd = '\n';
/* All of the values displayed in the terminal */
export function getTerminalDisplayValue(state: terminalStateT): string {
let stringVal = '';
/* Add the past history */
const { history, currentLine } = state;
for (let i = 0; i < history.length; i++) {
const entry = history[i];
if (entry.isCmd) {
stringVal += cmdLineStart;
} else {
stringVal += valueLineStart;
}
stringVal = `${stringVal}${entry.value}${lineEnd}`;
}
/* Add the current line */
stringVal += `${cmdLineStart}${currentLine}`;
return stringVal;
}
/* Calculate the current cursor position from the state */
export function calculateCursorPosition(state: terminalStateT): number {
const { cursorPosition, history } = state;
let pastLen = 0;
/* Add all of the previous commands */
for (let i = 0; i < history.length; i++) {
const entry = history[i];
if (entry.isCmd) {
pastLen += cmdLineStart.length;
} else {
pastLen += valueLineStart.length;
}
pastLen = pastLen + entry.value.length + lineEnd.length;
}
/* Add the start of line offset */
pastLen += cmdLineStart.length;
return pastLen + cursorPosition;
}
type recallT = {
cmd: string,
index: ?number
};
/* Recall a previous command */
export function recallPrevCommand(state: terminalStateT): ?recallT {
const { commandLineNumber, history } = state;
/* Start at end if commandLineNumber is undefined */
let startIndex = history.length;
if (commandLineNumber != null) {
startIndex = commandLineNumber;
}
for (let i = startIndex - 1; i >= 0; i--) {
const entry = history[i];
if (entry.isCmd) {
return { cmd: entry.value, index: i };
}
}
/* No Command was found */
return undefined;
}
/* Recall the next command */
export function recallNextCommand(state: terminalStateT): ?recallT {
const { commandLineNumber, history } = state;
/* Nothing to return if undefined */
if (commandLineNumber == null) {
return undefined;
}
for (let i = commandLineNumber + 1; i < history.length; i++) {
const entry = history[i];
if (entry.isCmd) {
return { cmd: entry.value, index: i };
}
}
/* No Command was found */
return { cmd: '', index: undefined };
}
/*
* This method parses a single command + args. It handles
* the tokenization and processing of flags, anonymous args,
* and named args.
*
* @param {string} input - the user input to parse
* @returns {Object} the parsed command/arg
*/
export function parseInput(input: string): terminalParsedObjT {
const tokens = input.split(/ +/);
const name = tokens.shift();
const flags = {};
const args = {};
let anonArgPos = 0;
while (tokens.length > 0) {
const token = tokens.shift();
if (token[0] === '-') {
if (token[1] === '-') {
const next = tokens.shift();
args[token.slice(2)] = next;
} else {
token.slice(1).split('').forEach(flag => {
flags[flag] = true;
});
}
} else {
args[anonArgPos++] = token;
}
}
return { name, flags, input, args };
}
/* Execute the command */
export async function executeCommand(currentLine: string): Promise<string[]> {
/* Parse command */
const parseObj: terminalParsedObjT = parseInput(currentLine);
const { name: commandName } = parseObj;
const commandExec = terminalCommands[commandName];
if (!commandExec) {
return [`${commandName}: command not found`];
}
const cmdReturn = await commandExec(parseObj);
return cmdReturn;
}
/* Jump to the end of the word */
export function nextWordPosition(cursorPosition: number, currentLine: string): number {
/* split the string */
const wordArray = currentLine.substr(cursorPosition).split(delimiters);
if (wordArray) {
let accumulator = 0;
for (let i = 0; i < wordArray.length; i++) {
const word = wordArray[i];
if (word.length) {
return cursorPosition + word.length + accumulator;
}
/* Skip the delimiter */
accumulator += 1;
}
}
const maxLen = currentLine.length;
return cursorPosition < maxLen ? cursorPosition : maxLen;
}
/* Jump to start of the previous word */
export function prevWordPosition(cursorPosition: number, currentLine: string): number {
const wordArray = currentLine.substr(0, cursorPosition).split(delimiters);
if (wordArray) {
let accumulator = 0;
for (let i = wordArray.length - 1; i >= 0; i--) {
const word = wordArray[i];
if (word.length) {
return cursorPosition - word.length - accumulator;
}
/* Skip the delimiter */
accumulator += 1;
}
}
const minLen = 0;
return cursorPosition > minLen ? cursorPosition : minLen;
}
/* Handle all of the hotkeys */
export async function handleHotKeys(
event: SyntheticKeyboardEvent<>,
state: terminalStateT
): Promise<terminalStateT> {
const { key } = event;
let { cursorPosition, currentLine, commandLineNumber } = state;
const { metaKeys } = state;
/* Push any new keys */
if (key === 'Meta' || key === 'Alt' || key === 'Control') {
/* Store the meta key if not already stored */
if (metaKeys.indexOf(key) === -1) {
metaKeys.push(key);
}
}
/* find presence of keys */
const meta: boolean = metaKeys.indexOf('Meta') >= 0;
const alt: boolean = metaKeys.indexOf('Alt') >= 0;
const control: boolean = metaKeys.indexOf('Control') >= 0;
/* There's got to be a more compact form */
if (meta && !alt && !control) {
/* META */
switch (key) {
/* Beginning of line */
case 'ArrowLeft':
cursorPosition = 0;
break;
/* End of line */
case 'ArrowRight':
cursorPosition = currentLine.length;
break;
/* Delete line */
case 'Backspace':
currentLine = '';
cursorPosition = 0;
commandLineNumber = undefined;
break;
/* Paste */
case 'v':
/* Insert the key at the cursor position */
currentLine = currentLine.substr(0, cursorPosition)
+ clipboard.readText() + currentLine.substr(cursorPosition);
cursorPosition += clipboard.readText().length;
commandLineNumber = undefined;
break;
default:
break;
}
} else if (!meta && alt && !control) {
/* ALT */
switch (key) {
case 'Backspace': {
const wordStart = prevWordPosition(cursorPosition, currentLine);
/* delete the word in question */
currentLine = currentLine.slice(0, wordStart) +
currentLine.slice(cursorPosition, currentLine.length);
cursorPosition = wordStart;
commandLineNumber = undefined;
break;
}
case 'ArrowLeft':
cursorPosition = prevWordPosition(cursorPosition, currentLine);
break;
/* End of the next word */
case 'ArrowRight':
cursorPosition = nextWordPosition(cursorPosition, currentLine);
break;
default:
break;
}
}
return {
...state, cursorPosition, currentLine, commandLineNumber
};
}
/* Handle a regular terminal input */
export async function handleTerminalInput(
event: SyntheticKeyboardEvent<>,
state: terminalStateT
): Promise<terminalStateT> {
const { metaKeys } = state;
let { cursorPosition, currentLine, history, commandLineNumber } = state;
const { key } = event;
/* Parse the key */
switch (key) {
/* Enter a command */
case 'Enter': {
/* Store the line */
history = update(history, {
$push: [{
value: currentLine,
isCmd: true
}]
});
/* Execute the command */
try {
const cmdReturn = await executeCommand(currentLine);
/* Update the object */
for (let i = 0; i < cmdReturn.length; i++) {
const cmdLine = cmdReturn[i];
history = update(history, {
$push: [{
value: cmdLine,
isCmd: false
}]
});
}
} catch (err) {
/* Display error in the mica terminal */
history = update(history, {
$push: [
{
value: `Error: ${err}`,
isCmd: false
},
{
value: 'See console for more details',
isCmd: false
}
]
});
/* Log the error */
console.log(`Error in terminal command: '${currentLine}'`, err);
}
currentLine = '';
cursorPosition = 0;
commandLineNumber = undefined;
/* */
break;
}
/* Delete a character */
case 'Backspace':
/* Don't delete past start of line */
if (cursorPosition > 0) {
/* Delete at the cursor position */
currentLine = currentLine.slice(0, cursorPosition - 1) +
currentLine.slice(cursorPosition, currentLine.length);
cursorPosition -= 1;
/* typing means that the line should be reset */
commandLineNumber = undefined;
}
break;
/* Navigate left */
case 'ArrowLeft':
if (cursorPosition > 0) {
cursorPosition -= 1;
}
break;
/* Navigate right */
case 'ArrowRight':
if (cursorPosition < currentLine.length) {
cursorPosition += 1;
}
break;
/* Recall previous line */
case 'ArrowUp': {
const recall = recallPrevCommand(state);
if (recall) {
currentLine = recall.cmd;
commandLineNumber = recall.index;
cursorPosition = currentLine.length;
}
break;
}
/* Move to next line */
case 'ArrowDown': {
const recall = recallNextCommand(state);
if (recall) {
currentLine = recall.cmd;
commandLineNumber = recall.index;
cursorPosition = currentLine.length;
}
break;
}
/* All other keys */
default:
/* Normal character */
if (typeof key === 'string' && key.length === 1) {
/* Insert the key at the cursor position */
currentLine = currentLine.substr(0, cursorPosition)
+ key + currentLine.substr(cursorPosition);
cursorPosition += 1;
/* typing means that the line should be reset */
commandLineNumber = undefined;
} else if (metaKeys.indexOf(key) === -1) {
/* Store the meta key if not already stored */
metaKeys.push(key);
}
break;
} /* End Switch */
return { ...state, cursorPosition, currentLine, history, commandLineNumber, metaKeys };
}
/* Store a reference to a callback function */
let terminalCallback;
export function registerCallback(callback: (string) => void): void {
terminalCallback = callback;
}
/* Logs terminal data asynchronously */
export function logAsyncData(data: string): void {
if (terminalCallback) {
terminalCallback(data);
}
}
/* Converts a Hex value or array of values to an ASCII string */
export function hexToString(data: number[] | number | Buffer): string {
/* Handle a single number */
const singleToString = (val: number) => {
let asciiHex = val.toString(16);
if (asciiHex.length === 1) {
asciiHex = `0${asciiHex}`;
}
return asciiHex.toUpperCase();
};
/* Single number */
if (typeof data === 'number') {
return singleToString(data);
}
/* If array */
let result = '';
for (let i = 0; i < data.length; i++) {
const val = data[i];
result += singleToString(val);
if (i !== data.length - 1) {
result += ':';
}
}
return result;
}
/* [] - END OF FILE */
|
export { _routeHandlersShorthandsPut as default } from '@miragejs/server';
|
import {service, downloadService} from './request'
// 验证码
export const verifyCode = data => { return service({method: 'post', responseType: 'arraybuffer', url: '/code/verifyCode', data, witchCredentials: true, headers: {'Content-Type': 'multipart/form-data'}}) }
// 登录
export const login = data => { return service({method: 'post', url: '/login/userLogin', data, headers: {'Content-Type': 'multipart/form-data'}}) }
// 退出
export const logout = () => { return service({method: 'post', url: '/login/logout', headers: {'Content-Type': 'multipart/form-data'}}) }
// 修改psd
export const modifyPassWord = data => { return service({method: 'post', url: '/login/modifyPassWord', data, headers: {'Content-Type': 'multipart/form-data'}}) }
// 图片上传
export const imgUpload = data => { return service({method: 'post', url: '/upload/imgUpload', data, headers: {'Content-Type': 'multipart/form-data'}}) }
// 首页
export const todayLogCount = () => { return service({method: 'get', url: '/main/todayLogCount'}) }
// 获取系统菜单
export const getUserMenu = () => { return service({method: 'post', url: '/menu/getMenuList', headers: {'Content-Type': 'multipart/form-data'}}) }
// 字典数据
export const getSysDictByParentCode = data => { return service({method: 'post', url: '/sysDict/getSysDictByParentCode', data, headers: {'Content-Type': 'multipart/form-data'}}) }
// 设备
export const listDevice = (data) => { return service({method: 'post', url: '/device/listDevice', data, headers: {'Content-Type': 'multipart/form-data'}}) }
// 设备新增
export const addDevice = data => { return service({method: 'post', url: '/device/addDevice', data, headers: {'Content-Type': 'application/json'}}) }
// 设备详情
export const deviceDetail = data => { return service({method: 'post', url: '/device/toUpdateDevice', data, headers: {'Content-Type': 'multipart/form-data'}}) }
// 设备修改
export const updateDevice = data => { return service({method: 'post', url: '/device/updateDevice', data, headers: {'Content-Type': 'application/json'}}) }
// // 删除
export const deleteDevice = data => { return service({method: 'post', url: '/device/deleteDevice', data, headers: {'Content-Type': 'multipart/form-data'}}) }
// 公司信息
export const getCompanyInfo = data => { return service({method: 'post', url: '/company/getCompanyInfo', data, headers: {'Content-Type': 'application/json'}}) }
// 公司修改
export const saveCompanyInfo = data => { return service({method: 'post', url: '/company/saveCompanyInfo', data, headers: {'Content-Type': 'application/json'}}) }
// 渠道员工-列表
export const listChannelUser = (data) => { return service({method: 'post', url: '/channel/listUser', data, headers: {'Content-Type': 'multipart/form-data'}}) }
// 渠道员工-新增
export const addChannelUser = data => { return service({method: 'post', url: '/channel/addUser', data, headers: {'Content-Type': 'application/json'}}) }
// 渠道员工-详情
export const ChannelUserDetail = data => { return service({method: 'post', url: '/channel/toUpdateUser', data, headers: {'Content-Type': 'multipart/form-data'}}) }
// 渠道员工-修改
export const updateChannelUser = data => { return service({method: 'post', url: '/channel/updateUser', data, headers: {'Content-Type': 'application/json'}}) }
// 渠道员工-导出
export const exportChannelUser = data => { return downloadService({method: 'post', responseType: 'blob', url: '/channel/dataExport', data, headers: {'Content-Type': 'application/json'}}) }
// 客户报备-列表
export const listCustomer = (data) => { return service({method: 'post', url: '/customer/listUser', data, headers: {'Content-Type': 'multipart/form-data'}}) }
// 客户报备-to新增
export const toAddCustomer = data => { return service({method: 'post', url: '/customer/toAddUser', data, headers: {'Content-Type': 'multipart/form-data'}}) }
// 客户报备-新增
export const addCustomer = data => { return service({method: 'post', url: '/customer/addUser', data, headers: {'Content-Type': 'application/json'}}) }
// 客户报备-详情
export const CustomerDetail = data => { return service({method: 'post', url: '/customer/toUpdateUser', data, headers: {'Content-Type': 'multipart/form-data'}}) }
// 客户报备-修改
export const updateCustomer = data => { return service({method: 'post', url: '/customer/updateUser', data, headers: {'Content-Type': 'application/json'}}) }
// 客户报备-删除
export const deleteCustomer = data => { return service({method: 'post', url: '/customer/deleteUser', data, headers: {'Content-Type': 'application/json'}}) }
// 客户报备-导出
export const exportCustomer = data => { return downloadService({method: 'post', responseType: 'blob', url: '/customer/dataExport', data, headers: {'Content-Type': 'application/json'}}) }
// 识别记录、陌生人记录
export const listRecord = (data) => { return service({method: 'post', url: '/record/listRecord', data, headers: {'Content-Type': 'multipart/form-data'}}) }
// 识别记录-导出
export const exportRecord = data => { return downloadService({method: 'post', responseType: 'blob', url: '/record/dataExport', data, headers: {'Content-Type': 'application/json'}}) }
// 图片质量参数配置-detail
export const getPicQuality = () => { return service({method: 'post', url: '/sysAlgorithm/qualityDetail', headers: {'Content-Type': 'multipart/form-data'}}) }
// 图片质量参数配置-保存
export const addPicQuality = data => { return service({method: 'post', url: '/sysAlgorithm/addQuality', data, headers: {'Content-Type': 'application/json'}}) }
// 识别参数配置-detail
export const sysAlgorithmDetail = () => { return service({method: 'post', url: '/sysAlgorithm/sysAlgorithmDetail', headers: {'Content-Type': 'multipart/form-data'}}) }
// 识别参数配置-保存
export const addSysAlgorithm = data => { return service({method: 'post', url: '/sysAlgorithm/addSysAlgorithm', data, headers: {'Content-Type': 'application/json'}}) }
|
import { useState } from "react";
import BarChartComp from "../components/BarChartComp";
import Card from "../components/Card";
import PieChartComp from "../components/PieChartComp";
import "../styles/Home.css";
const data = [
{ name: "Group B", value: 12, title: "Open" },
{ name: "Group A", value: 23, title: "Overdue" },
{ name: "Group C", value: 65, title: "Paid" },
];
const data1 = [
{ name: "Group B", value: 10, title: "Ongoing" },
{ name: "Group A", value: 15, title: "Overdue" },
{ name: "Group C", value: 15, title: "Completed" },
{ name: "Group C", value: 60, title: "Open" },
];
const barData = [{ name: "Group B", uv: 8, amt: 20 }];
const barData2 = [{ name: "Group B", uv: 18, amt: 20 }];
const Home = () => {
const [amount, setAmount] = useState(29310);
const [overDue, setOverdue] = useState(3000);
const res = amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
const due = overDue.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return (
<div className="backgroundHome universalCenter">
<div>
<div className="universalCenter ">
<Card title="Amount payable">
<div className="universalFlex">
<img
src="https://res.cloudinary.com/dydwwknyv/image/upload/v1625851606/Rectangle_67_qz7qnx_okl0mp.png"
style={{ width: "100px", height: "auto" }}
/>
<div style={{ lineHeight: "0" }}>
<h4>Employer Name</h4>
<button className="button_edit">Edit Profile</button>
</div>
</div>
<div style={{ lineHeight: "20px" }}>
<h3 style={{ fontWeight: "500" }}>Outstanding</h3>
<h1 style={{ fontFamily: "'Poppins', sans-serif" }}>₹ {res}</h1>
</div>
<hr color="#dee3f3" />
<div style={{ lineHeight: "20px" }}>
<h3 style={{ fontWeight: "500" }}>Overdue</h3>
<h1
style={{
color: "#F93A3A",
fontFamily: "'Poppins', sans-serif",
}}
>
₹ {due}
</h1>
</div>
</Card>
<Card title="Action Required">
<BarChartComp
data={barData2}
fill="#6360AB"
title="Gigs pending for approval"
tickCount=""
width={360}
/>
<hr color="#dee3f3" style={{ marginTop: "-10px" }} />
<BarChartComp
data={barData}
fill="#f7bd01"
title="Dispute Raised"
tickCount="1"
width={360}
/>
</Card>
<Card title="Invoice status">
<PieChartComp data={data} />
</Card>
</div>
<div className="universalCenter">
<div className="spreadCard uncheck gapCheck">
<h3
style={{
textAlign: "left",
marginTop: "30px",
}}
>
Ongoing gigs
</h3>
<div>
<BarChartComp
fill="#f93a3a"
title="Overdue milestone"
data={barData}
tickCount=""
width={700}
/>
<hr color="#dee3f3" style={{ marginTop: "-30px" }} />
<BarChartComp
data={barData2}
fill="#6360AB"
title="Upcoming milestone"
tickCount="1"
width={700}
/>
</div>
</div>
<div className="check gapCheck">
<Card title=" Ongoing gigs">
<BarChartComp
fill="#f93a3a"
title="Overdue milestone"
data={barData}
tickCount=""
width={360}
/>
<hr color="#dee3f3" style={{ marginTop: "-10px" }} />
<BarChartComp
data={barData2}
fill="#6360AB"
title="Upcoming milestone"
tickCount="1"
width={360}
/>
</Card>
</div>
<Card title="Gig status">
<PieChartComp data={data1} />
</Card>
</div>
</div>
</div>
);
};
export default Home;
|
/*!
* Copyright (c) 2020 Digital Bazaar, Inc. All rights reserved.
*/
'use strict';
/**
* Used as an umbrella wrapper around multiple verification errors.
*/
class VerificationError extends Error {
/**
* @param {Error|Error[]} errors
*/
constructor(errors) {
super('Verification error(s).');
this.name = 'VerificationError';
this.errors = [].concat(errors);
}
}
module.exports = VerificationError;
|
var ghpages = require('gh-pages');
var path = require('path');
ghpages.publish('dist', function (err) {
if (err) throw err
});
|
'use strict';
const _ = require('..');
const assert = require('assert');
describe('test', function() {
it('base', function() {
assert.ok(_.ipv4);
assert.ok(_.uuid());
});
});
|
import React from 'react';
import ToDo from './ToDo.js';
import '../styles/App.css'
export default class Inventory extends React.Component{
render (){
return(
<div>
<div className="all">
<div className="category">
<h2 className="meat">Meats</h2>
<ToDo category="meat"/>
</div>
<div className="category">
<h2 className="veggie">Veggies</h2>
<ToDo category="veggie"/>
</div>
<div className="category">
<h2 className="spice">Spices</h2>
<ToDo category="spice"/>
</div>
<div className="category">
<h2 className="fruit">Fruits</h2>
<ToDo category="fruit"/>
</div>
<div className="category">
<h2 className="dairy">Dairy</h2>
<ToDo category="dairy"/>
</div>
</div>
<button className="rbut" type="submit">Recipe Wizard</button>
</div>
)
}
}
|
//求和
Array.prototype.sum = function() {
for(var sum = i = 0; i < this.length; i++) {
sum += this[i]
}
return sum
}
//求最大值
Array.prototype.maxima = function() {
for(var i = 0, maxValue = Number.MIN_VALUE; i < this.length; i++) {
parseInt(this[i]) > maxValue && (maxValue = this[i]);
}
return maxValue
}
//应用
var arr = [1,21,3,4,22,45,6,7,32];
alert(arr.join("+")+"="+arr.sum());
alert(arr.join("|") + "中,最大的数是:" + arr.maxima());
|
const app = getApp()
Page({
onLoad() {
console.log(app.globalData)
}
})
|
import './App.css'
import AppHeader from './components/AppHeader';
import FrameworkPost from './components/FrameworkPost';
import Frameworkitem from './components/Frameworkitem';
import { useState } from 'react';
function App() {
const [selectedFrame,setSelectedFrame] = useState(null);
const [searchText,setSearchText] = useState('');
function onframeOpenClick() {
setSelectedFrame(frames[1]);
}
function onframeCloseClick(){
setSelectedFrame(null);
}
const filteredFrames = frame.filter((frame) => {
return frame.title.includes(seachText);
});
const frameElements = frames.filter(((frame) => {
return frame.title.includes(seachText);
})map((frame,index) => {
return <Frameworkitem key={index} frame={frame} onFrameClick={onframeOpenClick}/>;
});
let framePost = null;
if (!!selectedFrame) {
frameworkPost = FrameworkPost frame={selectedFrame} onBgclick={onframeCloseClick} />
}
return (
<div className="app">
<AppHeader />
<section className="app-section">
<div className="app-container">
<AppSeach value={searchText} onValueChange={setSearchText}>
<div className="app-grid">
<Frameworkitem frame={frame1}/>
</div>
</div>
</section>
{framePost}
</div>
);
}
export default App;
|
// noop for testing gatsby-theme debug
|
var mongoose = require('mongoose');
var rewardSchema = new mongoose.Schema({
name: {type: String, required: true},
points: {type: Number, required: true},
createdBy: {type: String, required: true},
created: {type: Date, default: Date.now, required: true},
image: String,
summary: {type: String, required: true},
description: {type: String, required: true}
});
module.exports = mongoose.model("Reward", rewardSchema);
|
import React from 'react';
import {Icon} from 'semantic-ui-react';
export default props => (
<Icon {...props}/>
);
|
import React, {Component} from 'react'
import MenuItem from 'material-ui/MenuItem'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
import axios from 'axios'
import localStorage from 'localStorage'
import * as roleActions from '../../Actions/RoleActions'
import * as defaultRoleActions from '../../Actions/DefaultRoleActions'
import {AUTH_BASE_URL} from '../../Config/Constants'
import {ValidatorForm} from 'react-form-validator-core'
import {underlineFocusStyle, floatingLabelFocusStyle, selectContainerStyle} from '../CSSModules'
import {selectionsRenderer, fetchDropdownOptions,} from '../Common'
import {SelectValidator} from 'react-material-ui-form-validator'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import {axiosInstance} from '../../Config/AxiosInstance'
import {toastr} from 'react-redux-toastr'
const requiredValidation = () => ['required'];
const errorMessage = () => ['this field is required'];
class Form extends Component {
constructor(props) {
super(props);
this.state = {
selectedDefaultRole: null,
defaultRolePresent: false,
};
this.handleDefaultRoleChange = this
.handleDefaultRoleChange
.bind(this);
this.handleSubmit = this
.handleSubmit
.bind(this);
}
handleDefaultRoleChange = (event, index, selectedDefaultRole) => this.setState({selectedDefaultRole});
componentDidMount() {
axios.get(AUTH_BASE_URL + "default_role/1", {
withCredentials: true,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': localStorage.getItem('token'),
}
}).then((response) => {
var defaultRoleDetails = response.data;
if (defaultRoleDetails) {
this.setState({selectedDefaultRole: defaultRoleDetails.roleId, defaultRolePresent: true})
}
}).catch((err) => {
toastr.error("Error while fetching default role details");
});
this
.props
.actions
.fetchAllRoles({limit: -1});
}
renderRoleList(selectedDefaultRole, fetchedRoles) {
if (fetchedRoles == null)
return;
return (
<SelectValidator fullWidth={true} value={selectedDefaultRole} name="selectedDefaultRole" validators={requiredValidation()} errorMessages={errorMessage()} floatingLabelText="Default Role" onChange={this.handleDefaultRoleChange} underlineFocusStyle={underlineFocusStyle} floatingLabelFocusStyle={floatingLabelFocusStyle}>
{fetchedRoles.map((role, index) => <MenuItem value={role.id} key={role.id} primaryText={role.name}/>)}
</SelectValidator>
)
}
componentWillReceiveProps(nextProps) {
if (nextProps.createResponse) {
toastr.success("Default role created successfully");
}
if (nextProps.updateResponse) {
toastr.success("Default role updated successfully");
}
}
handleSubmit(event) {
event.preventDefault();
var payload = {
roleId: this.state.selectedDefaultRole
}
if (this.state.selectedDefaultRole) {
this
.props
.actions
.update(1, payload);
} else {
this
.props
.actions
.create(payload);
}
}
render() {
const {fetchedRoles} = this.props;
const {selectedDefaultRole} = this.state;
return (
<MuiThemeProvider>
<ValidatorForm onSubmit={this.handleSubmit}>
{this.renderRoleList(selectedDefaultRole, fetchedRoles)}
<button class="btn btn-primary form-page-btn" type="submit">
Save
</button>
</ValidatorForm>
</MuiThemeProvider>
)
}
}
const mapStateToProps = (state) => ({defaultRole: state.defaultRole.defaultRole, createResponse: state.defaultRole.createResponse, updateResponse: state.defaultRole.updateResponse, fetchedRoles: state.roles.fetchedRoles});
const mapDispatchToProps = (dispatch) => ({
actions: bindActionCreators(Object.assign({}, defaultRoleActions, roleActions), dispatch)
});
export default connect(mapStateToProps, mapDispatchToProps)(Form)
|
(function() {
'use strict';
// Helper functions
global.clearWithBackspace = function(elementFinder) {
return elementFinder.getAttribute('value').then(function(value) {
var backspaces = '',
length = value.length;
for (var i = 0; i < length; i++) {
backspaces += protractor.Key.BACK_SPACE;
}
return elementFinder.sendKeys(backspaces);
});
};
/**
* Provides a place to put common beforeEach functionality.
*/
global.setUp = function() {
// Add our custom jasmine matchers
jasmine.getEnv().currentSpec.addMatchers(matchers.getCustomMatchers());
// Reset any excluded test-specific console errors.
global.consoleErrorHandler.resetExcluded();
// Close any hanging dialogs before running tests
sdk.closeDialogs();
};
/**
* Provides a place to put common afterEach functionality.
*/
global.tearDown = function() {
// Check console.log for errors
global.consoleErrorHandler.expectNoConsoleErrors();
// Check for hanging dialogs
sdk.expectNoDialogs();
};
function displayed(elementFinder, optionalTimeout, isDisplayed) {
browser.driver.wait(function () {
return elementFinder.isDisplayed().then(function (result) {
return result === isDisplayed;
});
}, optionalTimeout || 60000);
}
function present(elementFinder, optionalTimeout, isPresent) {
browser.driver.wait(function () {
return elementFinder.isPresent().then(function (result) {
return result === isPresent;
});
}, optionalTimeout || 60000);
}
global.wait = {
until: {
not: {
present: function (elementFinder, optionalTimeout) {
return present(elementFinder, optionalTimeout, false);
}
},
displayed: function (elementFinder, optionalTimeout) {
return displayed(elementFinder, optionalTimeout, true);
},
present: function (elementFinder, optionalTimeout) {
return present(elementFinder, optionalTimeout, true);
}
}
};
}());
|
import React, {useEffect, useState} from "react";
import {connect} from "react-redux";
import {useLocation, useParams, useHistory} from "react-router-dom";
import {api_post, load_user, load_user_repos} from "./api";
import {Button} from "react-bootstrap";
import Heart from "react-animated-heart";
import Nav from "./Nav"
function User({token, user, dispatch}) {
const location = useLocation();
const params = useParams();
const history = useHistory();
const searched_user = location.state?.user || {login: params.user_name};
const [userData, setUserData] = useState([]);
useEffect(async () => {
if (token) {
let data = await load_user_repos(token, searched_user.login);
setUserData(data);
}
}, [searched_user.login]);
useEffect(() => {
if (token && !user) {
load_user(token);
}
}, [token]);
if (!userData.data) {
return null;
}
const joinCall = async repo => {
const body = {repo: repo.full_name, url: repo.html_url, user: user.login};
const data = (await api_post("/user/recent", body)).recents;
dispatch({type: 'user/set', data: {...user, recents: data}});
history.push(`/room/${repo.full_name}`);
};
const isFavorited = repo => {
return user.favorites.filter(favorite => favorite.repo === repo.full_name).length
};
const toggleFavorite = async repo => {
const body = {repo: repo.full_name, url: repo.html_url, user: user.login};
const data = (await api_post("/user/favorite", body)).favorites;
dispatch({type: 'user/set', data: {...user, favorites: data}});
};
const sendFriendRequest = async () => {
const body = {inviter: user.login, invitee: searched_user.login};
await api_post("/user/request/send", body);
};
if (!user) {
return null;
}
return (
<div>
<Nav />
<h2>
<div>
{searched_user.login}{" "}
{searched_user.avatar_url && <img style={{width: "50px"}} src={searched_user.avatar_url} alt={"Avatar"}/>}
</div>
</h2>
<Button onClick={() => sendFriendRequest()}>Add Friend</Button>
<table className={"table table-striped"} style={{width: "50%"}}>
<thead>
<tr>
<th>Name</th>
<th/>
<th/>
</tr>
</thead>
<tbody>
{userData.data.map(repo => (
<tr key={repo.id}>
<td>
<a href={repo.html_url} target="_blank" rel="noreferrer">{repo.name}</a>
</td>
<td style={{padding: 0}}>
<Heart isClick={isFavorited(repo)} onClick={() => toggleFavorite(repo)}/>
</td>
<td>
<Button onClick={() => joinCall(repo)}>Join Call</Button>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default connect(({token, user}) => ({token, user}))(User);
|
import React from 'react';
import clsx from 'clsx';
import PropTypes from 'prop-types';
import { makeStyles } from '@material-ui/styles';
import { Card, CardContent, Grid, Typography} from '@material-ui/core';
import SentimentSatisfiedSharpIcon from '@material-ui/icons/SentimentSatisfiedSharp';
const useStyles = makeStyles(theme => ({
root: {
height: '100%'
},
content: {
alignItems: 'center',
display: 'flex'
},
title: {
fontWeight: 700
},
avatar: {
backgroundColor: theme.palette.error.main,
height: 32,
width: 32
},
icon: {
height: 20,
width: 20
},
difference: {
marginTop: theme.spacing(0.3),
display: 'flex',
alignItems: 'center'
},
differenceIcon: {
color: theme.palette.error.dark
},
differenceValue: {
color: theme.palette.error.dark,
marginRight: theme.spacing(1)
},
}));
const Pm25Levels = props => {
const { className, pm25level, pm25levelText, background, pm25levelColor, ...rest } = props;
const classes = useStyles();
const pm25BgColor = {
backgroundColor: background,
padding: 5,
height: 35,
}
const pm25_levelColor = {
color: pm25levelColor,
marginTop: 0,
}
return (
<Card
{...rest}
className={clsx(classes.root, className)}
>
<CardContent style = {pm25BgColor}>
{/* <Grid
container
justify="space-between"
>
<Grid item>
{/* <Avatar className={classes.avatar}> */}
{/* <SentimentSatisfiedSharpIcon className={classes.icon} style={pm25_levelColor} /> */}
{/* </Avatar> */}
{/* </Grid>
</Grid> */}
<div className={classes.difference}>
<Typography
className={classes.caption}
variant="caption"
>
<p style={pm25_levelColor}> {pm25level} </p>
<p style={pm25_levelColor}> {pm25levelText} </p>
</Typography>
</div>
</CardContent>
</Card>
);
};
Pm25Levels.propTypes = {
className: PropTypes.string,
pm25level: PropTypes.string,
pm25levelText: PropTypes.string,
background: PropTypes.string,
Pm25levelColor: PropTypes.string
};
export default Pm25Levels;
|
module.exports = 'Proceso de autoevaluación.'
|
define(["three"], function(THREE) {
camera = new THREE.PerspectiveCamera( 27, window.innerWidth / window.innerHeight, 5, 3500 );
camera.position.z = 2750;
return camera;
});
|
import React, { useState } from 'react';
import { Link, useHistory } from 'react-router-dom';
import axios from "axios";
export default function Register() {
const [username, setUserName] = useState();
const [password, setPassword] = useState();
const [errorMsg, setErrorMsg] = useState();
let history = useHistory();
async function registerUser(credentials) {
return axios.post("https://afternoon-hamlet-77607.herokuapp.com/api/register/", credentials)
.then(response => {
// Redirect here
history.push("/");
})
.catch(function (error) {
if (error.response) {
// Request made and server responded
if (error.response.data['username'][0]) {
console.log(error.response.data['username'][0]);
setErrorMsg(error.response.data['username'][0]);
}
}
});
}
const handleSubmit = async e => {
e.preventDefault();
await registerUser({
username,
password
});
}
return(
<div className="container">
<h1 className="text-black text-uppercase text-center my-4">Register</h1>
<div className="row">
<div className="col-md-6 col-sm-10 mx-auto p-0">
<div className="card p-3">
<form onSubmit={handleSubmit}>
<label>
<p>Username</p>
<input type="text" onChange={e => setUserName(e.target.value)}/>
</label>
<label>
<p>Password</p>
<input type="password" onChange={e => setPassword(e.target.value)}/>
</label>
<div>
<button className="btn btn-primary" type="submit">Submit</button>
</div>
</form>
<span>
Have an account? <Link to="/">Login</Link>
</span>
</div>
<h3 className="error"> { errorMsg } </h3>
</div>
</div>
</div>
)
}
|
var VolunteerProfileView = Backbone.View.extend({
initialize: function(options) {
this.options = options;
_.bindAll(this, 'render');
},
// events: {
// 'click #connect-with-volunteer': function (e) {
// $('#volunteerprofile').modal('hide');
// var volunteer_id = $(e.target)[0].dataset.id;
// var volunteer_first_name = $(e.target)[0].dataset.firstname;
// var volunteer_last_name = $(e.target)[0].dataset.lastname;
// var volunteer = new User({id: volunteer_id});
// volunteer.fetch({
// success: function (model, response, options) {
// console.log("success");
// swal({
// title: "Thank you!", //"สวัสดีครับ -- Thank you for connecting with the CEP Skype teacher!",
// text: volunteer_first_name + " " + volunteer_last_name + " จะได้รับอีเมลจากโครงการซิตี้ อิงลิช ที่มีชื่อและอีเมลของคุณอยู่ในนั้น และเราจะติดต่อคุณกลับเร็วๆ นี้",
// timer: 20000,
// showConfirmButton: true,
// animation: "slide-from-top"
// });
// console.log(model);
// // $("entire-main").html(model.get("first_name"));
// },
// error: function (model, response, options) {
// console.log("error");
// swal({
// title: "Error with database",
// text: "Please click on the same person's name again.",
// timer: 20000,
// showConfirmButton: true,
// animation: "slide-from-top"
// });
// console.log(response);
// }
// });
// }
// },
template: HandlebarsTemplates['dashboard/volunteer_profile'],
render: function() {
this.$el.html(this.template({
first_name: this.model.toJSON().first_name,
last_name: this.model.toJSON().last_name,
}));
return this;
}
});
|
angular.module('DayFlow', []).controller('DayFlowCtrl', function($scope,$http) {
$scope.pageObject = {
currentPage : 1,
totalPage : 0,
pageSize : 10,
pages : []
};
$scope.dayFlowRank = [];
$scope.getDayFlow = function(){
$scope.dayFlowSearch = {
params:{
pageSize:$scope.pageObject.pageSize,
currentPage:$scope.pageObject.currentPage
}
};
$http.get("/api/dayFlowRank",$scope.dayFlowSearch).success(function(data,status,headers){
$scope.pageObject.currentPage = headers('Page'); //当前页
$scope.pageObject.totalPage = headers('Page-Count'); //总页数
$scope.dayFlowRank = data; //当前页的信息
console.log(JSON.stringify($scope.dayFlowRank));
}).error(function(err){
$scope.dayFlowRank = [];
console.log(err);
});
};
$scope.init = function(){
$scope.getDayFlow();
// $scope.$watch('pageObject.totalPage',function(){myPaginationService.showFirstPageContent($scope.pageObject,1);});
};
$scope.init();
setInterval(function(){
$scope.init();
},5*60*1000);
});
|
// since this is a dynamic data,
// that is why we are importing action to.
import Jsonplaceholder from "../api/Jsonplaceholder";
export const fetchUser = (id) => async dispatch => {
const response = await Jsonplaceholder.get(`/users/${id}`);
console.log(response)
dispatch({type:'FETCH_USER', payload: response})
};
export const fetchPosts = () => async dispatch => {
const response = await Jsonplaceholder.get('/posts');
dispatch({type:'FETCH_POST', payload: response.data})
};
|
$('document').ready(function(){
$('#btn-menu').click(function(){
//segunda opcao
//$('header nav ul').toggle(300);
if($('header nav ul').is(':visible'))
{
$('header nav ul').hide("slide", {direction: "right"}, 300);
}else{
$('header nav ul').show("slide", {direction: "right"}, 300);
}
});
$('#pg-loja-virtual .sidebar h4').click(function(){
$('#pg-loja-virtual #categorias').toggle(300);
});
});
|
"use strict";
let canvas;
let canvasContext;
let ballX = 50;
let ballY = 50;
let ballSpeedX = 10;
let ballSpeedY = 4;
let player1Score = 0;
let player2Score = 0;
const WINNING_SCORE = 3;
let showingWinScreen = false;
let paddle1Y = 250;
let paddle2Y = 250;
const PADDLE_THICKNESS = 10;
const PADDLE_HEIGHT = 100;
function calculateMousePosition(event) {
let rect = canvas.getBoundingClientRect();
let root = document.documentElement;
let mouseX = event.clientX - rect.left - root.scrollLeft;
let mouseY = event.clientY - rect.top - root.scrollTop;
return {
x:mouseX,
y:mouseY
};
}
function handleMouseClick(event) {
if(showingWinScreen) {
player1Score = 0;
player2Score = 0;
showingWinScreen = false;
}
}
window.onload = function () {
canvas = document.getElementById("gameCanvas");
canvasContext = canvas.getContext("2d");
let framesPerSecond = 30;
//sets interval for movement
setInterval(callBoth, 1000/framesPerSecond);
//mousemove connects with paddle
canvas.addEventListener("mousemove",
function(event) {
let mousePosition = calculateMousePosition(event);
paddle1Y = mousePosition.y-(PADDLE_HEIGHT/2);
});
canvas.addEventListener("mousedown", handleMouseClick);
}
// create callBoth function
function callBoth () {
moveEverything();
drawEverything();
}
function ballReset() {
if(player1Score >= WINNING_SCORE ||
player2Score >= WINNING_SCORE) {
showingWinScreen = true;
}
ballSpeedX = -ballSpeedX;
ballX = canvas.width/2;
ballY = canvas.height/2;
}
function computerMovement() {
let paddle2YCenter = paddle2Y + (PADDLE_HEIGHT/2);
if(paddle2YCenter < ballY+35) {
paddle2Y += 6;
} else if(paddle2YCenter > ballY+35) {
paddle2Y -= 6;
}
}
function moveEverything () {
if(showingWinScreen) {
return;
}
computerMovement();
// let ball move right/left
ballX += ballSpeedX;
// let ball move up/down
ballY += ballSpeedY;
//bounce from left border
if(ballX < 0) {
if(ballY > paddle1Y &&
ballY < paddle1Y+PADDLE_HEIGHT) {
ballSpeedX = -ballSpeedX;
//balls bouncing correction
let deltaY = ballY-(paddle1Y+PADDLE_HEIGHT/2)
ballSpeedY = deltaY * 0.35;
} else {
player2Score++; //must be before ballReset()
ballReset();
}
}
//bounce from right border
if(ballX > canvas.width) {
if(ballY > paddle2Y &&
ballY < paddle2Y+PADDLE_HEIGHT) {
ballSpeedX = -ballSpeedX;
//balls bouncing correction
let deltaY = ballY-(paddle2Y+PADDLE_HEIGHT/2)
ballSpeedY = deltaY * 0.35;
} else {
player1Score++; //must be before ballReset()
ballReset();
}
}
//bounce from up
if (ballY < 0) {
ballSpeedY = -ballSpeedY;
}
//bounce from down
if (ballY > canvas.height) {
ballSpeedY = -ballSpeedY;
}
}
function drawNet() {
for(let i=0; i<canvas.height; i+=40) {
colorRect(canvas.width/2-1, i, 2, 20, "white");
}
}
function drawEverything() {
//black screen
colorRect(0, 0, canvas.width, canvas.clientHeight, "black");
if(showingWinScreen) {
canvasContext.fillStyle = "red";
canvasContext.font="20px Georgia";
if(player1Score >= WINNING_SCORE) {
canvasContext.fillText("LEFT PLAYER WON!", 300, 200);
} else if (player2Score >= WINNING_SCORE) {
canvasContext.fillText("RIGHT PLAYER WON!", 300, 200);
}
canvasContext.fillStyle = "yellow";
canvasContext.fillText("click to continue", 330, 500);
return;
}
drawNet();
//left player paddle
colorRect(0, paddle1Y, PADDLE_THICKNESS, PADDLE_HEIGHT, "white");
//draw the ball
//right computer paddle
colorRect(canvas.width-PADDLE_THICKNESS, paddle2Y, PADDLE_THICKNESS, PADDLE_HEIGHT, "white");
//draw the ball
colorCircle(ballX, ballY, 10, "red");
canvasContext.fillStyle = "yellow";
canvasContext.font="20px Georgia";
canvasContext.fillText("SCORE", 370, 75);
canvasContext.fillText(player1Score, 200, 100);
canvasContext.fillText(player2Score, canvas.width-200, 100);
}
function colorCircle(centerX, centerY, radius, drawColor) {
canvasContext.fillStyle = drawColor;
canvasContext.beginPath();
canvasContext.arc(centerX, centerY, radius, 0, Math.PI*2, true);
canvasContext.fill();
}
function colorRect (leftX, topY, width, height, drawColor) {
canvasContext.fillStyle = drawColor;
canvasContext.fillRect(leftX, topY, width, height);
}
|
import React, { useState, useEffect } from "react";
import {Avatar, Card} from 'antd';
import { RetweetOutlined, TwitterOutlined } from '@ant-design/icons';
import FactCheckPopover from "./FactCheckPopover";
class TweetCard extends React.Component {
onTweetClick() {
console.log('on tweet clicked')
}
render() {
return (
<Card style={{ width: 500, 'margin': '10px', 'boxShadow': '0px 0px 8px -1px rgba(0,0,0,0.33)' }}>
<p> <Avatar src={this.props.tweet.json.user.profile_image_url} /> {this.props.tweet.json.user.name} <TwitterOutlined onClick={()=> window.open(this.props.tweet.tweet_link, "_blank")}/></p>
<p>@{this.props.tweet.user_screen_name}</p>
<p>{this.props.tweet.text}</p>
<div style={{'display': 'flex', 'flexDirection': 'row', 'justifyContent': 'space-between'}}>
<p><RetweetOutlined/>{this.props.tweet.json.retweet_count}</p>
<FactCheckPopover factcheckresults={this.props.factcheckresults}/>
</div>
</Card>
);
}
}
export default TweetCard;
|
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import LoadingBar from '../LoadingBar/LoadingBar';
import CountryStats from './CountryStats/CountryStats';
import WorldSummary from './WorldStatSummary/WorldSummary';
import Card from 'react-bootstrap/Card';
import Toast from 'react-bootstrap/Toast';
import OverlayTrigger from 'react-bootstrap/OverlayTrigger';
import Button from 'react-bootstrap/Button';
import Tooltip from 'react-bootstrap/Tooltip';
import Alert from 'react-bootstrap/Alert';
function HomePage() {
const [latest, setLatest] = useState([]);
const [results, setResults] = useState([]);
const [loading, setLoading] = useState(true);
const [toastShow, setToastShow] = useState(true);
const [alertShow, setAlertShow] = useState(true);
useEffect(() => {
axios
.all([
axios.get('https://corona.lmao.ninja/v2/all'),
axios.get('https://corona.lmao.ninja/v2/countries')
])
.then(resArr => {
// console.log(resArr[1].data);
setLatest(resArr[0].data);
setResults(resArr[1].data);
setLoading(false);
// setGlobalDate(res.data);
// setIndiaData(res.data.Countries[100]);
})
.catch((err) => {
console.log(err);
});
}, []);
if(loading) {
return (
<LoadingBar loading={loading} />
);
}
const lastUpdated = new Date(parseInt(latest.updated)).toString();
return (
<div>
<br />
{
alertShow
? <div><Alert variant={'warning'} onClose={() => setAlertShow(false)} dismissible>
Use navigation menu on top for <strong>India only Stats</strong>.
</Alert>
<Alert variant={'info'} onClose={() => setAlertShow(false)} dismissible>
Hover / Click on <Button variant="outline-info" size="sm">
<span role="img" aria-label="info">ℹ️</span>
</Button> (present on right corners) wherever available to know more about each component!
</Alert></div> : null
}
{toastShow
? <div
aria-live="polite"
aria-atomic="true"
style={{
position: 'relative',
minHeight: '100px'
}}
>
<Toast
style={{
position: 'absolute',
top: 0,
right: 0,
}}
onClose={() => setToastShow(false)} show={toastShow} delay={5000} autohide
>
<Toast.Header>
<strong className="mr-auto">Last Updated at</strong>
</Toast.Header>
<Toast.Body>{lastUpdated}</Toast.Body>
</Toast>
</div> : null
}
<Card
className='text-center'
style={{margin: '10px', width: 'auto'}}
border="info"
bg='dark'
text='light'
>
<Card.Body>
<Card.Title><h2>Covid-19 Stats</h2></Card.Title>
<WorldSummary latest={latest} />
</Card.Body>
</Card>
<br />
<Card
className='text-center'
style={{margin: '10px', width: 'auto'}}
border="info"
bg='dark'
text='light'
>
<Card.Body>
<Card.Title>
Countrywise Stats
<p align="right">
<OverlayTrigger
placement={'left'}
overlay={
<Tooltip id={`tooltip-left`}>
Click on any of the <strong>Column Name</strong> to sort.<br />
Use <strong>ARROWS</strong> at the bottom to navigate to different page.<br />
Use <strong>DROPDOWN</strong> at the bottom to changes number of rows displayed per page.<br />
Use <strong>SEARCH BAR</strong> to filter by Country.
</Tooltip>
}
>
<Button variant="outline-info" size="sm">
<span role="img" aria-label="info">ℹ️</span>
</Button>
</OverlayTrigger>
</p>
</Card.Title>
<CountryStats results={results} />
</Card.Body>
</Card>
</div>
);
}
export default HomePage;
|
import { Col, Form, Input, Row, Select } from 'antd'
import React, { Component } from 'react'
import _ from 'lodash'
import propTypes from 'prop-types'
import styles from './JobInformationForms.sass'
const FormItem = Form.Item
const Option = Select.Option
class JobInformationForm extends Component {
static propTypes = {
form: propTypes.object,
job: propTypes.object,
saveUnfinshedJob: propTypes.func // eslint-disable-line react/no-unused-prop-types
}
createInputForm = () => {
const { getFieldDecorator } = this.props.form
return (
<FormItem
label='client'
labelCol={{ sm: { span: 4 } }}
wrapperCol={{ sm: { span: 10 } }}
>
{getFieldDecorator('customer', {initialValue: this.props.job.customer, rules: [{required: true}]})(
<Input
size='large'
placeholder='client'
type='input'
/>
)
}
</FormItem>
)
}
createSelectForm = () => {
const { getFieldDecorator } = this.props.form
return (
<FormItem
label={'assignment'}
labelCol={{ sm: { span: 4 } }}
wrapperCol={{ sm: { span: 10 } }}
>
{getFieldDecorator('assignment', { initialValue: this.props.job.assignment })(
<Select>
<Option value='Studio rental'>Studio rental</Option>
<Option value='Studio rental + Location'>Studio rental + Location</Option>
<Option value='Equipment rental'>Equipment rental</Option>
<Option value='Onscreen room'>Onscreen room</Option>
<Option value='Production'>Production</Option>
</Select>
)}
</FormItem>
)
}
createTextAreaForm = (name) => {
const { getFieldDecorator } = this.props.form
return (
<FormItem
label={'job description'}
labelCol={{ sm: { span: 4 } }}
wrapperCol={{ sm: { span: 10 } }}
>
{getFieldDecorator('description', { initialValue: this.props.job.description })(
<Input
size='large'
placeholder={name}
type='textarea'
autosize={{ minRows: 5, maxRows: 10 }}
/>
)}
</FormItem>
)
}
render () {
return (
<div className={styles.container}>
<Row>
<Col>
<Form onSubmit={this.handleSubmit}>
<FormItem
labelCol={{ sm: { span: 4 } }}
wrapperCol={{ sm: { span: 10 } }}
label='quotation'
>
<span>{this.props.job.id}</span>
</FormItem>
{this.createInputForm()}
{this.createSelectForm()}
{this.createTextAreaForm()}
</Form>
</Col>
<Col md={6} />
</Row>
</div>
)
}
}
function onFieldsChange (props, field) {
const updateField = _.map(field, value => value)[0]
props.saveUnfinshedJob(updateField)
}
export default Form.create({ onFieldsChange })(JobInformationForm)
|
/* --------------------
* yauzl-mac module
* yauzl internal functions copied from yauzl source code
* ------------------*/
'use strict';
// jshint quotmark:double
// Exports
const internals = module.exports = {
readAndAssertNoEof: function readAndAssertNoEof(reader, buffer, offset, length, position, callback) {
if (length === 0) {
// fs.read will throw an out-of-bounds error if you try to read 0 bytes from a 0 byte file
return setImmediate(function() { callback(null, new Buffer(0)); });
}
reader.read(buffer, offset, length, position, function(err, bytesRead) {
if (err) return callback(err);
if (bytesRead < length) {
return callback(new Error("unexpected EOF"));
}
callback();
});
},
emitErrorAndAutoClose: function emitErrorAndAutoClose(self, err) {
if (self.autoClose) self.close();
internals.emitError(self, err);
},
emitError: function emitError(self, err) {
if (self.emittedError) return;
self.emittedError = true;
self.emit("error", err);
}
};
|
const mongoose = require("mongoose");
const CommentSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: [true, "User is required"]
},
post: {
type: mongoose.Schema.Types.ObjectId,
ref: "Post",
required: [true, "Post is required"]
},
text: {
type: String,
require: [true, "Text is required"]
},
name: String,
avatar: String,
created: {
type: Date,
default: Date.now
},
updated: {
type: Date
}
});
module.exports = mongoose.model("Comment", CommentSchema);
|
var searchData=
[
['map',['Map',['../classMap.html#ae50ababdf30fcb0f5a10d38c1984eb75',1,'Map']]],
['move',['move',['../classConcreteMove.html#adbbcf93faa6dad1660a922618b905ff1',1,'ConcreteMove::move()'],['../classMove.html#ace4540308f0bbd21d71a18b2ff7c972d',1,'Move::move()'],['../classUnit.html#a8c6bfbaf9bf204baec6ba3c11468ec2f',1,'Unit::move()']]],
['movecommand',['moveCommand',['../classGame.html#a3b1e53d7df15b62d651830bbd47a7516',1,'Game']]]
];
|
/**
* Created by nick on 16-6-4.
*/
var siteTitle = '宁峰', //站点名称
pageTitle = { //各页面名称
'/': '首页',
'/index': '首页',
'/register': '注册',
'/login': '登录',
'/user/center': '用户中心',
'/user/info': '用户信息',
'/user/blog': '用户博客'
},
basePath = 'http://127.0.0.1'; //设置页面根路径
module.exports = { //对外开放配置
siteTitle: siteTitle,
pageTitle: pageTitle,
basePath: basePath,
setting: function( req, path, file ){
return {
title: pageTitle[ req.path ] + '-' + siteTitle, //组成当前页面标题
basePath: basePath,
currentPage: ( path || '' ) + ( file || req.path.replace(/(\/[a-z|A-Z]*)?$/,function($1){return $1 + $1}) ), //据当前访问路径生成静态文件路径
}
}
}
|
// jasmine test
// this test requires a BowlingCtrl
describe('Bowling controllers', function() {
describe('BowlingCtrl', function(){
it('should create "players" model with 0 players', function() {
var scope = {},
ctrl = new BowlingCtrl(scope);
expect(scope.game.players.length).toBe(0);
});
it('should add "players" ', function() {
var scope = {},
ctrl = new BowlingCtrl(scope);
scope.game.addPlayer("Matthieu");
expect(scope.game.players.length).toBe(1);
scope.game.addPlayer("Papa");
expect(scope.game.players.length).toBe(2);
});
});
});
describe("Players",function(){
it("should have a score of zero if ball has gone in the gutter each time",function(){
var i;
var player = new Player("foo");
for (i =0;i<20;i++) {
player.roll(0);
}
expect(player.score()).toBe(0);
expect(player.round).toBe(20);
});
it("should have a score of 20 if one pin has been hit each roll",function(){
var player = new Player("foo");
expect(player.name).toBe("foo");
for (var i =0;i<20;i++) {
player.roll(1);
}
expect(player.score()).toBe(20);
});
it("should have a score of 20 if a spare then 3 and 4 then nothing",function(){
var player = new Player("foo");
expect(player.name).toBe("foo");
player.roll(5);
player.roll(5);
player.roll(3);
player.roll(4);
expect(player.frameIsStrike(0)).toBe(false);
expect(player.frameIsSpare(0)).toBe(true);
expect(player.frameIsStrike(1)).toBe(false);
expect(player.frameIsSpare(1)).toBe(false);
for (var i =0;i<16;i++) {
player.roll(0);
}
expect(player.score()).toBe(20);
});
it("should have a score of 20 if a strike then 3 and 4 then nothing",function(){
var player = new Player("foo");
expect(player.name).toBe("foo");
player.roll(10);
// no roll (due to strike)
expect(player.frameIsStrike(0)).toBe(true);
expect(player.frameScore(0)).toBe(10);
player.roll(3);
player.roll(4);
expect(player.frameIsNormal(1)).toBe(true);
expect(player.frameScore(1)).toBe(7);
expect(player.frameScore(0)).toBe(17);
expect(player.frameIsStrike(1)).toBe(false);
expect(player.frameIsStrike(1)).toBe(false);
for (var i =0;i<14;i++) {
player.roll(0);
}
expect(player.score()).toBe(10+3+4+4+3);
player.roll(6);
player.roll(4);
expect(player.score()).toBe(10+3+4+4+3+10);
var s = player.scoreString();
player.reset();
expect(player.round ).toBe( 0 );
});
it("should have a score of 300 with only strikes",function(){
var player = new Player("foo");
for (var i =0;i<9;i++) {
expect(player.currentFrame()).toBe(i);
player.roll(10);
}
// now play last frame
expect(player.currentFrame()).toBe(9);
expect(player.currentChance()).toBe(0);
player.roll(10);
expect(player.currentFrame()).toBe(9);
expect(player.currentChance()).toBe(1);
player.roll(10);
expect(player.currentFrame()).toBe(9);
expect(player.currentChance()).toBe(2);
player.roll(10);
expect(player.frameIsStrike(0)).toBe(true);
expect(player.frameIsStrike(1)).toBe(true);
expect(player.frameIsStrike(2)).toBe(true);
expect(player.frameIsStrike(3)).toBe(true);
expect(player.frameIsStrike(4)).toBe(true);
expect(player.frameIsStrike(5)).toBe(true);
expect(player.frameIsStrike(6)).toBe(true);
expect(player.frameIsStrike(7)).toBe(true);
expect(player.frameIsStrike(8)).toBe(true);
expect(player.frameIsStrike(9)).toBe(true);
expect(player.frameIsStrike(10)).toBe(true);
expect(player.score()).toBe(300);
expect(player.frameScore(0)).toBe(30);
expect(player.frameScore(1)).toBe(30);
expect(player.frameScore(2)).toBe(30);
expect(player.frameScore(3)).toBe(30);
expect(player.frameScore(4)).toBe(30);
expect(player.frameScore(5)).toBe(30);
expect(player.frameScore(6)).toBe(30);
expect(player.frameScore(7)).toBe(30);
expect(player.frameScore(8)).toBe(30);
expect(player.frameScore(9)).toBe(30);
});
it("should update the standing pin correctly ",function(){
var player = new Player("foo");
// cannot knot up pin
expect(function() { player.roll(-1); }).toThrow("Invalid number of pin");
expect(function() { player.roll(12); }).toThrow("Invalid number of pin");
expect(player.standingPin()).toBe(10);
expect(player.currentFrame()).toBe(0);
expect(player.currentChance()).toBe(0);
player.roll(3);
expect(player.standingPin()).toBe(7);
expect(player.currentFrame()).toBe(0);
expect(player.currentChance()).toBe(1);
// cannot knot down more pin than available
expect(function() { player.roll(8); }).toThrow();
player.roll(3);
expect(player.standingPin()).toBe(10);
expect(player.currentFrame()).toBe(1);
expect(player.currentChance()).toBe(0);
// now a strike
player.roll(10);
expect(player.standingPin()).toBe(10);
expect(player.currentFrame()).toBe(2);
expect(player.currentChance()).toBe(0);
});
it("should allow to play 3 times if spare at last round",function(){
var player = new Player("foo");
for (var i =0;i<9;i++) {
expect(player.numberOfChanceInCurrentFrame()).toBe(2);
expect(player.currentFrame()).toBe(i);
player.roll(0);
player.roll(0);
expect(player.frameScore(i)).toBe(0);
expect(player.gameIsOver()).toBe(false);
}
expect(player.currentFrame()).toBe(9);
expect(player.numberOfChanceInCurrentFrame()).toBe(3);
expect(player.round).toBe(18);
player.roll(10);
expect(player.standingPin()).toBe(10);
expect(player.frameScore(9)).toBe(10);
expect(player.round).toBe(19);
expect(player.gameIsOver()).toBe(false);
player.roll(10);
expect(player.standingPin()).toBe(10);
expect(player.gameIsOver()).toBe(false);
expect(player.frameScore(9)).toBe(20);
expect(player.standingPin()).toBe(10);
expect(player.round).toBe(20);
expect(player.gameIsOver()).toBe(false);
player.roll(10);
expect(player.round).toBe(21);
expect(player.frameScore(9)).toBe(30);
expect(player.gameIsOver()).toBe(true);
expect(player.standingPin()).toBe(0);
expect(function(){ player.roll(1); }).toThrow();
});
describe("test random games",function(){
it("should have the correct result for BAR",function(){
var player = new Player("BAR");
[ 0,0 , 5,0, 6,2, 3,3, 6,4, 9,0, 5,3, 8,1, 1,0, 9,0].forEach(function(p) {
player.roll(p);
});
expect(player.score()).toBe(74);
});
it("should have the correct result for TIFF",function(){
var player = new Player("TIFF");
[ 0,0, 0,0, 0,9, 0,9, 0,0, 3,6, 0,9, 0,9, 6,3, 0,3].forEach(function(p) {
player.roll(p);
});
expect(player.score()).toBe(57);
});
it("should have the correct result for FELI",function(){
var player = new Player("FELI");
[ 0,8, 0,7, 8,0, 8,0, 0,6, 3,3, 3,5, 1,0, 3,4, 7,1 ].forEach(function(p) {
player.roll(p);
});
expect(player.score()).toBe(67);
});
it("should have the correct result for H",function(){
var player = new Player("H");
[ 0,0, 5,5, 3,5, 9,0, 5,0, 0,2, 7,3 , 7,3, 2,8, 5,2 ].forEach(function(p) {
player.roll(p);
});
expect(player.score()).toBe(88);
});
it("should have the correct result for G",function(){
var player = new Player("G");
[ 0,0, 0,0, 3,0, 10, 0,0, 10, 8,0, 6,0, 3,7 , 0,3 ].forEach(function(p) {
player.roll(p);
});
expect(player.gameIsOver()).toBe(true);
expect(player.score()).toBe(58);
});
it("should have the correct result for WORE",function(){
var player = new Player("WORE");
[ 8,2, 9,0, 7,1, 5,1, 10, 10, 10, 7,3, 9,0 , 10,7,1 ].forEach(function(p) {
player.roll(p);
});
expect(player.gameIsOver()).toBe(true);
expect(player.score()).toBe(165);
});
it("should have the correct result for LOBO",function(){
var player = new Player("LOBO");
[ 8,0, 8,2, 7,3, 7,3, 10, 7,3, 6,0, 7,1, 9,0 , 4,0 ].forEach(function(p) {
player.roll(p);
});
expect(player.gameIsOver()).toBe(true);
expect(player.score()).toBe(125);
});
});
});
describe("verifying people turns",function(){
it("should let player 1 play twice before letting player 2 play",function() {
var game = new Game();
game.addPlayer("Player 1");
game.addPlayer("Player 2");
expect(game.currentPlayer().name).toBe("Player 1");
game.roll(1);
expect(game.currentPlayer().name).toBe("Player 1");
game.roll(1);
expect(game.currentPlayer().name).toBe("Player 2");
game.roll(1);
expect(game.currentPlayer().name).toBe("Player 2");
game.roll(1);
expect(game.currentPlayer().name).toBe("Player 1");
game.reset();
});
});
describe("finding players ",function(){
var game;
beforeEach(function(){
game = new Game();
game.addPlayer("p1");
game.addPlayer("p2");
game.addPlayer("p3");
game.addPlayer("p4");
});
it("should not be possible to add two players with the same name",function(){
expect(function(){ game.addPlayer("p4");}).toThrow();
});
it("should find players",function(){
expect(game.findPlayer("p1")).toBeDefined();
expect(game.findPlayer("Hollow Man")).not.toBeDefined();
expect(game.findPlayer("p2")).toBeDefined();
expect(game.findPlayer("p3")).toBeDefined();
});
});
describe("detecting game status",function(){
it("should indicate 'new' when game hasn't started yet",function() {
var game = new Game();
expect(game.status()).toBe("new");
game.addPlayer("Player 1");
expect(game.status()).toBe("ready");
game.roll(1);
expect(game.status()).toBe("in progress");
for (var i=0;i<19;i++) game.roll(1);
expect(game.status()).toBe("completed");
})
});
|
import styled from 'styled-components/native';
import { View, Image } from 'react-native';
import { Button } from 'react-native-paper';
import { colors } from '../../infrastructure/theme/colors';
export const ButtonWrapper = styled(View)`
display: flex;
`
export const ButtonSecondary = styled(Button).attrs({
color: colors.brand.secondary,
mode: "contained"
})`
border-radius: 8px;
`
export const ButtonPrimary = styled(Button).attrs({
color: colors.brand.primary,
mode: "contained"
})`
border-radius: 8px;
`
|
import request from '@/utils/request'
import { urlFinance } from '@/api/commUrl'
const url = urlFinance
// const url = 'http://qa.oss.womaoapp.com/fwas-finance-admin/sys/'
// const url = 'http://192.168.0.226:8080/fwas-finance-admin/sys/'
const searchSettlementListUrl = url + 'settlement/searchSettlementListCtr'
const approvalSettmentUrl = url + 'settlement/updateSettlementStatusCtr'
const searchAuditorListUrl = url + 'payment/searchAuditorList'
const searchPaymentListUrl = url + 'payment/searchPaymentList'
const approvalPaymentUrl = url + 'payment/updatePaymentStatusCtr'
const searchPayeeListUrl = url + '/payment/searchPayeeList'
const payForPay = url + 'payment/payForPayment'
const download = url + 'order/downloadExcel'
// 核对发票以及结算信息
// 获取列表
export function searchSettlementList(params) {
return request({
url: searchSettlementListUrl,
method: 'post',
data: params
})
}
// 审核
export function approvalSettment(params) {
return request({
url: approvalSettmentUrl,
method: 'post',
data: params
})
}
// 详情
// 付款单
// 审核人
export function searchAuditorList() {
return request({
url: searchAuditorListUrl,
method: 'post',
data: {}
})
}
// 查询付款单列表
export function searchPaymentList(params) {
return request({
url: searchPaymentListUrl,
method: 'post',
data: params
})
}
// 审核
export function approvalPayment(params) {
return request({
url: approvalPaymentUrl,
method: 'post',
data: params
})
}
// 付款人
export function searchPayeeList() {
return request({
url: searchPayeeListUrl,
method: 'post',
data: {}
})
}
const getOrderListUrl = url + 'order/searchOrderList'
const getOrderRecordUrl = url + 'order/searchOrderWaterList'
const changeOrderStatusUrl = url + 'order/updateOrderStatus'
const getCashAcoountUrl = url + 'order/searchFundWaterList'
// 订单管理 列表
export function getOrderList(params) {
return request({
url: getOrderListUrl,
method: 'post',
data: params
})
}
// 订单流水流水
export function getOrderRecord(params) {
return request({
url: getOrderRecordUrl,
method: 'post',
data: params
})
}
// 修改订单状态
export function changeOrderStatus(params) {
return request({
url: changeOrderStatusUrl,
method: 'post',
data: params
})
}
// 资金流水
export function getCashAcoount(params) {
return request({
url: getCashAcoountUrl,
method: 'post',
data: params
})
}
// 下载资金流水查询及对账
export function downloadExcel(params) {
return request({
url: download,
method: 'post',
params,
responseType: 'arraybuffer'
})
}
// 立即支付
export function payForPayment(params) {
return request({
url: payForPay,
method: 'post',
data: params
})
}
|
function takeANumber(lineOfPeople, newName){
lineOfPeople.push(newName);
var numberInLine = lineOfPeople.length;
var msg = `Welcome, ${newName}. You are number ${numberInLine} in line.`
return msg;
}
function nowServing(lineOfPeople){
if (lineOfPeople.length > 0){
var currentCustomer = lineOfPeople.shift();
return `Currently serving ${currentCustomer}.`;
} else {
return "There is nobody waiting to be served!"
}
}
function currentLine(lineOfPeople){
var text, i;
if (lineOfPeople.length > 0){
text = "The line is currently: "
for(i = 0; i < lineOfPeople.length; i++){
if (lineOfPeople.length - i === 1){
text += `${i+1}. ${lineOfPeople[i]}`;
} else {
text += `${i+1}. ${lineOfPeople[i]}, `;
}
}
} else {
text = "The line is currently empty."
}
return text
}
|
const express = require("express");
const router = express.Router();
const passport = require("passport");
const customerController = require('../../controllers/api/customer_controller');
//for creating customers information
router.post('/createCustomer',customerController.createCustomer);
//for showing customers information
router.get('/showCustomer/:panNumber', passport.authenticate('jwt', {session: false}) ,customerController.showCustomer);
module.exports = router;
|
/*****************************************************************************************
* Copyright (C) 2016
* United Services Automobile Association
* All Rights Reserved
*
* File: usaa_video_siteCatalyst.js
*
* Target Chg Date Name Description
* ========== ========== ============ =========================
* 09/30/16 09/02/16 Justin Morales Fixed Sitecatalyst Defects
* 09/30/16 09/02/16 Gil Orona Added sitecatalyst to document system errors in linphone calls.
* 06/10/16 05/05/16 Vijay T Added Sitecatalyst for member & MSR disconnect.
* 05/13/2016 1/15/2016 Justin Morales Added new javascript functions for audio, mute, and hang up.
* 02/05/2016 1/20/2016 Justin Morales Created for video application.
*
*
*
*
*
*
* ******************************************************************************************/
function rarVideoSiteCatalyst(channel, event) {
resetRarVideoSiteCatalyst();
if (typeof USAA.ent.digitalData !== 'undefined' && typeof USAA.ent.digitalData.component !== 'undefined') {
USAA.ent.digitalData.page.activityType = "svc";
USAA.ent.digitalData.page.businessUnit = "ent";
USAA.ent.digitalData.page.productLOB = "ent";
USAA.ent.digitalData.page.productOffered = "n_a";
USAA.ent.digitalData.page.productQualifier = "n_a";
USAA.ent.digitalData.page.flowType = "rar";
if (event === 'rar_start') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.event.push({
'eventName': "tool_start"});
USAA.ent.DigitalAnalytics.pageView();
}
else if (event === 'rar_connected') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.event.push({
'eventName': "tool_complete"});
USAA.ent.DigitalAnalytics.pageView();
}
else if (event === 'c2see_closed_back') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.DigitalAnalytics.pageView();
}
else if (event === 'rar_flow') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'rar_options') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom51 = 'selected:c2s';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_closed' && event === 'c2see_closed_back') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom60 = 'c2see_closed_popup_back_button';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel ==='c2see_unavailable' && event === 'c2see_unavailable_back') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom60 = 'c2see_unavailable_popup_back_button';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_unsupported' && event === 'c2see_unsupported_back') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom60 = 'c2see_unsupported_popup_back_button';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_get_help' && event === 'c2see_decline') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom61 = 'c2see_get_help_decline';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_get_help' && event === 'c2see_accept') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom61 = 'c2see_get_help_accept';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_terms_conds' && event === 'c2see_terms_back') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom61 = 'c2see_terms_conds_back';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_terms_conds' && event === 'c2see_terms_accept') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom61 = 'c2see_terms_conds_accept';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_plugin_download' && event === 'c2see_plugin') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom62 = 'c2see_download_cancel';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_plugin_download' && event === 'c2see_plugin_accept') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom62 = 'c2see_download';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_multiple_devices' && event === 'c2see_multiple') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom63 = 'c2see_multiple_devices_Continue';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_only_camera_failed' && event === 'c2see_camera_failed') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom63 = 'c2see_Only_camera_failed_check_hardware';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_only_camera_failed' && event === 'c2see_camera_failed_continue') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom63 = 'c2see_Only_camera_failed_continue_without_camera';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_hardware_check_failure' && event === 'c2see_hardcheck_failed') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom64 = 'c2see_hardwarecheck_failure_Check_Hardware';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_mbrinqueue' && event === 'c2see_mbrinqueue_muted_on') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom53 = 'muted:on';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_mbrinqueue' && event === 'c2see_mbrinqueue_hang_on') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom54 = 'hangup:on';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_mbrinqueue' && event === 'c2see_mbrinqueue_shareself_on') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom55 = 'shareself:off';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_muted' && event === 'c2see_muted:on') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom53 = 'muted:on';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_hangup' && event === 'c2see_hangup:on') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom54 = 'hangup:on';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_shareself_off' && event === 'c2see_shareself:off') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom55 = 'shareself:off';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_mbronhold' && event === 'c2see_mbrhold_muted') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom53 = 'muted:on';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_mbronhold' && event === 'c2see_mbrhold_hangup') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom54 = 'hangup:on';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_mbronhold' && event === 'c2see_mbrhold_shareself') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom55 = 'shareself:off';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_connected' && event === 'c2see_connected_mutedOn') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom55 = 'muted:on';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_connected' && event === 'c2see_connected_mutedOff') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom55 = 'muted:off';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_mbrinqueue' && event === 'c2see_mbrinqueue_mutedOn') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom55 = 'muted:on';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_mbrinqueue' && event === 'c2see_mbrinqueue_mutedOff') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom55 = 'muted:off';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_mbronhold' && event === 'c2see_mbrhold_mutedOn') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom55 = 'muted:on';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_mbronhold' && event === 'c2see_mbrhold_mutedOff') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom55 = 'muted:off';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_connected' && event === 'c2see_connected_shareself:on') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom55 = 'shareself:on';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_connected' && event === 'c2see_connected_shareself:off') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom55 = 'shareself:off';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_mbrinqueue' && event === 'c2see_mbrinqueue_shareself:on') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom55 = 'shareself:on';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_msr_ended' && event === 'c2see_msr_ended') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_System_Disconnect' && event === 'c2see_System_Disconnect') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_mbrinqueue' && event === 'c2see_mbrinqueue_shareself:off') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom55 = 'shareself:off';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_mbronhold' && event === 'c2see_mbrhold_shareself:on') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom55 = 'shareself:on';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_mbronhold' && event === 'c2see_mbrhold_shareself:off') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom55 = 'shareself:off';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2s_mbr_ended' && event === 'c2s_mbr_ended') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom55 = 'hangup';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_mbrinqueue' && event === 'c2see_mbrinqueue_hangup') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom55 = 'hangup';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'c2see_mbronhold' && event === 'c2see_mbrhold__hangup') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom55 = 'hangup';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'share_my_video' && event === 'preview_video') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'share_my_video' && event === 'share_no') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom55 = 'share_video_selection:n';
USAA.ent.DigitalAnalytics.pageView();
}
else if (channel === 'share_my_video' && event === 'share_yes') {
USAA.ent.digitalData.page.pageDesc = channel;
USAA.ent.digitalData.component.attributes.custom55 = 'share_video_selection:y';
USAA.ent.DigitalAnalytics.pageView();
}
}
};
function resetRarVideoSiteCatalyst() {
if (typeof USAA.ent.digitalData !== 'undefined' &&
typeof USAA.ent.digitalData.component !== 'undefined')
{
USAA.ent.digitalData.component.attributes.toolOffered="";
USAA.ent.digitalData.page.activityType = "";
USAA.ent.digitalData.page.businessUnit = "";
USAA.ent.digitalData.page.productLOB = "";
USAA.ent.digitalData.page.productOffered = "";
USAA.ent.digitalData.page.productQualifier = "";
USAA.ent.digitalData.page.flowType = "";
USAA.ent.digitalData.page.pageDesc = "";
USAA.ent.digitalData.event = [];
USAA.ent.digitalData.component.attributes.custom51 = "";
USAA.ent.digitalData.component.attributes.custom52 = "";
USAA.ent.digitalData.component.attributes.custom53 = "";
USAA.ent.digitalData.component.attributes.custom54 = "";
USAA.ent.digitalData.component.attributes.custom55 = "";
USAA.ent.digitalData.component.attributes.custom56 = "";
USAA.ent.digitalData.component.attributes.custom57 = "";
USAA.ent.digitalData.component.attributes.custom58 = "";
USAA.ent.digitalData.component.attributes.custom59 = "";
USAA.ent.digitalData.component.attributes.custom60 = "";
USAA.ent.digitalData.component.attributes.custom61 = "";
USAA.ent.digitalData.component.attributes.custom62 = "";
USAA.ent.digitalData.component.attributes.custom63 = "";
USAA.ent.digitalData.component.attributes.custom64 = "";
USAA.ent.digitalData.component.attributes.custom65 = "";
}
}
function muteOnButtonContainerSiteCatalyst() {
if (document.getElementById("videoobject").className === '') {
rarVideoSiteCatalyst('c2see_connected', 'c2see_connected_mutedOn');
} else if (document.getElementById("holdorresume").style.display === 'block') {
rarVideoSiteCatalyst('c2see_mbronhold', 'c2see_mbrhold_mutedOn');
} else if (document.getElementById("callwithnovideo").style.display === 'block') {
rarVideoSiteCatalyst('c2see_mbrinqueue', 'c2see_mbrinqueue_mutedOn');
}
}
function muteOffButtonContainerSiteCatalyst() {
if (document.getElementById("videoobject").className === '') {
rarVideoSiteCatalyst('c2see_connected', 'c2see_connected_mutedOff');
} else if (document.getElementById("holdorresume").style.display === 'block') {
rarVideoSiteCatalyst('c2see_mbronhold', 'c2see_mbrhold_mutedOff');
} else if (document.getElementById("callwithnovideo").style.display === 'block') {
rarVideoSiteCatalyst('c2see_mbrinqueue', 'c2see_mbrinqueue_mutedOff');
}
}
function disconnectButtonContainerSiteCatalyst() {
if(document.getElementById("videoobject").className === '') {
rarVideoSiteCatalyst('c2s_mbr_ended', 'c2s_mbr_ended');
} else if(document.getElementById("holdorresume").style.display === 'block') {
rarVideoSiteCatalyst('c2see_mbronhold', 'c2see_mbrhold__hangup');
} else if(document.getElementById("callwithnovideo").style.display === 'block') {
rarVideoSiteCatalyst('c2see_mbrinqueue', 'c2see_mbrinqueue_hangup');
}
}
function shareViewOnMsrButtonContainerSiteCatalyst() {
if(document.getElementById("videoobject").className === '') {
rarVideoSiteCatalyst('c2see_connected', 'c2see_connected_shareself:on');
} else if(document.getElementById("holdorresume").style.display === 'block') {
rarVideoSiteCatalyst('c2see_mbronhold', 'c2see_mbrhold_shareself:on');
} else if(document.getElementById("callwithnovideo").style.display === 'block') {
rarVideoSiteCatalyst('c2see_mbrinqueue', 'c2see_mbrinqueue_shareself:on');
}
}
function shareViewOffMsrButtonContainerSiteCatalyst() {
if(document.getElementById("videoobject").className === '') {
rarVideoSiteCatalyst('c2see_connected', 'c2see_connected_shareself:off');
} else if(document.getElementById("holdorresume").style.display === 'block') {
rarVideoSiteCatalyst('c2see_mbronhold', 'c2see_mbrhold_shareself:off');
} else if(document.getElementById("callwithnovideo").style.display === 'block') {
rarVideoSiteCatalyst('c2see_mbrinqueue', 'c2see_mbrinqueue_shareself:on');
}
}
|
"use strict";
const { app, BrowserWindow, Menu, ipcMain } = require("electron");
const { autoUpdater } = require("electron-updater");
const { is } = require("electron-util");
const { readFileSync } = require("fs");
const {
ensureOnline,
createTray,
updateMediaControls
} = require("./helpers.js");
const config = require("./config");
const menu = require("./menu");
app.setAppUserModelId("com.botallen.youtubemusic");
// It's commented out as it throws an error if there are no published versions.
if (!is.development) {
const FOUR_HOURS = 1000 * 60 * 60 * 4;
setInterval(() => {
autoUpdater.checkForUpdates();
}, FOUR_HOURS);
autoUpdater.checkForUpdates();
}
// Prevent window from being garbage collected
let mainWindow;
const createMainWindow = async () => {
const win = new BrowserWindow({
title: app.name,
show: false,
width: 1280,
height: 800,
autoHideMenuBar: true,
icon: config.get("icons.default"),
webPreferences: {
nodeIntegration: true,
devTools: false
}
});
win.on("ready-to-show", () => {
win.show();
});
win.on("close", event => {
// Dereference the window
// For multiple windows store them in an array
event.preventDefault();
win.blur();
if (is.macos) {
// On macOS we're using `app.hide()` in order to focus the previous window correctly
app.hide();
} else {
win.hide();
}
});
await win.loadURL("https://music.youtube.com");
return win;
};
// Prevent multiple instances of the app
if (!app.requestSingleInstanceLock()) {
app.quit();
}
app.on("second-instance", () => {
if (mainWindow) {
if (mainWindow.isMinimized()) {
mainWindow.restore();
}
mainWindow.show();
}
});
app.on("window-all-closed", () => {
if (!is.macos) {
app.quit();
}
});
app.on("activate", async () => {
if (!mainWindow) {
mainWindow = await createMainWindow();
}
});
(async () => {
await Promise.all([ensureOnline(), app.whenReady()]);
Menu.setApplicationMenu(menu);
mainWindow = await createMainWindow();
createTray(mainWindow);
mainWindow.webContents.executeJavaScript(
readFileSync(config.get("browser"), "utf8")
);
})();
ipcMain.on("player-bar-status", (_, status) => {
if (is.windows) {
updateMediaControls(mainWindow, status);
}
});
|
const mongoose = require('mongoose')
var bondSchema = new mongoose.Schema({
cpf: { type: String, required: true },
n_cartao: { type: String, required: true }
})
const Bond = mongoose.model('Bond', bondSchema)
module.exports = Bond
|
import React, { useEffect, useState } from 'react'
import { useHistory } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import { Layout } from "antd"
import { unescape } from 'lodash'
import { checkCode } from "../features/authSlice"
import "./style.css"
export default function Auth() {
const history = useHistory()
const dispatch = useDispatch();
const { done, err } = useSelector(state => state.auth);
const [errors, setErrors] = React.useState({})
useEffect(() => {
let newParams = new URLSearchParams(window.location.search);
let code = newParams.get("code");
let error_description = newParams.get("error_description");
if (error_description) {
setErrors({
error: unescape(error_description)
})
}
if (code) {
dispatch(checkCode({ code }))
}
}, []);
useEffect(() => {
if (done) {
history.push("/home");
}
if (err) {
setErrors({
error: err
})
}
}, [done]);
return (
<Layout style={{ height: '100vh', justifyContent: 'center', alignItems: 'center', display: 'flex' }}>
{errors?.error && <div className="error">{errors?.error}</div>}
</Layout>
)
}
|
function TracksBoardUI() {
var d3 = wavesUI.timeline.d3;
var timeline;
var miniTimeline;
var scrollSegment;
var timeRulerAxis;
var timeRulerUIParentContainer;
var timeRulerUI;
var id;
var type;
var beatGrid;
var parentContainerId;
var tracksContainerId;
var miniTimelineContainerId;
var timeRulerContainerId;
var width;
var height;
var tracks = {};
var listeners = {};
var _;
this.get_id = function() { return _.id; }
this.get_type = function() { return _.type; }
// params: id, type, beatGrid, initialTimeDomain, width, height, parentContainerId
this.init = function (params) {
_ = this;
listeners = {
'board:set-current-time': {},
'board:set-time-domain': {},
'board:track:add': {},
'board:track:delete': {},
}
id = params.id;
type = params.type;
tracksContainerId = get_tracks_container_id(id, type);
miniTimelineContainerId = get_mini_timeline_container_id(id, type);
timeRulerContainerId = get_time_ruler_container_id(id, type);
parentContainerId = params.parentContainerId;
var selection;
if (parentContainerId)
selection = d3.select('#'+parentContainerId);
else {
parentContainerId = get_id_prefix(id, type)
selection = d3.select('body').append('div').attr('id', parentContainerId);
}
selection.append('div').attr('id', miniTimelineContainerId);
selection.append('div').attr('id', timeRulerContainerId);
selection.append('div').attr('id', tracksContainerId);
beatGrid =params.beatGrid;
initialTimeDomain = params.initialTimeDomain;
width = params.width;
height = params.height;
_ = this;
timeline = new wavesUI.timeline().xDomain(initialTimeDomain).width(width).height(height);
var aux = new wavesUI.segment().params({}).data([]);
timeline.add(aux);
create_mini_timeline(miniTimelineContainerId, width, 15, initialTimeDomain);
create_time_ruler(timeRulerContainerId, width, 15, initialTimeDomain);
}
function create_mini_timeline(containerId, width, height, domain) {
miniTimeline = new wavesUI.timeline()
.xDomain(domain)
.width(width)
.height(height);
scrollSegment = new wavesUI.segment()
.params({
interactions: {
editable: true,
selectable: true
},
opacity: 0.3,
handlerOpacity: 1
})
.data([{start: domain[0], duration: domain[1]}])
.color('grey');
miniTimeline.add(scrollSegment);
miniTimeline.on('drag', function(domElement, mouseEvent) {
_.set_time_domain(domElement.d.start, domElement.d.start + domElement.d.duration)
});
d3.select("#"+containerId).call(miniTimeline.draw);
}
function create_time_ruler(containerId, width, height, domain) {
var timeRulerUIParentContainer = d3.select(containerId).append('svg')
.attr('width', width)
.attr('height', height);
timeRulerAxis = d3.svg.axis()
.scale(timeline.xScale)
.tickSize(1,1)
.tickFormat(function(d) {
var form = "";
if (d > 3600)
form = '%Hh%Mm%Ss';
else if (d >= 60)
form = '%Mm%Ss';
else
form = '%Ss';
if (d % 1 !== 0)
form += '%Lms';
var date = new Date(d * 1000);
var format = d3.time.format(form);
return format(date);
});
timeRulerUI = timeRulerUIParentContainer.append('g')
.attr('class', 'x-axis')
.attr('transform', 'translate(0, 0)')
.attr('fill', '#555')
.attr('background', 'yellow')
.call(timeRulerAxis);
d3.select("#"+containerId).call(miniTimeline.draw);
}
// params: id, type, height (opt)
this.add_track = function (params) {
var track = new TrackUI();
var td = params;
var domId = get_track_container_id(td.id, td.type);
d3.select('#'+tracksContainerId).append('div').attr('id', domId);
track.init({
id: td.id,
type: td.type,
initialTimeDomain: initialTimeDomain,
width: width,
height: td.height || height,
beatGrid: beatGrid,
parentContainerId: domId
});
tracks[td.id] = track;
d3.select('#'+domId).append('br');
d3.select('#'+domId).append('div').attr('id', 'track-'+td.id+'-controls');
this.emit('board:track:add', {input: td, track: track});
return track;
}
this.remove_track = function(id) {
var domId = get_track_container_id(tracks[id].get_id(), tracks[id].get_type());
tracks[id].destroy();
d3.select('#'+domId).remove();
delete tracks[id];
this.emit('board:track:delete', {id: id});
}
this.get_track = function(id) {
return tracks[id];
}
this.set_scroll_time_range = function(end) {
for (var id in tracks)
tracks[id].set_scroll_time_range(end);
}
this.set_time_domain = function(start, end) {
own_set_time_domain(start, end);
for (var id in tracks)
tracks[id].set_time_domain(start, end);
}
this.set_current_time = function(time) {
for (var id in tracks)
tracks[id].set_current_time(time);
_.emit('board:set_current_time', { time: time });
}
this.toggle_follow_cursor = function(_follow) {
for (var id in tracks)
tracks[id].toggle_follow_cursor(_follow);
}
this.toggle_snap_to_grid = function(_snap) {
for (var id in tracks)
tracks[id].toggle_snap_to_grid(_snap);
}
this.set_beat_grid = function (newGrid, render) {
for (var id in tracks)
tracks[id].set_beat_grid(newGrid, true);
}
function own_set_time_domain (start, end) {
timeline.xScale.domain([start, end]);
timeline.xZoomSet();
timeRulerUI.call(timeRulerAxis);
}
this.get_track_controls_dom = function(trackId) {
//TODO
}
this.add_event_listener = function(eventType, callback, trackId) {
if (trackId) {
tracks[trackId].add_event_listener(eventType, callback);
} else if (eventType.search("element")==-1 && eventType.search("layer")==-1) {
var Ls = listeners[eventType];
Ls[callback] = callback;
} else {
for (var i in tracks)
tracks[trackId].add_event_listener(eventType, callback);
}
}
this.remove_event_listener = function(eventType, callback, trackId) {
if (trackId) {
tracks[trackId].remove_event_listener(eventType, callback);
} else
delete listeners[eventType][callback];
}
this.emit = function(eventType, params) {
var Ls = listeners[eventType];
if (Ls) {
var callbacksNames = Object.getOwnPropertyNames(Ls)
for (var i=0; i<callbacksNames.length; i++)
Ls[callbacksNames[i]](params);
}
}
this.destroy = function() {
for (var i in tracks)
tracks[i].destroy();
tracks = undefined;
d3 = undefined;
timeline = undefined;
miniTimeline = undefined;
scrollSegment = undefined;
timeRulerAxis = undefined;
timeRulerUIParentContainer = undefined;
timeRulerUI = undefined;
id = undefined;
beatGrid = undefined;
parentContainerId = undefined;
tracksContainerId = undefined;
miniTimelineContainerId = undefined;
timeRulerContainerId = undefined;
width = undefined;
height = undefined;
tracks = undefined;
listeners = undefined;
_ = undefined;
}
function get_id_prefix(id, type) { return type + "-tracks-board-" + id; }
function get_tracks_container_id(id, type) { return get_id_prefix(id, type) + "-tracks"; }
function get_mini_timeline_container_id(id, type) { return get_id_prefix(id, type) + "-miniTimeline"; }
function get_time_ruler_container_id(id, type) { return get_id_prefix(id, type) + "-timeRuler"; }
function get_track_container_id(id, type) { return get_id_prefix(id, type) + "-master-container";}
}
|
import axios from "axios";
import router from "@/router/index";
import SERVER from "@/api/spring";
export default {
postuserData({ commit }, info) {
axios
.post(info.location, info.data)
.then((res) => {
commit("SET_USERID", res.data.userid);
router.push({ path: "/perparation" });
})
.catch(() => alert("아이디 또는 비밀번호가 틀렸습니다"));
},
signup({ dispatch }, signupData) {
const info = {
location: SERVER.URL + SERVER.ROUTES.users,
data: signupData,
};
dispatch("postuserData", info);
},
logout({ commit }) {
commit("SET_USERID", null);
router.push({path: "/"})
},
login({ dispatch }, loginData) {
const info = {
location: SERVER.URL + SERVER.ROUTES.login,
data: loginData,
};
dispatch("postuserData", info);
}
}
|
/**
* Created by rob on 6/10/2017.
*/
import React, { Component } from 'react';
class ContactPage extends Component {
render() {
return (
<div className="ContactPage">
<p>
hello from route wee Haw
</p>
</div>
);
}
}
export default ContactPage;
|
import {Picture} from './pictures.js';
//继承Picture类
function ArcPic(parameter) {
Picture.call(this,'A',parameter);
}
ArcPic.prototype = new Picture();
ArcPic.prototype.constructor = ArcPic;
//重写topath方法
ArcPic.prototype.toPath = function(){
return this.command+this.parameter[0]+' '+this.parameter[1]+' '+this.parameter[2]+' '+
this.parameter[3]+' '+this.parameter[4]+' '+this.parameter[5]+' '+this.parameter[6];
};
//重写addLocation方法
ArcPic.prototype.addLocation = function (incX, incY) {
this.parameter[5] += incX;
this.parameter[6] += incY;
};
export {ArcPic};
|
/**
* @file TextBox.js
* @author leeight
*/
import {DataTypes, defineComponent} from 'san';
import {create} from './util';
import {asInput} from './asInput';
const cx = create('ui-textbox');
/* eslint-disable */
const template = `<div class="{{mainClass}}">
<div s-if="addon && addonPosition === 'begin'" class="${cx('addon')}">{{addon}}</div>
<textarea s-if="multiline"
s-ref="inputEl"
on-input="onInput"
on-keyup="onKeyUp($event)"
on-keydown="onKeyDown($event)"
on-keypress="onKeyPress($event)"
value="{=value=}"
disabled="{{disabled}}"
placeholder="{{placeholder}}"
style="{{textboxStyle}}"></textarea>
<input s-else
s-ref="inputEl"
on-input="onInput"
on-keyup="onKeyUp($event)"
on-keydown="onKeyDown($event)"
on-keypress="onKeyPress($event)"
on-focus="onFocus($event)"
on-blur="onBlur($event)"
on-click="onClick($event)"
value="{=value=}"
min="{{min}}",
max="{{max}}"
step="{{step}}"
type="{{type}}"
disabled="{{disabled}}"
placeholder="{{placeholder}}"
style="{{textboxStyle}}" />
<div s-if="addon && addonPosition === 'end'" class="${cx('addon', 'addon-end')}">{{addon}}</div>
</div>`;
/* eslint-enable */
const TextBox = defineComponent({
template,
computed: {
mainClass() {
return cx.mainClass(this);
},
textboxStyle() {
return cx.mainStyle(this);
}
},
initData() {
return {
disabled: false,
autofocus: false,
focusPosition: 'end', // 'end' | 'begin' | 'all'
type: 'text',
multiline: false,
skin: '',
placeholder: '',
addon: '',
addonPosition: 'begin', // 'begin' | 'end'
width: null,
height: null
};
},
dataTypes: {
/**
* 控件的禁用状态
*
* @default false
*/
disabled: DataTypes.bool,
/**
* 是否默认获取焦点
*
* @default false
*/
autofocus: DataTypes.bool,
/**
* 光标出现的位置
*
* @default end
*/
focusPosition: DataTypes.string,
/**
* 单行文本框的输入类型,可以控制输入 email, number, url 等格式
*
* @default text
*/
type: DataTypes.string,
/**
* 获取或者设置控件的值
*
* @bindx
*/
value: DataTypes.string,
/**
* 是否展示成多行输入的文本框(textarea)
*
* @default false
*/
multiline: DataTypes.bool,
/**
* 皮肤样式
*/
skin: DataTypes.string,
/**
* 设置 placeholder 的内容
*/
placeholder: DataTypes.string,
/**
* 输入框的前缀或者后缀文案
*/
addon: DataTypes.string,
/**
* addon 文案的位置,可以设置 begin 或者 end
*
* @default begin
*/
addonPosition: DataTypes.string,
/**
* 输入框的宽度
*/
width: DataTypes.number,
/**
* 输入框的高度
*/
height: DataTypes.number,
/**
* 当 type 设置成 number 的时候,有效
*/
min: DataTypes.number,
/**
* 当 type 设置成 number 的时候,有效
*/
max: DataTypes.number,
/**
* 当 type 设置成 number 的时候,有效
*/
step: DataTypes.number
},
attached() {
const autofocus = this.data.get('autofocus');
if (autofocus) {
this.focus();
}
},
focus() {
const inputEl = this.ref('inputEl');
const focusPosition = this.data.get('focusPosition');
if (inputEl) {
if (document.activeElement === inputEl) {
return;
}
if (typeof inputEl.selectionStart === 'number') {
if (focusPosition === 'end') {
// 光标在内容的后面
inputEl.selectionStart = inputEl.selectionEnd = this.data.get('value').length;
}
else if (focusPosition === 'all') {
// 全选
inputEl.selectionStart = 0;
inputEl.selectionEnd = this.data.get('value').length;
}
}
inputEl.focus();
}
},
onInput() {
const value = this.data.get('value');
this.fire('input', {value});
},
onFocus(e) {
this.fire('focus', e);
},
onBlur(e) {
this.fire('blur', e);
},
onKeyUp(e) {
this.fire('keyup', e);
},
onKeyDown(e) {
this.fire('keydown', e);
},
onKeyPress(e) {
const keyCode = e.which || e.keyCode;
if (keyCode === 13) {
this.fire('enter', e);
}
this.fire('keypress', e);
},
onClick(e) {
this.fire('click', e);
}
});
export default asInput(TextBox);
|
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import Vuetify from 'vuetify';
import 'vuetify/dist/vuetify.min.css';
import VueStar from 'vue-star';
import VModal from 'vue-js-modal';
import VueSweetalert2 from 'vue-sweetalert2';
Vue.use(VModal, { dynamic: true });
Vue.use(Vuetify);
Vue.config.productionTip = false;
Vue.component('VueStar', VueStar);
Vue.use(VueSweetalert2);
window.Kakao.init('9408758ec57aaebe1b8dba4464919e72');
window.Kakao.isInitialized();
new Vue({
vuetify: new Vuetify(),
router,
store,
render: (h) => h(App),
}).$mount('#app');
|
(function () {
"use strict";
class DangerZone {
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.hitbox = new RectHitbox(x, y, width, height);
this.active = false;
}
activate() {
this.active = true;
}
deactivate() {
this.active = false;
}
isActive() {
return this.active;
}
}
window.DangerZone = DangerZone;
}());
|
import { CartContext } from "./CartContext";
import "./cart.css";
import { Link } from "react-router-dom";
import CartItem from "./CartItem";
import { useContext } from "react";
function Cart() {
const { carrito, clear, CartQuantity, CartPrice } = useContext(CartContext);
return (
<div>
{CartQuantity() > 0 ? (
<div>
<table id="cart" className="table table-hover table-condensed">
<thead className="category-cart">
<tr>
<th className="category-1">Producto</th>
<th className="category-2">Precio</th>
<th className="category-3">Cantidad</th>
<th className=" category-4 text-center">Subtotal</th>
<th className="category-5"></th>
</tr>
</thead>
<tbody>
{carrito.map((articulo) => (
<CartItem articulo={articulo} />
))}
</tbody>
</table>
<tfoot>
<tr>
<td>
<Link to="/" className="btn btn-warning">
<i className="fa fa-angle-left"></i> Seguir Comprando
</Link>
</td>
<td>
<Link
to="/"
onClick={clear}
className="btn btn-clear btn-block"
>
Reiniciar Carrito <i className="fa fa-angle-right"></i>
</Link>
</td>
<td colspan="2" className="hidden-xs"></td>
<td className="hidden-xs text-center">
<strong className="total">Total: ${CartPrice()}</strong>
</td>
<td>
<Link to="/firebase" className="btn btn-success btn-block">
Pagar <i className="fa fa-angle-right"></i>
</Link>
</td>
</tr>
</tfoot>
</div>
) : (
<div>
<p>No hay articulo! </p>
</div>
)}
</div>
);
};
export default Cart;
|
import React from 'react';
import groupBy from 'lodash/groupBy';
const MONTHS_SHORT = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const getDisplayName = WrappedComponent => {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';
};
const groupByMonths = data => {
const currentYear = (new Date()).getFullYear();
const filteredDataByYear = data.filter(item => item.date.indexOf(currentYear) !== -1);
const groupedData = groupBy(filteredDataByYear, item => {
return (new Date(item.date)).getMonth();
});
return Object.keys(groupedData).map(month => ({
id: month,
amount: groupedData[month].reduce((a, b) => a + b.amount, 0),
month: MONTHS_SHORT[month]
}));
};
const groupByYears = data => {
const groupedData = groupBy(data, item => {
return item.date.substring(0, 4);
});
return Object.keys(groupedData).map(year => ({
id: year,
amount: groupedData[year].reduce((a, b) => a + b.amount, 0),
year: parseInt(year, 10)
}));
};
const sortDesc = data => {
return data.sort((a, b) => b.amount - a.amount);
};
function withAggregation(method) {
return function (WrappedComponent) {
function WithAggregation(props) {
const { list } = props;
switch (method) {
case 'groupByMonths': {
return (
<WrappedComponent list={groupByMonths(list)} />
);
}
case 'groupByYears': {
return (
<WrappedComponent list={groupByYears(list)} />
);
}
case 'sortDesc': {
return <WrappedComponent list={sortDesc(list)} />
}
default: {
return <WrappedComponent {...props} />
}
}
}
WithAggregation.displayName = `WithAggregation(${getDisplayName(WrappedComponent)})`;
return WithAggregation;
}
}
export default withAggregation;
|
import React from 'react'
export default function Subcribe() {
return (
<div className='section has-background-primary-light is-flex is-align-items-center is-justify-content-center is-flex-direction-column'>
<h2 className='has-text-link is-size-2 has-text-weight-semibold'>
Subscribe to Newsletter
</h2>
<p className='has-text-link is-size-6 my-5'>
Enter your email address to register to our newsletter subscription
delivered on regular basis!
</p>
<form className='filed is-flex px-6 py-5'>
<input
type='email'
placeholder='Email Adress'
className='input is-primary has-background-light '
/>
<button className='button is-primary is-capitalized '>Subcribe</button>
</form>
</div>
)
}
|
export default {
label: 'Pronoun',
id: 'pronoun',
list: [
{
id: 'reading',
type: 'passage',
label: 'Reading',
data: {
title: 'Pronouns',
text: [
`Pronoun are words used in place of nouns, to avoid repetition of nouns.`,
'# Personal Pronouns',
`They are used to indicate a specific or group of people or things.`,
`A personal pronoun can be used as subject or object in a sentence. In the below word pairs, the first one is used as subject and the second one is used as object.`,
{
type: 'hilight',
text: `I , me
we, us
she, her
he, him
they, them`
},
`'You' will be used as both subject and object.`,
'# Possesive Pronouns',
`They are used to show ownership or possession. eg: mine, yours, his, hers, ours, theirs`,
`# Demonstrative Pronouns`,
`They are used to point at something. eg: this, that, these, those, their`,
'# Reflexive Pronouns',
`It is used as an object that refers back to the subject. eg: myself, yourself, herself, himself, itself`,
{
type: 'hilight',
text: `She herself cooked the food.
I myself saw him.
He himself cut the cake.`
},
`# Emphatic Pronouns`,
`They are used to put emphasis on the subject. So usually they follow the subject.`,
{
type: 'hilight',
text: `He cuts himself while chopping the vegetables.
I don't trust myself in tough times.`
}
]
}
},
{
type: 'match',
label: 'Match Related Pronouns',
id: 'complete-word',
data: {
lang: 'en',
title: 'Match the pronouns that have similar meaning.',
text: `I, Me
He, Him
She, Her
They, Them
We, Us`
}
},
{
id: 'i-me',
label: 'I vs Me',
type: 'fillupOptions',
data: {
title: "Fill in the blanks with 'I' and 'me'.",
text: `Could you pass *me* the salt?
*I* don't want to go out now.
Vinoth and *I* are going to the movies.
Am *I* invited?
She gave *me* some coins.`,
options: 'I, me'
}
},
{
id: 'we-us',
label: 'We vs Us',
type: 'fillupOptions',
data: {
title: "Fill in the blanks with 'we' and 'us'.",
text: `Let *us* cross the road.
Can *we* all go to the swimming pool tomorrow?
*We* were talking to the principal.
Thank you for driving *us* to the market.
The teacher asked *us* to form a circle.`,
options: 'we, us'
}
},
{
id: 'she-her',
label: 'She vs Her',
type: 'fillupOptions',
data: {
title: "Fill in the blanks with 'she' and 'her'.",
text: `I gave *her* the books.
*She* doesn't have a pen.
*She* is so clever.
If I tell Roshima, *she* might tell Sunitha.
I will talk to *her* about this issue.`,
options: 'she, her'
}
},
{
id: 'they-them',
label: 'They vs Them',
type: 'fillupOptions',
data: {
title: "Fill in the blanks with 'they' and 'them'.",
text: `We asked *them* to keep the door open.
If you build it, *they* will come.
*They* are very nice people.
What do *they* want?
I have lost my keys. I can't find *them* anywhere.`,
options: 'they, them'
}
},
{
id: 'he-him',
label: 'He vs Him',
type: 'fillupOptions',
data: {
title: "Fill in the blanks with 'he' and 'him'.",
text: `If you see David, give *him* these books.
Does *he* want some coffee?
*He* is a wise man.
Did Mohan get the promotion *he* wanted?
I didn't recognize *him*.`,
options: 'he, him'
}
},
{
label: 'Pronouns',
type: 'fillupOptions',
data: {
text:
"Saranya likes to cook. Everyone likes *her (his) * cooking. \nKumar and his brother enjoy watching action films. This movie is for *them(they) *. \nDo you like movies? Please join *us (them) * at the theatre. \nI will meet Sangeetha tomorrow. I am meeting *her (him)* for the first time. \nYou left *your (yours) * text books on the table. \nI want to know *who (whom)* is going to play as villain. \nPlease eat whatever you want. The choice is *yours (your)*. \nRekha told *him (his)* about the celebration next week. \nRahul cannot come with *us (them)* today. \nShe grows Jasmine on her terrace. *They (Them)* smell sweet. \nPeacock is our national bird. *It (They)* has beautiful feathers. \nRam will visit *his (her) * grandmother this week. \nDon't walk fast. *We (Us)* feel tired. \nEvery Sunday, we meet *them (they)* at the sea shore. "
},
id: '200'
},
{
type: 'classifySentence',
label: 'Reflexive vs Emphatic Pronouns',
data: {
title:
'Classify the below sentences as Reflexive and Emphatic Pronouns.',
types: [
{
name: 'Reflexive',
text: `He cuts *himself* while chopping the vegetables.
I don't trust *myself* in tough times.
We blame *ourselves* for the accident.
He was speaking to *himself*.
Be careful. You may hurt *yourself*.`
},
{
name: 'Emphatic',
text: `She *herself* cooked the food.
I *myself* saw him.
He *himself* cut the cake.
We will watch the game *ourselves*.
We saw the President *himself*.`
}
]
},
id: 'reflexive-emphatic'
}
]
};
|
module.exports = {
port: 7000,
mongo: 'mongodb://localhost'
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.