text
stringlengths 7
3.69M
|
|---|
import { cid } from "is-ipfs"
import remove from "lodash/remove"
export default function makeIPFSUrl(
url,
ipfsHost = "https://gateway.pinata.cloud/ipfs/"
) {
if (cid(url)) return `${ipfsHost}${url}`
const urlArray = url.split("/")
const cidIndex = urlArray.findIndex((curr) => cid(curr))
const newCidPath = remove(urlArray, (_, i) => i >= cidIndex).join("/")
return `${ipfsHost}${newCidPath}`
}
|
/**
* Created by chaijiang on 2017/3/31.
*/
import React, {Component} from 'react'
import AppDispatcher from '../dispatcher/AppDispatcher'
import AppStore from '../stores/AppStore'
import Pandect from './parts/FeedRefresh/Pandect'
import { Row, Col } from 'antd';
import { Select } from 'antd';
const Option = Select.Option;
import { DatePicker } from 'antd';
const { RangePicker } = DatePicker;
import { Tabs, Icon } from 'antd';
const TabPane = Tabs.TabPane;
module.exports= class Test1 extends Component {
constructor(props) {
super(props)
this.state = {
buss_options:"iphone",
}
this.handleChange = this.handleChange.bind(this)
}
/****/
/**************************页面加载前********************************************/
componentWillMount(){
AppStore.addChangeListener(this._onChange.bind(this))
}
/**************************页面加载前********************************************/
/***************AppStore数据改变后触发事件中回调函数的绑定******************************/
componentDidMount(){
}
_onChange(){
this.setState(AppStore)
}
/***************AppStore数据改变后触发事件中回调函数的绑定******************************/
/******************************************改变端口号对应事件**********************/
handleChange(value){ //业务名
}
handleClick(value){ //平台(选平台时联动改变业务名还有版本中的值)
}
handleTap(value){ //版本
}
ClickChange(value){ //颗粒度
}
onChange(time, timeString) { //时间
}
/******************************************改变端口号对应事件**********************/
render() {
const styles = {
root: {
width: '100%',
height: 'auto',
minHeight: '100%',
margin: 0,
padding: '0',
background: 'rgba(78, 94, 120, 1)',
fontSize:16,
color:'white'
},
choose: {
width: '100%',
height: 'auto',
textAlign: 'center',
padding: '10px 20px 10px 20px',
fontcolor:'white',
background:'rgba(247, 247, 247, 1)',
color:'black'
},
col:{
padding:'10px 0px'
},
tab:{
width:'100%',
height: 'auto',
margin:'0 auto',
padding:0,
}
}
//选择框中循环读出数据生成选择选项
function getOptions(type){
const options=AppStore.data[type].map(obj => {
return(
<Option key={obj.key}>{obj.value}</Option>
)
})
return options
}
//读取业务线中数据
const business_select = getOptions("business")
//读取微博版本中数据
const version_select = getOptions("version")
//读取网络类型中数据
const netType_select = getOptions("netType")
//读取机型中数据
const computerType_select = getOptions("computerType")
return (
<div style={styles.root}>
<div style={styles.choose}>
<Row >
<Col xs={8} md={8} lg={3} style={styles.col}>
</Col>
<Col xs={8} md={8} lg={6} style={styles.col}>
<span>业务线:</span>
<Select defaultValue="111" style={{ width: '70%'}} size="large" onChange={this.handleClick}>
{business_select}
</Select>
</Col>
<Col xs={8} md={8} lg={6} style={styles.col}>
<span>微博版本:</span>
<Select defaultValue="7.2.0" multiple='True' style={{ width: '65%',}} size="large" onChange={this.handleChange}>
{version_select}
</Select>
</Col>
<Col xs={8} md={8} lg={6} style={styles.col}>
<span>网络类型:</span>
<Select defaultValue="All" style={{ width: '70%', }} size="large" onChange={this.handleTap}>
{netType_select}
</Select>
</Col>
<Col xs={8} md={8} lg={3} style={styles.col}>
</Col>
</Row>
<Row>
<Col xs={8} md={8} lg={3} style={styles.col}>
</Col>
<Col xs={8} md={4} lg={5} style={styles.col}>
<span>手机平台:</span>
<Select defaultValue="All" style={{ width: '60%' }} size="large" onChange={this.ClickChange}>
{computerType_select}
</Select>
</Col>
<Col xs={8} md={4} lg={5} style={styles.col}>
<span>时间粒度:</span>
<Select defaultValue="d" style={{ width: '60%' }} size="large" onChange={this.ClickChange}>
<Option value="d">一天</Option>
<Option value="w">一周</Option>
</Select>
</Col>
<Col xs={16} md={16} lg={8} style={styles.col}>
<span>时间:</span>
<RangePicker style={{width: '85%' }}
size="large" onChange={this.onChange}/>
</Col>
<Col xs={8} md={8} lg={3} style={styles.col}>
</Col>
</Row>
</div>
<div style={styles.tab}>
<Tabs defaultActiveKey="1" type="card" onChange={this.onChange} style={{marginBottom:0}}>
<TabPane tab="总览" key="1">
<Pandect data={AppStore.data.pansect}/>
</TabPane>
<TabPane tab="客户端性能" key="2">2222222</TabPane>
<TabPane tab="MAPI性能" key="3">2222222</TabPane>
<TabPane tab="平台性能" key="4">2222222</TabPane>
<TabPane tab="错误统计" key="5">2222222</TabPane>
</Tabs>
</div>
</div>
)
}
}
|
document.getElementById("notifier").innerHTML = "It's X's turn"
var win = "n";
function winChecker() {
if (cell1.childNodes[1].innerHTML == cell2.childNodes[1].innerHTML && cell1.childNodes[1].innerHTML == cell3.childNodes[1].innerHTML && cell1.childNodes[1].innerHTML != "") {
document.getElementById("notifier").innerHTML = cell1.childNodes[1].innerHTML + " wins!";
win = "y";
}
else if (cell1.childNodes[1].innerHTML == cell4.childNodes[1].innerHTML && cell1.childNodes[1].innerHTML == cell7.childNodes[1].innerHTML && cell1.childNodes[1].innerHTML != "") {
document.getElementById("notifier").innerHTML = cell1.childNodes[1].innerHTML + " wins!"
win = "y";
}
else if (cell1.childNodes[1].innerHTML == cell5.childNodes[1].innerHTML && cell1.childNodes[1].innerHTML == cell9.childNodes[1].innerHTML && cell1.childNodes[1].innerHTML != "") {
document.getElementById("notifier").innerHTML = cell1.childNodes[1].innerHTML + " wins!"
win = "y";
}
else if (cell2.childNodes[1].innerHTML == cell5.childNodes[1].innerHTML && cell2.childNodes[1].innerHTML == cell8.childNodes[1].innerHTML && cell2.childNodes[1].innerHTML != "") {
document.getElementById("notifier").innerHTML = cell2.childNodes[1].innerHTML + " wins!"
win = "y";
}
else if (cell3.childNodes[1].innerHTML == cell6.childNodes[1].innerHTML && cell3.childNodes[1].innerHTML == cell9.childNodes[1].innerHTML && cell3.childNodes[1].innerHTML != "") {
document.getElementById("notifier").innerHTML = cell3.childNodes[1].innerHTML + " wins!"
win = "y";
}
else if (cell4.childNodes[1].innerHTML == cell5.childNodes[1].innerHTML && cell4.childNodes[1].innerHTML == cell6.childNodes[1].innerHTML && cell4.childNodes[1].innerHTML != "") {
document.getElementById("notifier").innerHTML = cell4.childNodes[1].innerHTML + " wins!"
win = "y";
}
else if (cell7.childNodes[1].innerHTML == cell8.childNodes[1].innerHTML && cell7.childNodes[1].innerHTML == cell9.childNodes[1].innerHTML && cell7.childNodes[1].innerHTML != "") {
document.getElementById("notifier").innerHTML = cell7.childNodes[1].innerHTML + " wins!"
win = "y";
}
else if (cell3.childNodes[1].innerHTML == cell5.childNodes[1].innerHTML && cell3.childNodes[1].innerHTML == cell7.childNodes[1].innerHTML && cell3.childNodes[1].innerHTML != "") {
document.getElementById("notifier").innerHTML = cell3.childNodes[1].innerHTML + " wins!"
win = "y";
}
else if (cell1.childNodes[1].innerHTML != "" && cell2.childNodes[1].innerHTML != "" && cell3.childNodes[1].innerHTML != "" && cell4.childNodes[1].innerHTML != "" && cell5.childNodes[1].innerHTML != "" && cell6.childNodes[1].innerHTML != "" && cell7.childNodes[1].innerHTML != "" && cell8.childNodes[1].innerHTML != "" && cell9.childNodes[1].innerHTML != ""){
document.getElementById("notifier").innerHTML = "Tie!"
win = "y";
}
}
function iconDet() {
if (document.getElementById("turn").innerHTML == "O") {
document.getElementById("turn").innerHTML = "X";
return "O";
}
else if (document.getElementById("turn").innerHTML == "X") {
document.getElementById("turn").innerHTML = "O";
return "X";
}
}
var cell1 = document.getElementById('cell1');
cell1.style.cursor = 'pointer';
cell1.onclick = function(){
var icon = cell1.childNodes[1].innerHTML;
if (icon == "" && win == "n") {
cell1.childNodes[1].innerHTML = iconDet();
}
document.getElementById("notifier").innerHTML = "It's " + document.getElementById("turn").innerHTML + "'s turn";
winChecker();
Add();
}
var cell2 = document.getElementById('cell2');
cell2.style.cursor = 'pointer';
cell2.onclick = function(){
var icon = cell2.childNodes[1].innerHTML;
if (icon == "" && win == "n") {
cell2.childNodes[1].innerHTML = iconDet();
}
document.getElementById("notifier").innerHTML = "It's " + document.getElementById("turn").innerHTML + "'s turn";
winChecker();
Add();
}
var cell3 = document.getElementById('cell3');
cell3.style.cursor = 'pointer';
cell3.onclick = function(){
var icon = cell3.childNodes[1].innerHTML;
if (icon == "" && win == "n") {
cell3.childNodes[1].innerHTML = iconDet();
}
document.getElementById("notifier").innerHTML = "It's " + document.getElementById("turn").innerHTML + "'s turn";
winChecker();
Add();
}
var cell4 = document.getElementById('cell4');
cell4.style.cursor = 'pointer';
cell4.onclick = function(){
var icon = cell4.childNodes[1].innerHTML;
if (icon == "" && win == "n") {
cell4.childNodes[1].innerHTML = iconDet();
}
document.getElementById("notifier").innerHTML = "It's " + document.getElementById("turn").innerHTML + "'s turn";
winChecker();
Add();
}
var cell5 = document.getElementById('cell5');
cell5.style.cursor = 'pointer';
cell5.onclick = function(){
var icon = cell5.childNodes[1].innerHTML;
if (icon == "" && win == "n") {
cell5.childNodes[1].innerHTML = iconDet();
}
document.getElementById("notifier").innerHTML = "It's " + document.getElementById("turn").innerHTML + "'s turn";
winChecker();
Add();
}
var cell6 = document.getElementById('cell6');
cell6.style.cursor = 'pointer';
cell6.onclick = function(){
var icon = cell6.childNodes[1].innerHTML;
if (icon == "" && win == "n") {
cell6.childNodes[1].innerHTML = iconDet();
}
document.getElementById("notifier").innerHTML = "It's " + document.getElementById("turn").innerHTML + "'s turn";
winChecker();
Add();
}
var cell7 = document.getElementById('cell7');
cell7.style.cursor = 'pointer';
cell7.onclick = function(){
var icon = cell7.childNodes[1].innerHTML;
if (icon == "" && win == "n") {
cell7.childNodes[1].innerHTML = iconDet();
}
document.getElementById("notifier").innerHTML = "It's " + document.getElementById("turn").innerHTML + "'s turn";
winChecker();
Add();
}
var cell8 = document.getElementById('cell8');
cell8.style.cursor = 'pointer';
cell8.onclick = function(){
var icon = cell8.childNodes[1].innerHTML;
if (icon == "" && win == "n") {
cell8.childNodes[1].innerHTML = iconDet();
}
document.getElementById("notifier").innerHTML = "It's " + document.getElementById("turn").innerHTML + "'s turn";
winChecker();
Add();
}
var cell9 = document.getElementById('cell9');
cell9.style.cursor = 'pointer';
cell9.onclick = function(){
var icon = cell9.childNodes[1].innerHTML;
if (icon == "" && win == "n") {
cell9.childNodes[1].innerHTML = iconDet();
}
document.getElementById("notifier").innerHTML = "It's " + document.getElementById("turn").innerHTML + "'s turn";
winChecker();
Add();
}
function boardCleaner() {
document.getElementById("turn").innerHTML = "X";
document.getElementById("notifier").innerHTML = "It's X's turn";
cell1.childNodes[1].innerHTML = "";
cell2.childNodes[1].innerHTML = "";
cell3.childNodes[1].innerHTML = "";
cell4.childNodes[1].innerHTML = "";
cell5.childNodes[1].innerHTML = "";
cell6.childNodes[1].innerHTML = "";
cell7.childNodes[1].innerHTML = "";
cell8.childNodes[1].innerHTML = "";
cell9.childNodes[1].innerHTML = "";
win = 'n';
}
|
/**
* @properties={type:4,typeid:36,uuid:"2CFECE56-F6C0-42D8-840F-59ADBFA2DB24"}
*/
function tutti_i_dipendenti()
{
return ditte_pianificazione_to_ditte_pianificazionerighe && ditte_pianificazione_to_ditte_pianificazionerighe.getSize() > 0 ? 1 : 0;
}
|
/*a = parseInt(prompt("Enter the number"));
confirm(a*a);
var minute, hour, day, year;
minute = 1;
hour = minute * 60;
day = hour * 24;
year = day * 365;
confirm(hour);
confirm(day);
confirm(year);
a = parseInt(prompt("Enter first number"));
b = parseInt(prompt("Enter second number"));
alert(a+b);
alert(a-b);
alert(a*b);
alert(a/b);
var season = prompt("Enter the season");
if(season == "Winter"){
alert("Winter")
} else if(season == "winter"||season == "spring"||season == "summer"||season == "automn") {
alert("1 must be Uppercase");
} else if(season == "Summer") {
alert("Summer")
} else if(season == "Spring") {
alert("Spring")
} else if(season == "Automn") {
alert("Automn")
} else {
alert("It is not a season")
}
var z = +prompt("Enter the number in range from 0 to 59");
if(z<=15 && z >=0) {
alert("Number from first quarter")
} else if(z>15 && z<=30) {
alert("Number from second quarter")
} else if(z>30 && z<=45) {
alert("Number from third quarter")
} else if(z>45 && z<=60) {
alert("Number from fourth quarter")
} else {
alert("Number is not in a specified range")
}
z = +prompt("Enter the number in range from 0 to 59");
(z<=15 && z >=0) ? alert("Number from first quarter") :
(z>15 && z<=30) ? alert("Number from second quarter") :
(z>30 && z<=45) ? alert("Number from second quarter") :
(z>45 && z<=60) ? alert("Number from second quarter") :
alert("Number is not in a specified range");
var z = +prompt("Enter first number");
var x = +prompt("Enter second number");
if(x>z) {
console.log(x);
} else if (z>x) {
console.log(z);
} else
console.log("Numbers are equal");
function discount() {
var sumPurchase = +prompt("Enter the sum of your purchase");
var currency = 'UAN';
if(sumPurchase<1000) {
discountPurchase = sumPurchase * 0.03;
console.log("Your discount is", discountPurchase,currency);
} else if (sumPurchase>=1000 && sumPurchase < 5000) {
discountPurchase = sumPurchase * 0.05;
console.log("Your discount is", discountPurchase,currency);
} else if (sumPurchase>=5000) {
discountPurchase = sumPurchase * 0.1;
console.log("Your discount is", discountPurchase,currency);
}
}
discount();
function biggerNumber() {
var firstNumber = +prompt("Enter first number");
var secondNumber = +prompt("Enter second number");
if(firstNumber>secondNumber) {
console.log(firstNumber);
} else if (secondNumber>firstNumber) {
console.log(secondNumber)
} else {
console.log("They are equal")
}
}
biggerNumber();
function Price() {
var priceFirstThing = +prompt("Enter price first thing");
var priceSecondThing = +prompt("Enter price second thing");
var quantityFirstThing = +prompt("Enter quantity first thing");
var quantitySecondtThing = +prompt("Enter quantity second thing");
var currency = "UAN";
var firstThing = priceFirstThing * quantityFirstThing;
var secondThing = priceSecondThing * quantitySecondtThing;
var commonPrice = firstThing + secondThing;
console.log(commonPrice + " " + currency);
}
Price();
var arr = [1,2,3,4,5,6];
for (i = arr.length-1; arr[i] <= arr.length; i++) {
console.log(arr[i]);
}
var sum = 0;
var arr = [1,2,3,4,5];
for (i = 0; i < arr.length; i++) {
sum = sum + arr[i];
}
console.log(sum);
*/
|
import React, { Component } from 'react';
import Intro from "./components/Intro";
import CountryData from "./components/CountryData";
class App extends Component {
state = {
screenPhase: false
}
render() {
const screen = this.state.screenPhase ? <Intro/> : <CountryData/>
return (
<div>
{screen}
</div>
);
}
}
export default App;
|
const { data } = require("jquery");
module.exports = {
findAll: function(req){
return new Promise(function(resolve, reject) {
req.getConnection(function(err,connection){
let sql = 'SELECT * FROM countries where 1 = 1'
let condition = []
connection.query(sql,condition,function(err,results,fields)
{
if(err)
resolve(false)
if(results){
const country = JSON.parse(JSON.stringify(results));
resolve(country);
}else{
resolve(false);
}
})
})
});
},
findAllMoviesCountries: function(req,data = {}){
return new Promise(function(resolve, reject) {
req.getConnection(function(err,connection){
let sql = 'SELECT * FROM movie_countries INNER JOIN countries ON movie_countries.country_id = countries.id where 1 = 1 '
let condition = []
if(data.movie_id){
sql += " AND movie_id = ?"
condition.push(data.movie_id)
}
if(data.movie_country_ids){
sql += " AND movie_country_id IN ("+data.movie_country_ids.join(",")+")"
}
sql += " ORDER BY movie_countries.country_id DESC "
connection.query(sql,condition,function(err,results,fields)
{
if(err)
resolve(false)
if(results){
const country = JSON.parse(JSON.stringify(results));
resolve(country);
}else{
resolve(false);
}
})
})
});
}
}
|
/*
* ! Ext JS Library 3.1.0 Copyright(c) 2006-2009 Ext JS, LLC licensing@extjs.com
* http://www.extjs.com/license
*/
NavMenu = function(config) {
NavMenu.superclass.constructor.call(this, Ext.apply({
region : 'west',
title : '系统菜单',
split : true,
width : 160,
minSize : 175,
maxSize : 400,
collapsible : true,
margins : '0 0 5 5',
cmargins : '0 5 5 5',
rootVisible : false,
lines : false,
autoScroll : true,
root : new Ext.tree.TreeNode('rootitem'),
collapseFirst : false,
listeners : {
click : function(node) {
if (node) {
this.fireEvent('itemselect',
node.attributes.bean);
}
}
}
}, config));
this.feeds = this.root;
this.getSelectionModel().on({
'beforeselect' : function(sm, node) {
return node.isLeaf();
},
// 'selectionchange' : function(sm, node) {
// if (node) {
// this.fireEvent('feedselect', node.attributes.bean);
// }
// },
scope : this
});
this.addEvents({
itemselect : true
});
};
Ext.extend(NavMenu, Ext.tree.TreePanel, {
showWindow : function(btn, server) {
if (!this.win) {
this.win = new FeedWindow(this);
this.win.on('validfeed', this.addItem, this);
}
this.win.show(btn, server);
},
selectFirst : function() {
if (this.root.childNodes && this.root.childNodes.length > 0) {
this.root.childNodes[0].select();
}
},
selectById : function(id) {
if (!id) {
this.getSelectionModel().clearSelections();
return;
}
if (this.root.childNodes && this.root.childNodes.length > 0) {
Ext.each(this.root.childNodes, function(node, i) {
if (node && node.id == id) {
node.select();
return false;
}
});
}
},
findServerNode : function(id) {
return this.getNodeById(id);
},
addItem : function(attrs, inactive, preventAnim) {
var exists = this.getNodeById(attrs.id);
if (exists) {
exists.attributes.text = attrs.id;
exists.attributes.bean = attrs;
exists.setText(exists.attributes.text);
if (!inactive) {
exists.select();
exists.ui.highlight();
}
return;
}
var rawAttrs = {};
Ext.apply(rawAttrs, attrs);
Ext.apply(attrs, {
iconCls : 'feed-icon',
leaf : true,
cls : 'feed',
id : attrs.id,
text : attrs.text ? attrs.text : attrs.id,
bean : rawAttrs
});
var node = new Ext.tree.TreeNode(attrs);
this.feeds.appendChild(node);
if (!inactive) {
if (!preventAnim) {
Ext.fly(node.ui.elNode).slideIn('l', {
callback : node.select,
scope : node,
duration : .4
});
} else {
node.select();
}
}
return node;
},
// prevent the default context menu when you miss the node
afterRender : function() {
NavMenu.superclass.afterRender.call(this);
this.el.on('contextmenu', function(e) {
e.preventDefault();
});
}
});
Ext.reg('appNavMenu', NavMenu);
|
import axios from 'axios'
const article = {
state :{
articleInfo: {},
pageLoading: false
},
mutations:{
GETARTICLE(state,info) {
state.articleInfo = info
}
},
actions:{
getArticle({commit, state}, params){
return new Promise( (resolve, reject) => {
axios.get('/api/homeList.json', params)
.then( res => {
console.log(res)
commit('GETARTICLE', res.data)
resolve(res.data)
}).catch( err => {
reject(err)
})
})
}
}
}
export default article
|
import React from 'react';
import {Players} from './../api/players';
import PropTypes from 'prop-types'; // ES6
export default class Player extends React.Component{
render(){
//return <h4>Player class</h4>;
//need to use back ticks on this
let itemClassName = `item item--position-${this.props.player.rank}`;
return (
<div key = {this.props.player._id} className={itemClassName}>
<div className = "player">
<div>
<h3 className = "player__name">
{this.props.player.name}
</h3>
<p className = "player__stats">
{this.props.player.rank} place - {this.props.player.position} {this.props.player.score} point(s).
</p>
</div>
<div className = "player__actions">
<button className="button button--round" onClick ={() => Players.update(
{_id: this.props.player._id}, {$inc:{score: -1 }})
}>-1
</button>
<button className = "button button--round" onClick ={() => Players.update(
{_id: this.props.player._id}, {$inc:{score: 1 }})
}>+1
</button>
<button className = "button button--round" onClick ={() =>
Players.remove({_id: this.props.player._id})
}>X
</button>
</div>
</div>
</div>
);
}
}
Player.propTypes = { //defines the type sent to the class
player: PropTypes.object.isRequired
};
Player.defaultProps = { //default if nothing sent to class
//title: 'Default title'
}
|
/**
* @license
* Copyright 2014 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.setTestOnly();
goog.require('goog.testing.jsunit');
goog.require('lf.index');
function testHashCode() {
assertEquals(0, lf.index.hashCode(''));
// Space char's ASCII code is 32.
// Hash function is hash = hash * 31 + c, so hash code of 32 is 32,
// and hash code of two 32's are 32 * 32 = 1024
assertEquals(32, lf.index.hashCode(' '));
assertEquals(1024, lf.index.hashCode(' '));
}
function testHashArray() {
assertEquals('', lf.index.hashArray([]));
assertEquals('', lf.index.hashArray([null]));
assertEquals('0_', lf.index.hashArray(['', null]));
assertEquals('10', lf.index.hashArray([' ']));
assertEquals('10_10', lf.index.hashArray([' ', ' ']));
}
function testSlice() {
/** @const {!Array.<number>} */
var ARRAY = [0, 1, 2, 3, 4];
assertArrayEquals(ARRAY, lf.index.slice(ARRAY));
// Test empty array
assertArrayEquals([], lf.index.slice([]));
assertArrayEquals([], lf.index.slice([], 1));
assertArrayEquals([], lf.index.slice([], undefined, 1));
// Test LIMIT
assertArrayEquals([], lf.index.slice(ARRAY, 0));
assertArrayEquals([0], lf.index.slice(ARRAY, 1));
assertArrayEquals(ARRAY, lf.index.slice(ARRAY, ARRAY.length));
assertArrayEquals(ARRAY, lf.index.slice(ARRAY, ARRAY.length + 1));
// Test SKIP
assertArrayEquals(ARRAY, lf.index.slice(ARRAY, undefined, 0));
assertArrayEquals(ARRAY, lf.index.slice(ARRAY, ARRAY.length, 0));
for (var i = 0; i < ARRAY.length; ++i) {
assertArrayEquals([i], lf.index.slice(ARRAY, 1, i));
}
assertArrayEquals([], lf.index.slice(ARRAY, undefined, ARRAY.length));
}
|
var numero = 1
{
var numero = 2
console.log('dentro = ', numero)
}
console.log('fora =', numero)
/**
* Vai ser 2, para os dois console.log
* Pois, como já dito o var so tem dois escopos, se ele não tiver em uma função, então ele será declarado como variavél de escopo Global
*/
|
export const LIGHT_THEME = 'LIGHT_THEME'
export const DARK_THEME = 'DARK_THEME'
|
document.body.onkeypress = function(){document.body.classList.toggle('liked')}
|
import { combineReducers } from 'redux';
import * as types from './drinksTypes';
const drinks = (state = {}, { type, payload }) => {
switch (type) {
case types.GET_DRINKS:
return payload.data;
default:
return state;
}
};
const filter = (state = [], { type, payload }) => {
switch (type) {
case types.GET_FILTER_SUCCESS:
return payload.data.map(el => el.strCategory);
default:
return state;
}
};
const choice = (state = [], { type, payload }) => {
switch (type) {
case types.CHOICE:
return [...state, payload.category];
case types.REMOVE_CHOICE:
return state.filter(el => el !== payload.category);
case types.CHOICE_CLEAR:
return [];
default:
return state;
}
};
const isError = (state = null, { type, payload }) => {
switch (type) {
case types.GET_FILTER_ERROR:
return payload.error;
case types.GET_FILTER_START:
return null;
default:
return state;
}
};
const isLoading = (state = false, { type }) => {
switch (type) {
case types.GET_FILTER_START:
case types.LOADING:
return true;
case types.GET_FILTER_SUCCESS:
case types.GET_FILTER_ERROR:
case types.GET_DRINKS:
return false;
default:
return state;
}
};
export default combineReducers({
drinks,
filter,
choice,
isError,
isLoading,
});
|
/* ------------------------------------
sec161 テキストボックスの値を取得
-------------------------------------*/
function sec161() {
const value161 = document.querySelector('#input161').value;
if (value161) {
alert(value161);
} else {
alert('テキストを入力してください');
}
}
/* ------------------------------------
sec162 テキストボックスの変更を検知
-------------------------------------*/
function sec162() {
const form162 = document.querySelector('#form162');
const input162 = document.querySelector('#input162');
const result162i = document.querySelector('.result162i');
const result162c = document.querySelector('.result162c');
input162.addEventListener('input', handleInput);
input162.addEventListener('change', handleChange);
function handleInput(event) {
const value162 = event.target.value;
result162i.innerHTML = value162;
}
function handleChange(event) {
const value162 = event.target.value;
result162c.innerHTML = value162;
}
//enterで遷移させない
form162.addEventListener('submit', (e) => {
if (e.target.type !== "submit") {
e.preventDefault();
}
});
} sec162();
/* ------------------------------------
sec163 テキストエリアの値を取得
-------------------------------------*/
function sec163() {
const value163 = document.querySelector('#input163').value;
if (value163) {
alert(value163);
} else {
alert('テキストを入力してください');
}
}
/* ------------------------------------
sec164 テキストエリアの変更を検知
-------------------------------------*/
function sec164() {
const input164 = document.querySelector('#input164');
const result164i = document.querySelector('.result164i');
const result164c = document.querySelector('.result164c');
input164.addEventListener('input', handleInput);
input164.addEventListener('change', handleChange);
function handleInput(event) {
const value164 = event.target.value;
const htmlstr = value164.split('\n').join('<br>');
result164i.innerHTML = htmlstr;
}
function handleChange(event) {
const value164 = event.target.value;
result164c.innerHTML = value164;
}
} sec164();
/* ------------------------------------
sec166 チェックボックスの情報を取得
-------------------------------------*/
function sec166() {
const checkedA = document.querySelector('#checkA');
const checkedB = document.querySelector('#checkB');
const checkedC = document.querySelector('#checkC');
document.querySelectorAll('.check166').forEach(function (checkBtn) {
checkBtn.addEventListener('change', () => {
checkResult();
});
});
document.querySelector('#checkAll').addEventListener('click', (e) => {
if (e.target.checked == true) {
checkedA.checked = checkedB.checked = checkedC.checked = true;
} else {
checkedA.checked = checkedB.checked = checkedC.checked = false;
}
checkResult();
});
function checkResult() {
document.querySelector('.checkA').innerHTML = checkedA.checked;
document.querySelector('.checkB').innerHTML = checkedB.checked;
document.querySelector('.checkC').innerHTML = checkedC.checked;
}
} sec166();
/* ------------------------------------
sec167 ローカルファイルの情報を取得
-------------------------------------*/
function sec167() {
const input167 = document.querySelector('#input167');
input167.addEventListener('change', (e) => {
const files = e.target.files; //ファイルの配列
const file = files[0];
alert(`${file.name}が選択されました`);
});
} sec167();
/* ------------------------------------
sec168 ローカルファイルをテキストとして読み込む
-------------------------------------*/
function sec168() {
const input168 = document.querySelector('#input168');
const log = document.querySelector('.log168');
input168.addEventListener('input', (e) => {
const files = e.target.files;
const file = files[0];
//FileReaderのインスタンス作成
const reader = new FileReader();
reader.addEventListener('load', () => {
//load後resultを.logに出力
log.textContent = reader.result;
});
//テキストファイルとして読み込む
reader.readAsText(file);
});
} sec168();
/* ------------------------------------
sec169 ローカルファイルをDataURLとして読み込む
-------------------------------------*/
function sec169() {
const input169 = document.querySelector('#input169');
const log = document.querySelector('.log169 img');
input169.addEventListener('input', (e) => {
const files = e.target.files;
const file = files[0];
//FileReaderのインスタンス作成
const reader = new FileReader();
reader.addEventListener('load', () => {
//load後resultを.logに出力
log.src = reader.result;
});
//テキストファイルとして読み込む
reader.readAsDataURL(file);
});
} sec169();
/* ------------------------------------
sec171 ラジオボタンの変更を検知
-------------------------------------*/
function sec171() {
const form171 = document.querySelector('#form171');
const color171 = document.querySelector('.color171 span');
const food171 = document.querySelector('.food171 span');
form171.addEventListener('change', handleChange);
function handleChange(e) {
const colorValue = form171.color.value;
const foodValue = form171.food.value;
color171.innerHTML = colorValue;
food171.innerHTML = foodValue;
}
} sec171();
/* ------------------------------------
sec173 ドロップダウンメニューの変更を検知
-------------------------------------*/
function sec173() {
const select173 = document.querySelector('#select173');
const result173 = document.querySelector('.result173 span');
select173.addEventListener('change', handleChange);
function handleChange(e) {
const selectValue = select173.value;
result173.innerHTML = selectValue;
}
} sec173();
/* ------------------------------------
sec174 スライダーの情報を取得
-------------------------------------*/
function sec174() {
const range174 = document.querySelector('#range174');
const result174 = document.querySelector('.result174');
const value174 = range174.value;
result174.innerHTML = value174;
}
/* ------------------------------------
sec175 スライダーの情報を取得
-------------------------------------*/
function sec175() {
const range175 = document.querySelector('#range175');
const result175i = document.querySelector('.result175i');
const result175c = document.querySelector('.result175c');
range175.addEventListener('input', handleInput);
range175.addEventListener('change', handleChange);
function handleInput(e) {
const value175 = e.target.value;
result175i.innerHTML = value175;
}
function handleChange(e) {
const value175 = e.target.value;
result175c.innerHTML = value175;
}
} sec175();
/* ------------------------------------
sec176 カラーピッカーの情報を取得
-------------------------------------*/
function sec176() {
const color176 = document.querySelector('#color176');
const value176 = color176.value;
alert(value176);
}
/* ------------------------------------
sec177 カラーピッカーの情報を取得
-------------------------------------*/
function sec177() {
const color177 = document.querySelector('#color177');
const result177 = document.querySelector('.result177');
color177.addEventListener('change', (e) => {
const value177 = e.target.value;
result177.innerHTML = value177;
result177.style.backgroundColor = value177;
});
} sec177();
/* ------------------------------------
sec178 都道府県のプルダウンをつくる
-------------------------------------*/
function sec178() {
//JISコードに対応した都道府県の連想配列
const prefList = [
{ value: 1, name: '北海道' },
{ value: 2, name: '青森県' },
{ value: 3, name: '岩手県' },
{ value: 4, name: '宮城県' },
{ value: 5, name: '秋田県' },
{ value: 6, name: '山形県' },
{ value: 7, name: '福島県' },
{ value: 8, name: '茨城県' },
{ value: 9, name: '栃木県' },
{ value: 10, name: '群馬県' },
{ value: 11, name: '埼玉県' },
{ value: 12, name: '千葉県' },
{ value: 13, name: '東京都' },
{ value: 14, name: '神奈川県' },
{ value: 15, name: '新潟県' },
{ value: 16, name: '富山県' },
{ value: 17, name: '石川県' },
{ value: 18, name: '福井県' },
{ value: 19, name: '山梨県' },
{ value: 20, name: '長野県' },
{ value: 21, name: '岐阜県' },
{ value: 22, name: '静岡県' },
{ value: 23, name: '愛知県' },
{ value: 24, name: '三重県' },
{ value: 25, name: '滋賀県' },
{ value: 26, name: '京都府' },
{ value: 27, name: '大阪府' },
{ value: 28, name: '兵庫県' },
{ value: 29, name: '奈良県' },
{ value: 30, name: '和歌山県' },
{ value: 31, name: '鳥取県' },
{ value: 32, name: '島根県' },
{ value: 33, name: '岡山県' },
{ value: 34, name: '広島県' },
{ value: 35, name: '山口県' },
{ value: 36, name: '徳島県' },
{ value: 37, name: '香川県' },
{ value: 38, name: '愛媛県' },
{ value: 39, name: '高知県' },
{ value: 40, name: '福岡県' },
{ value: 41, name: '佐賀県' },
{ value: 42, name: '長崎県' },
{ value: 43, name: '熊本県' },
{ value: 44, name: '大分県' },
{ value: 45, name: '宮崎県' },
{ value: 46, name: '鹿児島県' },
{ value: 47, name: '沖縄県' }
];
//select
const selectElement = document.querySelector('#pref');
//option初期表示
let optionString = '<option value="">選択ください</option>';
//optionを配列から作成
prefList.forEach((item) => {
//都道府県ごとにvalueとnameを反映
optionString += `<option value="${item.value}">${item.name}</option>`;
});
//optionをselectに追加
selectElement.innerHTML = optionString;
//変更時のイベント
selectElement.addEventListener('change', (e) => {
//現在の値
const index = e.target.selectedIndex;
const value178 = e.target.options[index].text;
console.log(value178);
//メッセージ作成(三項演算子)
const message = value178 === '' ? '選択されていません' : `選択されているのは${value178}です`;
document.querySelector('.log178').innerHTML = message;
});
} sec178();
/* ------------------------------------
sec179 フォームの送信時に処理を行う
-------------------------------------*/
function sec179() {
const form179 = document.querySelector('#form179');
form179.addEventListener('submit', handleSubmit);
function handleSubmit(e) {
const isYes = confirm('この内容で送信していいです?');
if (isYes === false) {
e.preventDefault();
}
}
} sec179();
|
let x = 1280;
let y = 606;
let hourCircleSize = 250;
let hourCircleXaxis = hourCircleSize;
let minCircleSize = 200;
let minCircleXaxis = minCircleSize;
let secCircleSize = 150;
let secCircleXaxis = secCircleSize;
function setup() {
createCanvas(x,y); // make an HTML canvas element width x height pixels
}
function draw() {
background('#C7DDF5');
fill('#9ACEFF');
circle(hourCircleXaxis, y/2, hourCircleSize);
hourCircleXaxis= hourCircleSize + ((hour() % 12) * ((x - 2*hourCircleSize) / 11));
fill('#669ACC');
circle(minCircleXaxis, y/2, minCircleSize);
minCircleXaxis= minCircleSize + ((minute()) * ((x - 2*minCircleSize) / 59));
fill('#F336799');
circle(secCircleXaxis, y/2, secCircleSize);
secCircleXaxis= secCircleSize + ((second()) * ((x - 2*secCircleSize) / 59));
/* Included implementation of translate(), push(), and pop() but unnecessary
push();
fill('#9ACEFF');
translate(hourCircleXaxis, 0);
circle(0, y/2, hourCircleSize);
hourCircleXaxis= hourCircleSize + ((hour() % 12) * ((x - 2*hourCircleSize) / 11));
pop();
push();
translate(minCircleXaxis, 0);
fill('#669ACC');
circle(0, y/2, minCircleSize);
minCircleXaxis= minCircleSize + ((minute()) * ((x - 2*minCircleSize) / 59));
pop();
push();
translate(secCircleXaxis, 0);
fill('#F336799');
circle(0, y/2, secCircleSize);
secCircleXaxis= secCircleSize + ((second()) * ((x - 2*secCircleSize) / 59));
pop();*/
}
|
import React, { useState } from 'react';
import { useEffect } from 'react/cjs/react.development';
import ProductForm from './ProductForm'
import axios from 'axios'
import {navigate} from '@reach/router'
import DeleteProduct from './DeleteProduct'
const ProductEdit = props => {
const {products, id, setProducts} = props
const currProduct = products.filter(product=> product._id===id)[0]
const [editProduct, setEditProduct] = useState({})
useEffect( ()=>{
setEditProduct(currProduct)
}, [currProduct])
const handleSubmit = (e)=> {
e.preventDefault()
console.log(editProduct)
axios.put("http://localhost:8000/api/products/update/"+editProduct._id, editProduct)
.then(updatedProduct => {
let tmpArr = [...products]
for(let i=0;i<tmpArr.length;i++){
if(tmpArr[i]._id === id){
tmpArr[i] = updatedProduct.data
}
}
setProducts(tmpArr)
window.location.replace("/")
})
.catch(err => console.log(err))
}
return (
<div>
<h1>Editing</h1>
<ProductForm handleSubmit={handleSubmit} setProduct={setEditProduct} product={editProduct} />
<DeleteProduct id={id} />
</div>
);
};
export default ProductEdit;
|
require('./TriviaScene.styl');
import React, { PropTypes, Component } from 'react';
import { UIScene } from '../ui';
import { connect } from 'react-redux';
import { TriviaChoice } from '../sections';
import _ from 'underscore';
@connect((state, { params }) => ({
trivia: state.trivias.get(params.triviaId),
}))
class TriviaScene extends Component {
static displayNmae = 'TriviaScene';
static propTypes = {
trivia: PropTypes.object.isRequired,
params: PropTypes.object.isRequired,
style: PropTypes.object,
};
static defaultProps = {
trivia: {},
params: {},
};
renderLoading() {
return (
<div className="ncss-container fixed-fluid p4-sm u-sm-t u-full-height">
<div className="trivia-scene-content u-sm-tc u-va-m u-align-center u-sm-tr">
<div className="ncss-row pb12-md pb12-lg">
<h2 className="ncss-brand placeholder bg-offwhite"></h2>
</div>
<div className="ncss-row">
<div className="ncss-col-sm-6 u-align-center avatar pl1-sm choice-col">
<div className="trivia-choice ncss-brand h1 u-va-m z0 placeholder bg-offwhite" />
<div className="ncss-brand h3 text-color-dark-grey placeholder bg-offwhite" />
</div>
<div className="ncss-col-sm-6 u-align-center avatar pl1-sm choice-col">
<div className="trivia-choice ncss-brand h1 u-va-m z0 placeholder bg-offwhite" />
<div className="ncss-brand h3 text-color-dark-grey placeholder bg-offwhite" />
</div>
</div>
</div>
</div>
);
}
renderContent() {
const { trivia, params } = this.props;
const { question, choices, voted } = trivia.toJS();
const { triviaId } = params;
return (
<div className="ncss-container fixed-fluid p4-sm u-sm-t u-full-height">
<div className="trivia-scene-content u-sm-tc u-va-m u-align-center u-sm-tr">
<div className="ncss-row pb12-md pb12-lg" key={`trivia-${params.triviaId}`}>
<h2 className="ncss-brand">{question}</h2>
</div>
<div className="ncss-row">
{
_.map(choices, (choiceData, choiceId) =>
<TriviaChoice
key={`trivia-choice-${choiceId}`}
id={choiceId}
triviaId={triviaId}
choiceData={choiceData}
active={!voted}
/>
)
}
</div>
</div>
</div>
);
}
render() {
const { trivia, style } = this.props;
return (
<UIScene
name="trivia"
style={style}
content={() => (Object.keys(trivia).length > 0 ?
this.renderContent() : this.renderLoading()
)}
/>
);
}
}
export default TriviaScene;
|
export default {
updateSelectedMenuId(state, menuId) {
state.selectedMenuId = menuId;
}
}
|
import Layout from '../components/Layout'
import SignupComponent from '../components/auth/SignupComponent'
const Signup = () => {
return (
<Layout>
<h2 className="text-center pt-4 pb-4">Signup</h2>
<div className="row flex-center">
<div className="col md-6 sm-6">
<SignupComponent/>
</div>
</div>
</Layout>
)
}
export default Signup;
|
// <!--
// Etapy w tym projekcie
// HTML
// 1. utwórz element <button> i <ul> w <body>
// JS
// 1. pobierz element button za pomocą metody querySelector i przypis wynik do zmiennej
// 2. ustaw nasłuchiwanie (metodę addEventListener) na click na pobrany element button
// 3. jako drugi argument metody adEventListener podaj funkcję anonimową.
// 4. zadaniem funkcji anonimowej jest stworzyć nowy element li, który będzie zawierał w sobie tekst (właściwość textContent) w postaci kolejnych liczb nieparzystych (1,3,5 itd) czyli: <li>1</li><li>3</li> itd. Posłuż się w tym celu zmienną (pamietaj by stworzyć ją za pomocą słowa let a nie const), którą utworzysz w zasięgu globalnym a będziesz modyfikował w funkcji (za każdym razem funkcja zwiększy ją o dwa).
// 5. Każdy element <li>, który zawiera liczbę podzielną przez 3 (a wiec zwracającą 0 z dzielenia przez 3) ma mieć większą font. (1) dodawaj więc (w funkcji, za pomocą instrukcji warunkowej) do takiego elementu klasę o nazwie big (już określona w css). Wykorzystaj instrukcję warunkową i modulo.
// -->
const btn = document.querySelector("button");
let number = 1;
btn.addEventListener("click", function () {
const LiEl = document.createElement("li");
document.body.appendChild(LiEl);
LiEl.textContent = number;
if (number % 3 == 0) {
LiEl.classList.add("big");
}
number = number + 2;
})
|
var AnimationRadix = new RadixTree(null, undefined);
AnimationRadix.set("delta", function (token, stream, keyframe) {
stream.i += 5;
keyframe.isDelta = true;
});
Globals.private.parse2 = function(stream){
var temp = stream.data.substring(stream.i);
var nums = temp.match(/\s+(-?[\d\.]+)\s+(-?[\d\.]+)\s?/);
var array = new Array(2);
if (nums.length == 3) {
array[0] = nums[1] - 0;
array[1] = nums[2] - 0;
stream.i += nums[0].length;
}else{
throw new Error("incorrect number of numbers: "+temp);
}
return array;
};
Globals.private.parse1 = function(stream){
var temp = stream.data.substring(stream.i);
var nums = temp.match(/\s+(-?[\d\.]+)\s?/);
var t = 0;
if (nums.length == 2) {
t = nums[1] - 0;
stream.i += nums[0].length;
}else{
throw new Error("incorrect number of numbers: "+temp);
}
return t;
};
Globals.private.parseStr = function(stream){
var temp = stream.data.substring(stream.i);
var nums = temp.match(/\s+(-?[^\s]+)\s?/);
var t = "";
if (nums.length == 2) {
t = nums[1];
stream.i += nums[0].length;
}else{
throw new Error("incorrect number of strs: "+temp);
}
return t;
};
AnimationRadix.set("move", function (token, stream, keyframe) {
stream.i += 4;
var a = Globals.private.parse2(stream);
keyframe.transform.x = a[0];
keyframe.transform.y = a[1];
});
AnimationRadix.set("scale", function (token, stream, keyframe) {
stream.i += 5;
var a = Globals.private.parse2(stream);
keyframe.transform.sx = a[0];
keyframe.transform.sy = a[1];
});
AnimationRadix.set("width", function (token, stream, keyframe) {
stream.i += 5;
keyframe.width = Globals.private.parse1(stream);
});
AnimationRadix.set("time", function (token, stream, keyframe) {
stream.i += 4;
keyframe.time = Globals.private.parse1(stream);
});
AnimationRadix.set("alpha", function (token, stream, keyframe) {
stream.i += 5;
keyframe.transform.a = Globals.private.parse1(stream);
});
AnimationRadix.set("equation", function (token, stream, keyframe) {
stream.i += 8;
keyframe.equation = Globals.private.parseStr(stream);
});
AnimationRadix.set("image", function (token, stream, keyframe) {
stream.i += 5;
keyframe.image = Globals.private.parseStr(stream);
});
AnimationRadix.set("height", function (token, stream, keyframe) {
stream.i += 6;
keyframe.height = Globals.private.parse1(stream);
});
AnimationRadix.set(" ", function (token, stream, keyframe) {
stream.i++;
});
|
export default class ChessHuman {
isHuman() {
return true;
}
async requestMove(fen) {
// do nothing... wait for a drag and drop event
return {};
}
choosePromotion(source, target, choices) {
// lets do this the easy way for now
while (true) {
const choice = prompt(
`Choose one of the following promotion options:\n${choices.join(", ")}`,
choices[choices.length - 1]
);
// user chose to cancel
if (!choice) {
return null;
}
// user chose a valid option, we're done, otherwise try again
if (choices.indexOf(choice) >= 0) {
return { source, target, promotion: choice };
}
}
}
}
|
import { createAction } from '@reduxjs/toolkit';
export const login = createAction('auth/login');
export const logout = createAction('auth/logout');
export const getProductsSuccess = createAction('products/get');
export const getWishlist = createAction('wishlist/get');
export const addWishlistProduct = createAction('wishlist/put');
export const removeWishlistProduct = createAction('wishlist/remove');
export const setFilters = createAction('filters/set');
export const setFiltersVisible = createAction('filters/setVisible');
|
class PlayerEditor extends React.Component {
state = {
player: {}
}
findPlayerById = (id) =>
findPlayerById(id)
.then(player => this.setState({player}))
componentDidMount = () => {
const id = window.location.search.split("=")[1]
this.findPlayerById(id)
}
savePlayerName = () =>
renamePlayer(this.state.player)
savePlayerTeam = () =>
changePlayerTeam(this.state.player)
savePlayerManager = () =>
changePlayerManager(this.state.player)
saveAge = () =>
changeAge(this.state.player)
saveHeight = () =>
changeHeight(this.state.player)
savePlayerPayment = () =>
changePlayerPayment(this.state.player)
savePlayerBank = () =>
changePlayerBank(this.state.player)
saveStatistic = () =>
changeStatistic(this.state.player)
render() {
return(
<div className="container">
<h1>Player Editor: <br/> {this.state.player.player_name}</h1>
ID: <input className="form-control" readOnly={true}
value={this.state.player.id}/> <br/>
Player Name: <input
onChange={(event) => this.setState({
player: {
...this.state.player,
player_name: event.target.value}})}
className="form-control"
value={this.state.player.player_name}/>
<button onClick={this.savePlayerName}>
Save Player Name
</button> <br/> <br/>
Team ID, current Team ID: {this.state.player.team_id}: <input
onChange={(event) => this.setState({
player: {
...this.state.player,
team_player: event.target.value}})}
className="form-control"
value={this.state.player.team_player}/>
<button onClick={this.savePlayerTeam}>
Save Team ID
</button> <br/> <br/>
Manager ID, current Manager ID: {this.state.player.manager_id}: <input
onChange={(event) => this.setState({
player: {
...this.state.player,
manager_player: event.target.value}})}
className="form-control"
value={this.state.player.manager_player}/>
<button onClick={this.savePlayerManager}>
Save Manager ID
</button> <br/> <br/>
Age: <input
onChange={(event) => this.setState({
player: {
...this.state.player,
age: event.target.value}})}
className="form-control"
value={this.state.player.age}/>
<button onClick={this.saveAge}>
Save Age
</button> <br/> <br/>
Height: <input
onChange={(event) => this.setState({
player: {
...this.state.player,
height: event.target.value}})}
className="form-control"
value={this.state.player.height}/>
<button onClick={this.saveHeight}>
Save Height
</button> <br/> <br/>
Player Payment: <input
onChange={(event) => this.setState({
player: {
...this.state.player,
player_payment: event.target.value}})}
className="form-control"
value={this.state.player.player_payment}/>
<button onClick={this.savePlayerPayment}>
Save Player Payment
</button> <br/> <br/>
Player Bank: <input
onChange={(event) => this.setState({
player: {
...this.state.player,
player_bank: event.target.value}})}
className="form-control"
value={this.state.player.player_bank}/>
<button onClick={this.savePlayerBank}>
Save Player Bank
</button> <br/> <br/>
Statistic: <input
onChange={(event) => this.setState({
player: {
...this.state.player,
statistic: event.target.value}})}
className="form-control"
value={this.state.player.statistic}/>
<button onClick={this.saveStatistic}>
Save Statistic
</button> <br/> <br/>
<a href="player-list.html">
Done
</a> <br/> <br/> <br/> <br/> <br/> <br/>
</div>
)
}
}
ReactDOM.render(
<PlayerEditor/>, document.getElementById("root"))
|
import React, { Component, Fragment } from 'react';
import { Container, Form,Col,Button, Row } from 'react-bootstrap';
class consultantAndCareerAdvisorReg extends Component {
render() {
return (
<Fragment>
<div className="page__bg ">
<Container>
<p className="pageSection__title pt-5">Consultant / Career Advisor</p>
<p className="greyBar"></p>
<Form className="mt-4" action="https://halcyonbd.com/talent/advisor" method="POST" enctype="multipart/form-data">
<Form.Row>
<Form.Group as={Col} >
<Form.Label className="from__label clientReg__formLabel">Name</Form.Label>
<Form.Control className="formArea formAreaBorder" name="name" type="text" placeholder="Type Your Full Name" />
</Form.Group>
<Form.Group as={Col} >
<Form.Label className="from__label clientReg__formLabel">Email</Form.Label>
<Form.Control className="formArea formAreaBorder" name="email" type="email" placeholder="Type Your Email Address" />
</Form.Group>
</Form.Row>
<Form.Row>
<Form.Group as={Col} >
<Form.Label className="from__label clientReg__formLabel">Password</Form.Label>
<Form.Control className="formArea formAreaBorder" name="password" type="password" placeholder="Choose a Password" />
</Form.Group>
<Form.Group as={Col} >
<Form.Label className="from__label clientReg__formLabel">Re-Type Password</Form.Label>
<Form.Control className="formArea formAreaBorder" type="password" placeholder="Retype Password" />
</Form.Group>
</Form.Row>
<Form.Row>
<Form.Group as={Col} >
<Form.Label className="from__label clientReg__formLabel">Mobile No.</Form.Label>
<Form.Control className="formArea formAreaBorder" name="phone" type="text" placeholder="Enter Your Mobile No" />
</Form.Group>
<Form.Group as={Col} >
<Form.Label className="from__label clientReg__formLabel">Address</Form.Label>
<Form.Control className="formArea formAreaBorder" name="address" type="text" placeholder="Type Your Address" />
</Form.Group>
</Form.Row>
<Form.Row>
<Form.Group as={Col} >
<Form.Label className="from__label clientReg__formLabel">Company Name</Form.Label>
<Form.Control className="formArea formAreaBorder" name="company_name" type="text" placeholder="Type Your Company Name" />
</Form.Group>
<Form.Group as={Col} >
<Form.Label className="from__label clientReg__formLabel">Designation</Form.Label>
<Form.Control className="formArea formAreaBorder" name="designation" type="text" placeholder="Type Your Designation" />
</Form.Group>
</Form.Row>
<Form.Row>
<Form.Group as={Col} >
<Form.Label className="from__label clientReg__formLabel">Specialist Field</Form.Label>
<Form.Control className="formAreaBorder formArea__dropDown" name="specilist_field" as="select" defaultValue="Finance">
<option>Finance</option>
<option>Accounting</option>
<option>Supply Chain</option>
<option>Trade Marketing</option>
<option>Business Management</option>
<option>Marketing</option>
<option>Sales</option>
<option>HR</option>
</Form.Control>
</Form.Group>
<Form.Group as={Col} >
<Form.Label className="from__label clientReg__formLabel">Linkedin Profile</Form.Label>
<Form.Control className="formArea formAreaBorder" type="text" name="linkedin" placeholder="Enter Your Linkedin Profile URL" />
</Form.Group>
</Form.Row>
<Form.Group className="clientRegFrom__address">
<Form.Label className="from__label clientReg__formLabel mt-2">About Yourself</Form.Label>
<Form.Control className="formArea formAreaBorder" type="text" name="about_you" placeholder="Write About Yourself" as="textarea" rows={3} />
</Form.Group>
<Form.Group className="clientRegFrom__address">
<Form.Label className="from__label clientReg__formLabel mt-3">Upload Image</Form.Label>
<Form.Control className="formArea formAreaFileUpload" type="file" name="specilist_image"/>
<p className="fileUpload__note">*Max file size 2MB, Regulation: 450px, X 600px</p>
</Form.Group>
<div className="mt-5">
<label className="checkbox__label checkbox__boxItem ">User Type</label>
<select className="option_css" name="role">
<option value="3">Consultant</option>
<option value="4">Advisor</option>
</select>
</div>
<Row>
<Col lg="6" md="6" sm="12">
<div className="mt-5">
<input type="checkbox"/>
<label className="checkbox__label"> I agree to the Talent Tracker Terms of Use. Terms & Conditions</label><br/>
</div>
</Col>
<Col lg="6" md="6" sm="12">
<div className="mt-4">
<Button className="grdiantBtn freelanceRecruiterReg__btn" type="submit"> REGISTRATION </Button>
</div>
</Col>
</Row>
</Form>
</Container>
</div>
</Fragment>
);
}
}
export default consultantAndCareerAdvisorReg;
|
/* exported TOOLS */
'use strict';
/**
* tools for works with strings.
*
* @version 1.0
*/
var TOOLS = (function() {
// define exportable methods of the module
var exports = {};
/**
* truncate string and adds three dots if too long.
*
* @param {string} string - a string that you want to truncate.
* @param {number} maxLength - lenght of the string that you want to truncate.
* @returns {string} a truncated string.
*/
exports.truncatechars = function(string, maxLength) {
var defaultLength = 24,
length = maxLength ? maxLength : defaultLength;
if (string.length > length) {
return string.substr(0, length) + '...';
}
return string;
};
/**
* unescape unicode string.
*
* @param {string} value - decoded in unicode string.
* @returns {string} unescape string.
*/
exports.unescapeUnicode = function(value) {
return unescape(
value.toString().replace(/\\u([\d\w]{4})/gi, function(match, grp) {
return String.fromCharCode(parseInt(grp, 16));
})
);
};
/**
* returns array with random values.
*
* @param {number} length Length of the random array.
* @param {number} max A max value of the random array.
* @returns {Array} array with random numbers.
*/
exports.randomArray = function(length, max) {
var DEFAULT_LENGTH = 10,
DEFAULT_MAX = 100,
maxLength = typeof length !== 'undefined' ? length : DEFAULT_LENGTH,
maxNum = typeof max !== 'undefined' ? max : DEFAULT_MAX;
return Array.apply(Object, Array(maxLength)).map(function() {
return Math.round(Math.random() * maxNum);
});
};
/**
* generate random color HEX code
*
* @returns {string} HEX code.
*/
exports.getRandomColor = function() {
var numeral = 16,
start = 2,
end = 8;
return '#' + (Math.random().toString(numeral)).slice(start, end);
};
/**
* generate array of random HEX colors
*
* @param {number} length - length of the array.
* @returns {array} array of HEX colors.
*/
exports.getRandomColors = function(length) {
return Array.apply(Object, Array(length)).map(function() {
return exports.getRandomColor();
});
};
return exports;
}());
|
/**
* http通用工具函数
*/
import axios from 'axios';
import { message } from 'antd';
import * as config from './config';
const toQueryPair = (key, value) =>{
///<summary>将键值对转为URL参数</summary>
if (typeof value == 'undefined') {
return key;
}
return key + '=' + encodeURIComponent(value === null ? '' : String(value));
//return key + '=' + (value == null ? '' : String(value));
}
export const toQueryString = (obj) =>{
if(obj){
var ret = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
key = encodeURIComponent(key);
var values = obj[key];
if (values && values.constructor === Array) { //数组
var queryValues = [];
for (var i = 0, len = values.length, value; i < len; i++) {
value = values[i];
queryValues.push(toQueryPair(key, value));
}
ret = ret.concat(queryValues);
} else { //字符串
ret.push(toQueryPair(key, values));
}
}
}
return ret.join('&');
}else{
return ''
}
};
const getCookie = (name) => {
let arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
if(arr=document.cookie.match(reg))
return unescape(arr[2]);
else
return null;
};
//设置统一的请求头
export const createAxiosInstance = (token) =>{
let headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Origin':'*'
};
let authToken = token?'Bearer '+ token : getCookie('authorization')
if(authToken){
let Authorization = {'Authorization': authToken}
Object.assign(headers,Authorization)
}
const instance = axios.create({
baseURL: config.BASE_API,
timeout: 10000,
headers: headers,
})
return instance
}
window.axiosInstance = createAxiosInstance();
export const post = (url, params) =>{
let formParams = toQueryString(params)
window.axiosInstance.post(url, formParams)
}
//统一的请求接口
export const fetch = (method,url,params) => {
let promise = new Promise((resolve, reject) => {
window.axiosInstance[method](url, params)
.then(function (response) {
if(response.data && response.data.code == 401){
window.location.href = '#/login'
return
}
resolve(response.data)
})
.catch(function (e) {
console.error("fetch 请求出错了");
reject('网络故障,请稍后再试')
});
// 超时处理
setTimeout(() => reject('系统繁忙,请稍后再试'), 20000);
});
return promise;
}
|
import $ from 'jquery';
import _ from 'lodash'
import Backgrid from 'backgrid';
import Epoxy from 'igui_root/node_modules/backbone.epoxy/backbone.epoxy';
import Utils from 'igui_root/src/scripts/utils';
var TableRadioCellView = Backgrid.Cell.extend(Epoxy.View.mixin());
TableRadioCellView = Utils.extend.call(TableRadioCellView, {
className: 'radio-cell',
render: function() {
this.$el.empty();
var name = this.column.get('name');
var value = this.column.get('value');
var $elem = $(`<label class="themed-radio">
<input type="radio" name="${name + this.rowViewCid}"
value="${value}" data-bind="checked:${name}">
<span></span>
</label>`)
this.$el.append($elem);
this.delegateEvents();
this.applyBindings();
return this;
}
}, {
_optionsToAttach: ['rowViewCid']
});
export default TableRadioCellView;
|
/* eslint-disable jsx-a11y/click-events-have-key-events */
/* eslint-disable jsx-a11y/no-noninteractive-element-interactions */
import React, { useState } from 'react';
import Carousel from 'react-bootstrap/Carousel';
const ControlledCarousel = ({ currentStyle }) => {
const [index, setIndex] = useState(0);
const handleSelect = (selectedIndex) => {
setIndex(selectedIndex);
};
const renderThumbnails = () => (currentStyle.photos && (
currentStyle.photos.map((thumbnail, i) => (
<img
className="d-block thumbnail-image"
src={thumbnail.url}
alt="thumbnail"
onClick={() => setIndex(i)}
/>
))
));
return (
<div className="carousel-container">
<Carousel
autoPlay={false}
interval={null}
wrap={false}
indicators={false}
activeIndex={index}
onSelect={handleSelect}
>
{currentStyle.photos && (
currentStyle.photos.map((photo) => (
<Carousel.Item>
<img
className="d-block w-100"
src={photo.url}
alt="First slide"
/>
</Carousel.Item>
))
)}
</Carousel>
<div className="thumbnails-container">
<div className="thumnails-list">{renderThumbnails()}</div>
</div>
</div>
);
};
export default ControlledCarousel;
|
import React from 'react';
import { toggleEditingSections, fetchMenu, addSection, removeSection, addSubject, removeSubject } from '../../redux/actions';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import PropTypes from 'prop-types';
import SidebarItem from './SidebarItem';
class Sidebar extends React.Component {
constructor(props) {
super(props);
this.onClassClick = this.onClassClick.bind(this);
}
componentDidMount() {
this.props.fetchMenu();
}
render() {
const {
signedIn,
editingSections,
sections,
onEditSections,
onAddSection,
onRemoveSection,
onAddSubject,
onRemoveSubject
} = this.props;
return (
<nav className="main__sidebar sidebar">
<ul className="sidebar__list">
{sections.map((section) =>
<SidebarItem key={section.id} name={section.name} icon="folder-o"
editing={editingSections} onRemove={() => onRemoveSection(section.id)}>
{section.subjects.map((subject) =>
<SidebarItem key={subject.id} name={subject.name} icon="file-o"
editing={editingSections} to={`/class/${subject.id}`}
onRemove={() => onRemoveSubject(subject.id)} />
)}
{editingSections ? <SidebarItem name="Dodaj przedmiot" icon="plus"
onClick={() => onAddSubject(section.id)} /> : ''}
</SidebarItem>
)}
{editingSections ? <SidebarItem name="Dodaj sekcję" icon="plus" onClick={onAddSection} /> : ''}
{signedIn ?
<SidebarItem name={editingSections ? 'Zakończ edycje' : 'Edytuj sekcje'}
icon="wrench" onClick={onEditSections} />
: null}
</ul>
</nav>
);
}
onClassClick(classId) {
this.props.history.push(`/class/${classId}`);
}
}
Sidebar.propTypes = {
signedIn: PropTypes.bool.isRequired,
editingSections: PropTypes.bool.isRequired,
sections: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
subjects: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.string.isRequired,
name: PropTypes.string.isRequired
}).isRequired).isRequired
}).isRequired).isRequired,
fetchMenu: PropTypes.func.isRequired,
onEditSections: PropTypes.func.isRequired,
onAddSection: PropTypes.func.isRequired,
onRemoveSection: PropTypes.func.isRequired,
onAddSubject: PropTypes.func.isRequired,
onRemoveSubject: PropTypes.func.isRequired
};
const mapStateToProps = state => ({
signedIn: state.signedIn,
editingSections: state.editingSections,
sections: state.sections
});
const mapDispatchToProps = dispatch => ({
fetchMenu: () => dispatch(fetchMenu()),
onEditSections: () => dispatch(toggleEditingSections()),
onAddSection: () => {
const name = prompt('Podaj nazwę sekcji:');
if (!name) return;
dispatch(addSection(name));
},
onRemoveSection: id => dispatch(removeSection(id)),
onAddSubject: sectionId => {
const name = prompt('Podaj nazwę przedmiotu:');
if (!name) return;
dispatch(addSubject(name, sectionId))
},
onRemoveSubject: id => dispatch(removeSubject(id))
});
export default withRouter(
connect(
mapStateToProps,
mapDispatchToProps
)(Sidebar)
);
|
'use strict';
var templates = {
rankingCard: document.getElementById('ranking_card_template'),
exchangesListItem: document.getElementById('exchanges_listitem'),
scanProfileListItem: document.getElementById('scan_profiles_listitem'),
triggerListItem: document.getElementById('trigger_listitem')
}
var storage = {
exchanges: [
{
value: 'binance',
text: 'Binance',
intervals: [
{value: '1m', text: '1 minuto'},
{value: '5m', text: '5 Minutos'},
{value: '30m', text: '30 Minutos'},
{value: '1h', text: '1 Hora'},
{value: '4h', text: '4 Horas'},
{value: '12h', text: '12 Horas'},
{value: '1d', text: '1 Dia'},
{value: '1w', text: '1 Semana'},
{value: '1M', text: '1 Mes'},
]
},
{
value: 'bittrex',
text: 'Bittrex',
intervals: [
{value: 'oneMin', text: '1 minuto'},
{value: 'fiveMin', text: '5 Minutos'},
{value: 'thirtyMin', text: '30 Minutos'},
{value: 'hour', text: '1 Hora'},
{value: 'day', text: '1 Dia'}
]
}
],
};
storage.fetch = function(endpoint, slotName, onSuccess, onError){
//ESTO ES TOTALMENTE PRECARIO Y ES A FIN DE MAQUETADO
if (!storage[slotName]) {
sendAjaxRequest(endpoint, 'GET', null, (status, results) => {
if (status===200) {
storage[slotName]=results
if (onSuccess) onSuccess()
} else {
if (onError) onError(status)
//onError ? onError(status) : null
}
})
} else {
if (onSuccess) onSuccess()
}
}
var app = {
userData: {},
spinner: document.getElementById('spinner'),
notification: document.querySelector('.mdl-js-snackbar'),
registerDialog: document.getElementById('register_dialog'),
loginDialog: document.getElementById('login_dialog'),
newBookmarkDialog: document.getElementById('new_bookmark_dialog'),
rankingPanel: document.getElementById('ranking_panel'),
exchangesPanel: document.getElementById('exchanges_panel'),
scanProfilesPanel: document.getElementById('scan_profiles_panel'),
triggersPanel: document.getElementById('triggers_panel'),
navHome: document.getElementById('btn_home_nav'),
navBookmarks: document.getElementById('btn_bookmarks_nav'),
navExchanges: document.getElementById('btn_exchanges'),
navTriggers: document.getElementById('btn_triggers_nav'),
newBookmarkButton : document.getElementById('new_bookmark_button'),
newAccountButton: document.getElementById('new_account'),
registerButton: document.getElementById('register_button'),
loginButton: document.getElementById('login_button'),
logoutButton : document.getElementById('logout_button'),
strategySaveButton: document.getElementById('strategy_save_button'),
exchangesSelect: document.getElementById('strategy-exchange'),
intervalsSelect: document.getElementById('strategy-interval'),
triggersSelect: document.getElementById('strategy-trigger')
};
/***************************************************************************
* UI events
****************************************************************************/
document.addEventListener("DOMContentLoaded", e => {
sendAjaxRequest('/accounts/check', 'GET', null, callBackCheckSession)
})
app.newBookmarkButton.addEventListener('click', e => {
e.preventDefault()
hideAll()
showElement(app.newBookmarkDialog)
})
app.navExchanges.addEventListener('click', e => {
e.preventDefault()
hideAll()
showElement(app.exchangesPanel)
})
app.navHome.addEventListener('click', e => {
e.preventDefault()
hideAll()
showElement(app.rankingPanel)
})
app.navBookmarks.addEventListener('click', e => {
e.preventDefault()
hideAll()
showElement(app.scanProfilesPanel)
})
app.navTriggers.addEventListener('click', e => {
e.preventDefault()
hideAll()
showElement(app.triggersPanel)
})
app.logoutButton.addEventListener('click', () => {
sendAjaxRequest('/accounts/logout', 'GET')
})
app.newAccountButton.addEventListener('click', () => {
hideElement(app.loginDialog);
showElement(app.registerDialog);
})
app.registerButton.addEventListener('click', () => {
var parameters = JSON.stringify({
"userid": document.getElementById('reg-userid').value,
"name": document.getElementById('reg-name').value,
"phone": document.getElementById('reg-phone').value,
"password": document.getElementById('reg-password').value
})
hideElement(app.registerDialog)
sendAjaxRequest("/accounts/register", "POST", parameters, callBackRegister)
})
app.loginButton.addEventListener('click', () => {
var parameters = JSON.stringify({
"userid": document.getElementById('userid').value,
"password": document.getElementById('password').value
})
hideElement(app.loginDialog)
sendAjaxRequest("/accounts/login", "POST", parameters, callBackLogin)
})
app.exchangesSelect.addEventListener('change', ()=>{
var exchs = storage.exchanges.filter(
(exch) => {return exch.value === app.exchangesSelect.value}
)
renderIntervalOptions(exchs[0].intervals)
})
app.strategySaveButton.addEventListener('click', e => {
var parameters = JSON.stringify({
"exchange": app.exchangesSelect.value,
"coin": document.getElementById('strategy-coin').value,
"asset": document.getElementById('strategy-asset').value,
"interval": app.intervalsSelect.value,
"trigger": app.triggersSelect.value
})
sendAjaxRequest("/bookmarks", "POST", parameters, callBackNewBookmark)
})
/***************************************************************************
* UI methods
****************************************************************************/
function showElement(element){
element.classList.remove("hide");
componentHandler.upgradeElement(element)
}
function hideElement(element){
element.classList.add("hide");
}
function hideAll(){
hideElement(app.registerDialog)
hideElement(app.loginDialog)
hideElement(app.scanProfilesPanel)
hideElement(app.rankingPanel)
hideElement(app.exchangesPanel)
hideElement(app.newBookmarkDialog)
hideElement(app.triggersPanel)
}
function removeListitems(list) {
while(list.childElementCount>0){
list.removeChild(list.firstChild)
}
}
function removeOptions(select) {
for(var i=0; i < select.options.length; i++) {
select.remove(i)
}
}
function renderRanking(){
removeListitems(app.rankingPanel)
storage.ranking.forEach(element => {
var e = templates.rankingCard.cloneNode(true)
e.getElementsByClassName('name')[0].innerText = element.name
e.getElementsByClassName('price_btc')[0].innerText = element.price_btc
e.getElementsByClassName('price_usd')[0].innerText = element.price_usd
e.getElementsByClassName('vol_24h_usd')[0].innerText = element.vol_24h_usd
e.getElementsByClassName('percent_change_24h')[0].innerText = element.percent_change_24h + '%'
app.rankingPanel.appendChild(e)
showElement(e)
})
}
function renderExchangesPanel(){
let list = app.exchangesPanel.getElementsByClassName('mdl-list')[0]
removeListitems(list)
storage.exchanges.forEach(
exchange => {
var e = templates.exchangesListItem.cloneNode(true)
e.getElementsByClassName('name')[0].innerText = exchange.text
list.appendChild(e)
showElement(e)
}
)
}
function renderTriggersPanel(){
let list = app.triggersPanel.getElementsByClassName('mdl-list')[0]
removeListitems(list)
storage.triggers.forEach(
trigger => {
var e = templates.triggerListItem.cloneNode(true)
e.getElementsByClassName('trigger_name')[0].innerText = trigger.name
e.getElementsByClassName('trigger_termA')[0].innerText = trigger.termA
e.getElementsByClassName('trigger_operator')[0].innerText = trigger.operator
e.getElementsByClassName('trigger_termB')[0].innerText = trigger.termB
list.appendChild(e)
showElement(e)
}
)
}
function renderScanProfilesList(){
let list = app.scanProfilesPanel.getElementsByClassName('mdl-list')[0]
removeListitems(list)
storage.scanProfiles.forEach(p => {
var e = templates.scanProfileListItem.cloneNode(true)
e.getElementsByClassName('scan_profile_exchange')[0].innerText = p.exchange
e.getElementsByClassName('scan_profile_coin')[0].innerText = p.coin
e.getElementsByClassName('scan_profile_asset')[0].innerText = p.asset
e.getElementsByClassName('scan_profile_interval')[0].innerText = p.interval
list.appendChild(e)
showElement(e)
})
}
function renderIntervalOptions(intervals) {
var html = "<option></option>"
removeOptions(app.intervalsSelect)
intervals.forEach(
(interval) => { html += "<option value='" + interval.value + "'>" + interval.text + "</option>" }
)
app.intervalsSelect.innerHTML = html
}
function renderTriggersOptions() {
var html = "<option></option>"
removeOptions(app.triggersSelect)
storage.triggers.forEach(
trigger => {html += "<option value='" + trigger.id + "'>" + trigger.name + "</option>"}
)
app.triggersSelect.innerHTML = html
}
function showNotification(message, timeout, actionText, actionHandler){
var data = {
message: message,
timeout: timeout,
actionText: actionText
}
if (actionHandler) {
data.actionHandler = actionHandler(event)
}
app.notification.MaterialSnackbar.showSnackbar(data)
}
/***************************************************************************
* Callbacks
****************************************************************************/
function initApp(response) {
app.userData = response
//TODO: Faltan los onError de todos estos fetch
storage.fetch('/ranking', 'ranking', ()=>{
renderRanking()
showElement(app.rankingPanel)
})
storage.fetch('/exchanges', 'exchanges', renderExchangesPanel)
storage.fetch('/scan-profiles', 'scanProfiles', renderScanProfilesList)
storage.fetch('/triggers', 'triggers', () => {
renderTriggersOptions()
renderTriggersPanel()
})
}
function callBackCheckSession(status, response) {
if (status === 200) {initApp(response)}
if (status === 401) {showElement(app.loginDialog)}
}
function callBackLogin(status, response) {
if (status === 200) {initApp(response) }
if (status === 401) {
showNotification('Combinacion incorrecta!', 4000, 'ok')
showElement(app.loginDialog)
}
}
function callBackRegister(status, response) {
if (status === 200) {
hideElement(app.registerDialog);
showElement(app.loginDialog);
}
if (status === 401) {
showNotification('Esa cuenta ya existe!', 4000, 'Ok')
showElement(app.registerDialog);
}
if (status === 500) {
//showElement(app.registerError);
}
}
function callBackNewBookmark(status, response) {
if (status === 200) {
hideElement(app.newBookmarkDialog)
} else {
//TODO: Inform error
}
}
/***************************************************************************
* Server comm
****************************************************************************/
function sendAjaxRequest(endpoint, method, parameters, onComplete) {
var request = new XMLHttpRequest();
showElement(app.spinner);
request.onreadystatechange = function() {
if (request.readyState === XMLHttpRequest.DONE) {
hideElement(app.spinner);
var res = [];
if (request.response) res = JSON.parse(request.response);
if (onComplete) onComplete(request.status, res)
}
}
request.open(method, endpoint, true);
request.setRequestHeader('Content-Type', 'application/json');
request.send(parameters);
}
|
'use strict';
angular.module('AdBase').factory('loginResource',['$http', function($http){
var service = {};
var urlBase = '/adbase.server/rest/logins',
searchInput = {
entity:{},
start:0,
max:100,
fieldNames:[]
},
entity = {};
service.create = function(entity){
return $http.post(urlBase,entity);
};
service.update = function(entity){
return $http.put(urlBase+'/'+entity.id,entity);
};
service.findBy = function(entitySearchInput){
return $http.post(urlBase+'/findBy',entitySearchInput);
};
service.findByLike = function(entitySearchInput){
return $http.post(urlBase+'/findByLike',entitySearchInput);
};
service.nextLogin = function(entityId){
return $http.get(urlBase+'/nextLogin/'+entityId);
};
service.previousLogin = function(entityId){
return $http.get(urlBase+'/previousLogin/'+entityId);
};
service.findById = function(entityId){
return $http.get(urlBase+'/'+entityId);
};
service.deleteById = function(entityId){
return $http.delete(urlBase+'/'+entityId);
};
service.listAll = function(start,max){
return $http.get(urlBase,{params: {start: start,max:max}});
};
service.getSearchInput = function(){
return searchInput ;
};
service.getEntity = function(){
return entity ;
};
service.processPasswordChange = function(data){
return $http.post(urlBase+'/processPasswordChange',data);
};
service.changeUserPassword = function(data){
return $http.post(urlBase+'/changeUserPassword',data);
};
service.changeMyPassword = function(data){
return $http.post(urlBase+'/changeMyPassword',data);
};
service.findManagedLogins = function(searchInput){
return $http.post(urlBase+'/findManagedLogins',searchInput);
};
function getSearchInput(){
return searchInput ;
};
return service;
}]);
|
import React, { useState, useRef, useEffect } from "react";
import "./app.css";
import Newposts from "./utils/newpost/Newposts";
import Editposts from "./utils/EditPosts/Editposts";
import Allposts from "./utils/AllPosts/Allposts";
import { Stats } from "./utils/stats/stats";
import { Comments } from "./utils/comments/comments";
import { Settins } from "./utils/settings/settins";
import { Dash } from "./utils/Dash/dash";
import { BrowserRouter as Router, Route, Redirect } from "react-router-dom";
import { CgSidebarRight } from "react-icons/cg";
import { SideContents } from "./utils/SideContents";
import { RiEyeCloseLine, RiEyeLine } from "react-icons/ri";
import axios from "axios";
import { connect } from "react-redux";
import { Fullscreen } from "../components/Spinner/fullscreen";
import { url } from "../baseHost";
var slugify = require("slugify");
const AdminApp = (props) => {
const [toggle, setToggle] = useState(false);
const [showPass, setShowPass] = useState(false);
const [Spinin, setSpining] = useState(false)
const sidetoggler=useRef()
const [background, setprofileImg] = useState(
"https://upload.wikimedia.org/wikipedia/en/6/69/ImagineCover.jpg"
);
const [loggedin, setLoggen] = useState(0);
const profile = useRef();
const password = useRef();
const username = useRef();
// useEffect(() => {
// setLoggen(props.Login.state);
// }, [props.Login.state]);
useEffect(() => {
axios
.get(`${url}/admin`,{headers: {
token: localStorage.getItem('token'),
}})
.then((data) => {
console.log(data.data)
props.user(data.data)
if(data.data.state){
if(window.location.pathname==="/admin-login"){
console.log('hiiqfwfq')
window.location.pathname="/admin"
}
}else{
setSpining(false)
}
});
}, [loggedin]);
useEffect(() => {
if (props.Login.data !== undefined) {
setprofileImg(
`${url}/${
props.Login.data.image.split("/")[0]
}/${slugify(`${props.Login.data.image.split("/")[1]}`, {
replacement: "%20",
remove: false, // remove characters that match regex, defaults to `undefined`
locale: "vi", // language code of the locale to use
})}`
);
}
}, [props.Login]);
const handleSubmit = () => {
(async () => {
setSpining(true)
const apiData = await fetch(`${url}/admin-login`, {
method: "POST",
body: JSON.stringify({
name: username.current.value,
password: password.current.value,
}),
credentials: "include", // added this part
headers: {
"Content-Type": "application/json",
},
});
setLoggen(loggedin+1)
const token =await apiData.json();
// console.log(token)
// console.log(token.token)
localStorage.setItem('token',token.token)
})();
};
const handleToggle = () => {
try{
if (!toggle) {
setTimeout(() => {
sidetoggler.current.classList.add("ttoggle_admin");
}, 390);
} else {
sidetoggler.current.classList.remove("ttoggle_admin");
}
}catch(err){
}
setToggle(!toggle);
};
const untoggle=()=>{
try{
if(window.screen.width<600){
sidetoggler.current.classList.remove("ttoggle_admin");
setToggle(!toggle);
}
}catch(err){
}
}
const changeProfileImg = () => {
profile.current.dispatchEvent(
new MouseEvent("click", {
bubbles: true,
cancelable: true,
clientX: 100,
clientY: 100,
})
);
};
const handleSelectProfile = (e) => {
let pix = new FormData();
pix.append("profile", e.target.files[0]);
const config = {
headers: {
"content-type": "multipart/form-data",
},
withCredentials: true,
};
axios.post(`${url}/admin-profile`, pix, config);
};
return (
<Router>
<Route path="/admin">
{props.Login.state===false? (
<Redirect to="/admin-login" />
) :<>{props.Login.state===true?(
<div className="adminApp">
<div
ref={ sidetoggler}
className="sideBar"
style={{ width: `${toggle ? "7%" : "22%"}` }}
>
<div className="toggle_admin">
<span onClick={handleToggle}>
<CgSidebarRight />
</span>
</div>
<SideContents unshow={untoggle} />
</div>
<div
className="constainer"
style={{ width: `${toggle ? "93%" : "78%"}` }}
>
<div className="AdminNav">
<div className="intack">
<span onClick={handleToggle}>
<CgSidebarRight />
</span>
</div>
<div>
<div className="Adminlogout">logOut</div>
<div
className="profileImg"
onClick={changeProfileImg}
style={{ backgroundImage: `url(${background})` }}
></div>
<input
onChange={handleSelectProfile}
type="file"
ref={profile}
id="profile_file"
style={{ display: "none" }}
/>
</div>
</div>
<div className="content">
<Route exact path="/admin">
<Dash />
</Route>
<Route path="/admin/newpost">
<Newposts />
</Route>
<Route path="/admin/editposts/:id">
<Editposts />
</Route>
<Route path="/admin/settings">
<Settins />
</Route>
<Route path="/admin">
<Comments />
</Route>
<Route path="/admin/stats">
<Stats />
</Route>
<Route path="/admin/allposts">
<Allposts />
</Route>
</div>
</div>
</div>
):<Fullscreen/>} </>}
</Route>
<Route path="/admin-login">
{props.Login.state===false?(<div className="admin_login">
{Spinin?<Fullscreen/>:''}
<div className="login_bal">
<div></div>
<div>
<p>username</p>
<div>
<input ref={username} type="text" />
</div>
</div>
<div>
<p>password</p>
<div>
<input
ref={password}
type={showPass === true ? "text" : "password"}
/>
<span onClick={() => setShowPass(!showPass)}>
{showPass ? <RiEyeLine /> : <RiEyeCloseLine />}
</span>
</div>
</div>
<div className="submit_cont">
<label>
<input type="checkbox" />
<span>Remember me</span>
</label>
<button onClick={handleSubmit}>Login</button>
</div>
</div>
</div>):<Redirect to="/admin" />}
</Route>
</Router>
);
};
const mapStateToProps = (state) => {
return {
Login: state.Admin,
};
};
//this sets the dispatch method props for the dispatching data
const setter = (dispatch) => {
return {
user: (body) => {
dispatch({ type: "user", payload: body });
},
// Title: (t) => {
// dispatch({ type: "title", payload: t });
// },
// specs: (name, spec) => {
// dispatch({ type: "spec", payload: { name, spec } });
// },
// major: (major) => {
// dispatch({ type: "major", payload: major });
// },
};
};
export default connect(mapStateToProps, setter)(AdminApp);
|
import { quizData } from '../data.js';
export function questionToDelete() {
//Let user choose which question to delete
const deleteTheQuestion = window.prompt(
'Enter the question you want to delete!'
);
//filter the questions list ad removing only the deleted question:
quizData.questions = quizData.questions.filter(
(data) => data.text != deleteTheQuestion
);
}
|
import { Link } from "react-router-dom";
import tw from 'tailwind-styled-components'
export const StyledIntroItemNavLink = tw(Link)`
text-blue-700
hover:underline
`
|
import express from 'express';
import path from 'path';
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 3000;
app.use(express.static(path.resolve('build')));
app.use(bodyParser.json());
app.get('/*', (req, res) => {
res.sendFile(path.resolve('build/index.html'));
});
app.listen(port, () => {
console.log(`server started on port ${port}`);
});
|
//------------------slider--------------------------------
theimage = new Array();
// Format: theimage[...]=[image URL, link URL, name/description]
theimage[0]=["images/1.jpg", "", "Leopards in yala"];
theimage[1]=["images/2.jpg", "", "Elephants in yala"];
theimage[2]=["images/3.jpg", "", "Birds in yala"];
theimage[3]=["images/4.jpg", "", "Animals"];
theimage[4]=["images/5.jpg", "", "Safari "];
theimage[5]=["images/6.jpg", "", "Crocodile"];
theimage[6]=["images/7.jpg", "", "Deer"];
theimage[7]=["images/8.jpg", "", "Camping"];
theimage[8]=["images/9.jpg", "", "Hotels"];
theimage[9]=["images/10.jpg", "", "Leopards"];
playspeed=3000;// ms
//#####
i=0;
//###########################################
window.onload=function(){
preloadSlide();
SetSlide(0);
//autoplay
PlaySlide();
};
//###########################################
function SetSlide(num) {
i=num%theimage.length;
if(i<0)i=theimage.length-1;
document.images.imgslide.src=theimage[i][0];
document.getElementById('slidebox').innerHTML=theimage[i][2];
document.getElementById('slidecount').innerHTML= " "+(i+1)+" - "+theimage.length;
}
//###########################################
function PlaySlide() {
if (!window.playing) {
PlayingSlide(i+1);
if(document.slideshow.play){
document.slideshow.play.value=" Stop ";
}
}
else {
playing=clearTimeout(playing);
if(document.slideshow.play){
document.slideshow.play.value=" Play ";
}
}
if(document.images.imgPlay){
setTimeout('document.images.imgPlay.src="'+imgStop+'"',1);
imgStop=document.images.imgPlay.src;
}
}
//###########################################
function PlayingSlide(num) {
playing=setTimeout('PlayingSlide(i+1);SetSlide(i+1);', playspeed);
}
//###########################################
function preloadSlide() {
for(k=0;k<theimage.length;k++) {
theimage[k][0]=new Image().src=theimage[k][0];
}
}
//###########################################
|
import DS from 'ember-data';
export default DS.Model.extend({
givenName: DS.attr('string'),
familyName: DS.attr('string'),
nickname: DS.attr('string'),
identicon: DS.attr('string'),
isActive: DS.attr('boolean'),
isStaff: DS.attr('boolean'),
demographics: DS.hasMany('demographic'),
children: DS.hasMany('child'),
emailNextSession: DS.attr('boolean'),
emailNewStudies: DS.attr('boolean'),
emailStudyUpdates: DS.attr('boolean'),
emailResponseQuestions: DS.attr('boolean')
});
|
/**
* @name CourseCard
*
* @author Chris Holle
* @author Mario Arturo Lopez Martinez
*
* @overview Card to be used to display course name and projects under a
* certain course when activated.
*
* @param {string} name name of course
* @param {string} semester current Semester
* @param {string} active true if the card is active, false if not active
* @param {string} year course year
* @param {string} number course number designated by registrar
* @param {string} prefix course prefix designated by department
*
* @example
*
* <CourseCard
* name="Engineering Design II"
* semester="Spring"
* year="2020"
* number="4390"
* prefix="ENG"
* active
* />
* @TODO: Add verification modal for delete
* @TODO: Refactor Delete Modal out of file
* @TODO: Only show options when on Dashboard
*/
import React, { useState } from "react"
import styled from "styled-components"
import { FaEllipsisV } from "react-icons/fa"
import {
Col,
Dropdown,
DropdownItem,
DropdownMenu,
DropdownToggle,
Modal,
ModalBody,
ModalHeader,
Row,
} from "reactstrap"
import Button from "components/btn"
import EditCourseForm from "components/forms/editCourseForm"
const CourseCard = styled.div`
padding: 1.6rem;
box-shadow: 2px 2px 12px rgba(0, 0, 0, 0.2);
margin: 10px;
width: 325px;
height: 120px;
text-align: left;
border-top: 2px solid ${props => props.theme.secondaryGreen};
transition-duration: 0.3s;
&:hover {
box-shadow: 2px 2px 14px rgba(0, 0, 0, 0.4);
background: ${props => props.theme.secondaryGreen};
border-top: 2px solid ${props => props.theme.secondaryGold};
}
&:hover h4 {
color: white;
}
&:hover p {
color: ${props => props.theme.secondaryGold};
}
&.active {
box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.2);
background: ${props => props.theme.secondaryGreen};
border-top: 2px solid ${props => props.theme.secondaryGold};
transform: translateY(-5px);
cursor: pointer;
}
&.active h4 {
color: white;
}
&.active p {
color: ${props => props.theme.secondaryGold};
}
`
const CourseName = styled.h4`
font-family: "BioSans", sans-serif;
color: ${props => props.theme.primaryGreen};
text-align: left;
`
const CourseSemester = styled.p`
font-family: Georgia, serif;
font-size: 18px;
text-transform: capitalize;
line-height: 10px;
text-align: left;
color: #c3c3c3;
`
// TODO: Add dropdown menu with edit and delete
// TODO: Create child callback to send information on delete
// TODO: Create child callback to send information on edit
export default ({
id,
prefix,
number,
semester,
active,
year,
name,
startDate,
endDate,
onChildClick,
}) => {
const [dropdownOpen, setDropdownOpen] = useState(false)
const toggle = () => setDropdownOpen(prevState => !prevState)
// delete modal items
const [del_modal, setDeleteModal] = useState(false)
const delete_modal_toggle = () => setDeleteModal(!del_modal)
// edit modal items
const [edit_modal, setEditModal] = useState(false)
const edit_modal_toggle = () => setEditModal(!edit_modal)
function handleClick(id) {
onChildClick(id) // pass any argument to the callback
}
return (
<CourseCard className={`${active ? "active" : ""}`}>
<Row>
<Col>
<CourseName>
{prefix} {number} {name}
</CourseName>
<CourseSemester>
{semester} {year}
</CourseSemester>
</Col>
<Col md={2}>
<Dropdown isOpen={dropdownOpen} toggle={toggle}>
<DropdownToggle
style={{ background: "inherit", border: "none", outline: "none" }}
data-toggle="dropdown"
aria-haspopup
aria-expanded={dropdownOpen}
>
<div className="card-tools-icon">
<FaEllipsisV />
</div>
</DropdownToggle>
<DropdownMenu>
<DropdownItem header>Course Tools</DropdownItem>
<DropdownItem onClick={edit_modal_toggle}>Edit</DropdownItem>
<DropdownItem onClick={delete_modal_toggle}>Delete</DropdownItem>
</DropdownMenu>
</Dropdown>
</Col>
</Row>
<Modal isOpen={del_modal} toggle={delete_modal_toggle}>
<ModalHeader
toggle={delete_modal_toggle}
style={{ textAlign: "center" }}
>
Delete Course
</ModalHeader>
<ModalBody>
<h4 style={{ textAlign: "center" }}>
{" "}
Are you sure you want to delete course {name}?
</h4>
<hr />
<Button
onClick={delete_modal_toggle}
border
rounded
small
textColor="primary-green"
>
Cancel
</Button>
<Button
onClick={() => handleClick(id)}
small
border
textColor="primary-green"
style={{ float: "right" }}
>
Delete
</Button>
</ModalBody>
</Modal>
<Modal isOpen={edit_modal} backdrop="static" toggle={edit_modal_toggle}>
<ModalHeader toggle={edit_modal_toggle}>Edit Course</ModalHeader>
<ModalBody>
<EditCourseForm
id={id}
prefix={prefix}
number={number}
active={active}
name={name}
year={year}
semester={semester}
startDate={startDate}
endDate={endDate}
onEditSuccess={edit_modal_toggle}
/>
</ModalBody>
</Modal>
</CourseCard>
)
}
|
const appConfig = {
version: '__version__'
};
export default appConfig;
|
import carOne from "../assets/car1.png";
import carTwo from "../assets/car2.png";
import carThree from "../assets/car3.png";
import carFour from "../assets/car4.png";
import carFive from "../assets/car5.png";
import carSix from "../assets/car6.png";
const rides = [
{
img: carOne,
title: "Taxi",
persons: "4",
bags: "4",
price: "10",
features: [
"Free Cancellation",
"Free Waiting Time",
"Free Meet & Greet with Welcome Sign",
"Your Own Private Transfer, Not Shared",
"Max Capacity: 4 Passengers & 4 Suitcases",
"Vehicle will be Toyota Voxy or Similar",
],
},
{
img: carTwo,
title: "VIP & Exec",
persons: "3",
bags: "3",
price: "15",
features: [
"Free Cancellation",
"Free Waiting Time",
"Free Meet & Greet with Welcome Sign",
"Your Own Private Transfer, Not Shared",
"Max Capacity: 3 Passengers & 3 Suitcases",
"Vehicle will be Mercedes or Similar",
],
},
{
img: carThree,
title: "Small Bus",
persons: "8",
bags: "8",
price: "30",
features: [
"Free Cancellation",
"Free Waiting Time",
"Free Meet & Greet with Welcome Sign",
"Your Own Private Transfer, Not Shared",
"Max Capacity: 8 Passengers & 8 Suitcases",
"Vehicle will be Mercedes or Similar",
],
},
{
img: carFour,
title: "Family Taxi",
persons: "6",
bags: "6",
price: "20",
features: [
"Free Cancellation",
"Free Waiting Time",
"Free Meet & Greet with Welcome Sign",
"Your Own Private Transfer, Not Shared",
"Max Capacity: 6 Passengers & 6 Suitcases",
"Vehicle will be Mercedes or Similar",
],
},
{
img: carFive,
title: "Coach",
persons: "30",
bags: "30",
price: "50",
features: [
"Free Cancellation",
"Free Waiting Time",
"Free Meet & Greet with Welcome Sign",
"Your Own Private Transfer, Not Shared",
"Max Capacity: 30 Passengers & 30 Suitcases",
"Vehicle will be Mercedes or Similar",
],
},
{
img: carSix,
title: "Mini Bus",
persons: "6",
bags: "6",
price: "20",
features: [
"Free Cancellation",
"Free Waiting Time",
"Free Meet & Greet with Welcome Sign",
"Your Own Private Transfer, Not Shared",
"Max Capacity: 6 Passengers & 6 Suitcases",
"Vehicle will be Mercedes or Similar",
],
},
];
export default rides;
|
function loadLogin(){
$('#google').click(loginGoogle);
$('#facebook').click(loginFaceBook);
$('#github').click(loginGitHub);
$('#twitter').click(loginTwitter);
localStorage.removeItem('userLogged');
// Initialize Firebase
var config = {
apiKey: "AIzaSyB65JCI354B-wD5TjaDDscMWqrYl_NHLPg",
authDomain: "ebest-38a9f.firebaseapp.com",
databaseURL: "https://ebest-38a9f.firebaseio.com",
projectId: "ebest-38a9f",
storageBucket: "ebest-38a9f.appspot.com",
messagingSenderId: "552646215125"
};
firebase.initializeApp(config);
firebase.auth().signOut().then(function () {
// Sign-out successful.
}).catch(function (error) {
// An error happened.
console.log(error);
});
function loginGoogle() {
fireBaseLog(new firebase.auth.GoogleAuthProvider());
}
function loginFaceBook() {
fireBaseLog(new firebase.auth.FacebookAuthProvider());
}
function loginTwitter() {
fireBaseLog(new firebase.auth.TwitterAuthProvider());
}
function loginGitHub() {
fireBaseLog(new firebase.auth.GithubAuthProvider());
}
function fireBaseLog(provider) {
firebase.auth().signInWithPopup(provider).then(function (result) {
var user = result.additionalUserInfo.profile.name;
console.log(result);
save(user, "userLogged");
window.location.href = "index.html";
}).catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode, errorMessage);
});
}
}
|
import React from "react";
import {
ScrollView,
StyleSheet,
View,
TextInput,
Text,
Button
} from "react-native";
import { Avatar, ListItem } from "react-native-elements";
import Icon from "react-native-vector-icons/MaterialIcons";
import { findFollows, emptyFindFollows } from "../actions/findFollowsAction";
import { addFollows } from "../actions/addFollowsAction";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { firestoreConnect } from "react-redux-firebase";
import { compose } from "redux";
class SearchFriendsScreen extends React.Component {
static navigationOptions = {
title: "Search",
headerStyle: {
backgroundColor: "#8F52AD"
},
headerTintColor: "#fff",
headerTitleStyle: {
fontWeight: "bold"
}
};
state = {
name: ""
};
componentDidMount() {
this.props.emptyFindFollows();
}
componentDidUpdate(prevProps, prevState) {
const { name } = this.state;
if (name.length > 0) {
if (name !== prevState.name) {
this.props.findFollows(name.trim());
}
}
}
render() {
let list = [];
if (this.props.searchFollowsReducer) {
this.props.searchFollowsReducer.map(id => {
list.push(id);
});
}
return (
<ScrollView style={styles.container}>
<View>
<TextInput
style={styles.textInput}
clearButtonMode="always"
onChangeText={name => this.setState({ name })}
/>
</View>
<View style={styles.list}>
{this.props.users.map(user =>
list.map(
id =>
user.id === id &&
(this.props.profile.follows.indexOf(user.id) === -1 ? (
<ListItem
key={user.id}
containerStyle={styles.listItem}
title={user.firstName + " " + user.secondName}
titleStyle={styles.listText}
avatar={{ uri: user.avatar }}
roundAvatar
avatarContainerStyle={styles.avatarContainerStyle}
avatarStyle={styles.avatarStyle}
rightIcon=<Icon
name="person-add"
size={25}
style={{ marginRight: 5, color: "#8F52AD" }}
onPress={() =>
this.props.addFollows(user.id, this.props.auth.uid)
}
/>
onPress={() =>
this.props.navigation.navigate("UserPageScreen", {
id: user.id
})
}
/>
) : (
<ListItem
key={user.id}
containerStyle={styles.listItem}
title={user.firstName + " " + user.secondName}
titleStyle={styles.listText}
avatar={{ uri: user.avatar }}
roundAvatar
avatarContainerStyle={styles.avatarContainerStyle}
avatarStyle={styles.avatarStyle}
rightIcon=<Icon
name="check"
size={25}
style={{ marginRight: 5, color: "#8F52AD" }}
/>
onPress={() =>
this.props.navigation.navigate("UserPageScreen", {
id: user.id
})
}
/>
))
)
)}
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#F9F9F9"
},
textInput: {
height: 40,
borderColor: "#8F52AD",
borderWidth: 1,
marginHorizontal: 5,
marginTop: 5,
backgroundColor: "#fff"
},
list: {
marginTop: 7,
backgroundColor: "#FFF"
},
listItem: {
paddingTop: 17,
paddingBottom: 17,
borderBottomWidth: 0
},
listText: {
flex: 7,
fontSize: 18,
marginLeft: 15
},
avatarContainerStyle: {
width: 50,
height: 50,
marginLeft: 5
},
avatarStyle: {
width: 60,
height: 60,
borderRadius: 50
}
});
function mapStateToProps(state) {
return {
profile: state.firebase.profile,
auth: state.firebase.auth,
users: state.firestore.ordered.users,
searchFollowsReducer: state.searchFollowsReducer
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(
{
findFollows,
emptyFindFollows,
addFollows
},
dispatch
);
}
export default compose(
connect(
mapStateToProps,
mapDispatchToProps
),
firestoreConnect([{ collection: "users" }])
)(SearchFriendsScreen);
|
/*==================================================
Prototype
====================================================*/
Swiper.prototype = {
isSafari: (function () {
var ua = navigator.userAgent.toLowerCase();
return (ua.indexOf('safari') >= 0 && ua.indexOf('chrome') < 0 && ua.indexOf('android') < 0);
})(),
isUiWebView: /(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent),
isArray: function (arr) {
return Object.prototype.toString.apply(arr) === '[object Array]';
},
/*==================================================
Feature Detection
====================================================*/
support: {
touch : (window.Modernizr && Modernizr.touch === true) || (function () {
return !!(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch);
})(),
transforms3d : (window.Modernizr && Modernizr.csstransforms3d === true) || (function () {
var div = document.createElement('div').style;
return ('webkitPerspective' in div || 'MozPerspective' in div || 'OPerspective' in div || 'MsPerspective' in div || 'perspective' in div);
})(),
flexbox: (function () {
var div = document.createElement('div').style;
var styles = ('WebkitBox msFlexbox MsFlexbox WebkitFlex MozBox flex').split(' ');
for (var i = 0; i < styles.length; i++) {
if (styles[i] in div) return true;
}
})(),
observer: (function () {
return ('MutationObserver' in window || 'WebkitMutationObserver' in window);
})()
},
};
|
import {
MODAL_OPEN,
MODAL_CLOSE,
POSTS_REMOVE_CONFIRM,
WEATHER_CITY_SELECTED,
} from '../../types';
export default (state = false, action) => {
switch (action.type) {
case WEATHER_CITY_SELECTED:
case POSTS_REMOVE_CONFIRM:
return true;
case MODAL_CLOSE:
return false;
case MODAL_OPEN:
return true;
default:
return state;
}
};
|
export { styled, setup } from './styled';
export { extractCss } from './core/update';
export { css, glob, keyframes } from './css';
|
'use strict';
const path = require('path');
module.exports = {
async loadTemplates(provider) {
const createFilePath = path.join(provider.serverless.config.servicePath,
'.serverless', 'configuration-template-create.json');
const updateFilePath = path.join(provider.serverless.config.servicePath,
'.serverless', 'configuration-template-update.json');
provider.templates = {
create: provider.serverless.utils.readFileSync(createFilePath),
update: provider.serverless.utils.readFileSync(updateFilePath)
};
}
};
|
/**
* @fileoverview Layout based utils to enforce common patterns
* @author Gabriel Womble
*/
import { VARIANTS } from 'lib/constants';
const { OVERLAY, SIDEPANEL } = VARIANTS;
/**
* Gets the sidepanel variant based on media query
* @returns {string} sidepanelVariant
* @param {boolean} isMobile - isMobile bool from useMedia media object
*/
function getSidepanelVariant({ isMobile }) {
return isMobile
? OVERLAY
: SIDEPANEL;
}
export { getSidepanelVariant };
|
import './style.scss';
import { Header } from './components/header';
console.log(`this is index`);
// SET INITIAL APPLICATION STATE
let STATE = [];
function getPokes() {
fetch('https://pokeapi.co/api/v2/pokemon/')
.then((res) => res.json())
.then((res) => {
STATE = [...res.results];
console.log(STATE);
renderApp(STATE);
})
.catch((err) => console.error(`🤔 ${err} has occured!`));
}
getPokes();
const template = (bud) =>
`<li class="pokeItem" data-url=${bud.url}>${bud.name}</li>`;
// DOM building
function renderApp(STATE) {
const list = document.querySelector('.main-list');
STATE.forEach((i) => {
list.insertAdjacentHTML('afterbegin', template(i));
});
const header = document.querySelector('.container');
const headerH1 = document.querySelector('.container h1');
header.insertAdjacentHTML('afterbegin', Header('Pokemon App'));
initListClicks();
}
function initListClicks() {
const allListItems = document.querySelectorAll('li.pokeItem');
allListItems.forEach((i) =>
i.addEventListener('click', function() {
const pokeUrl = i.dataset.url;
fetch(i.dataset.url)
.then((res) => res.json())
.then((res) => renderPoke(res))
.catch((err) => console.error(`🤔 ${err} has occured!`));
})
);
}
function renderPoke(data) {
const mainSection = document.querySelector('main');
mainSection.innerHTML = '';
console.log(data);
const { sprites, moves, abilities, name } = data;
const pokeTemplate = `<div>
<h2>${name}</h2>
<h4>Sprites:</h4>
<ul class="sprites-list">
${Object.entries(sprites)
.map((s) => {
if (s[1] === null) {
console.log(`no sprite available for ${s[0]}`);
} else {
return `<img src=${s[1]} alt=${s[0]} title=${s[0]}/>`;
}
})
.join('')}
</ul>
<h4>Abilities:</h4>
<ul class="abilities-list">
${abilities.map((a) => `<li>` + a.ability.name + `</li>`).join('')}
</ul>
<h4>Moves:</h4>
<ul class="moves-list">
${moves.map((m) => `<li>` + m.move.name + `</li>`).join('')}
</ul>
</div>`;
mainSection.insertAdjacentHTML('afterbegin', pokeTemplate);
}
|
module.exports = (function() {
function generateBackground() {
var $bg = $('<div id="popoutBackground" style="position:absolute;z-index:999;width:100%;height:100%;background-color:black;opacity:.6"></div>')
$('body').append($bg)
}
function setPosition($elem, id, callback) {
$elem.attr('id', 'pop-'+id)
$('body').append($elem)
$elem.css({
"display": "none",
"position": "absolute",
"z-index": 999,
"left": function() {
var elemWidth = Number($elem.css('width').slice(0, -2))
var windowWidth = $(window).width()
return (windowWidth - elemWidth)/2
},
"top": function() {
var elemHeight = Number($elem.css('height').slice(0, -2))
var windowHeight = $(window).height()
return (windowHeight - elemHeight)/2
}
})
$elem.show()
}
function removePopById(id) {
$('#pop-'+id).remove()
$('#popoutBackground').remove()
}
function lawProtocal() {
generateBackground();
var $pop = $('<div class="jyopenboxbox"><div class="fengxiantext"><div class="title">合买隐私和法律风险协议</div><dl><dt><span>-</span>合买隐私</dt><dd>您同意参与合买后,200和2000以上的单子,会分享给您的关注用户。这些用户将会看到您本人头像、昵称、以及单子信息,单子信息包括操作方向、操作点位、花费金额、止损止盈、交易盈亏。用户还能通过您的个人简介,了解您的最近10单交易、总盈利以及单笔最高盈利。您的其他信息微盘宝官方保证不会公开。</dd><dt><span>-</span>法律风险协议</dt><dd>您同意参与合买后,200和2000以上的单子,会分享给您的关注用户。这些用户将会看到您本人头像、昵称、以及单子信息,单子信息包括操作方向、操作点位、花费金额、止损止盈、交易盈亏。用户还能通过您的个人简介,了解您的最近10单交易、总盈利以及单笔最高盈利。您的其他信息微盘宝官方保证不会公开。</dd></dl></div><div class="btnbox"><div class="btnboxbtn01">关闭</div></div></div>')
setPosition($pop, 'lawProtocal')
$pop.find('.btnboxbtn01').click(function() {
removePopById('lawProtocal')
})
}
function combinationNameConfirm(name, callback) {
generateBackground();
var $pop = $('<div class="jyopenboxbox"><div class="close"></div><div class="hemainame"><p class="text01">您的合买名字是:</p><p class="text02">'+name+'</p><p class="text03">温馨提示:<br />名字确认后不可更改,好听的名字可以提高人气哦!</p></div><div class="btnbox"><div class="btnboxbtn01">好的,我确定了</div></div></div>')
setPosition($pop, 'combinationNameconfirm')
$pop.find('.close').click(function() {
removePopById('combinationNameconfirm')
})
$pop.find('.btnboxbtn01').click(function() {
removePopById('combinationNameconfirm')
callback()
})
}
function combinationNameError(msg) {
generateBackground();
var $pop = $('<div class="jyopenboxbox"><div class="close"></div><div class="boxtext"><p><span class="icon01"></span>'+msg+'</p></div><div class="btnbox"><div class="btnboxbtn01">好的</div></div></div>')
setPosition($pop, 'combinationNameError')
$pop.find('.btnboxbtn01').click(function() {
removePopById('combinationNameError')
})
}
function attentionDel(okCB, cancelCB) {
generateBackground();
var $pop = $('<div class="jyopenboxbox"><div class="close"></div><div class="boxtext"><p><span class="icon02"></span>确定取消关注达人吗?</p></div><div class="btnbox"><div class="btnboxbtn01 nop">否</div><div class="btnboxbtn01 yep">是</div></div></div>')
setPosition($pop, 'attentionDel')
$pop.find('.nop, .close').click(function() {
removePopById('attentionDel')
cancelCB&&cancelCB()
})
$pop.find('.yep').click(function() {
removePopById('attentionDel')
okCB&&okCB()
})
}
function checkTitle() {
generateBackground();
var $pop = $('<div class="jyopenboxbox"><div class="close"></div><div class="boxtext"><p><span class="icon01"></span>这个名字其他人已使用,请更换。</p></div><div class="btnbox"><div class="btnboxbtn01">好的</div></div></div>')
setPosition($pop, 'checkTitle')
$pop.find('.btnboxbtn01').click(function() {
removePopById('checkTitle')
})
}
function superiorCancel(callback) {
generateBackground();
var $pop = $('<div class="jyopenboxbox"><div class="close"></div><div class="boxtext"><p><span class="icon02"></span>您要取消合买吗?</p></div><div class="btnbox"><div class="btnboxbtn01 nop">否</div><div class="btnboxbtn01 yep">是</div></div></div>')
setPosition($pop, 'superiorCancel')
$pop.find('.nop, .close').click(function() {
removePopById('superiorCancel')
})
$pop.find('.yep').click(function() {
removePopById('superiorCancel')
callback()
})
}
function existCurrBid() {
generateBackground();
var $pop = $('<div class="jyopenboxbox"><div class="close"></div><div class="boxtext openCenter"><p>您当前已有持仓单,需平仓后参与合买</p></div><div class="btnbox"><div class="btnboxbtn01 nop">好的</div></div></div>')
setPosition($pop, 'existCurrBid')
$pop.find('.nop, .close').click(function() {
removePopById('existCurrBid')
})
}
function specifiedNaming() {
generateBackground();
var $pop = $('<div class="jyopenboxbox"><div class="close"></div><div class="boxtext openCenter"><p>命名只能是中文、英文、数字和“-”、“_”。</p></div><div class="btnbox"><div class="btnboxbtn01 nop">好的</div></div></div>')
setPosition($pop, 'specifiedNaming')
$pop.find('.nop, .close').click(function() {
removePopById('specifiedNaming')
})
}
function forHintWithOneButton(msg) {
generateBackground();
var $pop = $('<div class="jyopenboxbox"><div class="close"></div><div class="boxtext openCenter"><p>'+msg+'</p></div><div class="btnbox"><div class="btnboxbtn01 nop">好的</div></div></div>')
setPosition($pop, 'forHintWithOneButton')
$pop.find('.nop, .close').click(function() {
removePopById('forHintWithOneButton')
})
}
return {
lawProtocal: lawProtocal,
combinationNameError: combinationNameError,
combinationNameConfirm: combinationNameConfirm,
attentionDel: attentionDel,
checkTitle: checkTitle,
superiorCancel: superiorCancel,
existCurrBid: existCurrBid,
specifiedNaming: specifiedNaming,
forHintWithOneButton: forHintWithOneButton
}
})()
|
$('document').ready(function() {
$('div[data-async-partial]').each(function(){
var element = $(this);
var url = element.data('async-partial');
$.get(url, function(data) {
element.html(data)
})
})
});
|
import firebase from "firebase"
const firebaseConfig = {
apiKey: process.env.REACT_APP_API_KEY,
authDomain: process.env.REACT_APP_DOMAIN,
databaseURL: process.env.REACT_APP_DB_URL,
projectId: process.env.REACT_APP_PROJECT_ID,
storageBucket: process.env.REACT_APP_STORAGE,
messagingSenderId: process.env.REACT_APP_MESSAGE_SENDER_ID,
appId: process.env.REACT_APP_APP_ID,
};
const firebaseApp = firebase.initializeApp(firebaseConfig)
const auth = firebaseApp.auth()
const provider = new firebase.auth.GoogleAuthProvider()
export {auth,provider};
export default auth
|
const base = require('../base')
// 和彩云网盘
const pName = 'com.chinamobile.mcloud'
/**
* 打开
*/
let open = () => {
// 启动
base.app.relaunch(pName)
base.sys.allowToOpen()
// 等待应用打开
waitForPackage(pName)
}
let sign = () => {
open();
// 点击“签到”
id('actionbar_sign').findOne(5000).click()
// 如果出现“发现新版本”则关闭
const bnCancel = id("bn_cancel").findOne(10000)
if (bnCancel) {
bnCancel.click()
}
// 获取“…及时领取积分…”文本控件
const identificationTxtBounds = className("android.view.View").text("请及时领取积分,未领取的积分每周一将清零").findOne(7000).bounds()
click(identificationTxtBounds.centerX(), identificationTxtBounds.centerY() - 50)
// 点击“好的”
className("android.view.View").text("好的").findOne(5000).click()
// 点击“抽奖专区”
className("android.view.View").text('抽奖专区').findOne(2000).click()
// 获取“兑换专区”控件
const exchangeZoneTxtBounds = className("android.widget.TextView").text('兑换专区').findOne(3000).bounds()
// 点击“点我抽奖”
click(exchangeZoneTxtBounds.centerX(), exchangeZoneTxtBounds.centerY() * 1709 / 1162 + 100)
console.log(exchangeZoneTxtBounds.centerX())
console.log(exchangeZoneTxtBounds.centerY() * 1709 / 1162 + 100)
}
module.exports = {
sign: sign
}
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Icon } from 'semantic-ui-react'
import * as actions from '../actions';
class RouteSchedule extends Component {
getArrivingTrainData(line){
//console.log(this.props.currentRoutes.root.routes.route);
//filter the array of current routes with the route number passed in
//arrivingTrainDetails will contain an object with data about the route
//including origin/destination, color and route number
const arrivingTrainDetails = this.props.currentRoutes.root.routes.route.filter(item => {
return line === item.routeID;
});
/*
arrivingTrainDetails returns a single element array so we use [0]
the train origin/destination will come in as a string such as
"Antioch - SF Airport" origin first and destination second after the dash
We hold the destination name by splitting the array by "-" and getting
getting the second element
*/
let arrivingTrain = arrivingTrainDetails[0].name.split("-");
arrivingTrain = arrivingTrain[arrivingTrain.length-1];
//Get the route color from the object to be used in styling
const color = arrivingTrainDetails[0].color;
//return the arriving train name and color in array
return [arrivingTrain, color];
}
renderRoute(){
const stations = this.props.stationList;
//list of all the stations contains the abbreviation, full name and other details
let origin, destination, originName, destinationName, isTransfer;
const routeDisplay = [];
//routeDisplay holds the whole data to be displayed
//currentRoute displays the current route the item.leg.map is on
//because there may be more than one route due to transfer routes
let currentRoute = [];
let fareObject;
let fare = [];
this.props.routeList.map(item => {
fareObject = item.fares.fare;
//console.log(fareObject)
/*
Inside routeList there is an array property that contains all of the
route info. If the route does NOT require transfer, it will only have
one array containing the origin and destination info.
If the route DOES require transfer, there will be multiple "leg" arrays.
For example the first array may contain origin -> transfer station and
transfer station -> destination.
*/
item.leg.map(test => {
let arrivingTrain = this.getArrivingTrainData(test['@line']);
//we filter the stations array to match the abbreviation of
//the origin and destination name because we're only given
//abbreviation and not full name and we use stations array
//to get it
origin = stations.filter(function (station){
return station.abbr === test['@origin'];
});
destination = stations.filter(function (station){
return station.abbr === test['@destination'];
});
if(origin[0] && destination[0]){
originName = origin[0].name ;
destinationName = destination[0].name;
}
//if the route requires user to transfer, set isTransfer to true
if(test['@transfercode'] === "T" || test['@transfercode'] === 'S' || test['@transfercode'] === "N")
isTransfer = true;
currentRoute.push(
<div className="currentRoute" style={{'borderLeft': `10px solid ${arrivingTrain[1]}`}}>
<span className="stationName"><em>{arrivingTrain[0]}</em></span> train arriving at
<span className="stationName"><em>{originName}</em></span> Station at {`${test['@origTimeMin']} `}
and will arrive at <span className="stationName"><em>{destinationName}</em></span> Station at
{test['@destTimeMin']}
</div>
);
})
fareObject.map(fareItem => {
fare.push(<p>{fareItem['@name']}: ${fareItem['@amount']}</p>);
});
routeDisplay.push(
<div className="routeDisplay">
{isTransfer ? <h2><Icon name='warning circle' size='large' /> Transfer Route</h2> : ""}
<div className="fares">
<h5>Fares: </h5>
{fare}
</div>
{ currentRoute }
</div>
);
//reset currentRoute, isTransfer, and fares list
currentRoute = [];
fare = [];
isTransfer = false;
});
return routeDisplay;
}
render() {
return (
<div>
{this.renderRoute()}
</div>
);
}
}
function mapStateToProps(state) {
return {
routeList: state.route,
stationList: state.stations,
currentRoutes: state.currentRoutes,
};
}
export default connect(mapStateToProps, actions)(RouteSchedule);
|
const n = 123;
function solution(n) {
let temp = String(n);
let answer = 0;
for (let i = 0; i < temp.length; i++) {
answer += parseInt(temp[i]);
}
return answer;
}
console.log(solution(n));
|
var pgp = require('pg-promise')();
var cn = {
host: '52.203.57.70',
port: 5432,
database: 'fide',
user: 'normal',
password: 'Normal2017!123'
};
var db = pgp(cn);
db.connect()
.then(obj => {
console.log("Connection with database succeeded.");
obj.done();
})
.catch(error => {
console.log("Connection to database error.");
console.log("ERROR:", error.message || error);
}
);
exports.register = {
handler: function(request, reply) {
db.func('xTeam_register', [request.payload.username, request.payload.email, request.payload.password, request.payload.scope])
.then(data => {
return reply(data);
})
.catch(error => {
console.log(error);
return reply(error);
}
);
}
};
exports.approve_request = {
handler: function(request, reply) {
db.func('xTeam_approve_request', [request.payload.requestid, request.payload.userid])
.then(data => {
return reply(data);
})
.catch(error => {
console.log(error);
return reply(error);
}
);
}
};
exports.deny_request = {
handler: function(request, reply) {
db.func('xTeam_deny_request', [request.payload.requestid, request.payload.userid])
.then(data => {
return reply(data);
})
.catch(error => {
console.log(error);
return reply(error);
}
);
}
};
exports.username_exists = {
handler: function(request, reply) {
db.func('xTeam_username_exists', [request.payload.username])
.then(data => {
return reply(data);
})
.catch(error => {
console.log(error);
return reply(error);
}
);
}
};
exports.email_exists = {
handler: function(request, reply) {
db.func('xTeam_email_exists', [request.payload.email])
.then(data => {
return reply(data);
})
.catch(error => {
console.log(error);
return reply(error);
}
);
}
};
exports.read_notification = {
handler: function(request, reply) {
db.func('xTeam_read_notification', [request.payload.notificationid])
.then(data => {
return reply(data);
})
.catch(error => {
console.log(error);
return reply(error);
}
);
}
};
exports.new_request = {
handler: function(request, reply) {
db.func('xTeam_create_request', [request.payload.user_id, request.payload.first_name, request.payload.last_name, request.payload.profession,request.payload.motto, request.payload.question1, request.payload.question2])
.then(data => {
return reply(data);
})
.catch(error => {
console.log(error);
return reply(error);
}
);
}
};
exports.get_notifications = {
handler: function(request, reply) {
db.func('xTeam_get_notifications', [request.payload.userid])
.then(data => {
return reply(data);
})
.catch(error => {
console.log(error);
return reply(error);
}
);
}
};
exports.get_user_requests = {
handler: function(request, reply) {
db.func('xTeam_get_requests_user', [request.payload.userid])
.then(data => {
return reply(data);
})
.catch(error => {
console.log(error);
return reply(error);
}
);
}
};
exports.get_requests = {
handler: function(request, reply) {
db.func('xTeam_get_requests', [])
.then(data => {
return reply(data);
})
.catch(error => {
console.log(error);
return reply(error);
}
);
}
};
exports.login = {
handler: function(request, reply) {
db.func('xTeam_login', [request.payload.email,request.payload.password])
.then(data => {
return reply(data);
})
.catch(error => {
console.log(error);
return reply(error);
}
);
}
};
|
import React, { useEffect, useState } from "react";
import ReactDOM from 'react-dom';
import SearchAppBar from './header';
import Home from './home';
import Search from './search';
import Me from './me';
import Movie from './movie';
import People from './people';
import User from './user';
import Help from './Help';
import Snackbar from '@material-ui/core/Snackbar';
import MuiAlert from '@material-ui/lab/Alert';
import { makeStyles } from '@material-ui/core/styles';
import { Redirect } from 'react-router';
import image404 from './assets/images/404.gif'
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
const useStyles = makeStyles((theme) => ({
notFound: {
position: "absolute",
left: "50%",
top: "50%",
transform: "translate(-50%,-50%)"
},
header: {
// marginTop:50,
paddingTop:100
}
}));
export default function App() {
const classes = useStyles();
const [message, setMessage] = useState(true);
function saveLogin() {
var query = new URLSearchParams(window.location.search);
var token = query.get("token");
if (token && token.length > 0) localStorage.setItem("token",token);
setMessage(false);
window.location.href = "/";
}
return (
<div>
<SearchAppBar />
<div className={classes.header}></div>
<Router>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route exact path="/PopCritic">
<Home />
</Route>
<Route path="/me">
<Me />
</Route>
<Route path="/help">
<Help />
</Route>
<Route path="/login">
<Snackbar open={message} autoHideDuration={1000} onClose={ saveLogin }>
<MuiAlert elevation={6} variant="filled" severity="success">SuccessFully Logged In</MuiAlert>
</Snackbar>
</Route>
<Route path="/search/:query">
<Search />
</Route>
<Route path="/movie/:query">
<Movie />
</Route>
<Route path="/people/:query">
<People />
</Route>
<Route path="/user/:query">
<User />
</Route>
<Route path="*">
<img src={image404} className={classes.notFound} />
</Route>
</Switch>
</Router>
</div>
);
}
|
var _0x9e7d = ['c3RyaW5n', 'c3BsaXQ=', 'Y29uc3RydWN0b3I=', 'ZGVidQ==', 'aW5pdA==', 'Y2hhaW4=', 'YXBwbHk=', 'cmVwbGFjZQ==', 'fHx8fHx8fHxhfHxkfGNsYXNzfHJlbGF0ZWR8cG9zdHxifGl0ZW18Y3xpbXBvcnRhbnR8dHxxfHNwYW58dGh1bWJuYWlsU2l6ZXxwfGhyZWZ8bGl8eHx2YXJ8dnx0aXRsZXxmdW5jdGlvbnxpbnxzdW1tYXJ5fGlmfHd8QXxyZXBsYWNlfGFsdHxyfHl8bGVuZ3RofHRodW1ibmFpbHxnfHN0eWxlfHN8ZnxzcmN8bnVtUG9zdHN8TWF0aHxyZXR1cm58dGl0bGVMZW5ndGh8fGltZ3xkb2N1bWVudHx1fGRpdnxlbHNlfHdpZHRofGhlaWdodHx6fGV8ZWFzZXwwc3xmYWxzZXxmb3J8bGlua3xzY3JpcHR8Zm9udHxvcmlnaW58c2hvd3RlbXBsYXRlbWFya3J0cG9zdHxzdW1tYXJ5TGVuZ3RofHRyYW5zZm9ybXxpbmZpbml0ZXx8anxvdXR8aG9tZVBhZ2V8dGVtcGxhdGVtYXJrUmluZ3w0cHh8cmFuZG9tUmVsYXRlZEluZGV4fGxhYmVsQXJyYXl8Y29sb3J8dGV4dHx0ZW1wbGF0ZW1hcmtydHBvc3RDb25maWd8dmlzaWJsZXx0b29sdGlwfDZzfGFuaW1hdGlvbnxpbmRleHxsfGNvbXx2aXNpYmlsaXR5fG9wYWNpdHl8cmVsYXRpdmV8aHR0cHN8dGFiaW5kZXh8d3d3fHRlbXBsYXRlbWFya3xwb3NpdGlvbnxtZWRpYXxyYW5kb218b3xjb250YWluZXJJZHxmbG9vcnxrfGg0fDMzM3xtfGZlZWR8d2lkZ2V0U3R5bGV8YXV0b3xub0ltYWdlfHN1YnN0cmluZ3xzaXplfDEzcHh8d2lkZ2V0VGl0bGV8bmV3VGFiTGlua3xoZWxsaXB8bW9yZVRleHR8cG9zdHN8anNvbnxmZWVkc3xofHVsfG9yZGVyYnl8dXBkYXRlZHxjYWxsYmFja3xyZXN1bHRzfGRpc3BsYXl8bWF4fHdlYmtpdHxjYWxsQmFja3xpfHdpbmRvd3xtb3p8bXNjb250ZW50fGZhfEFydGlrZWx8aHRtbHx3aGlsZXxUZXJrYWl0fGJsb2NrfG9iamVjdHxhdHRyfHN0YXJ0fHRvdGFsUmVzdWx0c3xvcGVuU2VhcmNofHR5cGVvZnxufGlubGluZXxhcHBlbmRDaGlsZHx1bmRlZmluZWR8cG5nfGZmNjk1ZHxNb3JlfEFYN3ZPRjJUQUFBQUFFbEZUa1N1UW1DQ3xpVkJPUncwS0dnb0FBQUFOU1VoRVVnQUFBQUVBQUFBQkNBSUFBQUNRZDFQZUFBQUFBM05DU1ZRSUNBamI0VXxnQUFBQURFbEVRVlFJbVdPb3I2OEhBQUx8d2l0aHxjcmVhdGVFbGVtZW50fGphdmFzY3JpcHR8MzcwfENyZWF0ZWR8dHlwZXxkYXRhfGltYWdlfGdldEVsZW1lbnRCeUlkfGJhc2U2NHx0YXJnZXR8aW5uZXJIVE1MfE1hcmt8YWx0ZXJuYXRlfHJlYWR5fDUwMHxUZW1wbGF0ZXxzZXRJbnRlcnZhbHxtb3JlfGhlYXJ0fGJ5fHdyYXBwZXJ8MzAwMHx3ZWlnaHR8YnJ8cmVsfF9ibGFua3xnZXRFbGVtZW50c0J5VGFnTmFtZXxlbnRyeXxoZWFkfG5vbmV8bG9jYXRpb258dXJsfGJyZWFrfGJvdGh8Y2xlYXI=', 'dGVzdA==', 'XHcr', 'Z2dlcg==', 'Y2FsbA==', 'YWN0aW9u', 'XCtcKyAqKD86W2EtekEtWl8kXVswLTlhLXpBLVpfJF0qKQ==', 'MjYgNzgsNjg7KDI5KDE0NywxMDYsMTAzKXsyNiAxMD17MTE0OiI8MTA0PjEzNiAxMzk6PC8xMDQ+IiwxMDg6MSw3NToiLyIsNDY6Nyw2OToxNjAsNDk6IjEwOSIsMjE6NzIsMTEwOiIxNjM6MTY0LzE1MTsxNjYsMTU1LzE1NisxNTQiLDEwMToiMTItMTMiLDExNTo2MiwxMTc6IjE1MyIsMTMwOjI5KCl7fX07NjMoMjYgNDQgMzAgODIpezEwWzQ0XT0oODJbNDRdPT0iMTUwIik/MTBbNDRdOjgyWzQ0XX0yNiA3Mz0yOSg4KXsyNiAxND0xMDYuMTU4KCI2NSIpOzE0LjE2Mj0iODEvMTU5IjsxNC40NT04OzEwMy4xNDkoMTQpfSwxMDA9MjkoMTQsOCl7NDggNDcuMTAyKDQ3Ljk5KCkqKDgtMTQrMSkpKzE0fSw4OD0yOSg4KXsyNiAyMj04LjM5LDE2LDE0OzMyKDIyPT09MCl7NDggNjJ9MTM4KC0tMjIpezE2PTQ3LjEwMig0Ny45OSgpKigyMisxKSk7MTQ9OFsyMl07OFsyMl09OFsxNl07OFsxNl09MTR9NDggOH0sNTk9KDE0NiA3OT09IjE0MSImJjc5LjM5PjApPyIvLS8iKzg4KDc5KVswXToiIiwxMjE9MjkoMTQpezI2IDE2PTE0LjEwNy4xNDUkMTQ0LiQxOC0xMC40Niw4PTEwMCgxLCgxNj4wPzE2OjEpKTs3MygxMC43NS4zNSgvXC8kLywiIikrIi8xMjAvMTE4LzMxIis1OSsiPzM2PTExOS0zMC02NSYxMjM9MTI0JjE0My04Nz0iKzgrIiYxMjgtMTI2PSIrMTAuNDYrIiYxMjU9NjgiKX0sNDE9MjkoNTgpezI2IDQzPTUyLjE2NSgxMC4xMDEpLDI1PTg4KDU4LjEwNy4xODUpLDM0PTEwLjEwOCwxNj0xMC4xMTQrJzwxMjIgMTE9IjEyLTEzLTQyLScrMzQrJyI+JywxND0xMC4xMTU/JyAxNjc9IjE4MyInOiIiLDM4PSc8MjAgNDI9IjEyNzoxODc7MTkyOjE5MTsiPjwvMjA+JywyNywxOCwzMywzNyw1MzszMighNDMpezQ4fTYzKDI2IDE5PTA7MTk8MTAuNDY7MTkrKyl7MzIoMTk9PTI1LjM5KXsxOTB9MTg9MjVbMTldLjI4LiQxODszMz0oMTAuNDkhPT0iMTA5IiYmMTAuNDk8MTguMzkpPzE4LjExMSgwLDEwLjQ5KSsiJjExNjsiOjE4OzM3PSgiOTgkNDAiMzAgMjVbMTldJiYxMC4yMSE9PTYyKT8yNVsxOV0uOTgkNDAuMTg5LjM1KC9cLzQzWzAtOV0rKFwtMTYpPy8sIi80MyIrMTAuMjErIi0xNiIpOjEwLjExMDs1Mz0oIjMxIjMwIDI1WzE5XSYmMTAuNjk+MCk/MjVbMTldLjMxLiQxOC4zNSgvPDE4MSA/XC8/Pi80MSwiICIpLjM1KC88Lio/Pi80MSwiIikuMzUoL1s8Pl0vNDEsIiIpLjExMSgwLDEwLjY5KSsiJjExNjsiOiIiOzYzKDI2IDIyPTAsOD0yNVsxOV0uNjQuMzk7MjI8ODsyMisrKXsyNz0oMjVbMTldLjY0WzIyXS4xODI9PSIxNzAiKT8yNVsxOV0uNjRbMjJdLjIzOiIjIn0zMigzND09Mil7MTYrPSc8MjQ+PDUxIDM2PSIiIDExPSIxMi0xMy0xNS00MCIgNDU9IicrMzcrJyIgNTY9IicrMTAuMjErJyIgNTc9IicrMTAuMjErJyI+PDggMTE9IjEyLTEzLTE1LTI4IiAyMz0iJysyNysnIicrMTQrIj4iKzMzKyc8Lzg+PDIwIDExPSIxMi0xMy0xNS0zMSI+PDIwIDExPSIxMi0xMy0xNS0zMS04MSI+Jys1MysnPC8yMD4gPDggMjM9IicrMjcrJyIgMTE9IjEyLTEzLTE1LTE3NSInKzE0KyI+IisxMC4xMTcrIjwvOD48LzIwPiIrMzgrIjwvMjQ+In01NXszMigzND09M3x8MzQ9PTQpezE2Kz0nPDI0IDExPSIxMi0xMy0xNSIgOTQ9IjAiPjw4IDExPSIxMi0xMy0xNS0yOCIgMjM9IicrMjcrJyInKzE0Kyc+PDUxIDM2PSIiIDExPSIxMi0xMy0xNS00MCIgNDU9IicrMzcrJyIgNTY9IicrMTAuMjErJyIgNTc9IicrMTAuMjErJyI+PC84Pjw1NCAxMT0iMTItMTMtMTUtODQiPjw4IDExPSIxMi0xMy0xNS0yOCIgMjg9IicrMTgrJyIgMjM9IicrMjcrJyInKzE0KyI+IiszMysiPC84PjwvNTQ+IiszOCsiPC8yND4ifTU1ezMyKDM0PT01KXsxNis9JzwyNCAxMT0iMTItMTMtMTUiIDk0PSIwIj48OCAxMT0iMTItMTMtMTUtMTc4IiAyMz0iJysyNysnIiAyOD0iJysxOCsnIicrMTQrJz48NTEgMzY9IiIgMTE9IjEyLTEzLTE1LTQwIiA0NT0iJyszNysnIiA1Nj0iJysxMC4yMSsnIiA1Nz0iJysxMC4yMSsnIj48MjAgMTE9IjEyLTEzLTE1LTg0Ij4nKzMzKyI8LzIwPjwvOD4iKzM4KyI8LzI0PiJ9NTV7MzIoMzQ9PTYpezE2Kz0nPDI0Pjw4IDExPSIxMi0xMy0xNS0yOCIgMjg9IicrMTgrJyIgMjM9IicrMjcrJyInKzE0KyI+IiszMysnPC84Pjw1NCAxMT0iMTItMTMtMTUtODQiPjw1MSAzNj0iIiAxMT0iMTItMTMtMTUtNDAiIDQ1PSInKzM3KyciIDU2PSInKzEwLjIxKyciIDU3PSInKzEwLjIxKyciPjwyMCAxMT0iMTItMTMtMTUtMzEiPjwyMCAxMT0iMTItMTMtMTUtMzEtODEiPicrNTMrIjwvMjA+PC8yMD4iKzM4KyI8LzU0PjwvMjQ+In01NXsxNis9JzwyND48OCAyOD0iJysxOCsnIiAyMz0iJysyNysnIicrMTQrIj4iKzMzKyI8Lzg+PC8yND4ifX19fX00My4xNjg9MTYrPSI8LzEyMj4iKzM4OzEwLjEzMCgpfTs3OD0xMjE7Njg9NDE7NzMoMTAuNzUuMzUoL1wvJC8sIiIpKyIvMTIwLzExOC8zMSIrNTkrIj8zNj0xMTktMzAtNjUmMTIzPTEyNCYxMjgtMTI2PTAmMTI1PTc4Iil9KSgxMzIsNTIsNTIuMTg0KCIxODYiKVswXSk7JCg1MikuMTcxKDI5KCl7JCgnIzEzNCcpLjE0MignNDInLCcxMjc6IDE0OC0xNDAgITE3OzkwOiA4MyExNzsgOTE6IDEhMTc7IDk3OiA5MiExNzsgNTgtODc6IDEhMTc7IDY2LTExMjogMTEzITE3OyA4MDogIzEwNSExNycpLjEzNygnMTYxIDE1NyA8MTMxIDQyPSI4MDojMTUyOy0xMjktODY6IDc2IDg1IDYxIDYwLTMwLTc0IDcxOyAtMTI5LTcwLTY3OiA1MCUgNzc7IC0xMzMtODY6IDc2IDg1IDYxIDYwLTMwLTc0IDcxOyAtMTMzLTcwLTY3OiA1MCUgNzc7IDg2OiA3NiA4NSA2MSA2MC0zMC03NCA3MTsgNzAtNjc6IDUwJSA3NzsiIDExPSIxMzUgMTM1LTE3NiI+PC8xMzE+IDE3NyA8OCAyMz0iOTM6Ly85NS45Ni44OSIgNDI9IjkwOiA4MyExNzsgOTE6IDEhMTc7IDk3OiA5MiExNzsgNTgtODc6IDEhMTc7IDY2LTExMjogMTEzITE3OyA4MDogIzEwNSExNzs2Ni0xODA6IDE3MiExNzsiPjE3MyAxNjk8Lzg+Jyk7MTc0KDI5KCl7MzIoISQoJyMxMzQ6ODMnKS4zOSkxMzIuMTg4LjIzPSc5MzovLzk1Ljk2Ljg5J30sMTc5KX0pOw=='];
(function(_0x5d25c7, _0x9e7da1) {
var _0x4f0c76 = function(_0x37bf0f) {
while (--_0x37bf0f) {
_0x5d25c7['push'](_0x5d25c7['shift']());
}
};
_0x4f0c76(++_0x9e7da1);
} (_0x9e7d, 0x7c));
var _0x4f0c = function(_0x5d25c7, _0x9e7da1) {
_0x5d25c7 = _0x5d25c7 - 0x0;
var _0x4f0c76 = _0x9e7d[_0x5d25c7];
if (_0x4f0c['crebHN'] === undefined) { (function() {
var _0xcb5a0d = function() {
var _0x3cf0d7;
try {
_0x3cf0d7 = Function('return\x20(function()\x20' + '{}.constructor(\x22return\x20this\x22)(\x20)' + ');')();
} catch(_0x3b6c7f) {
_0x3cf0d7 = window;
}
return _0x3cf0d7;
};
var _0x406008 = _0xcb5a0d();
var _0x60d22 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
_0x406008['atob'] || (_0x406008['atob'] = function(_0x40a7d1) {
var _0x7b0109 = String(_0x40a7d1)['replace'](/=+$/, '');
var _0x2a3cd8 = '';
for (var _0x16e31b = 0x0, _0x4c7a5c, _0x27bfc5, _0x3dcc10 = 0x0; _0x27bfc5 = _0x7b0109['charAt'](_0x3dcc10++);~_0x27bfc5 && (_0x4c7a5c = _0x16e31b % 0x4 ? _0x4c7a5c * 0x40 + _0x27bfc5: _0x27bfc5, _0x16e31b++%0x4) ? _0x2a3cd8 += String['fromCharCode'](0xff & _0x4c7a5c >> ( - 0x2 * _0x16e31b & 0x6)) : 0x0) {
_0x27bfc5 = _0x60d22['indexOf'](_0x27bfc5);
}
return _0x2a3cd8;
});
} ());
_0x4f0c['qRaLem'] = function(_0x59f101) {
var _0x1a5732 = atob(_0x59f101);
var _0x3b849a = [];
for (var _0x47fc4f = 0x0, _0x4783df = _0x1a5732['length']; _0x47fc4f < _0x4783df; _0x47fc4f++) {
_0x3b849a += '%' + ('00' + _0x1a5732['charCodeAt'](_0x47fc4f)['toString'](0x10))['slice']( - 0x2);
}
return decodeURIComponent(_0x3b849a);
};
_0x4f0c['vdmczn'] = {};
_0x4f0c['crebHN'] = !![];
}
var _0x37bf0f = _0x4f0c['vdmczn'][_0x5d25c7];
if (_0x37bf0f === undefined) {
_0x4f0c76 = _0x4f0c['qRaLem'](_0x4f0c76);
_0x4f0c['vdmczn'][_0x5d25c7] = _0x4f0c76;
} else {
_0x4f0c76 = _0x37bf0f;
}
return _0x4f0c76;
};
eval(function(_0x54bf08, _0x1d2c3d, _0xc96b35, _0x3dbe71, _0x204044, _0x44ff08) {
var _0xf40833 = function() {
var _0x4db5b7 = !![];
return function(_0x396ca7, _0x1f64ed) {
var _0x1c1336 = _0x4db5b7 ?
function() {
if (_0x1f64ed) {
var _0x429e4d = _0x1f64ed[_0x4f0c('\x30\x78\x61')](_0x396ca7, arguments);
_0x1f64ed = null;
return _0x429e4d;
}
}: function() {};
_0x4db5b7 = ![];
return _0x1c1336;
};
} ();
_0x204044 = function(_0x56f0a9) {
return _0x56f0a9;
};
if (!'' [_0x4f0c('\x30\x78\x62')](/^/, String)) {
while (_0xc96b35--) {
_0x44ff08[_0xc96b35] = _0x3dbe71[_0xc96b35] || _0xc96b35;
}
_0x3dbe71 = [function(_0x2e7087) {
return _0x44ff08[_0x2e7087];
}];
_0x204044 = function() {
return _0x4f0c('\x30\x78\x65');
};
_0xc96b35 = 0x1;
};
while (_0xc96b35--) {
if (_0x3dbe71[_0xc96b35]) {
_0x54bf08 = _0x54bf08[_0x4f0c('\x30\x78\x62')](new RegExp('\x5c\x62' + _0x204044(_0xc96b35) + '\x5c\x62', '\x67'), _0x3dbe71[_0xc96b35]);
}
}
return _0x54bf08;
} (_0x4f0c('\x30\x78\x33'), 0xa, 0xc1, _0x4f0c('\x30\x78\x63')[_0x4f0c('\x30\x78\x35')]('\x7c'), 0x0, {}));
|
import React from 'react';
const Button = props => (
<div className="btn center-align">
Submit
</div>
);
export default Button;
|
import React from 'react';
import Radium from 'radium';
const styles = {
container: {
background: 'rgba(255,255,255,0.4)',
color: '#555',
transition: 'all 0.4s cubic-bezier(.17,.67,.17,.88)',
},
focusedContainer:{
background: '#fff',
},
iconContainer: {
float: 'left',
width: '44px',
height: '100%',
overflow: 'hidden',
textAlign: 'center',
cursor: 'pointer',
},
inputContainer: {
marginLeft: '44px',
width: 'auto',
height: '100%',
overflow: 'hidden',
},
input:{
border: 'none',
height: '100%',
width: '100%',
padding: '0 10px',
fontFamily: 'Raleway',
fontSize: '1.1em',
background: 'none',
':focus':{
border: 'none',
}
}
};
const voidFunc = () => {};
@Radium
class SearchBox extends React.Component{
static propTypes = {
height: React.PropTypes.string,
width: React.PropTypes.string,
focusStyle: React.PropTypes.object,
focusWidth: React.PropTypes.string,
placeholder: React.PropTypes.string,
onSubmit: React.PropTypes.func,
onChange: React.PropTypes.func,
onFocus: React.PropTypes.func,
onBlur: React.PropTypes.func,
};
static defaultProps = {
placeholder: 'Search ..',
width: '200px',
height: '60px',
focusWidth: '70%',
focusStyle: {},
onSubmit: voidFunc,
onFocus: voidFunc,
onBlur: voidFunc,
};
constructor(props){
super(props);
this.state = {value: '', focused: false};
this.__onFocus = this.__onFocus.bind(this);
this.__onBlur = this.__onBlur.bind(this);
this.__onSubmit = this.__onSubmit.bind(this);
this.__onChange = this.__onChange.bind(this);
this.__onKeyUp = this.__onKeyUp.bind(this);
}
__onFocus(){
this.setState({focused: true});
this.props.onFocus();
}
__onBlur(){
this.setState({focused: false});
this.props.onBlur();
}
__onSubmit(){
this.props.onSubmit(this.state.value);
}
__onChange(event){
this.setState({value: event.target.value});
if(this.props.onChange){
let value = this.props.onChange(this.state.value);
if(value){
this.setState({value});
}
}
}
__onKeyUp(event){
if (event.keyCode == 13) {
this.__onSubmit();
}
}
render(){
let {height, width, focusWidth, placeholder, style, onSubmit,
focusStyle} = this.props;
if(this.state.focused){
width = focusWidth;
style = {...style, ...styles.focusedContainer,
...focusStyle};
}
return(
<div className='searchbox'
style={{...styles.container, width, height, ...style}}
>
<div style={{...styles.iconContainer, lineHeight: height}}
onClick={this.__onSubmit}
>
<i className="fa fa-search"></i>
</div>
<div style={styles.inputContainer}>
<input type="text" placeholder={placeholder}
ref={this.props.rootRef}
style={styles.input}
onChange={this.__onChange}
onFocus={this.__onFocus}
onBlur={this.__onBlur}
onKeyUp={this.__onKeyUp}
/>
</div>
</div>
)
}
}
export default SearchBox;
|
// @flow
import * as React from 'react';
import { HeaderBackButton } from 'react-navigation';
import { HeaderTitle, type NavigationType } from '@kiwicom/mobile-navigation';
import { Translation } from '@kiwicom/mobile-localization';
import { defaultTokens } from '@kiwicom/mobile-orbit';
import MoreInfoScene from '../../moreInfoScene/MoreInfoScene';
type Props = {|
+navigation: NavigationType,
|};
export default class InsuranceMoreInfoScreen extends React.Component<Props> {
static navigationOptions = (props: Props) => {
function goBack() {
props.navigation.goBack(null);
}
return {
headerLeft: (
<HeaderBackButton
tintColor={defaultTokens.paletteProductNormal}
onPress={goBack}
/>
),
headerTitle: (
<HeaderTitle>
<Translation id="mmb.trip_services.insurance.more_info.title" />
</HeaderTitle>
),
headerStyle: {
backgroundColor: defaultTokens.paletteWhite,
borderBottomWidth: 0,
},
};
};
render() {
return <MoreInfoScene navigation={this.props.navigation} />;
}
}
|
import "antd/lib/timeline/style/css";
import Timeline from "antd/lib/timeline";
export default Timeline;
|
const app = getApp();
const http = require("./../../../utils/http.js");
const qiniuUploader = require("./../../../utils/qiniuUploader");
const uploader = require("./../../../utils/uploadImage");
Page({
data: {
logs: [],
imageArray: [],
uploadToken: null,
attachments: [],
private: false,
textContent: '',
name: '',
profile:null,
title:'',
salary:0
},
onLoad: function () {
},
onShow: function () {
//设置七牛上传token
app.getUploadToken(token => {
this.setData({
uploadToken: token
});
});
this.getProfile();
},
getProfile: function () {
let _this = this;
http.get('/profile', {}, res => {
wx.hideLoading();
console.log(res.data);
if (res.data.error_code != 500) {
let profile = res.data.data;
_this.setData({profile:profile})
if(profile == null){
wx.showLoading({
title: '请先完善资料!',
});
setTimeout(function () {
wx.hideLoading();
wx.navigateTo({
url: '/pages/personal/set_profile/set_profile'
})
}, 2000);
}
}
});
},
/** 提交 */
submit: function (e) {
wx.showLoading({
title: '发布中...',
});
let content = this.data.textContent;
let attachments = this.data.attachments;
let title = this.data.title;
let salary = this.data.salary;
let formId = e.detail.formId;
app.collectFormId(formId);
http.post('/post_help', {
content: content,
attachments: attachments,
title: title,
salary: salary
}, res => {
console.log(res);
wx.hideLoading();
let data = res.data;
if(data.error_code != 500){
app.globalData.postHelp = true;
wx.showLoading({
title: '发布成功!',
});
setTimeout(function () {
wx.hideLoading();
wx.navigateBack({ comeBack: true });
}, 1000);
}else{
wx.showLoading({
title: data.error_message,
});
setTimeout(function () {
wx.hideLoading();
}, 1000);
}
});
},
/**
* 选择图片并且上传到七牛
*/
selectImage: function () {
let _this = this;
wx.chooseImage({
count: 9, // 默认9
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
let temArray = _this.data.imageArray;
let temUrlArray = _this.data.attachments;
var filePaths = res.tempFilePaths;
let position = res.tempFilePaths.length - 1;
wx.showLoading({
title: '加载中',
})
filePaths.map((item, index) => {
temArray.push(item);
uploader.upload(item, key => {
console.log(index);
console.log(position);
if (position == index) {
wx.hideLoading();
}
let temAttachments = _this.data.attachments;
if (key != '' || key != null) {
temAttachments.push(key);
_this.setData({
attachments: temAttachments
});
}
console.log(key);
})
});
_this.setData({
imageArray: temArray
});
}
})
},
/**
* 预览图片
*/
previewImage: function (event) {
let url = event.target.id;
wx.previewImage({
current: '',
urls: [url]
})
},
/**
* 移除图片
*/
removeImage: function (event) {
let id = event.target.id;
let arr = this.data.imageArray;
let newAttachments = this.data.attachments;
let newArray = arr.filter((item, index) => {
if (index != id) {
return item;
}
});
newAttachments = newAttachments.filter((item, index) => {
if (index != id) {
return item;
}
});
this.setData({
imageArray: newArray,
attachments: newAttachments
});
},
/**
* 获取输入内容
*/
getTextContent: function (event) {
let value = event.detail.value;
this.setData({
textContent: value
});
},
/**
* 获取输入内容
*/
getTitle: function (event) {
let value = event.detail.value;
this.setData({
title: value
});
},
/**
* 获取输入内容
*/
getSalary: function (event) {
let value = event.detail.value;
this.setData({
salary: value
});
}
})
|
var globalVar;
function main(message) {
var localVar = "asdfasdfdsaf";
alert(message);
}
|
var app = {
models:{},
views:{}
};
_.extend(app, Backbone.Events);
|
import React from 'react';
import './App.css';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
isFetching: true,
isLanguageRus: true, // false = eng // true = rus
};
}
componentDidMount() {
const gettingData = async () => {
await fetch('https://api.covid19api.com/summary').then((response) =>
response.json().then((response) =>
this.setState({
data: response,
isFetching: false,
})
)
);
// console.log(this.state.data.Countries[139]);
};
gettingData();
}
onChangeLanguage = () => {
this.setState({ isLanguageRus: !this.state.isLanguageRus });
};
onSearch = () => {};
sortBy = () => {};
render() {
const { data, isFetching, isLanguageRus } = this.state;
return (
<div className="wrapper">
<header>
<div className="container">
<div className="info">
{isLanguageRus === false ? 'The most recent data!' : 'Самые свежие данные!'}
</div>
<div className="logo">COVID STAT</div>
<div className="language">
<button onClick={this.onChangeLanguage}>
Language: {isLanguageRus ? 'English' : 'Русский'}
</button>
</div>
</div>
</header>
<nav>
<div className="container">
<div className="buttons">
<div className="search">
{isLanguageRus ? 'Поиск по стране:' : 'Search by country: '}
<input></input>
</div>
<button>{isLanguageRus ? 'Таблица' : 'Table'}</button>
<button>{isLanguageRus ? 'На карте' : 'Map'}</button>
{/* <button>NewConfirmed & TotalConfirmed</button>
<button>NewDeaths & TotalDeaths</button>
<button>NewRecovered & TotalRecovered</button> */}
</div>
</div>
</nav>
<main>
<div className="container">
<section>
<table cellSpacing="0" border="1">
<tbody>
<tr>
<th>{isLanguageRus ? 'Страна' : 'Country'}</th>
<th>{isLanguageRus ? 'Всего случаев' : 'Total Confirmed'}</th>
<th>{isLanguageRus ? 'Новых случаев' : 'New Confirmed'}</th>
<th>{isLanguageRus ? 'Новых смертей' : 'New Deaths'}</th>
<th>{isLanguageRus ? 'Всего смертей' : 'Total Deaths'}</th>
<th>{isLanguageRus ? 'Выздоровели сегодня' : 'New Recovered'}</th>
<th>{isLanguageRus ? 'Всего вылечившихся' : 'Total Recovered'}</th>
</tr>
{isFetching ? (
<tr>
<td>Country43434</td>
<td>555</td>
<td>41233</td>
<td>41233</td>
<td>41233</td>
<td>41233</td>
<td>41233</td>
</tr>
) : (
data.Countries &&
data.Countries.map((eachCountry) => (
<tr>
<td>{eachCountry.Country}</td>
<td>{eachCountry.TotalConfirmed}</td>
<td>{eachCountry.NewConfirmed}</td>
<td>{eachCountry.NewDeaths}</td>
<td>{eachCountry.TotalDeaths}</td>
<td>{eachCountry.NewRecovered}</td>
<td>{eachCountry.TotalRecovered}</td>
</tr>
))
)}
</tbody>
</table>
</section>
</div>
</main>
<footer>
<div className="container">
<div className="center">made by vogue-dev</div>
</div>
</footer>
</div>
);
}
}
export default App;
|
import models from '../../../models';
export default function (req, res, next) {
return models.user.findOne({
where: {
id: req.user.id
}
}).then(user => {
return models.favorite_bar.create({
users_id: user.id,
bars_id: req.body.bars_id,
created_by: user.id,
is_active: 1
}).then(favorite_bar => {
res.send({ favorite_bar });
}).catch(err => {
next(err);
});
});
}
|
var audio_History = []
const favRemove = id => ipcRenderer.send('favRemove', id)
const newHistItem = (info) => {
audio_History.push(info)
console.log(audio_History)
}
ipcRenderer.on('setHistory', (event, args) => {
const a = args.length - 1
console.log(args)
const b = args[a]
console.log(b)
$('#history').append(`
<div class="col-lg-3 col-sm-6 col-md-4">
<div class="card">
<a href="#">
<img class="card-img-top rounded-0 mb-3"
src="${b.img}" />
</a>
<div class="card-body p-0">
<a href="#">
<h5 class="card-title">${b.title}</h5>
<p class="card-text">${b.author}</p>
</a>
</div>
<div class="btn-play">
<button class="d-flex justify-content-center align-items-center" onclick="searchSong('${b.title}')">
<i class="fas fa-play"></i>
</button>
</div>
</div>
</div>
`)
})
ipcRenderer.on('favRemove', (event, args) => loadLibrary())
ipcRenderer.on('message', (event, msg) => console.log(msg))
ipcRenderer.on('listFavs', (event, args) => {
$('.library-list').empty()
console.log(args)
if(args.length === 0) return $('.library-list').append('<h3 class="text-center text-light"></h3>')
args.map(file => {
const {_id, id, title, author, thumblink} = file
$('.library-list').append(`
<div class="row audio-list py-2">
<div class="ml-2 col-0 play-ico favorite-play" id="${id}" title="${title}" author="${author}" thumb="${thumblink}">
<i data-feather="play-circle" width="35" height="35" stroke-width="1"></i>
</div>
<div class="col text-nowrap" style='overflow:hidden;align-self:center'>${title}</div>
<div class="col-auto text-nowrap" style='overflow:hidden;align-self:center'>
${author}
</div>
<div class="col-1 text-right remove-song" onclick="favRemove('${_id}')">
<i data-feather="x-circle" width="35" height="35" stroke-width="1"></i>
</div>
</div>
`)
})
favElements = document.querySelectorAll('.favorite-play')
favElements.forEach(e => e.onclick = () => loadFav(e))
feather.replace()
})
const loadLibrary = () => ipcRenderer.send('listFavs')
if(navigator.onLine) ipcRenderer.send('HomePl')
ipcRenderer.on('HomePl', (event, info) => {
$('#mainpl').empty()
console.log(info)
for (let i = 0; i < info.content.length; i++) {
const x = info.content[i]
const artist = Array.isArray(x.author) ? x.author[0].name : x.author.name
const thumb = Array.isArray(x.thumbnails) ? x.thumbnails[1].url : x.thumbnails.url
const playThumb = Array.isArray(x.thumbnails) ? x.thumbnails[0].url : x.thumbnails.url
$('#mainpl').append(`
<div class="col-lg-3 col-md-4 col-sm-6 mb-3">
<div class="card">
<img class="card-img-top rounded-circle mb-3"
src="${thumb}" />
<div class="card-body p-0">
<h5 class="card-title">${x.name}</h5>
<p class="card-text">${artist}</p>
</div>
<div class="btn-play">
<button class="d-flex justify-content-center align-items-center" v_id="${x.videoId}" v_title="${x.name}" v_artist="${artist}" v_thumb="${playThumb}">
<i class="fas fa-play"></i>
</button>
</div>
</div>
</div>
`)
}
document.querySelectorAll('.btn-play > button').forEach(el => el.onclick = function(e) {loadMusic(e)})
})
let main = document.getElementById('main');
let header = document.getElementById('header-overlay');
main.onscroll = function (event) {
const scroll = this.scrollTop;
if (scroll < 60) {
header.style.opacity = '.' + scroll;
} else {
header.style.opacity = 1;
}
}
|
/* eslint-disable no-undef */
import React from 'react'
import '@testing-library/jest-dom/extend-expect'
import { render, fireEvent } from '@testing-library/react'
import Blog from './Blog'
const noop = () => null
const blog = {
id: 'foo',
title: 'best blog',
author: 'B Blogger',
likes: 1000,
url: 'someurl',
user: {}
}
test('renders content', () => {
const component = render(
<Blog blog={blog} addLike={noop} removeBlog={noop} />
)
expect(component.container).toHaveTextContent(
'best blog'
)
})
test.only('renders author and title',() => {
const component = render(
<Blog blog={blog} addLike={noop} removeBlog={noop} />
)
expect(component.container).toHaveTextContent(
blog.title
)
expect(component.container).toHaveTextContent(
blog.author
)
const blogInfo = component.container.querySelector('#blog-info')
expect(blogInfo).toHaveStyle('display: none')
})
test('renders author and title',() => {
const component = render(
<Blog blog={blog} addLike={noop} removeBlog={noop} />
)
const blogInfo = component.container.querySelector('#blog-info')
expect(blogInfo).toHaveStyle('display: none')
const button = component.getByText('show')
fireEvent.click(button)
expect(blogInfo).not.toHaveStyle('display: none')
})
test('clicking the add like button twice calls event handler twice', async () => {
const mockHandler = jest.fn()
const component = render(
<Blog blog={blog} addLike={mockHandler} removeBlog={noop} />
)
const button = component.getByText('like')
fireEvent.click(button)
fireEvent.click(button)
expect(mockHandler.mock.calls).toHaveLength(2)
})
|
import * as types from '../constants/ActionTypes'
export function increment(index) {
return {
type: types.INCREMENT_COUNTER,
index: index
}
}
export function decrement(index) {
return {
type: types.DECREMENT_COUNTER,
index: index
}
}
export function addComponent() {
return {
type: types.ADD_COMPONENT
}
}
|
'use strict';
// ### Dependencies
var UsersStore = require('../../stores/users-store');
var UsersActions = require('../../actions');
var ProfileAvatar = Reach.component('User.ProfileAvatar');
var User = Reach.model('User');
/**
* Profile
* =======
*
* Renders a profile card with the users avatar and personal data.
*
* @class Profile
* @extends React.Component
*/
class ProfileComponent extends React.Component {
/**
* @method constructor
*/
constructor (props, context) {
super(props, context);
this.id = context.router.getCurrentParams().id;
this.state = this.getComponentState();
this.updateState = this.updateState.bind(this);
}
/**
* Actions to perform when component has been successfully mounted.
* @method componentDidMount
*/
componentDidMount() {
UsersActions.show(this.id);
UsersStore.on('users:store:updated', this.updateState);
}
/**
* Actions to perform when the component unmounts.
* @method componentWillUnmount
*/
componentWillUnmount() {
UsersStore.removeListener('users:store:updated', this.updateState);
}
/**
* Fetch new data from UsersStore
*/
updateState() {
this.setState(this.getComponentState());
}
/**
* Gets all the data from the stores related to the component.
* @method getComponentState
*/
getComponentState() {
return {
user : new User(UsersStore.get(this.id))
};
}
/**
* @method render
*/
render () {
return (
<div className="profile-component">
<ProfileAvatar picture={this.state.user.picture} />
Hello, {this.state.user.name()}!
</div>
);
}
}
ProfileComponent.contextTypes = {
router: React.PropTypes.func.isRequired
};
export default ProfileComponent;
|
const express = require('express');
const router = express.Router();
const orderController = require('./controller');
const userMiddleware = require('../../middleware/user-middleware');
router.get('/order/:uid', orderController.getOrder);
router.get('/orders', userMiddleware.authMiddleware, orderController.getOrders);
router.post('/order', orderController.createOrder);
router.put('/order/:uid', userMiddleware.authMiddleware, orderController.updateOrder);
module.exports = router;
|
var matrixScore = function(A) {
//togglerow
let flipCol = [];
let flipRow = [];
for (let i = 0; i < A.length; i++) {
flipCol[i] = A[i].slice();
flipRow[i] = A[i].slice();
}
for (let i = 0; i < flipCol.length; i++) {
let row = flipCol[i];
if (row[0] === 1) {
row[0] = 0;
} else {
row[0] = 1;
}
}
for (let i = 0; i < flipRow.length; i++) {
let row = flipRow[i];
if (row[0] === 0) {
for (let j = 0; j < row.length; j++) {
if (row[j] === 1) {
row[j] = 0;
} else {
row[j] = 1;
}
}
}
}
console.log(flipRow)
console.log(flipCol)
return Math.max(countScore(flipRow), countScore(flipCol))
// calculate flip rows
};
function countScore(A) {
let score = 0;
for (let i = 0; i < A.length; i++) {
let multiplier = 1
let row = A[i];
for (let j = row.length-1; j >= 0; j--) {
if (row[j] === 1) {
score += (multiplier)
}
multiplier *= 2;
}
}
return score
}
// console.log(countScore([[1,1,1,1],[1,0,0,1],[1,1,1,1]]))
console.log(matrixScore([[0,0,1,1],[1,0,1,0],[1,1,0,0]]))
|
'use strict'
/** @typedef {import('@adonisjs/framework/src/Request')} Request */
/** @typedef {import('@adonisjs/framework/src/Response')} Response */
/** @typedef {import('@adonisjs/framework/src/View')} View */
// /** @type {typeof import('@adonisjs/lucid/src/Lucid/Model')} */
const UserTask = use('App/Models/UserTask')
const moment = use('moment')
/**
* Resourceful controller for interacting with tasks
*/
class AnswerController {
/**
* Show a list of all tasks.
* GET tasks
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
* @param {View} ctx.view
*/
async index({ request, response, view }) {
const userTasks = await UserTask.query()
.whereNotNull('answer')
.whereNotNull('answered_at')
.whereDoesntHave('user', (builder) => {
builder.where('is_admin', true)
}).with('user').with('task').fetch()
return view.render('pages.admin.answers.index', { answers: userTasks.toJSON() })
}
/**
* Render a form to be used for creating a new task.
* GET tasks/create
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
* @param {View} ctx.view
*/
async create({ request, response, view }) {
}
/**
* Create/save a new task.
* POST tasks
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
*/
async store({ request, response }) {
}
/**
* Display a single task.
* GET tasks/:id
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
* @param {View} ctx.view
*/
async show({ params, request, response, view }) {
}
/**
* Render a form to update an existing task.
* GET tasks/:id/edit
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
* @param {View} ctx.view
*/
async edit({ params, request, response, view }) {
}
/**
* Update task details.
* PUT or PATCH tasks/:id
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
*/
async update({ params, request, response }) {
const { id } = params
const userTask = await UserTask.find(id)
userTask.checked = request.input('checked')
userTask.checked_at = Date.now()
userTask.save()
return 'OK'
}
/**
* Delete a task with id.
* DELETE tasks/:id
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
*/
async destroy({ params, request, response }) {
}
}
module.exports = AnswerController
|
const dbconnection = require('../config/connection');
exports.getCities = () => dbconnection.query('SELECT * FROM citys ;');
|
/*
* Copyright (C) 2021 Radix IoT LLC. All rights reserved.
*/
import dataPointTagsEditorTemplate from './dataPointTagsEditor.html';
import './dataPointTagsEditor.css';
class DataPointTagsEditorController {
static get $$ngIsClass() { return true; }
static get $inject() { return ['maDataPointTags']; }
constructor(maDataPointTags, $timeout) {
this.maDataPointTags = maDataPointTags;
}
$onInit() {
this.ngModelCtrl.$render = () => this.render();
}
updateTagKeys() {
this.tagKeys = Object.keys(this.tags);
}
render() {
this.tags = Object.assign({}, this.ngModelCtrl.$viewValue);
this.updateTagKeys();
}
deleteTagKey(key) {
delete this.tags[key];
this.updateTagKeys();
this.setViewValue();
}
tagKeysChanged() {
// add selected tag keys into the tags object
for (const key of this.tagKeys) {
if (!this.tags.hasOwnProperty(key)) {
this.tags[key] = undefined;
}
}
// remove deselected tag keys from the tags object
for (const key of Object.keys(this.tags)) {
if (!this.tagKeys.includes(key)) {
delete this.tags[key];
}
}
this.setViewValue();
}
tagValueChanged(key) {
this.setViewValue();
}
setViewValue() {
this.ngModelCtrl.$setViewValue(Object.assign({}, this.tags));
}
}
export default {
template: dataPointTagsEditorTemplate,
controller: DataPointTagsEditorController,
require: {
ngModelCtrl: 'ngModel'
}
};
|
import strategySchema from '../schemas/strategySchema'
import mongoose from 'mongoose'
const Strategy = mongoose.model('strategy', strategySchema)
export default Strategy
|
! function() {
"use strict";
function e(e) {
var t = [];
for (var i in e) e.hasOwnProperty(i) && e[i] && t.push(i);
return t.join(" ")
}
var t = null;
Polymer({
is: "paper-drawer-panel",
behaviors: [Polymer.IronResizableBehavior],
properties: {
defaultSelected: {
type: String,
value: "main"
},
disableEdgeSwipe: {
type: Boolean,
value: !1
},
disableSwipe: {
type: Boolean,
value: !1
},
dragging: {
type: Boolean,
value: !1,
readOnly: !0,
notify: !0
},
drawerWidth: {
type: String,
value: "256px"
},
edgeSwipeSensitivity: {
type: Number,
value: 30
},
forceNarrow: {
type: Boolean,
value: !1
},
hasTransform: {
type: Boolean,
value: function() {
return "transform" in this.style
}
},
hasWillChange: {
type: Boolean,
value: function() {
return "willChange" in this.style
}
},
narrow: {
reflectToAttribute: !0,
type: Boolean,
value: !1,
readOnly: !0,
notify: !0
},
peeking: {
type: Boolean,
value: !1,
readOnly: !0,
notify: !0
},
responsiveWidth: {
type: String,
value: "768px"
},
rightDrawer: {
type: Boolean,
value: !1
},
selected: {
reflectToAttribute: !0,
notify: !0,
type: String,
value: null
},
drawerToggleAttribute: {
type: String,
value: "paper-drawer-toggle"
},
drawerFocusSelector: {
type: String,
value: 'a[href]:not([tabindex="-1"]),area[href]:not([tabindex="-1"]),input:not([disabled]):not([tabindex="-1"]),select:not([disabled]):not([tabindex="-1"]),textarea:not([disabled]):not([tabindex="-1"]),button:not([disabled]):not([tabindex="-1"]),iframe:not([tabindex="-1"]),[tabindex]:not([tabindex="-1"]),[contentEditable=true]:not([tabindex="-1"])'
},
_transition: {
type: Boolean,
value: !1
}
},
listeners: {
tap: "_onTap",
track: "_onTrack",
down: "_downHandler",
up: "_upHandler",
transitionend: "_onTransitionEnd"
},
observers: ["_forceNarrowChanged(forceNarrow, defaultSelected)", "_toggleFocusListener(selected)"],
ready: function() {
this._transition = !0, this._boundFocusListener = this._didFocus.bind(this)
},
togglePanel: function() {
this._isMainSelected() ? this.openDrawer() : this.closeDrawer()
},
openDrawer: function() {
requestAnimationFrame(function() {
this.toggleClass("transition-drawer", !0, this.$.drawer), this.selected = "drawer"
}.bind(this))
},
closeDrawer: function() {
requestAnimationFrame(function() {
this.toggleClass("transition-drawer", !0, this.$.drawer), this.selected = "main"
}.bind(this))
},
_onTransitionEnd: function(e) {
var t = Polymer.dom(e).localTarget;
if (t === this && ("left" !== e.propertyName && "right" !== e.propertyName || this.notifyResize(), "transform" === e.propertyName && (requestAnimationFrame(function() {
this.toggleClass("transition-drawer", !1, this.$.drawer)
}.bind(this)), "drawer" === this.selected))) {
var i = this._getAutoFocusedNode();
i && i.focus()
}
},
_computeIronSelectorClass: function(t, i, r, n, a) {
return e({
dragging: r,
"narrow-layout": t,
"right-drawer": n,
"left-drawer": !n,
transition: i,
peeking: a
})
},
_computeDrawerStyle: function(e) {
return "width:" + e + ";"
},
_computeMainStyle: function(e, t, i) {
var r = "";
return r += "left:" + (e || t ? "0" : i) + ";", t && (r += "right:" + (e ? "" : i) + ";"), r
},
_computeMediaQuery: function(e, t) {
return e ? "" : "(max-width: " + t + ")"
},
_computeSwipeOverlayHidden: function(e, t) {
return !e || t
},
_onTrack: function(e) {
if (!t || this === t) switch (e.detail.state) {
case "start":
this._trackStart(e);
break;
case "track":
this._trackX(e);
break;
case "end":
this._trackEnd(e)
}
},
_responsiveChange: function(e) {
this._setNarrow(e), this.selected = this.narrow ? this.defaultSelected : null, this.setScrollDirection(this._swipeAllowed() ? "y" : "all"), this.fire("paper-responsive-change", {
narrow: this.narrow
})
},
_onQueryMatchesChanged: function(e) {
this._responsiveChange(e.detail.value)
},
_forceNarrowChanged: function() {
this._responsiveChange(this.forceNarrow || this.$.mq.queryMatches)
},
_swipeAllowed: function() {
return this.narrow && !this.disableSwipe
},
_isMainSelected: function() {
return "main" === this.selected
},
_startEdgePeek: function() {
this.width = this.$.drawer.offsetWidth, this._moveDrawer(this._translateXForDeltaX(this.rightDrawer ? -this.edgeSwipeSensitivity : this.edgeSwipeSensitivity)), this._setPeeking(!0)
},
_stopEdgePeek: function() {
this.peeking && (this._setPeeking(!1), this._moveDrawer(null))
},
_downHandler: function(e) {
!this.dragging && this._isMainSelected() && this._isEdgeTouch(e) && !t && (this._startEdgePeek(), e.preventDefault(), t = this)
},
_upHandler: function() {
this._stopEdgePeek(), t = null
},
_onTap: function(e) {
var t = Polymer.dom(e).localTarget,
i = t && this.drawerToggleAttribute && t.hasAttribute(this.drawerToggleAttribute);
i && this.togglePanel()
},
_isEdgeTouch: function(e) {
var t = e.detail.x;
return !this.disableEdgeSwipe && this._swipeAllowed() && (this.rightDrawer ? t >= this.offsetWidth - this.edgeSwipeSensitivity : t <= this.edgeSwipeSensitivity)
},
_trackStart: function(e) {
this._swipeAllowed() && (t = this, this._setDragging(!0), this._isMainSelected() && this._setDragging(this.peeking || this._isEdgeTouch(e)), this.dragging && (this.width = this.$.drawer.offsetWidth, this._transition = !1))
},
_translateXForDeltaX: function(e) {
var t = this._isMainSelected();
return this.rightDrawer ? Math.max(0, t ? this.width + e : e) : Math.min(0, t ? e - this.width : e)
},
_trackX: function(e) {
if (this.dragging) {
var t = e.detail.dx;
if (this.peeking) {
if (Math.abs(t) <= this.edgeSwipeSensitivity) return;
this._setPeeking(!1)
}
this._moveDrawer(this._translateXForDeltaX(t))
}
},
_trackEnd: function(e) {
if (this.dragging) {
var i = e.detail.dx > 0;
this._setDragging(!1), this._transition = !0, t = null, this._moveDrawer(null), this.rightDrawer ? this[i ? "closeDrawer" : "openDrawer"]() : this[i ? "openDrawer" : "closeDrawer"]()
}
},
_transformForTranslateX: function(e) {
return null === e ? "" : this.hasWillChange ? "translateX(" + e + "px)" : "translate3d(" + e + "px, 0, 0)"
},
_moveDrawer: function(e) {
this.transform(this._transformForTranslateX(e), this.$.drawer)
},
_getDrawerContent: function() {
return Polymer.dom(this.$.drawerContent).getDistributedNodes()[0]
},
_getAutoFocusedNode: function() {
var e = this._getDrawerContent();
return this.drawerFocusSelector ? Polymer.dom(e).querySelector(this.drawerFocusSelector) || e : null
},
_toggleFocusListener: function(e) {
"drawer" === e ? this.addEventListener("focus", this._boundFocusListener, !0) : this.removeEventListener("focus", this._boundFocusListener, !0)
},
_didFocus: function(e) {
var t = this._getAutoFocusedNode();
if (t) {
var i = Polymer.dom(e).path,
r = (i[0], this._getDrawerContent()),
n = i.indexOf(r) !== -1;
n || (e.stopPropagation(), t.focus())
}
},
_isDrawerClosed: function(e, t) {
return !e || "drawer" !== t
}
})
}();
|
const checkbox_numbers = document.getElementById('numbers')
const checkbox_uppercase = document.getElementById('uppercase')
const checkbox_lowercase = document.getElementById('lowercase')
const checkbox_symbols = document.getElementById('symbols')
const checkbox_length = document.getElementById('length')
const textbox_result = document.getElementById('result')
const click_generate = document.getElementById('generate')
const click_clipboard = document.getElementById('clipboard')
function randomNumber() {
return String.fromCharCode(Math.floor(Math.random()*10)+48)
}
function randomUpper() {
return String.fromCharCode(Math.floor(Math.random()*26)+65)
}
function randomLower() {
return String.fromCharCode(Math.floor(Math.random()*26)+97)
}
function randomSymbol() {
const symbols = '!@#$%¨&*(){}[]=<>/,.';
return symbols[Math.floor(Math.random()*symbols.length)]
}
function randomGenerator(useNumber, useUpper, useLower, useSymbol, size) {
var result = '';
var random;
for (var i = 0; i < size;) {
random = Math.floor(Math.random() * 4);
if (random === 0 && useNumber === true) {
result += randomNumber();
i++;
}
if (random === 1 && useUpper === true) {
result += randomUpper();
i++;
}
if (random === 2 && useLower === true) {
result += randomLower();
i++;
}
if (random === 3 && useSymbol === true) {
result += randomSymbol();
i++;
}
}
textbox_result.innerText = result
}
click_generate.addEventListener('click', () => {
var size = parseInt(checkbox_length.value);
const useNumber = checkbox_numbers.checked;
const useUpper = checkbox_uppercase.checked;
const useLower = checkbox_lowercase.checked;
const useSymbol = checkbox_symbols.checked;
randomGenerator(useNumber, useUpper, useLower, useSymbol, size);
})
click_clipboard.addEventListener('click', () => {
const str = document.createElement('textarea');
str.value = textbox_result.textContent;
document.body.appendChild(str);
str.select();
document.execCommand('copy');
str.remove();
alert('Copied to clipboard.')
})
|
import Controller from '@ember/controller';
export default Controller.extend({
actions: {
saveProduct() {
this.model.save();
this.transitionToRoute('product');
}
}
});
|
import _ from 'lodash'
import Utils from 'igui_root/src/scripts/utils';
import Backgrid from 'backgrid';
import TableHeaderView from 'igui_root/src/scripts/widgets/table/TableHeaderView';
import TableBodyView from 'igui_root/src/scripts/widgets/table/TableBodyView';
var TableGridView = Utils.extend.call(Backgrid.Grid, {
header: TableHeaderView,
body: TableBodyView,
footer: null,
initialize: function(options) {
if (this.tree) {
var grid = this;
var loadBranchQuery = grid.tree.loadBranchQuery || function (qb, model) {
qb.eq(grid.tree.parentIdAttr, model.id);
};
var getChildCollection = grid.tree.getChildCollection || function (collection) {
return new collection.constructor();
};
this.$el.treetable({
expandable: true,
column: this.tree.columnIndex || 0,
onNodeExpand: function () {
var node = this;
var model = node.row.data('model'),
childCollection = getChildCollection(grid.collection, model);
loadBranchQuery(childCollection.qb, model);
childCollection.getAllPages({reset: true}).done(function () {
var addedModels = grid.collection.add(childCollection.models, {at: grid.collection.indexOf(model) + 1});
node.__childModels__ = addedModels;
});
},
onNodeCollapse: function () {
var node = this;
var removeChildModels = function (node) {
if (!_.isEmpty(node.__childModels__)) {
grid.collection.remove(node.__childModels__);
node.__childModels__ = null;
}
_.each(node.children, removeChildModels);
};
removeChildModels(node);
grid.$el.treetable("unloadBranch", node);
}
});
this.tree.ttTree = this.$el.data('treetable');
this.tree.ttPlugin = this.$el.treetable.bind(this.$el);
// update treetable plugin upon removing rows before removing from view
//TODO do similar update for 'add' event
this.listenTo(this.collection, 'remove', function (model) {
// grid.$el.treetable('collapseNode', model.id);
var node = grid.$el.treetable('node', model.id);
var parent = node && node.parentNode();
if (parent) {
parent.removeChild(node, false);
if (_.isEmpty(parent.children)) {
parent.__childModels__ = null;
parent.collapse();
}
}
});
}
options = _.extend({}, options);
options.tree = this.tree;
return this._super(options);
}
}, {
_optionsToAttach: ['tree']
});
export default TableGridView;
|
const express = require("express");
const app = express();
let html = `
<html>
<style>
body{
margin: 0;
padding: 0;
background: #272727;
color: #fff;
font-family: sans-serif
}
.main{
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
</style>
<body>
<div class="main">
<h1>Happy Hacking 😇</h1>
</div>
</body>
</html>
`;
app.get("/", (req, res) => {
res.send(html);
});
app.get("/login", async(req, res) => {
let username = await req.query.username;
let password = await req.query.password;
console.log(`${username} : ${password}`); // show username and password in console
// do whatever with these
res.redirect("http://instagram.com");//redirect as your wish
});
// server
const serverPort = process.env.PORT || 3000;
app.listen(serverPort, () => console.log(`happy-hacking@${serverPort}`));
|
import React from "react";
import { Segment } from "semantic-ui-react";
import { useDispatch } from "react-redux";
import { BACKEND_HOST } from "./ip";
export function ChartNoteCard(props) {
const dispatch = useDispatch();
const showNote = size => {
dispatch({ type: "CHANGE_MODAL", key: "display", payload: "note" });
dispatch({ type: "CHANGE_MODAL", key: "size", payload: size });
dispatch({ type: "CHANGE_MODAL", key: "open", payload: true });
};
const makeNoteVisible = note => {
fetch(`http://${BACKEND_HOST}/notes/${note.id}`, {
method: "PATCH",
headers: {
Authorization: `Bearer ${localStorage.token}`,
"Content-Type": "application/json"
}
});
};
return (
<Segment className='baseline-space-between' style={{ padding: "5px" }}>
<span
onClick={() => {
showNote("large");
dispatch({ type: "STORE_SELECTED_NOTE", payload: props.note });
}}>
{props.note.note_title}
</span>
{props.note.visible_to_user === true ? (
<button className='mini ui green icon button'>Visible</button>
) : (
<button className='mini ui icon button' onClick={() => makeNoteVisible(props.note)}>
Visible
</button>
)}
</Segment>
);
}
|
self.addEventListener('push', e => {
const data = e.data.json();
e.waitUntil(
self.registration.showNotification(data.title, {
body: data.body
//icon: "icon url"
})
);
});
|
const db = require('../database');
const opencage = require('opencage-api-client');
const opencage_apikey = require('../opencageUser');
module.exports = {
async alignAllAddresses(req, res) {
console.log("alignAllAddresses()");
const addressQuery = `SELECT * FROM Address WHERE Addressid > 1000 AND Addressid <= 1100`
var lat = null
var lng = null
var street = null
var city = null
var country = null
var fullAddress = null
async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
}
db.query(addressQuery)
.then(result =>
{
asyncForEach(result.rows, async (address) => {
street = address.street
city = address.city
country = address.country
fullAddress = `${street}, ${city}, ${country}`
await opencage.geocode({q: `'${fullAddress}'`, key: opencage_apikey})
.then(data =>
{
JSON.stringify(data)
if (data.status.code == 200 && data.results.length > 0)
{
lat = data.results[0].geometry.lat
lng = data.results[0].geometry.lng
}
})
.catch(error => {console.log('error', error.message)});
var updateQuery = `UPDATE Address SET Coordinates = (point(${lat}, ${lng})) WHERE AddressID = ${address.addressid};`
console.log(updateQuery)
})
res.json("bla")
})
.catch(err => res.status(404).send(`Query error: ${err.stack}`))
},
}
|
const express = require('express')
const router = express.Router()
const indexRoutes = require('./index')
const userRoutes = require('./user')
// imports all routes to one file
router.use('/', indexRoutes)
router.use('/user', userRoutes)
module.exports = router
|
// Variables
// ----------------------------------
// Modules
var path = require('path'),
sh = require('shelljs'),
cli = require('cli-color');
// Messages
var error = cli.red.bold,
info = cli.cyan,
done = cli.green;
// Check
var nodeCheck = sh.which('node'),
gitCheck = sh.which('git');
// Paths
var themePath = './wp-content/themes/default/',
pluginsPath = './wp-content/plugins/',
gitClone = 'git clone https://github.com',
svnClone = 'svn checkout http://plugins.svn.wordpress.org/',
wpRepo = 'https://github.com/WordPress/WordPress.git',
twentyList = [
'./wp-content/themes/twentyten',
'./wp-content/themes/twentyeleven',
'./wp-content/themes/twentytwelve',
'./wp-content/themes/twentythirteen',
'./wp-content/themes/twentyfourteen',
'./wp-content/themes/twentyfifteen'
];
// Scaffolding
// ----------------------------------
sh.echo(info('→ Initializing...'));
sh.rm('-rf', ['./node_modules', './.git', '.gitignore', '.editorconfig', '.travis.yml', 'newproject.js', 'package.json', 'README.md', 'logo-bp.jpg']);
// Check if Git exists
if (!gitCheck) {
sh.echo(error('✖ This task requires Git to run.'));
process.exit(1);
} else {
// Install WordPress
sh.echo(info('→ Installing WordPress...'));
sh.exec('git clone ' + wpRepo);
sh.mv('./WordPress/*', './');
sh.rm('-rf', ['./WordPress']);
sh.echo(done('✔ WordPress successfully installed!'));
// Scaffolding
sh.echo(info('→ Creating Structure...'));
sh.mkdir('-p', themePath);
sh.mv('./init/templates/wordpress/*', themePath);
sh.mv(themePath + '__wp-config.txt', './wp-config.php');
sh.mv(themePath + '__gitignore.txt', './.gitignore');
sh.mv(themePath + '__htaccess.txt', themePath + 'htaccess.txt');
sh.rm('-rf', ['./init']);
sh.rm('-rf', twentyList);
sh.echo(done('✔ Created!'));
// Install WP Plugins
sh.echo(info('→ Installing Plugins...'));
function clonePlugin(pluginSrc, pluginDist, pluginName, pluginType) {
sh.echo(info('→ Clonning ' + pluginName + '...'));
if (pluginType === 'git') {
sh.exec(path.join(gitClone, pluginSrc));
}
if (pluginType === 'svn') {
sh.exec(path.join(svnClone, pluginSrc));
}
sh.mv(pluginDist, pluginsPath);
sh.echo(done('✔ ' + pluginName + ' successfully cloned!'));
}
// Design Optimization and Performance
clonePlugin('/elliotcondon/acf.git', './acf', 'Advanced Custom Fields', 'git');
clonePlugin('/wp-plugins/admin-menu-editor.git', './admin-menu-editor', 'Admin Menu Editor', 'git');
clonePlugin('/wp-plugins/contact-form-7.git', './contact-form-7', 'Contact Form 7', 'git');
clonePlugin('/wp-plugins/w3-total-cache.git', './w3-total-cache', 'W3 Total Cache', 'git');
// SEO Tools
clonePlugin('/Yoast/wordpress-seo.git', './wordpress-seo', 'Yoast', 'git');
clonePlugin('/Yoast/google-analytics-for-wordpress.git', './google-analytics-for-wordpress', 'Google Analytics for WordPress', 'git');
clonePlugin('/wp-plugins/reduce-bounce-rate.git', './reduce-bounce-rate', 'Reduce Bounce Rate', 'git');
clonePlugin('/Automattic/jetpack.git', './jetpack', 'Jetpack', 'git');
// Security and Backup
clonePlugin('/wp-plugins/updraftplus.git', './updraftplus', 'UpdraftPlus Backup and Restoration', 'git');
clonePlugin('/wp-plugins/wordfence.git', './wordfence', 'Wordfence Security', 'git');
clonePlugin('/login-lockdown/trunk login-lockdown', './login-lockdown', 'Login LockDown', 'svn');
sh.echo(done('✔ Plugins successfully installed!'));
}
// Setup
// ----------------------------------
sh.echo(info('→ Setting up project...'));
// Grant Permission
sh.echo(info('→ Setting permission to folders and files...'));
sh.chmod('755', './');
sh.echo(done('✔ Done!'));
// Move on to "./src" folder
sh.echo(info('→ Installing dependencies....'));
sh.cd(themePath + './src');
// Check if NodeJS exists and install dependencies
if (!nodeCheck) {
sh.echo(error('✖ This task requires NodeJS to run.'));
process.exit(1);
} else {
sh.exec('npm install');
sh.echo(done('✔ Node Modules successfully installed!'));
}
// Final Message
sh.echo(done('✔ All Done!'));
sh.echo(info('\n!!! Remember to setup your "wp_config.php" file'));
|
define(["foo"], function (_foo) {
"use strict";
for (let _i = 0; _i < _foo.array.length; _i++) {
let elem = array[_i];
console.log(elem);
}
});
|
function cancel(command, tour) {
return function() {
localStorage[command] = true;
tour.cancel();
}
}
function dashboard() {
var tour = new Shepherd.Tour({
defaults: {
classes: 'shepherd-theme-arrows',
}
});
tour.addStep('step1', {
text: "Why don't you take a tour of shuttl?",
title: 'Welcome to the shuttl Demo!',
classes: 'shepherd shepherd-open shepherd-theme-arrows shepherd-transparent-text',
buttons: [
{
text: 'No',
classes: 'shepherd-button-secondary',
action: cancel("dashComplete", tour)
},
{
text: 'Yes',
classes: 'shepherd-button-example-primary',
action: tour.next
}
]
});
tour.addStep('step2', {
title: 'Organization dashboard',
text: 'This is where you see your websites. <br/>We built Shuttl so that you can maintain multiple websites without a seperate account.',
attachTo: '.main-content bottom',
classes: 'shepherd shepherd-open shepherd-theme-arrows shepherd-transparent-text',
buttons: [
{
text: 'stop',
classes: 'shepherd-button-secondary',
action: cancel("dashComplete", tour)
},
{
text: 'Back',
classes: 'shepherd-button-secondary',
action: tour.back
},
{
text: 'Continue',
classes: 'shepherd-button-example-primary',
action: tour.next
}
]
});
var step3 = 'This is how you create a website.'
step3 += '<br/>We believe that everything should be as simple as possible. <br/>Simply enter the name of the website and press add.';
tour.addStep('step3', {
title: 'Website Creation',
text: step3,
attachTo: '.inputForm bottom',
classes: 'shepherd shepherd-open shepherd-theme-arrows shepherd-transparent-text',
buttons: [
{
text: 'stop',
classes: 'shepherd-button-secondary',
action: cancel("dashComplete", tour)
},
{
text: 'Back',
classes: 'shepherd-button-secondary',
action: tour.back
},
{
text: 'Continue',
classes: 'shepherd-button-example-primary',
action: tour.next
}
]
});
tour.addStep('step4', {
title: 'Website List',
text: "This section lists out the websites that belong to your organization.",
attachTo: '.websites top',
classes: 'shepherd shepherd-open shepherd-theme-arrows shepherd-transparent-text',
buttons: [
{
text: 'stop',
classes: 'shepherd-button-secondary',
action: cancel("dashComplete", tour)
},
{
text: 'Back',
classes: 'shepherd-button-secondary',
action: tour.back
},
{
text: 'Continue',
classes: 'shepherd-button-example-primary',
action: tour.next
}
]
});
tour.addStep('step5', {
title: 'Website Name',
text: "This is the name of your website and it links to the website dashboard",
attachTo: '.cell.input a bottom',
classes: 'shepherd shepherd-open shepherd-theme-arrows shepherd-transparent-text',
buttons: [
{
text: 'stop',
classes: 'shepherd-button-secondary',
action: cancel("dashComplete", tour)
},
{
text: 'Back',
classes: 'shepherd-button-secondary',
action: tour.back
},
{
text: 'Continue',
classes: 'shepherd-button-example-primary',
action: tour.next
}
]
});
tour.addStep('step6', {
title: 'Rename',
text: "Click this button to rename your website",
attachTo: '.cell.edit bottom',
classes: 'shepherd shepherd-open shepherd-theme-arrows shepherd-transparent-text',
buttons: [
{
text: 'stop',
classes: 'shepherd-button-secondary',
action: cancel("dashComplete", tour)
},
{
text: 'Back',
classes: 'shepherd-button-secondary',
action: tour.back
},
{
text: 'Continue',
classes: 'shepherd-button-example-primary',
action: tour.next
}
]
});
tour.addStep('step7', {
title: 'Delete',
text: "Click this button to delete your website",
attachTo: '.cell.delete bottom',
classes: 'shepherd shepherd-open shepherd-theme-arrows shepherd-transparent-text',
buttons: [
{
text: 'stop',
classes: 'shepherd-button-secondary',
action: cancel("dashComplete", tour)
},
{
text: 'Back',
classes: 'shepherd-button-secondary',
action: tour.back
},
{
text: 'Continue',
classes: 'shepherd-button-example-primary',
action: tour.next
}
]
});
tour.addStep('step8', {
title: 'Delete Multiple',
text: "Check this checkbox to be able to delete multiple websites at once",
attachTo: '.cell.check bottom',
classes: 'shepherd shepherd-open shepherd-theme-arrows shepherd-transparent-text',
buttons: [
{
text: 'stop',
classes: 'shepherd-button-secondary',
action: cancel("dashComplete", tour)
},
{
text: 'Back',
classes: 'shepherd-button-secondary',
action: tour.back
},
{
text: 'Continue',
classes: 'shepherd-button-example-primary',
action: function() {
$(".cell.check input").trigger("click");
setTimeout(function(){
tour.next();
}, 5);
}
}
]
});
tour.addStep('step8', {
title: 'Delete Multiple',
text: "Once all sites are checked, use this to delete them.",
attachTo: '#delete bottom',
classes: 'shepherd shepherd-open shepherd-theme-arrows shepherd-transparent-text',
buttons: [
{
text: 'stop',
classes: 'shepherd-button-secondary',
action: cancel("dashComplete", tour)
},
{
text: 'Back',
classes: 'shepherd-button-secondary',
action: tour.back
},
{
text: 'Continue',
classes: 'shepherd-button-example-primary',
action: function() {
$(".cell.check input").trigger("click");
tour.next();
}
}
]
});
tour.addStep('step9', {
title: 'Moving On',
text: "This is it for this this portion of the tour. Click on a website to continue the tour.",
attachTo: '#main-nav bottom',
classes: 'shepherd shepherd-open shepherd-theme-arrows shepherd-transparent-text',
buttons: [
{
text: 'stop',
classes: 'shepherd-button-secondary',
action: cancel("dashComplete", tour)
},
{
text: 'Back',
classes: 'shepherd-button-secondary',
action: tour.back
},
{
text: 'Finish',
classes: 'shepherd-button-example-primary',
action: cancel("dashComplete", tour)
}
]
});
return tour;
}
export default {
tour: dashboard
}
|
const test = require('tape');
const isEmpty = require('./isEmpty.js');
test('Testing isEmpty', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof isEmpty === 'function', 'isEmpty is a Function');
t.equal(isEmpty(new Map()), true, 'Returns true for empty Map');
t.equal(isEmpty(new Set()), true, 'Returns true for empty Set');
t.equal(isEmpty([]), true, 'Returns true for empty array');
t.equal(isEmpty({}), true, 'Returns true for empty object');
t.equal(isEmpty(''), true, 'Returns true for empty string');
t.equal(isEmpty([1, 2]), false, 'Returns false for non-empty array');
t.equal(isEmpty({ a: 1, b: 2 }), false, 'Returns false for non-empty object');
t.equal(isEmpty('text'), false, 'Returns false for non-empty string');
t.equal(isEmpty(123), true, 'Returns true - type is not considered a collection');
t.equal(isEmpty(true), true, 'Returns true - type is not considered a collection');
//t.deepEqual(isEmpty(args..), 'Expected');
//t.equal(isEmpty(args..), 'Expected');
//t.false(isEmpty(args..), 'Expected');
//t.throws(isEmpty(args..), 'Expected');
t.end();
});
|
import React from 'react'
import { Element } from 'react-scroll';
import ToyInfo from "../ToyInfo/ToyInfo";
import styles from "./WebPages.module.css"
import { ToyItems } from "../../../../store/contents/portfolio/ToyItems";
import webpageList from "../../../../assets/images/webpages"
import LazyItem from "../../../LazyItems/LazyItem/LazyItem";
const WebPages = () => {
return <>
<Element>
<ToyInfo item={ToyItems[0][0]} />
<div className={styles.Imgs}>
{
webpageList.map((page) => {
return <LazyItem src={page.src} alt={page.alt} />
})
}
</div>
</Element></>
}
export default WebPages;
|
/**
* @license
* Copyright (c) 2018 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
// Import statements in Polymer 3.0 can now use package names.
// polymer-element.js now exports PolymerElement instead of Element,
// so no need to change the symbol.
import { PolymerElement, html } from '@polymer/polymer/polymer-element.js';
import '@polymer/polymer/lib/elements/dom-if.js';
import '@polymer/paper-checkbox/paper-checkbox.js';
import '@polymer/paper-input/paper-input.js';
import { setPassiveTouchGestures } from '@polymer/polymer/lib/utils/settings';
import './fields-group.js';
import 'ag-grid-polymer';
import ClickableCellRenderer from './clickable-renderer'
class AGGridDemo extends PolymerElement {
static get properties () {
return {
message: {
type: String,
value: ''
},
pie: {
type: Boolean,
value: false,
observer: 'togglePie'
},
loadComplete: {
type: Boolean,
value: false
}
};
}
constructor() {
// If you override the constructor, always call the
// superconstructor first.
super();
// Resolve warning about scroll performance
// See https://developers.google.com/web/updates/2016/06/passive-event-listeners
setPassiveTouchGestures(true);
this.columnDefs = [
{ headerName: "Make", field: "make", sortable: true },
{ headerName: "Model", field: "model" , sortable: true },
{ headerName: "Price", field: "price" , sortable: true , editable:true},
{
headerName: "Clickable Component",
field: "make",
cellRendererFramework: 'clickable-renderer'
}
];
this.rowData = [
{ make: "Toyota", model: "Celica", price: 35000 },
{ make: "Ford", model: "Mondeo", price: 32000 },
{ make: "Porsche", model: "Boxter", price: 72000 }
];
this.components = {
clickableCellRenderer: ClickableCellRenderer,
}
}
firstDataRendered(params) {
params.api.sizeColumnsToFit()
}
ready(){
// If you override ready, always call super.ready() first.
super.ready();
// Output the custom element's HTML tag to the browser console.
// Open your browser's developer tools to view the output.
console.log(this.tagName);
}
static get template () {
// Template getter must return an instance of HTMLTemplateElement.
// The html helper function makes this easy.
return html`
<link rel="stylesheet" href="../../node_modules/ag-grid-community/dist/styles/ag-grid.css">
<link rel="stylesheet" href="../../node_modules/ag-grid-community/dist/styles/ag-theme-material.css">
<h1>Grid Demo</h1>
<app-toolbar> ddd</app-toolbar>
<ag-grid-polymer style="width: 100%; height: 350px;"
class="ag-theme-material"
rowData="{{rowData}}"
suppressCellSelection
columnDefs="{{columnDefs}}"
on-first-data-rendered="{{firstDataRendered}}">
</ag-grid-polymer>
`;
}
}
// Register the element with the browser.
customElements.define('aggrid-demo', AGGridDemo);
|
(function(exports) {
var ALL_NUMBERS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var numberCollection = new Collection(ALL_NUMBERS);
var imagePathCollection;
function initialize() {
$.get('/numeralia_images', function(imagePaths) {
imagePathCollection = new Collection(imagePaths);
generateQuestion();
});
}
function generateQuestion() {
var randomImagePath = imagePathCollection.chooseRandom();
var randomQuantity = numberCollection.chooseRandom();
_setImage(randomImagePath);
_setImageVocabLabel(randomImagePath);
_setQuantityLabel(randomQuantity);
}
function _setImage(imagePath) {
document.getElementById('image').src = imagePath;
}
function _setImageVocabLabel(imagePath) {
document.getElementById('vocab').innerHTML = _getFileNameWithoutExtension(imagePath);
}
function _setQuantityLabel(quantity) {
document.getElementById('quantity').innerHTML = quantity;
}
function _getFileNameWithoutExtension(filePath) {
return filePath.match(/([^/]+)\.\w{2,3}$/)[1].replace(/(\w)\(/g, '$1 (');
}
exports.initialize = initialize;
exports.generateQuestion = generateQuestion;
})(this);
|
import React, {Component} from "react"
import "./switchDot.scss"
export default class SwitchDot extends Component {
constructor(props){
super(props);
this.state = {
dots: this.props.dots,
currentdot: 0,
}
}
handledot=(val)=>{
this.setState({
currentdot: val,
})
this.props.onChange(val);//回调函数传递参数给父组件
}
render () {
const DotsElements = []; // 保存点元素
for(let i = 0;i<this.state.dots;i++){
DotsElements.push(
<div key={i} className={this.state.currentdot === i? "dot active" : "dot"} onClick={()=>{this.handledot(i)}}></div>
)
}
return (
<div className="switchdot-container">
<div className="dot-box">
{DotsElements}
</div>
</div>
)
}
}
|
import axios from "./axios";
import User from "../util/user";
export const getCategory = () => axios.get("/category");
export const updateCategory = params => {
const token = User.getToken();
return axios.post("/category", params, {
headers: {
token
}
});
};
|
var fs = require('fs'),
path = require('path'),
util = require('util'),
logger = require('morgan'),
bodyParser = require('body-parser'),
express = require('express'),
cookieParser = require('cookie-parser'),
config = require('./config'),
server = express(),
ipAddress = (process.env.OPENSHIFT_NODEJS_IP) ? process.env.OPENSHIFT_NODEJS_IP : null,
portNumber = normalizePort(process.env.OPENSHIFT_NODEJS_PORT || process.env.PORT || process.env.port || config.defaultPort);
server.set('port', portNumber);
// view engine setup
server.set('views', path.join(__dirname, 'views'));
server.set('view engine', 'jade');
server.use(logger('dev'));
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: false }));
server.use(cookieParser());
server.use(require('stylus').middleware(path.join(process.cwd(), 'public')));
server.use(express.static(path.join(process.cwd(), 'public')));
//CORS access
server.use(function (req, res, next) {
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Origin", "*");
next();
});
server.use('/', require('./routes/index'));
server.use('/api/v1/', require('./routes/api'));
server.use('/api/v2/', require('./routes/api'));
// express error handlers
server.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: (server.get('env') === 'development') ? err : {}
});
});
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
console.log('server listening for requests on port: %d', portNumber);
server.listen(portNumber, ipAddress);
module.exports = server;
|
import {combineReducers} from 'redux';
import authenticate from './authenticate';
import leftMenu from './leftMenu';
import globalMessages from './globalMessages';
import pageLoading from './pageLoading';
export default combineReducers({
authenticate,
leftMenu,
globalMessages,
pageLoading
});
|
import { Track } from '../core/Track.js';
export class Flag extends Track {
constructor( o = {}, parent ) {
super( o, parent )
this.type = 'flag'
this.needPrev = true;
this.h = 84;
this.hmax = Math.floor(( this.h - this.tt - this.tb )/18)-1;
this.init();
}
update( f ) {
super.update( f )
let value = this.v === undefined ? '' : this.items[this.v].value;
if( !value ) value = this.prev === undefined ? '' : this.items[this.prev].value;
if( this.select || this.parent.fullActve ){
this.c[5].style.background = this.v !== undefined ? this.acolor : 'none';
}
return value;
}
draw() {
let py = 0;
let lng = this.items.length;
for( let i = 0; i !== lng; i++ ){
this.items[i].setPy( py );
if( py < this.hmax ) py++;
else py = 0;
}
}
changeHeight() {
this.hmax = Math.floor(( this.h - this.tt - this.tb )/18)-1;
this.draw();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.