text
stringlengths 7
3.69M
|
|---|
import "./ToggleButton.css";
const ToggleButton = ({ isOn, onToggle, label, dataTestid }) => (
<button
data-test-id={dataTestid}
data-on={isOn}
className="toggleButton"
onClick={onToggle}
>
<div className="toggle">
<div />
</div>
<div className="label">{label}</div>
</button>
);
export default ToggleButton;
|
'use strict';
app.controller('PositionAdd', ['$scope', '$state', 'uiLoad','JQ_CONFIG',
function($scope, $state, uiLoad, JQ_CONFIG) {
$scope.formData = {};
$scope.formData.org = sessionStorage.getItem("treeId");
$scope.formData.superName = sessionStorage.getItem("treeName");
if($scope.permBtn&&$scope.permBtn.length>0&&$scope.permBtn.indexOf("add")<0){//判断是否有修改权限
$("#add").remove();
}
// 提交并添加数据
$scope.submit = function() {
var url = app.url.position.api.save;
app.utils.getData(url, $scope.formData, function(dt) {
$state.go('app.position.list');
$scope.$parent.reload();
});
};
$scope.return = function(){
$state.go('app.position.list');
$scope.$parent.reload();
};
}
]);
|
var _KT_ELEMENT_ID = 0;
class KtRenderable extends HTMLTemplateElement {
constructor() {
super();
/**
*
* @type {KtHelper}
* @protected
*/
this._hlpr = new KtHelper();
/**
* Array with all observed elements of this template
*
* null indicates, the template was not yet rendered
*
* @type {HTMLElement[]}
* @protected
*/
this._els = null;
this._attrs = {"debug": false};
/**
* The internal element id to identify which elements
* to render.
*
* @type {number}
* @protected
*/
this._ktId = ++_KT_ELEMENT_ID;
}
attributeChangedCallback(attrName, oldVal, newVal) {
this._attrs[attrName] = newVal;
}
_log(v1, v2, v3) {
let a = [ this.constructor.name + "#" + this.id + "[" + this._ktId + "]:"];
for (let e of arguments)
a.push(e);
if (this._attrs.debug !== false)
console.log.apply(this, a);
}
/**
* Walk through all elements and try to render them.
*
* if a element has the _kaMb (maintained by) property set,
* check if it equals this._kaId (the element id). If not,
* skip this node.
*
*
* @param {HTMLElement} node
* @param {object} $scope
*/
renderRecursive(node, $scope) {
if (node.hasOwnProperty("_kaMb") && node._kaMb !== this._ktId)
return;
let refPromise = null;
// Register references
if (node instanceof HTMLElement && node.hasAttribute("*ref")) {
let refname = node.getAttribute("*ref");
refPromise = $scope.$ref[refname];
$scope.$ref[refname] = node;
}
// Register id of cloned node
if (node instanceof HTMLElement && node.hasAttribute("*id")) {
node.id = node.getAttribute("*id");
}
if (typeof node.render === "function") {
node.render($scope);
return;
}
for(let curNode of node.childNodes) {
if (node.ktSkipRender === true)
return;
this.renderRecursive(curNode, $scope);
}
if (refPromise !== null && typeof refPromise !== "undefined" && typeof refPromise.resolve === "function") {
// Resolve promise registered with waitRef()
refPromise.resolve(node);
}
}
_removeNodes() {
if (this._els === null)
return;
for (let el of this._els) {
if (typeof el._removeNodes === "function")
el._removeNodes();
if (this.parentElement !== null)
this.parentElement.removeChild(el);
}
this._els = null;
}
/**
* Clone and append all elements in
* content of template to the next sibling.
*
* @param sibling
* @protected
*/
_appendElementsToParent(sibling) {
if (typeof sibling === "undefined")
sibling = this.nextSibling;
let cn = this.content.cloneNode(true);
this._els = [];
for (let cel of cn.children) {
cel._kaMb = this._ktId;
this._els.push(cel);
}
this.parentElement.insertBefore(cn, sibling);
}
}
|
function() {
var app = $$(this).app;
var self = $(this);
$("pre", self).each(function() {
var pre = $(this);
var js = pre.text();
var r = js.match(/\$\(\"\#([^\"]*)\"\)/);
if (r) {
var id = r[1];
var code_id = 'code-'+id;
pre.wrap('<div id="'+code_id+'"></div>');
$('#'+code_id).evently(app.ddoc.vendor.couchapp.evently.docs.topic.edit, app, [id]);
}
});
};
|
var express = require('express');
var http = require('http');
var path = require('path');
var socketIO = require('socket.io');
var app = express();
var server = http.Server(app);
var io = socketIO(server);
var users = {};
var games = {};
var lobby = [];
var port = 5000;
app.set('port', port);
app.use('/static', express.static(__dirname + '/static'));
app.get('/', function(request, response) {
response.sendFile(path.join(__dirname, 'index.html'));
});
server.listen(port, function() {
console.log('Starting server on port ' + port);
});
class Track {
constructor(name, vertices) {
this.name = name;
this.vertices = vertices;
this.lengths = [];
this.distance = 0;
for (var i=1; i<this.vertices.length; i++) {
var vertex = this.vertices[i];
var prev = this.vertices[i-1];
var dist = Math.sqrt((vertex.x - prev.x)*(vertex.x - prev.x) + (vertex.y - prev.y)*(vertex.y - prev.y));
this.distance += (dist);
this.lengths.push(dist);
}
}
distanceToXY(dist) {
var walker = 0;
var start = 0;
for (var i=0; i<this.lengths.length; i++) {
start = walker;
walker += this.lengths[i];
if (dist < walker) {
var vertex = this.vertices[i+1];
var prev = this.vertices[i];
return (new Point(prev.x + (vertex.x - prev.x) * ((dist - start) / (walker - start)), prev.y + (vertex.y - prev.y) * ((dist - start) / (walker - start))));
}
}
}
}
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
distanceTo(x, y) {
return Math.sqrt((x - this.x)*(x - this.x) + (y - this.y)*(y - this.y));
}
}
var tracks = [new Track(name='track1', vertices=[new Point(0.5, 0), new Point(0.5, 0.2), new Point(0.2, 0.5), new Point(0.3, 0.6), new Point(0.7, 0.2), new Point(0.8, 0.3), new Point(0.5, 0.6), new Point(0.5, 1)])]
class Enemy {
constructor(id, size, color, speed, progress, hp, damage, owner, gameID) {
this.id = id;
this.progress = progress;
this.gameID = gameID;
this.owner = owner;
var location = games[this.gameID].players[this.owner].track.distanceToXY(this.progress);
this.x = location.x;
this.y = location.y;
this.size = size;
this.color = color;
this.speed = speed;
this.hp = hp;
this.damage = damage;
}
tick() {
this.progress += this.speed;
if (this.progress < games[this.gameID].players[this.owner].track.distance) {
var location = games[this.gameID].players[this.owner].track.distanceToXY(this.progress);
this.x = location.x;
this.y = location.y;
} else {
for (var i=0; i<games[this.gameID].players[this.owner].enemies.length; i++) {
if (games[this.gameID].players[this.owner].enemies[i] == this) {
games[this.gameID].players[this.owner].lives -= this.damage;
games[this.gameID].players[this.owner].enemies.splice(i, 1);
break;
}
}
}
}
takeDamage(damage) {
this.hp -= damage;
if (this.hp <= 0) {
for (var i=0; i<games[this.gameID].players[this.owner].enemies.length; i++) {
if (games[this.gameID].players[this.owner].enemies[i] == this) {
games[this.gameID].players[this.owner].enemies.splice(i, 1);
break;
}
}
}
}
}
class Grunt extends Enemy {
constructor(id, owner, gameID) {
super(id, 0.015, 'red', 0.002, 0, 1, 1, owner, gameID);
}
}
class Raider extends Enemy {
constructor(id, owner, gameID) {
super(id, 0.022, 'blue', 0.0035, 0, 2, 2, owner, gameID);
}
}
class Wave {
constructor(enemy, number, timeBetween, timeAfter) {
this.enemy = enemy;
this.quantity = quantity;
this.timeBetween = timeBetween;
this.timeAfter = timeAfter;
}
}
var waves = [
[
new Wave(enemy='Grunt', quantity=10, timeBetween=500, timeAfter=15000)
],
[
new Wave(enemy='Grunt', quantity=10, timeBetween=250, timeAfter=500),
new Wave(enemy='Raider', quantity=10, timeBetween=400, timeAfter=10000)
],
[
new Wave(enemy='Grunt', quantity=10, timeBetween=500, timeAfter=1000),
new Wave(enemy='Raider', quantity=20, timeBetween=400, timeAfter=10000)
],
[
new Wave(enemy='Raider', quantity=30, timeBetween=300, timeAfter=10000)
],
[
new Wave(enemy='Raider', quantity=100, timeBetween=50, timeAfter=10000)
],
[
new Wave(enemy='Raider', quantity=500, timeBetween=50, timeAfter=10000)
]
];
io.on('connection', function(socket) {
socket.on('new player', function() {
users[socket.id] = {
id: socket.id,
name: 'player',
wins: 0,
losses: 0,
inGame: null
}
findMatch(socket);
});
socket.on('income', function() {
var player = games[users[socket.id].inGame].players[socket.id];
player.gold += player.income * player.honor;
});
socket.on('built', function(tower) {
var player = games[users[socket.id].inGame].players[socket.id];
player.gold -= tower.cost;
player.towers.push(tower);
});
socket.on('expense', function(cost) {
var player = games[users[socket.id].inGame].players[socket.id];
player.gold -= cost;
});
socket.on('attack', function(projectile) {
var player = games[users[socket.id].inGame].players[socket.id];
player.projectiles.push(projectile);
});
socket.on('damage', function(enemyID, damage, projectile) {
try {
var player = games[users[socket.id].inGame].players[socket.id];
if (projectile && projectile != null) {
for (var i in player.projectiles) {
if (player.projectiles[i].ownerID == projectile.ownerID && player.projectiles[i].id == projectile.id) {
player.projectiles[i].pierce -= 1;
if (player.projectiles[i].pierce <= 0) {
player.projectiles.splice(i, 1);
break;
}
}
}
}
player.enemies[enemyID].takeDamage(damage);
} catch (e) {
console.log(e);
}
});
socket.on('disconnect', function() {
if (users[socket.id]) {
if (users[socket.id].inGame == null) {
for (var i=0; i<lobby.length; i++) {
if (lobby[i] == users[socket.id]) {
lobby.splice(i, 1);
}
}
} else {
var game = games[users[socket.id].inGame];
users[game.players[socket.id].opponent].inGame = null;
findMatch(users[game.players[socket.id].opponent]);
delete games[users[socket.id].inGame];
}
delete users[socket.id];
}
});
});
function findMatch(socket) {
if (lobby.length > 0) {
var firstInLine = lobby.splice(0, 1)[0].id;
var gameid = String(firstInLine) + String(socket.id);
games[gameid] = {
id: gameid,
startTime: new Date(),
lastSpawnTime: 0,
waitTime: 0,
time: 0,
wave: 0,
subwave: 0,
spawnNumber: 0,
enemyID: 0,
players: {}
};
games[gameid].players[firstInLine] = {
id: firstInLine,
opponent: socket.id,
track: tracks[0],
lives: 100,
gold: 300000,
income: 100,
honor: 1,
incomeTime: 6000,
canBuild: ['Archer', 'Sniper', 'ChainGunner'],
towers: [],
projectiles: [],
enemies: []
};
games[gameid].players[socket.id] = {
id: socket.id,
opponent: firstInLine,
track: tracks[0],
lives: 100,
gold: 300000,
income: 100,
honor: 1,
incomeTime: 6000,
canBuild: ['Archer', 'Sniper', 'ChainGunner'],
towers: [],
projectiles: [],
enemies: []
}
users[socket.id].inGame = gameid;
users[firstInLine].inGame = gameid;
} else {
lobby.push(users[socket.id]);
}
}
setInterval(function() {
try {
for (var i in games) {
var game = games[i];
game.time = new Date() - game.startTime;
if (waves[game.wave]) {
var currWave = waves[game.wave][game.subwave];
if (game.waitTime != 0) {
if (game.time - game.lastSpawnTime > game.waitTime) {
for (var j in game.players) {
var player = game.players[j];
player.enemies.push(new (eval(currWave.enemy))(id=game.enemyID, owner=player.id, gameID=game.id));
game.enemyID += 1;
}
game.spawnNumber += 1;
if (game.spawnNumber >= currWave.quantity) {
if (waves[game.wave][game.subwave + 1]) {
game.subwave += 1;
game.spawnNumber = 0;
game.waitTime = currWave.timeAfter;
} else {
game.wave += 1;
game.subwave = 0;
game.spawnNumber = 0;
game.waitTime = currWave.timeAfter;
}
}
game.lastSpawnTime += game.waitTime;
game.waitTime = 0;
}
} else if (game.spawnNumber < currWave.quantity) {
if (game.time - game.lastSpawnTime > currWave.timeBetween) {
for (var j in game.players) {
var player = game.players[j];
player.enemies.push(new (eval(currWave.enemy))(id=game.enemyID, owner=player.id, gameID=game.id));
game.enemyID += 1;
}
game.spawnNumber += 1;
if (game.spawnNumber >= currWave.quantity) {
if (waves[game.wave][game.subwave + 1]) {
game.subwave += 1;
game.spawnNumber = 0;
game.waitTime = currWave.timeAfter;
} else {
game.wave += 1;
game.subwave = 0;
game.spawnNumber = 0;
game.waitTime = currWave.timeAfter;
}
}
game.lastSpawnTime += currWave.timeBetween;
}
}
}
for (var j in game.players) {
var player = game.players[j];
for (var k=player.projectiles.length-1; k>=0; k--) {
var projectile = player.projectiles[k];
projectile.x += projectile.speed * projectile.direction.x;
projectile.y += projectile.speed * projectile.direction.y;
if (projectile.range < Math.sqrt((projectile.x - projectile.start.x)*(projectile.x - projectile.start.x)+(projectile.y - projectile.start.y)*(projectile.y - projectile.start.y))) {
player.projectiles.splice(k, 1);
}
}
for (var k in player.enemies) {
game.players[j].enemies[k].tick();
}
io.to(player.id).emit('state', game);
}
//io.sockets.emit('state', players, buttons, currentTrack);
}
} catch (e) {
console.log(e);
}
}, 1000 / 60);
|
$(document).ready(function() {
$('#story-form-submit').click(function(e){
e.preventDefault();
});
});
|
import React, {useState, useEffect} from 'react';
import {isChrome, isFirefox, isWindows, isMacOs, isEdge,
osVersion,osName, fullBrowserVersion, browserVersion,
browserName} from 'react-device-detect';
function App() {
const [browser, setBrowser] = useState(' ');
const [window, setWindow] = useState('');
useEffect(()=>{
if(isFirefox){
setBrowser('Firefox');
}
if(isChrome){
setBrowser('Chrome');
}
if(isEdge){
setBrowser('Microsoft Edge');
}
});
useEffect(()=>{
if(isWindows){
setWindow('Windows')
}
if(isMacOs){
setWindow('Mac')
}
}, []);
return (
<div>
<center>
<div style={top}>
<h2>Here we are using some </h2>
<h1>React-Device-Detect's Selectors and Views</h1>
</div>
<hr/>
<h3 style={{color:"blue"}}>
The underline values different for different browser and Operating System.
</h3>
<hr/>
<div style={middle}>
<h1>You are using the browser : <i><u> {browser}</u></i></h1>
<h1>You are using <i><u>{window} {osVersion} </u></i> Operating System </h1>
</div>
<hr/>
<h2>Details</h2>
<div style={bottom}>
<h3>Operating System : <u>{osName}</u> </h3>
<h3>Browser Name : <u>{browserName}</u></h3>
<h3>Browser Version : <u>{browserVersion}</u> </h3>
<h3>Full-Browser Version : <u>{fullBrowserVersion}</u></h3>
</div>
<hr/>
</center>
</div>
);
}
const top = {
color:"darkgreen"
}
const middle= {
color: "brown"
}
const bottom = {
color:"darkgoldenrod"
}
export default App;
|
import { applyMiddleware, createStore, compose, combineReducers } from "redux";
import thunk from "redux-thunk";
import movie from "./movie";
import TMDBConfig from "./TMDBConfig";
export const reducers = combineReducers({
movie,
TMDBConfig
});
const middleware = [thunk];
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
export default createStore(
reducers,
composeEnhancers(applyMiddleware(...middleware))
);
|
define(function() {
'use strict';
var Animal;
Animal = (function() {
function Animal(name, species, numberOfLegs) {
if (validateData(name, "string")) {
this._name = name;
}
if (validateData(species, "string")) {
this._species = species;
}
if (validateData(numberOfLegs, "number")) {
this._numberOfLegs = numberOfLegs;
}
}
Animal.prototype.getSpecies = function () {
var species = this._species;
return species;
};
Animal.prototype.getNumberOfLegs = function () {
var numberOfLegs = this._numberOfLegs;
return numberOfLegs;
};
function validateData(item, type) {
if (typeof item === type || isFinite(item)) {
return true;
}
else {
throw new Error(item + " must be a " + type + " variable");
}
}
return Animal;
})();
return Animal;
});
|
// 初始化模板容器
TemplateHelper = function() {
// 当前模板容器
this.CurrentTemplateContainer;
// 已加载加载的块列表
this.TemplateBlockList;
this.InitContainer = function(containerDiv) {
this.CurrentTemplateContainer = containerDiv;
this.TemplateBlockList = new Array();
}
this.GetBlockById = function(id) {
for (var i = 0; i < this.TemplateBlockList.length; i++) {
var block = this.TemplateBlockList[i];
if (block.Id == id) {
return block;
}
}
return null;
}
this.GetTopBlocks = function() {
var blocks = new Array();
for (var i = 0; i < this.TemplateBlockList.length; i++) {
var block = this.TemplateBlockList[i];
if (block.ParentId == -1) {
blocks.push(block);
}
}
return blocks;
}
this.GetJsonString = function() {
var json = new String();
for (var i = 0; i < this.TemplateBlockList.length; i++) {
var block = this.TemplateBlockList[i];
json += block.GetJsonString();
}
return json;
}
this.SetDefaultValue = function() {
var flag = false;
for (var i = 0; i < this.TemplateBlockList.length; i++) {
var block = this.TemplateBlockList[i];
if (block.SetDefaultValue && block.SetDefaultValue()) {
flag = true;
}
}
return flag;
}
this.AddTemplateBlock_List = function(index, title, category, dataType, defaultValue, parentId) {
var parentBlock = this.GetBlockById(parentId);
var block = new TemplateBlock_List();
block.Id = index;
block.ParentId = parentId;
block.ParentBlock = parentBlock;
block.DataType = dataType;
block.DisplayName = title;
block.DefaultValue = defaultValue;
if (parentBlock) {
parentBlock.AddChild(block);
parentBlock.ChildrenItem.push(block);
}
else {
block.Create();
this.CurrentTemplateContainer.appendChild(block.Dom);
this.TemplateBlockList.push(block);
}
}
this.AddTemplateBlock_Item = function(index, title, category, dataType, defaultValue, showTitle, isFloat, titleWidth, inputWidth, inputHeight, parentId) {
var parentBlock = this.GetBlockById(parentId);
var block = new TemplateBlock_Item();
block.Id = index;
block.ParentId = parentId;
block.ParentBlock = parentBlock;
block.DataType = dataType;
block.DisplayName = title;
block.DefaultValue = defaultValue;
block.ShowTitle = showTitle;
block.IsFloat = isFloat;
block.TitleWidth = titleWidth;
block.InputWidth = inputWidth;
block.InputHeight = inputHeight;
if (parentBlock) {
parentBlock.AddChild(block);
parentBlock.ChildrenItem.push(block);
}
else {
block.Create();
this.CurrentTemplateContainer.appendChild(block.Dom);
this.TemplateBlockList.push(block);
}
}
}
|
import { connect } from "react-redux"
import { Tab } from "@components/core"
import { addTab, selectTab, removeTab } from "./actions"
import { tabReducer } from "./reducers"
import { store } from "@services"
import "./tabList.scss"
store.addReducer(`tabList`, tabReducer)
const mapStateToProps = (state, ownProps) => ({
tabs: state.tabList.tabs.sort((a, b) => a.id - b.id),
currentTab: state.tabList.currentTab
})
const mapDispatchToProps = dispatch => ({
handleAddTab: e => {
e.stopPropagation()
dispatch(addTab())
},
handleSelectTab: (e, id) => {
e.stopPropagation()
dispatch(selectTab(id))
},
handleRemoveTab: (e, id) => {
e.stopPropagation()
dispatch(removeTab(id))
}
})
const TabList = ({ tabs, currentTab, handleSelectTab, handleRemoveTab, handleAddTab }) => (
<aside styleName="tabList">
<h1>Tab List</h1>
{tabs?.length > 0 && (
<ul>
{tabs.map(tab => (
<Tab
key={tab.id}
id={tab.id}
selected={currentTab === tab.id}
selectTab={handleSelectTab}
removeTab={handleRemoveTab}
/>
))}
</ul>
)}
<span styleName="separator" />
<button styleName="newTabBtn" onClick={handleAddTab}>
<label>New Tab</label>
</button>
</aside>
)
export default connect(mapStateToProps, mapDispatchToProps)(TabList)
|
const User = require('../models/users');
const createUser = async (ctx) => {
try{
const newUser = new User(ctx.body);
const token = await newUser.generateAuthToken();
newUser.save();
ctx.res.send(token);
}catch(e){
ctx.res.status(400).send();
}
};
const findUser = async ctx => {
try{
const user = await User.findByCredentials(ctx.body.email, ctx.body.password);
if(user) {
const token = await user.generateAuthToken();
ctx.res.send(token);
}else {
ctx.res.status(400).send();
}
}catch(e){
ctx.res.status(400).send();
}
};
module.exports = {
createUser: createUser,
findUser: findUser
};
|
const merge = require('webpack-merge')
const nodeExternals = require('webpack-node-externals')
const VueSSRServerPlugin = require('vue-server-renderer/server-plugin')
const path = require('path')
const config = require('./getconfig')
const webpack = require('webpack')
const webpackBaseConfig = require('./webpack.base.conf')
const env = process.env.NODE_ENV || 'production'
module.exports = merge(webpackBaseConfig, {
entry: {
app: './src/entry/server.js'
},
target: 'node',
devtool: 'source-map',
output: {
path: path.resolve(config.dist, 'server'),
libraryTarget: 'commonjs2'
},
// node_modules下所有模块都不打包(css除外)
externals: nodeExternals({
modulesDir: path.resolve(__dirname, '../../node_modules'),
whitelist: /\.(css|sass|scss)$/
}),
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(env || 'production'),
'process.env.VUE_ENV': '"server"'
}),
new VueSSRServerPlugin()
]
})
|
var React = require('react');
var Backbone = require('backbone');
var BaseLayout = require('./layouts/base.jsx').BaseLayout;
var User = require('../models/user.js').User;
class SignupContainer extends React.Component {
createAccount(info){
var user = new User(info);
user.save().then(function(data){
localStorage.setItem('user', JSON.stringify(data));
Backbone.history.navigate('', {trigger: true});
});
}
render(){
return (
<BaseLayout>
<SignupForm action={this.createAccount}/>
</BaseLayout>
)
}
}
class SignupForm extends React.Component {
constructor(props){
super(props)
this.updateEmail = this.updateEmail.bind(this);
this.updatePassword = this.updatePassword.bind(this);
this.handleSignup = this.handleSignup.bind(this);
this.state = {
username: '',
password: ''
};
}
updateEmail(e){
this.setState({username: e.target.value});
}
updatePassword(e){
this.setState({password: e.target.value});
}
handleSignup(e){
e.preventDefault();
this.props.action(this.state);
}
render(){
return (
<div className="col-md-8">
<h1>Create Account</h1>
<form onSubmit={this.handleSignup} id="signup">
<div className="form-group">
<label htmlFor="email">Email</label>
<input onChange={this.updateEmail} id="signup-email" className="form-control" type="text" name="email" placeholder="Email Address" />
</div>
<div className="form-group">
<label htmlFor="email">Password</label>
<input onChange={this.updatePassword} id="signup-password" className="form-control" type="password" name="password" placeholder="Don't Share This!" />
</div>
<input className="btn btn-primary" type="submit" value="Sign Up!" />
</form>
</div>
)
}
}
module.exports = {
SignupContainer
}
|
import React from 'react';
export default class Dano extends React.Component {
constructor(props) {
super(props);
this.state = {
InBal: this.props.bone[0][1],
OutBal: this.props.bone[0][2],
ModBal: this.props.bone[0][3],
InGdp: this.props.bone[0][1],
OutGdp: this.props.bone[0][2],
ModGdp: this.props.bone[0][3]
}
}
render( ) {
return(
<div className={'col-md-12'} style={{padding: '0'}}>
<div className={'col-md-6'}>
<p>
{this.props.bone[0][0]}
</p>
<p className={'numero'} style={{float: 'right'}}>
{this.props.bone[0][3]}
</p>
</div>
<div className={'col-md-6'}>
<p>
{this.props.bone[1][0]}
</p>
<p className={'numero'} style={{float: 'right'}}>
{this.props.bone[1][3]}
</p>
</div>
</div>
);
}
}
|
// import express
const express = require('express');
// require dotenv
const dotenv = require('dotenv');
// require morgan
const morgan = require('morgan');
// require colors
const colors = require('colors');
// require the devcamp router
const devCampRouter = require('./routes/bootcamp');
// import connect to db
const connectDb = require('./config/db');
// create an app using express
const app = express();
// load the configuration
dotenv.config({ path: './config/config.env'});
// connect to the db
connectDb();
// set the port
const PORT = process.env.PORT || 3000;
// log the requests made in dev mode
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}
// set the bootcamp routes
app.use('/api/v1/bootcamps', devCampRouter);
// function for starting the server
const server = app.listen(
PORT,
console.log(`Server runninng in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold)
);
// GLOBALE FUNCTION FOR HANDLING unhandledpromise rejection
process.on('unhandledRejection', (error, promise) => {
// log the error
console.log(`Error: ${error}`.red.bold);
// shutdown the server
server.close(() => process.exit(1));
});
|
import { storage } from "utils/storage";
import { authTypes } from "./types";
const initialState = {
isLogged: storage("accessToken").has(),
profile: null,
};
export const authReducer = (state = initialState, action) => {
switch (action.type) {
case authTypes.AUTH_SIGN_IN_SUCCESS: {
return {
...state,
profile: action.payload,
isLogged: true
}
}
case authTypes.AUTH_LOGOUT: {
return {
...initialState,
isLogged: false
}
}
case authTypes.AUTH_GET_PROFILE_SUCCESS: {
return {
...state,
profile: action.payload
}
}
default:
return state;
}
};
|
var Item = require('models/item_group');
var Input = require('components/input');
var Events = require('utils/events');
module.exports = React.createClass({
getInitialState(){
return {
editing_title: false
}
},
_startEditTitle(){
this.state.editing_title = true;
this.forceUpdate();
},
_doneEditTitle(){
this.state.editing_title = false;
Events.trigger("loading:start");
console.log('triggered');
this.forceUpdate();
this.props.model.save({success: function() {
Events.trigger("loading:finish");
this.forceUpdate();
}});
},
render: function(){
var group = this.props.model;
var Title;
if(this.state.editing_title){
Title = <div className="title">
<Input model={group} onBlur={this._doneEditTitle} onChange={this._change} name="title"/>
</div>
} else {
Title = <div className="title" onDoubleClick={this._startEditTitle}>{group.get('title')}</div>
}
return (
<div className="item-group" id={"item"+group.props}>
{Title}
{
group.get('items').map((model, i)=>{
return <Item model={model} />
})
}
</div>
)
}
});
|
import React from 'react'
import styled from 'styled-components'
import { useSpring, animated } from 'react-spring'
const WeekNumber = styled(animated.label)`
font-family: "Times New Roman", Times, serif;
font-size: 2rem;
border-radius: 50%;
border: none;
display: flex;
align-items: center;
justify-content: center;
margin: 1rem;
@media (max-width: 600px){
font-size: 1.5rem;
margin: 0.5rem;
}
`;
function WeekNumberButton(props)
{
const { children, selected, outter, inner } = props;
const textColor = outter ? "lightgrey" : (inner ? "grey" : "black");
const rotation = outter ? "scale(0.5,0.8)" : (inner ? "scale(0.7,0.9)" : "");
const spring = useSpring({
color: textColor,
transform: rotation,
})
return (
<WeekNumber style={spring}>
{children}
</WeekNumber>
)
}
export default WeekNumberButton
|
let canvas = {};
export default function(lcanvas) {
canvas = lcanvas;
return {
run(data) {
document.getElementById('test').src = data.cropedImage;
}
}
};
|
var i = 0;
function insert() {
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/haohuola';
MongoClient.connect(url, function(err, db) {
if (err) {
setTimeout(function() {
insert();
}, 2000);
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
console.log('Connection established to', url);
var collection = db.collection('post');
var time = new Date().getTime();
var content = '双11明天就到,聚美优品官方目前在度放出了一张50元的无门槛现金券,领取的方法和之前,输入手机号,提交验证码,然后在聚美的APP端首页就能看到入口(下拉一点,点击微博报名)。 <br /><br />此券同样是等到双11当天的零点使用,目前还没放出单品,不过券已经可以开始提前领取了,还没下载APP的赶紧吧。<br /><br />慢慢买神价格推送13群:334213266<strong>(第一时间推送各种神价格、神券,你懂的)</strong><br /><br /><img src="http://7xippu.com1.z0.glb.clouddn.com/hao/1447135733288194.jpg" alt="" /><br /><br /><img src="http://7xippu.com1.z0.glb.clouddn.com/hao/1447135734511128.jpg" alt="" />';
var post = {
'id': time,
'time': time,
'title': '聚美优品:50元现金券 提前领取 双11当天零点启用',
'content': content,
'short_content': content.substr(0, 100).replace(/<[^>].*?>/g, ""),
'article_title': '聚美优品:50元现金券 提前领取',
'author': '慢慢买',
'link': 'http://h5.jumei.com/activity/free/bm',
'mall': '聚美优品',
'thumbnail': 'http://7xippu.com1.z0.glb.clouddn.com/hao/1447135734591376.jpg?imageView2/1/w/160/h/160',
'price': '双11当天零点启用',
'tag': '其它类别, 聚美优品',
'country': 'CN',
'istmall': 1,
'istaobao': 0,
'category': 'daily',
'mobile': 'http://h5.jumei.com/activity/free/bm'
}
collection.insert(post, function(err, result) {
if (err) {
console.log(err);
setTimeout(function() {
insert();
}, 2000);
} else {
console.log('success');
console.log(i);
i += 1;
insert();
}
db.close();
})
}
});
}
insert();
|
(function(){
var once=false;
do{
console.log('Entrou ao menos uma vez!');
}while(once);
var person={
name:'marcos',
age:30,
weight:'100kg',
birthday:'june28',
}
var counter=0;
for(prop in person){
console.log('the '+prop+' of person is '+person[prop]+'')
counter++;
};
console.log('The person has '+counter+' properties')
function moreThan(param){
return param>person.age ? true : false;
}
console.log('The person has more than '+person.age+' years old?',moreThan(42))
var numbers=[];
for(var i=0;i<20;i++){
if(i>10) break;
numbers.push(i)
}
console.log(numbers);
numbers=[];
for(var i=0;i<=20;i++){
if(i%2!==0){
continue;
}
numbers.push(i);
}
console.log(numbers)
})();
|
class Account {
constructor(authorities, user) {
this.authorities = authorities;
this.user = user;
}
applyData(json) {
Object.assign(this, json);
}
}
module.exports = Account;
|
import axios from "axios";
const Axios = axios.create({
withCredentials: true,
});
const getUrl = (route) => {
return `${process.env.REACT_APP_API}${route}`;
};
export { getUrl, Axios };
|
import React from 'react';
import './Quadrant.css';
class Quadrant extends React.Component {
render() {
return (
<div onClick={this.iWasClicked} className="task-list">
<span><b>
{this.props.name}
</b>
</span>
<div>
<ul>
{this.props.children}
</ul>
</div>
</div>
);
}
iWasClicked = () => {
this.props.onClick(this.props.id);
}
}
export default Quadrant;
|
const svg = d3.select('svg');
const width = +svg.attr('width');
const height = +svg.attr('height');
//console.log(width, height);
const g = svg.append('g')
.attr('transform', `translate(${width / 2}, ${height / 2})`)
const circle = g.append('circle');
circle.attr('r', height / 2);
circle.attr('fill', '#F1C40F');
circle.attr('stroke', '#1B2631');
const eyeYOffset = -80
const eyeRadius = 20
const eyeSpacing = 100
const eyesG = g
.append('g')
.attr('transform', `translate(0, ${eyeYOffset})`)
const leftEye = eyesG
.append('circle')
.attr('r', eyeRadius)
.attr('cx', -eyeYOffset)
const rightEye = eyesG
.append('circle')
.attr('r', eyeRadius)
.attr('cx', eyeYOffset)
const eyebrowsG = eyesG
.append('g')
.attr('transform', `translate(0, ${-40})`);
const leftEyebrow = eyebrowsG
.append('rect')
.attr('x', 50)
.attr('width', 50)
.attr('height', 10)
const rightEyebrow = eyebrowsG
.append('rect')
.attr('x', -100)
.attr('width', 50)
.attr('height', 10)
eyebrowsG
.transition().duration(2000)
.attr('transform', `translate(0, ${-70})`)
.transition().duration(2000)
.attr('transform', `translate(0, ${-40})`)
const mouth = g
.append('path')
.attr('d', d3.arc()({
innerRadius: 100,
outerRadius: 90,
startAngle: Math.PI / 1.5,
endAngle: Math.PI * 3 / 2.3
}))
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Redirect, Link, withRouter } from 'react-router-dom';
import { AuthService } from './AuthGuard';
import { AuthenticationService } from './services/auth.service';
import './style.css';
export class Login extends Component {
debugger;
authService = AuthService;
isLoggedIn = false;
authenticationService = new AuthenticationService();
state = {
toDashboard: false
}
constructor(props) {
super(props);
}
getUserInfo = () => {
return {
email: document.getElementById('defaultLoginFormEmail').value,
password: document.getElementById('defaultLoginFormPassword').value
}
}
login = () => {
let userInfo = this.getUserInfo();
this.authenticationService.login(userInfo).subscribe((response) => {
if(response.loggedIn) {
this.setState(() => ({
toDashboard : true
}));
}
});
}
render() {
if(this.state.toDashboard) {
return <Redirect to="dashboard"/>
}
return (
<div className="row justify-content-md-center">
<div className="col-md-4 col-md-auto">
<form className="text-center border border-light p-5 m-10" onSubmit={this.login}>
<p className="h4 mb-4">Sign in</p>
<input type="email" id="defaultLoginFormEmail" className="form-control mb-4" placeholder="E-mail" required/>
<input type="password" id="defaultLoginFormPassword" className="form-control mb-4" placeholder="Password" required/>
<div className="d-flex justify-content-around">
<div>
<div className="custom-control custom-checkbox">
<input type="checkbox" className="custom-control-input" id="defaultLoginFormRemember" />
<label className="custom-control-label" htmlFor="defaultLoginFormRemember">Remember me</label>
</div>
</div>
<div>
<a href="">Forgot password?</a>
</div>
</div>
<button className="btn btn-info btn-block my-4" type="submit">Sign in</button>
<p>Not a member?
<Link from="/" to='/register' >Register</Link >
</p>
</form>
</div>
</div>
);
}
}
|
'use strict';
/**
* @ngdoc directive
* @name laoshiListApp.directive:apply
* @description
* # apply
*/
angular.module('laoshiListApp')
.directive('apply', ['Job_', 'User_', 'laoshiListApi', 'users', 'apply', '$q', '$cookies', function (Job_, User_, laoshiListApi, users, apply, $q, $cookies) {
// update the firebase DB with a link to the CV in S3
function updateUserCV(id, cvURL) {
var user = User_(id);
user.cv = cvURL;
return user.$save();
}
// main set of functions
function link (scope) {
// our original, empty applicant
scope.applicant = {};
function emailExists(email) {
console.log(email);
scope.extantID = users.emailExists(email);
return scope.extantID;
};
/*
* checks to see if we have a user; if so, returns its userid;
* if not, creates a new user, returning the userid; would like
* this to set a cookie so that if they apply to more than one job
* in the same session without logging in,
* 1) we won't be creating multiple user accounts for the same user
* 2) they won't have to reinput their name, email address and cv (if uploaded)
*/
function getUserId() {
var defer = $q.defer();
// we already have a user
if(scope.userid) {
defer.resolve(scope.userid);
} else {
// of course, this allows people to apply for jobs in someone else's name, as long as they know their email address
// but i think this is probabyl a problem everywhere
// we probably, however, should not set a cookie, because in that case the person would probably have access to the CV of
// whoever's email address the record is attached to
// check if this email has been used before, before doing anything else
users.emailExists(scope.applicant.email).then(function(userid) {
// if it has, use it
defer.resolve(userid);
// if it hasn't, we've never seen this guy before
}, function() {
// make a new user
users.addNew(scope.applicant.name, scope.applicant.email).then(function(ref) {
// set to scope for next time this is called
scope.userid = ref.key();
// set a cookie with this information
// consider the length of this cookie -- currently for a single session
$cookies.put('applicant_id', ref.key());
// resolve the promise on the new id
defer.resolve(ref.key());
}, function(error) {
defer.reject(error);
})
})
}
// return the promise
return defer.promise;
}
if(scope.userid) {
scope.user = User_(scope.userid);
}
// all alerts start empty
scope.alerts = [];
// hold the value of the button, which will change
scope.doneApplied = 'Submit';
// uploads CVs for all users extant and otherwise
scope.uploadCV = function(cv) {
if(cv.length < 1) {
return;
}
if(scope.alerts.length === 0) {
scope.alerts.push({type: 'info', msg: 'Attempting to upload your CV...'});
}
getUserId().then(function(userID) {
laoshiListApi.uploadCV(cv, userID).then(function(cvURL) {
scope.alerts.push({type:'success', msg:'Your cv has been uploaded: <a target = "blank_" href="' + cvURL + '">' + cvURL + '</a>'});
},
function(error) {
scope.alerts.push({type:'danger', msg: 'cv not uploaded'});
}
)})
}
// updateUserCV(userID, cvURL).then(function() {
// scope.alerts.push({type:'success', msg:'Your cv has been uploaded: <a target = "blank_" href="' + cvURL + '">' + cvURL + '</a>'});
// }, function(error) {
// scope.alerts.push({type:'danger', msg: 'link to cv not saved'});
// });
// }, function(error) {
// scope.alerts.push({type: 'danger', msg: error});
// }
// )
// })
// }
// calls methods that log the applicant and email him/her
scope.apply = function() {
scope.alerts.push({type:'success', msg: 'Attempting to submit application...'});
if(scope.applicant.why) {
var coverLetter = {
text: scope.applicant.why || '',
type: 'text/plain'
}
}
getUserId().then(function(userid) {
apply.addApplicant(userid, scope.jobid, coverLetter).then(
function(success) {
//$scope.alerts.splice(0,1);
scope.alerts.push({type:'success', msg: 'Your job application has been submitted'});
scope.doneApplied = 'Thanks for applying!';
}, function(error) {
console.log(error);
scope.alerts.push({type:'warning', msg: 'Unable to submit job applicant'});
}
)
});
}
}
return {
templateUrl: 'views/templates/apply.html',
restrict: 'E',
scope: {
jobid: '=',
userid: '='
},
link: link
}
}]);
|
// let hour = 12;
// let isWeekend = true;
// if (hour < 10 || hour > 18 || isWeekend) {
// alert( 'The office is closed.' ); // it is the weekend
// }
// // Multiple OR’ed values:
// let firstName = "";
// let lastName = "";
// let nickName = "SuperCoder";
// alert( firstName || lastName || nickName || "Anonymous"); // SuperCoder
// // && (AND) Operator
// let hour = 12;
// let minute = 30;
// if (hour == 12 && minute == 30){
// alert('The time is 12:30');
// };
// Task 1 OR
alert(null || 2 || undefined); //returns the first truthy 2
// Task 2
alert(alert(1) || 2 || alert(3)); // returns the first truthy 1, then 2
// Task 3 AND
alert(alert(1) && alert(2)); //returns the last true value 1 and undefined
// Task 4 OR, AND, OR
alert(null || 2 && 3 || 4); //returns 3 because && has a higer precedence than ||
// Task 5
let age = prompt('How old are you ?');
if(age >= 14 && age <= 90){
alert('Hello !')
}
// Task 6
let age2 = prompt('How old are you?');
if(!(age2 >= 14 && age2 <= 90));{
alert('Hey hey')
}
// Task 7
let user = prompt("Who's there ?");
let password = prompt('Enter password');
if(user === 'Admin'){
if(password === 'TheMaster'){
alert('Welcome');
}
else if(password == '' || password === null){
alert('Cancelled');
}
else{
alert("Wrong password");
}
}
else if(user === '' || user === null){
alert('Cancelled');
}
else{
alert("I don't know you");
}
|
//冒泡排序
function bubSort(arr){
for(var i=0;i<arr.length-1;i++){
for(var j=0;j<arr.length-1-i;j++){
if(arr[j]>arr[j+1]){
var temp;
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}
//选择排序
function selSort(arr){
for(var i=0;i<arr.length-1;i++){
for(var j=i;j<arr.length-1;j++){
if(arr[i]>arr[j+1]){
var temp;
temp=arr[i];
arr[i]=arr[j+1];
arr[j+1]=temp;
}
}
}
return arr;
}
//随机数
function randomNum(num1,num2){
return parseInt(num1+Math.random()*(num2-num1+1));
}
//返回最大值
function getMax(arr){
var max = arr[0];
for(var i=0;i<arr.length;i++){
if(max<arr[i]){
max = arr[i]
}
}
return max;
}
//返回最小值
function getMin(arr){
var min = arr[0];
for(var i=0;i<arr.length;i++){
if(min>arr[i]){
min = arr[i]
}
}
return min;
}
//去重
function norepaetFn(arr){
var arr1=[];
for(var i=0;i<arr.length;i++){
if(arr1.indexOf(arr[i])==-1){
arr1.push(arr[i]);
}
}
return arr1;
}
//随机生成颜色
function randomColor(){
var r=parseInt(randomNum(0,255)).toString(16);//随机产生0~255之间的数并将其转换成16进制
var g=parseInt(randomNum(0,255)).toString(16);
var b=parseInt(randomNum(0,255)).toString(16);
var str=[r,g,b];
for(var i=0;i<str.length;i++){
if(str[i].length<2){//位数不足两位补0;
str[i]+="0";
}
}
var strColor=str.join("");//将str数组分割,去掉逗号;
return "#"+strColor;
}
//将时间对象转换成字符串的时间
function date1String(date,sign){//date是时间对象
sign=sign==undefined?'/':sign;
return date.getFullYear()+sign+date.getMonth()+sign+
date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
}
//判断位数是不是一个个位数
function isDblNum(item){
return item = item<10?'0'+item:item;
}
//获得元素标签 传的是一个对象
function getEleMent(alist){
var arr=[];
for(var i=0;i<ali.length;i++){
var liNodeAll=alist[i].childNodes;
for(var j=0;j<liNodeAll.length;j++){
if(liNodeAll[j].nodeType==1){
arr.push(liNodeAll[j]);
}
}
}
return arr;
}
//算一个有父级元素且使用了position,距离最左边的距离
function offset(ele){
var obj={};//创建一个对象
obj.left=ele.offsetLeft;//给对象添加属性和属性值
obj.top=ele.offsetTop;
while(ele.offsetParent){//如果ele存在使用position的父级元素
ele=ele.offsetParent;
obj.left+=ele.offsetLeft;
obj.top+=ele.offsetTop;
}
return obj;
}
//兼容class 从多个class中取得指定class
function getClassName(ele,_name){
var aDiv = document.getElementsByTagName(ele);
var arr = [];
var str = new RegExp('\\b'+_name+'\\b','i');
for(var i=0;i<aDiv.length;i++){
if(aDiv[i].className.match(str)){
arr.push(aDiv[i]);
}
}
return arr;
}
function move(obj,json,fn){
clearInterval(obj.timer);
obj.timer=setInterval(function(){
var oStop=true;
for(var attr in json){
var icur=0;
if(attr=='opacity'){
icur=parseInt(parseFloat(getStyle(obj,attr))*100);
}else{
icur=parseInt(getStyle(obj,attr));
}
if(icur!=json[attr]){
oStop=false;
}
//速度
var speed=0;
speed=(json[attr]-icur)/8;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(attr=='opacity'){
obj.style.filter="alpha(opacity:"+(icur+speed)+")";
obj.style.opacity=(icur+speed)/100;
}else{
obj.style[attr]=icur+speed+'px';
}
}
if(oStop){
clearInterval(obj.timer);
if(fn){
fn();
}
}
},30)
}
function move1(obj,json,fn){
clearInterval(obj.timer);
obj.timer=setInterval(function(){
var oStop=true;
for(var attr in json){
var icur=0;
if(attr=='opacity'){
icur=parseInt(parseFloat(getStyle(obj,attr))*100);
}else{
icur=parseInt(getStyle(obj,attr));
}
if(icur!=json[attr]){
oStop=false;
}
//速度
var speed=0;
speed=(json[attr]-icur)/3;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(attr=='opacity'){
obj.style.filter="alpha(opacity:"+(icur+speed)+")";
obj.style.opacity=(icur+speed)/100;
}else{
obj.style[attr]=icur+speed+'px';
}
}
if(oStop){
clearInterval(obj.timer);
if(fn){
fn();
}
}
},30)
}
//获得非行间样式
function getStyle(obj,attr){
if(obj.currentStyle){
return obj.currentStyle[attr];
}else{
return getComputedStyle(obj,false)[attr];
}
}
|
var libs = {
portal: require('/lib/xp/portal'), // Import the portal functions
thymeleaf: require('/lib/xp/thymeleaf'), // Import the Thymeleaf rendering function
};
// Specify the view file to use
var conf = {
view: resolve('default.html')
};
// Handle the GET request
exports.get = function(req) {
// Get the content that is using the page
var content = libs.portal.getContent();
var site = libs.portal.getSite();
var config = libs.portal.getSiteConfig();
// Fragment handling (single fragments should use this page controller automatically to render itself)
var isFragment = content.type === 'portal:fragment';
var mainRegion = isFragment ? null : content.page.regions.main;
var colorize = config.colorize ? "colorize" : "";
// Prepare the model that will be passed to the view
var model = {
content: content,
mainRegion: mainRegion,
siteName: site.displayName,
isFragment: isFragment,
colorize: colorize,
};
// Render the dynamic HTML with values from the model
var body = libs.thymeleaf.render(conf.view, model);
// Return the response object
return {
body: body
}
};
|
const formatTime = date => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
/**
* 获取时间和星期几
*/
function dateLater(dates, later) {
let dateObj = {};
let show_day = new Array('周日', '周一', '周二', '周三', '周四', '周五', '周六');
let date = new Date(dates);
date.setDate(date.getDate() + later);
let day = date.getDay();
let yearDate = date.getFullYear();
let month = ((date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : date.getMonth() + 1);
let dayFormate = (date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate());
dateObj.time = yearDate + '-' + month + '-' + dayFormate;
dateObj.week = show_day[day];
return dateObj;
}
function checkIsEmpty(obj) {
if (obj == null || obj.length <= 0) {
return true;
}
return false;
}
function isPhoneAvailable(phone) {
var myreg = /^[1][3,4,5,6,7,8][0-9]{9}$/;
if (!myreg.test(phone)) {
return false;
} else {
return true;
}
}
function isFunction(functionObj) {
if (functionObj && typeof functionObj == "function") {
return true;
}
return false;
}
module.exports = {
formatTime: formatTime,
dateLater: dateLater,
checkIsEmpty: checkIsEmpty,
isPhoneAvailable: isPhoneAvailable,
isFunction: isFunction,
}
|
const express = require("express");
// Importar path
const path = require("path");
// Importar morgan para mostrar el trafico que hay en el servidor
const morgan = require("morgan");
// Importar body-parser para manejar los datos que hay en body
const bodyParser = require("body-parser");
// Importar passport para permitir el inicio de sesión
const passport = require("./config/passport");
// Importar express-session para manejar las sesiones de usuario
const session = require("express-session");
// Importar cookie-parser para habilitar el manejo de cookies en el sitio
const cookieParser = require("cookie-parser");
// Importar connect-flash para disponer de los errores en todo el sitio
const flash = require("connect-flash");
// Importar multer para facilitar el manejo de imágenes
const multer = require("multer");
// Importar shortid
const shortid = require("shortid");
// Handlebars
const Handlebars = require("handlebars");
const exphbs = require("express-handlebars");
const {
allowInsecurePrototypeAccess,
} = require("@handlebars/allow-prototype-access");
// End handlebars
// Importamos las variables de entorno
require("dotenv").config();
// Importamos las rutas
const router = require("./routers/index.router");
// Crear la conexión con la base de datos
const db = require("./config/db");
// Importar helpers con funciones comunes para todo el sitio
const helpers = require("./helpers");
// Importamos los modelos modelos
require("./models/user");
require("./models/category");
require("./models/imageProduct");
require("./models/order");
require("./models/orderDetail");
require("./models/product");
//Realizamos la conexión con la base de datos
db.sync()
.then(() => console.log("Conectado con el servidor de BD"))
.catch((error) => console.log(error));
const app = express();
// >Settings
// Configuramos el puerto para el servidor
app.set("port", process.env.PORT || 3000);
app.set("host", process.env.HOST || "0.0.0.0");
// Configuramos la ruta de las vistas
app.set("views", path.join(__dirname, "views"));
// Configuramos el motor de vista Handlebars
app.engine(
".hbs",
exphbs({
defaultLayout: "main",
// Definimos la carpeta layout
layoutsDir: path.join(app.get("views"), "layouts"),
// Definimos la carpeta partials
partialsDir: path.join(app.get("views"), "partials"),
// Definimos la carpeta de los helpers
helpers: require("./helpers/handlebars"),
// Definimos la extension del motor
extname: ".hbs",
// Prevenimos el error recomendado por Handlebars
handlebars: allowInsecurePrototypeAccess(Handlebars),
})
);
// Definimos que el motor de vistas es Handlebars
app.set("view engine", ".hbs");
// >Middleware
// Configuracion de morgan para mostrar el trafico en el servidor
app.use(morgan("dev"));
// Configuracion de body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Habilitar el uso de cookieParser
app.use(cookieParser());
// Habilitar las sesiones de usuario
app.use(
session({
secret: process.env.SESSIONSECRET,
resave: false,
saveUninitialized: false,
})
);
// Habilitar el uso de connect-flash para compartir mensajes
app.use(flash());
// Crear una instancia de passport y cargar nuestra estrategia
app.use(passport.initialize());
app.use(passport.session());
// Pasar algunos valores mediante middleware
app.use((req, res, next) => {
// Pasar el usuario a las variables locales de la petición
res.locals.usuario = { ...req.user } || null;
res.locals.messages = req.flash();
// Pasar valores de variables por el helper
res.locals.vardump = helpers.vardump;
// Continuar con el camino del middleware
next();
});
// Definimos los parámetros para multer
const storage = multer.diskStorage({
// Definimos donde se van a guardar las imagenes
destination: path.join(__dirname, "public/img/uploads"),
filename: (req, file, cb, filename) => {
// Configuramos que las imágenes se guarden con un código generado por shortId
cb(null, shortid.generate() + path.extname(file.originalname));
},
});
// Mandamos los parámetros antes definidos y configuramos que recibirá del input llamado image
app.use(multer({ storage }).single("image"));
// >Static files
// Configuración de la carpeta publica
app.use(express.static(path.join(__dirname, "public")));
// >Routes
// Mandamos a llamar las rutas
app.use("/", router());
app.use(function (req, res, next) {
res
.status(404)
.render("information/notFound", {
title: "Pagina no encontrada | GloboFiestaCake's",
});
});
// >Global variable
// Inizialiazar el server
app.listen(app.get("port"), app.get("host"), () => {
console.log(`Server started on port ${app.get("port")}`);
});
|
import { arr, num, func } from 'types';
import { isFunc } from 'validators';
export default function firsts(params) {
if (isFunc(params)) {
return function innerFuncFirsts(data) {
let result = [];
for (let i = 0; i < arr(data).length; i++) {
let e = data[i];
if (func(params)(e) === true) {
result.push(e);
} else {
return result;
}
}
return result;
};
} else {
return function innerFirsts(data) {
return arr(data).slice(0, num(params));
}
}
};
|
const zeromq = require("zeromq");
function ServiceBalancer(upstream) {
this.upstream = upstream;
this.dealers = [];
this.cursor_index = 0;
}
ServiceBalancer.prototype.listen = function() {
this.upstream.forEach((address) => {
this.dealers.push(createDealer(address, this.callback));
});
};
ServiceBalancer.prototype.close = function() {
this.dealers.forEach((dealer) => {
dealer.close();
});
this.dealers = [];
};
ServiceBalancer.prototype.send = function(frames) {
const handler = this.dealers[this.cursor_index];
this.cursor_index = (this.cursor_index + 1) % this.dealers.length;
handler.send(frames);
};
ServiceBalancer.prototype.onMessage = function(callback) {
this.callback = callback;
};
const createDealer = function(address, callback) {
const socket = zeromq.socket("dealer").connect(address);
socket.on("message", (...frames) => {
callback(...frames);
});
const dealer = {
address,
close: function() {
socket.close();
},
send: function(frames) {
socket.send(frames);
}
};
return dealer;
};
module.exports = ServiceBalancer;
|
import Web3 from 'web3';
import React, { useState, useEffect } from 'react'
import Head from 'next/head';
import { useToasts } from 'react-toast-notifications';
import { useRouter } from 'next/router';
import { Container, Row, Col } from 'react-grid-system';
import { useHistory, useParams } from "react-router-dom";
import { useAppContext } from "../../libs/contextLib";
import { getInventoryForCreator, getProfileForCreator, getStoreForCreator, getBalance } from "../../functions/UIStateFunctions.js";
import { removeMainnetAddress, addMainnetAddress, resubmitAsset, getStuckAsset, setName, getLoadout, withdrawSILK, depositSILK } from "../../functions/AssetFunctions.js";
import Loader from "../../components/Loader";
import CardGrid from "../../components/CardGrid";
import ProfileHeader from "../../components/Profile";
export default ({ data }) => {
const { addToast } = useToasts();
const history = useHistory();
const router = useRouter()
const { id } = router.query;
const { globalState, setGlobalState } = useAppContext();
const [inventory, setInventory] = useState(null);
const [balance, setBalance] = useState(null);
const [loadout, setLoadout] = useState(null);
const [profile, setProfile] = useState(data.profile);
const [store, setStore] = useState(null);
const [selectedView, setSelectedView] = useState("inventory");
const [loading, setLoading] = useState(false);
const [stuck, setStuck] = useState(false);
useEffect(() => {
if (id && !profile || !balance || !inventory || !store || !loadout) {
getData();
}
}, []);
const getData = () => {
(async () => {
const profile = await getProfileForCreator(id);
setProfile(profile);
})();
(async () => {
const inventory = await getInventoryForCreator(id);
if (inventory.length > 0) {
setInventory(inventory);
} else {
setInventory([]);
}
})();
(async () => {
const store = await getStoreForCreator(id);
setStore(store);
})();
(async () => {
const loadout = await getLoadout(id);
setLoadout(loadout);
})();
(async () => {
const balance = await getBalance(id);
setBalance(balance);
})();
}
const handleViewToggle = (view) => {
setSelectedView(view);
}
const logout = () => {
setGlobalState({ ...globalState, logout: "true" });
}
const handleSuccess = (msg, link) => {
if (typeof msg === "object") {
msg = JSON.stringify(msg);
}
addToast("Success!", { link: link, appearance: 'success', autoDismiss: true, });
console.log("success!");
setLoading(false);
if (window != "undefined") {
getData();
}
}
const handleError = (err) => {
addToast("Error: " + err, { appearance: 'error', autoDismiss: true, })
console.log("error", err);
setLoading(false);
}
const handleAddMainnetAddress = async () => {
addToast("Connecting mainnet address.", { appearance: 'info', autoDismiss: true, });
await addMainnetAddress(globalState, handleSuccess, handleError);
}
const handleRemoveMainnetAddress = async () => {
addToast("Removing mainnet address.", { appearance: 'info', autoDismiss: true, });
await removeMainnetAddress(globalState, handleSuccess, handleError);
}
const ethEnabled = () => {
if (window.ethereum) {
window.web3 = new Web3(window.ethereum);
window.ethereum.enable();
return true;
}
alert("Please install MetaMask to use Webaverse!");
return false;
}
const loginWithMetaMask = async (func) => {
if (!ethEnabled()) {
return;
} else {
const web3 = window.web3;
try {
const eth = await window.ethereum.request({ method: 'eth_accounts' });
if (eth && eth[0]) {
//setMainnetAddress(eth[0]);
return eth[0];
} else {
ethereum.on('accountsChanged', (accounts) => {
//setMainnetAddress(accounts[0]);
func();
});
return false;
}
} catch(err) {
handleError(err);
}
}
}
const handleDeposit = async (e) => {
if(e) {
e.preventDefault();
}
setLoading(true);
try {
const ethAccount = await loginWithMetaMask(handleWithdraw);
if (ethAccount) {
const amount = prompt("How much SILK do you want to transfer?", "10");
const mainnetAddress = prompt("What mainnet address do you want to transfer to?", "0x0");
await depositSILK(amount, mainnetAddress, globalState, handleSuccess, handleError);
handleSuccess();
} else {
setLoading(false);
}
} catch (err) {
handleError(err.toString());
}
}
const handleWithdraw = async (e) => {
if(e) {
e.preventDefault();
}
setLoading(true);
try {
const ethAccount = await loginWithMetaMask(handleWithdraw);
if (ethAccount) {
const amount = prompt("How much SILK do you want to transfer?", "10");
const mainnetAddress = prompt("What mainnet address do you want to transfer from?", "0x0");
await withdrawSILK(amount, mainnetAddress, globalState.address, globalState, handleSuccess, handleError);
handleSuccess();
} else {
setLoading(false);
}
} catch (err) {
handleError(err.toString());
}
}
return (<>
<Head>
<title>{profile.name} | Webaverse</title>
<meta name="description" content={"Check out " + profile.name + "'s items on Webaverse."} />
<meta property="og:title" content={profile.name + "'s account | Webaverse"} />
<meta property="og:image" content={profile.avatarPreview ? profile.avatarPreview.replace(/\.[^.]*$/, '.png') : "./preview.png"} />
<meta name="theme-color" content="#c4005d" />
<meta name="twitter:card" content="summary_large_image" />
</Head>
{
loading || !loadout || !store || !inventory || !balance || !profile ?
<Loader loading={true} />
:
<div>
{[
(<ProfileHeader key="profileHeader" loadout={loadout} balance={balance} profile={profile} />),
(<div key="profileBodynav" className="profileBodyNav">
<div className="profileBodyNavContainer">
{store && store.length > 0 && (
<a className={`profileNavLink ${selectedView === "store" ? "active disable" : ""}`} onClick={() => {
handleViewToggle("store");
}}>
Store
</a>)}
{inventory && inventory.length > 0 && (
<a className={`profileNavLink ${selectedView === "inventory" ? "active disable" : ""}`} onClick={() => handleViewToggle("inventory")}>
Inventory
</a>)}
{globalState && globalState.address === id.toLowerCase() && (
<a className={`profileNavLink ${selectedView === "settings" ? "active disable" : ""}`} onClick={() => handleViewToggle("settings")}>
Settings
</a>)}
</div>
</div>),
(<div key="profileBodyAssets" className="profileBodyAssets">
{[
selectedView === "store" && store && (
<CardGrid key="storeCards" data={store} globalState={globalState} cardSize="small" />
),
selectedView === "inventory" && inventory && (
<CardGrid key="inventoryCards" data={inventory} globalState={globalState} cardSize="small" />
)
]}
</div>),
selectedView === "settings" && globalState && globalState.address == id.toLowerCase() && (
<div key="settingsButtonsContainer" className="settingsButtonsContainer">
{[
profile && profile.mainnetAddress !== "" && (<a key="removeMainnetAddressButton" className="button" onClick={() => handleRemoveMainnetAddress()}>
Remove mainnet address
</a>),
(<a key="connectMainnetAddressButton" className="button" onClick={() => handleAddMainnetAddress()}>
Connect mainnet address
</a>),
(<a key="SILKToMainnetButton" className="button" onClick={() => handleDeposit()}>
Transfer SILK to mainnet
</a>),
(<a key="SILKResubmitButton" className="button" onClick={async () => {
setLoading(true);
await resubmitAsset("FT", null, globalState, handleSuccess, handleError);
handleSuccess();
}}>
Resubmit SILK transfer
</a>),
(<a key="SILKButton" className="button" onClick={() => handleWithdraw()}>
Transfer SILK from mainnet
</a>),
(<a key="nameChangeButton" className="button" onClick={() => {
const name = prompt("What is your name?", "Satoshi");
setName(name, globalState, handleSuccess, handleError)
setLoading(true);
}}>
Change Name
</a>),
(<a key="logoutButton" className="button" onClick={() => logout()}>
Logout
</a>)
]}
</div>
)
]}
</div>
}</>)
}
export async function getServerSideProps(context) {
const id = context.params.id;
const profile = await getProfileForCreator(id);
return {
props: {
data: {
profile: profile,
}
}
}
}
|
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const ssh2_1 = require("ssh2");
const path_1 = __importDefault(require("path"));
const inquirer_1 = __importDefault(require("inquirer"));
class SSH {
/**
* 后缀
*/
constructor(optionos) {
this.optionos = optionos;
this.listener = {};
this.client = new ssh2_1.Client();
}
/**
* 连接服务器
*/
connect() {
return new Promise((resolve, reject) => {
//连接ssh
this.client.on('ready', () => {
resolve(true);
}).on('error', (err) => {
reject('服务器连接错误:' + err);
}).connect(this.optionos);
});
}
/**
* 执行命令
*/
shells(cmd) {
return new Promise((resolve, reject) => {
this.client.shell((err, stream) => {
if (err)
reject(err);
let buffer = '';
stream.on('close', () => {
this.client.end();
resolve(buffer);
}).on('data', (data) => {
buffer += data;
}).stderr.on('data', (data) => {
reject(data);
});
stream.end(cmd);
});
});
}
/**
* 输入密码
*/
entryPassword(text) {
return new Promise((resolve, reject) => {
inquirer_1.default.prompt({
type: 'password',
name: 'type',
message: text,
}).then((result) => {
if (result.type != null) {
this.optionos.password = result.type;
resolve(result.type);
}
}).catch(err => {
reject(err);
});
});
}
on(name, callback) {
this.listener[name] = callback;
return this;
}
/**
* 上传文件
*/
uploadFile(source, remoteTarget) {
const remotePath = remoteTarget + '/' + path_1.default.basename(source);
return new Promise((resolve, reject) => {
try {
this.client.sftp((err, sftp) => {
if (err) {
reject(err);
}
sftp.fastPut(source, remotePath, {
step: (processed, chunk, total) => {
this.listener['progress']({
total,
processed,
});
}
}, (err) => {
if (err) {
return reject(new Error(err.errno == -4058 ? '本地:' + err.message : ('服务器SFTP错误:' + err.message + remotePath)));
}
this.listener = [];
resolve(true);
});
});
}
catch (err) {
reject(err);
}
});
}
}
exports.default = SSH;
|
import React from 'react'
import { NavLink } from 'react-router-dom'
const NavBar = () => {
return (
<nav className="navbar">
<ul className="navbar__nav-items">
<li>
<NavLink to="/">Home</NavLink>
</li>
<li>
<NavLink to="/booking">Booking</NavLink>
</li>
</ul>
</nav>
)
}
export default NavBar
|
const express = require('express')
const router = express.Router()
const login = require('./auth/login')
const signup = require('./auth/signup')
const todo = require('./todos/todo')
router.use('/signup', signup)
router.use('/login', login)
router.use('/todo', todo)
module.exports = router
|
'use strict';
module.exports = {
up: function(queryInterface, Sequelize) {
return queryInterface.bulkDelete('Authors', null, {})
.then(() => {
return queryInterface.bulkInsert('Authors', [{
firstName: 'Nelkon',
lastName: 'Parker',
dateOfBirth: '12-03-1876',
dateOfDeath: '15-10-1994',
createdAt: new Date(),
updatedAt: new Date()
}, {
firstName: 'Charles',
lastName: 'Philip',
dateOfBirth: '12-03-1820',
dateOfDeath: '15-10-1900',
createdAt: new Date(),
updatedAt: new Date()
}], {});
});
},
down: function(queryInterface, Sequelize) {
return queryInterface.bulkDelete('Authors', null, {});
}
};
|
import styled from "styled-components"
export const EditorHeader = styled.div`
display: flex;
justify-content: space-between;
`
export const EmptyBorderDiv = styled.div`
width: 1rem;
border-bottom: 1px solid rgba(255, 255, 255, 0.7);
margin-right: -1px; //to overlap right bottom corner of the border
`
export const TabWrapper = styled.div`
margin-top: 0.8rem;
overflow-x: auto;
white-space: nowrap;
::-webkit-scrollbar {
width: 0;
height: 0;
background: transparent;
}
> button {
padding: 1.2rem;
//for overlaping border
:not(:last-of-type) {
margin-right: -1px; //to avoid black spacing due to left-right border at tip
border-right-color: #171717;
}
}
`
export const ApplyChangesBtnWrapper = styled.div`
flex-grow: 1;
padding: 0.8rem 1rem 0.8rem 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.7);
display: flex;
justify-content: space-between;
white-space: nowrap;
button: first-child {
font-size: 2rem;
}
button {
img {
transform: ${({ isRotate }) => `rotateZ(${360 * isRotate}deg)`};
vertical-align: middle;
height: 20px;
transition: transform 1s ease;
}
}
`
|
/* eslint-disable new-cap */
import { act } from 'preact/test-utils';
import { mount } from 'enzyme';
import { Config } from '../../config';
import FilePickerApp, { $imports } from '../FilePickerApp';
import { checkAccessibility } from '../../../test-util/accessibility';
import mockImportedComponents from '../../../test-util/mock-imported-components';
function interact(wrapper, callback) {
act(callback);
wrapper.update();
}
describe('FilePickerApp', () => {
let container;
let fakeConfig;
const renderFilePicker = (props = {}) => {
const preventFormSubmission = e => e.preventDefault();
return mount(
<Config.Provider value={fakeConfig}>
<FilePickerApp onSubmit={preventFormSubmission} {...props} />
</Config.Provider>,
{
attachTo: container,
}
);
};
beforeEach(() => {
fakeConfig = {
filePicker: {
formAction: 'https://www.shinylms.com/',
formFields: { hidden_field: 'hidden_value' },
canvas: {
groupsEnabled: false,
ltiLaunchUrl: 'https://lms.anno.co/lti_launch',
},
},
};
container = document.createElement('div');
document.body.appendChild(container);
$imports.$mock(mockImportedComponents());
});
afterEach(() => {
$imports.$restore();
container.remove();
});
/**
* Check that the expected hidden form fields were set.
*/
function checkFormFields(wrapper, expectedContent, expectedGroupSet) {
const formFields = wrapper.find('FilePickerFormFields');
assert.deepEqual(formFields.props(), {
children: [],
content: expectedContent,
formFields: fakeConfig.filePicker.formFields,
groupSet: expectedGroupSet,
ltiLaunchURL: fakeConfig.filePicker.canvas.ltiLaunchUrl,
});
}
it('renders form with correct action', () => {
const wrapper = renderFilePicker();
const form = wrapper.find('form');
assert.equal(form.prop('action'), 'https://www.shinylms.com/');
});
it('renders content selector when content has not yet been selected', () => {
const wrapper = renderFilePicker();
assert.isTrue(wrapper.exists('ContentSelector'));
});
function selectContent(wrapper, content) {
const picker = wrapper.find('ContentSelector');
interact(wrapper, () => {
picker.props().onSelectContent(
typeof content === 'string'
? {
type: 'url',
url: content,
}
: content
);
});
}
function selectGroupConfig(
wrapper,
{ useGroupSet = false, groupSet = null }
) {
const groupSelector = wrapper.find('GroupConfigSelector');
interact(wrapper, () => {
groupSelector.props().onChangeGroupConfig({
useGroupSet,
groupSet,
});
});
}
context('when groups are not enabled', () => {
it('submits form when content is selected', () => {
const onSubmit = sinon.stub().callsFake(e => e.preventDefault());
const wrapper = renderFilePicker({ onSubmit });
selectContent(wrapper, 'https://example.com');
assert.called(onSubmit);
checkFormFields(
wrapper,
{
type: 'url',
url: 'https://example.com',
},
null /* groupSet */
);
});
it('shows activity indicator when form is submitted', () => {
const wrapper = renderFilePicker();
assert.isFalse(wrapper.exists('FullScreenSpinner'));
selectContent(wrapper, 'https://example.com');
assert.isTrue(wrapper.exists('FullScreenSpinner'));
});
});
context('when group configuration is enabled', () => {
beforeEach(() => {
fakeConfig.filePicker.canvas.groupsEnabled = true;
});
it('does not submit form when content is selected', () => {
const onSubmit = sinon.stub().callsFake(e => e.preventDefault());
const wrapper = renderFilePicker({ onSubmit });
selectContent(wrapper, 'https://example.com');
assert.notCalled(onSubmit);
});
[
{
content: 'https://example.com',
summary: 'https://example.com',
},
{
content: { type: 'file', id: 'abcd' },
summary: 'PDF file in Canvas',
},
{
content: { type: 'vitalsource', bookID: 'abc', cfi: '/1/2' },
summary: 'Book from VitalSource',
},
].forEach(({ content, summary }) => {
it('displays a summary of the assignment content', () => {
const wrapper = renderFilePicker();
selectContent(wrapper, content);
assert.equal(
wrapper.find('[data-testid="content-summary"]').text(),
summary
);
});
});
it('truncates long URLs in assignment content summary', () => {
const wrapper = renderFilePicker();
selectContent(
wrapper,
'https://en.wikipedia.org/wiki/Cannonball_Baker_Sea-To-Shining-Sea_Memorial_Trophy_Dash'
);
assert.equal(
wrapper.find('[data-testid="content-summary"]').text(),
'en.wikipedia.org/…/Cannonball_Baker_Sea-To-Shining-Sea_Memorial_…'
);
});
it('disables "Continue" button when group sets are enabled but no group set is selected', () => {
const wrapper = renderFilePicker();
selectContent(wrapper, 'https://example.com');
selectGroupConfig(wrapper, { useGroupSet: true, groupSet: null });
assert.isTrue(
wrapper.find('LabeledButton[children="Continue"]').prop('disabled')
);
});
[true, false].forEach(useGroupSet => {
it('submits form when "Continue" button is clicked', () => {
const onSubmit = sinon.stub().callsFake(e => e.preventDefault());
const wrapper = renderFilePicker({ onSubmit });
selectContent(wrapper, 'https://example.com');
selectGroupConfig(wrapper, { useGroupSet, groupSet: 'groupSet1' });
assert.notCalled(onSubmit);
interact(wrapper, () => {
wrapper.find('LabeledButton[children="Continue"]').props().onClick();
});
assert.called(onSubmit);
checkFormFields(
wrapper,
{
type: 'url',
url: 'https://example.com',
},
useGroupSet ? 'groupSet1' : null
);
});
});
it('shows activity indicator when form is submitted', () => {
const wrapper = renderFilePicker();
assert.isFalse(wrapper.exists('FullScreenSpinner'));
selectContent(wrapper, 'https://example.com');
selectGroupConfig(wrapper, { useGroupSet: true, groupSet: 'groupSet1' });
interact(wrapper, () => {
wrapper.find('LabeledButton[children="Continue"]').props().onClick();
});
assert.isTrue(wrapper.exists('FullScreenSpinner'));
});
});
it('shows error dialog if an error occurs while selecting content', () => {
const wrapper = renderFilePicker();
const error = new Error('Something went wrong');
interact(wrapper, () => {
wrapper.find('ContentSelector').prop('onError')({
title: 'Something went wrong',
error,
});
});
const errDialog = wrapper.find('ErrorDialog');
assert.equal(errDialog.length, 1);
assert.equal(errDialog.prop('error'), error);
});
it('dismisses error dialog if user clicks close button', () => {
const error = new Error('Failed to load');
const wrapper = renderFilePicker();
interact(wrapper, () => {
wrapper.find('ContentSelector').prop('onError')({
title: 'Something went wrong',
error,
});
});
const errDialog = wrapper.find('ErrorDialog');
const onCancel = errDialog.prop('onCancel');
assert.isFunction(onCancel);
interact(wrapper, onCancel);
assert.isFalse(wrapper.exists('ErrorDialog'));
});
it(
'should pass a11y checks',
checkAccessibility({
content: () => renderFilePicker(),
})
);
});
|
const people = [
{
name: 'Arisa',
department: 'BP',
gender: 'F'
},
{
name: 'Ham',
department: 'IT',
gender: 'F'
},
{
name: 'Alice',
department: 'IT',
gender: 'F'
},
{
name: 'Anna',
department: 'DA',
gender: 'F'
},
{
name: 'Larry',
department: 'Sales',
gender: 'M'
},
{
name: 'Ria',
department: 'Sales',
gender: 'F'
},
{
name: 'JD',
department: 'Sales',
gender: 'M'
},
{
name: 'Thor',
department: 'Sales',
gender: 'M'
},
{
name: 'Karl',
department: 'Sales',
gender: 'M'
},
{
name: 'Rachel',
department: 'Sales',
gender: 'F'
}
];
function listByGender(gender) {
let nameByGender = [];
for(let i in people){
if(gender === 'M' && people[i].gender === 'M'){
nameByGender.push(people[i].name);
}
if(gender === 'F' && people[i].gender === 'F'){
nameByGender.push(people[i].name);
}
}
console.log(nameByGender);
}
// Test:
//listByGender('M'); // Output: Includes Larry, JD, Thor, and Karl
//listByGender('F'); // Output: Includes Arisa, Ham, Alice, Anna, Ria,
function groupByDepartment(){
var groupedDept = []; //unique values
var deptList = []; //store unique departments
var result = []; //store grouped names by department
for(let j = 0; j < people.length; j++){
if(!groupedDept[people[j].department]){
deptList.push(people[j].department);
groupedDept[people[j].department] = deptList;
}
}
for (let k in deptList){
var nameList = []; //store names
for (let l in people){
if(people[l].department === deptList[k]){
nameList.push(people[l].name);
}
}
//store results in json array
result.push({
"Department": deptList[k],
"Name": nameList
});
}
console.log(result);
}
groupByDepartment();
/* Output:
[ { Department: 'BP', Name: [ 'Arisa' ] },
{ Department: 'IT', Name: [ 'Ham', 'Alice' ] },
{ Department: 'DA', Name: [ 'Anna' ] },
{ Department: 'Sales', Name: [ 'Larry', 'Ria', 'JD', 'Thor', 'Karl', 'Rachel' ] } ]
*/
|
import React, { Component } from "react";
import settings from "../../resources/settings.svg";
import observableDiff from "deep-diff";
import "../../styles/options_dropDown.css";
import GeneralConfig from "./general_config";
import ButtonConfig from "./button_config";
class OptionsDropDown extends Component {
state = {
optionsVisible: false,
device: JSON.parse(JSON.stringify(this.props.device)) //Make a deep copy
};
index = (obj, is, value) => {
if (typeof is == "string") return this.index(obj, is.split("."), value);
else if (is.length === 1 && value !== undefined) return (obj[is[0]] = value);
else if (is.length === 0) return obj;
else return this.index(obj[is[0]], is.slice(1), value);
};
onChange = e => {
var newDevice = this.state.device;
var path = e.target.getAttribute("path");
this.index(newDevice, path, e.target.value);
if (newDevice.type === "button") {
if (!newDevice.button_config) {
newDevice.button_config = {};
}
}
this.setState({ device: newDevice });
};
onSubmit = e => {
e.preventDefault();
var changes = {};
var differences = observableDiff(this.props.device, this.state.device);
if (!differences) return;
differences.forEach(d => {
if (d.path[0] !== "status" && d.path[0] !== "connected")
changes[d.path[0]] = this.state.device[d.path[0]];
});
changes.deviceId = this.props.device.deviceId;
this.props.onEvent("configChange", changes);
};
onButtonClick = () => {
this.setState(prevState => ({
optionsVisible: !prevState.optionsVisible
}));
};
render() {
const { device, optionsVisible } = this.state;
console.log(device);
return (
<div>
<div
className={"options-button " + (optionsVisible ? "active" : "")}
onClick={this.onButtonClick}>
<img src={settings} alt="Options" />
</div>
<div className={"options-dropDown " + (optionsVisible ? "visible" : "")}>
<form action="#" onSubmit={this.onSubmit}>
<GeneralConfig
device={device}
deviceTypes={this.props.deviceTypes}
onChange={this.onChange}
/>
{device.type === "button" ? (
<ButtonConfig device={device} onChange={this.onChange} />
) : (
""
)}
<button className="submit" type="submit" style={{ float: "right" }}>
Submit changes
</button>
</form>
</div>
</div>
);
}
}
export default OptionsDropDown;
|
import { existsSync, mkdirSync, writeFileSync } from 'fs'
import { Router } from 'express'
import QRCode from 'qrcode'
import axios from 'axios'
import { Settings } from '../models/settings'
const systemSettings = async () => {
const settings = new Settings()
const { results } = await settings.all()
const systemSettings = results.reduce((previousValue, currentValue) => {
previousValue[currentValue.key] = currentValue.value
return previousValue
}, {})
return systemSettings
}
const generateQRCode = (value) => {
return new Promise((resolve, reject) => {
QRCode.toDataURL(value, (err, url) => {
if (err) {
reject(err)
} else {
resolve(url)
}
})
})
}
const router = Router()
router.get('/systeminfo', async (req, res) => {
const systemConfig = await systemSettings()
const url = `http://${systemConfig.host}:${systemConfig.port}/`
const urlQRCode = await generateQRCode(url)
res.json({ ...systemConfig, urlQRCode })
})
router.get('/version', async (req, res) => {
const { data } = await axios.get(
'https://activestreamhc.github.io/activestreamhc-nn/data.json'
)
const tag = process.env.TAG.replace(':', '')
let version = ''
if (tag && tag !== '') {
version = data[tag]
} else {
version = data.version
}
let result = {}
if (version) {
result = { version }
} else {
result = {
error: true,
message:
'自動更新システム設定の問題を発生しました。システム管理者に連絡してください。',
}
}
res.json(result)
})
router.post('/upgrade', (req, res, next) => {
const filepath = process.cwd() + '/tmp'
if (!existsSync(filepath)) {
try {
mkdirSync(filepath)
} catch (error) {
console.error(error)
}
}
writeFileSync(`${filepath}/upgrade`, '')
res.json({ result: true })
})
router.post('/updatehost', async (req, res, next) => {
const filepath = process.cwd() + '/tmp'
if (!existsSync(filepath)) {
try {
mkdirSync(filepath)
} catch (error) {
console.error(error)
}
}
const hostConfig = req.body
const host = hostConfig.info.host || ''
const gateway = hostConfig.info.gateway || ''
const settings = new Settings()
const { results } = await settings.all()
const hostConfigKey = 'hostConfig'
const hostConfigInfo = results.filter((item) => {
return item.key === hostConfigKey
})
if (hostConfigInfo.length > 0) {
const updateSettings = new Settings()
updateSettings.uid = hostConfigInfo[0].uid
updateSettings.value = JSON.stringify(hostConfig)
updateSettings.update()
} else {
const insertSettings = new Settings()
insertSettings.key = hostConfigKey
insertSettings.value = JSON.stringify(hostConfig)
insertSettings.insert()
}
writeFileSync(`${filepath}/update_host`, `${host},${gateway}`)
res.json({ result: true })
})
router.post('/voice', async (req, res, next) => {
const voice = req.body.voice || '0'
const settings = new Settings()
const { results } = await settings.all()
const voiceConfigKey = 'voice'
const voiceConfigInfo = results.filter((item) => {
return item.key === voiceConfigKey
})
if (voiceConfigInfo.length > 0) {
const updateSettings = new Settings()
updateSettings.uid = voiceConfigInfo[0].uid
updateSettings.value = voice
updateSettings.update()
} else {
const insertSettings = new Settings()
insertSettings.key = voiceConfigKey
insertSettings.value = voice
insertSettings.insert()
}
res.json({ result: true })
})
export default router
|
var slideIndex = 2;
$(document).ready(function() {
showSlides(slideIndex);
});
function plusDivs(n) {
showSlides(slideIndex += n);
}
function showSlides(n) {
var i;
var slides = $(".card-c");
if (n > slides.length + 1) {
slideIndex = 2
n = 2
}
if (n < 2) {
slideIndex = slides.length+1;
n = slides.length+1;
}
$(slides).css('display', 'none');
$(".card-c:nth-child("+n+")").css("display", "block");
}
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
function myFunction()
{
delay(function(){
var input = document.getElementById("ville");
var autocomplete = new google.maps.places.Autocomplete(input);
}, 300 );
}
function delete_func(n)
{
console.log(n);
n.parentNode.parentNode.removeChild(n.parentNode);
}
function hiddenfunc()
{
var myInput = "";
$('.p-city-container').each(function(i, el) {
x = $(el).find(".p-input").text();
myInput += x + "|";
});
myInput = myInput.slice(0, -1);
$(".city_content_input").append("<input type=\"hidden\" name=\"city\" value=\""+myInput+"\">");
}
$(window).keydown(function(event){
if(event.keyCode == 13){
event.preventDefault();
if( $("#ville").val() != "")
{
setTimeout(function(){
var input = $("#ville").val();
$("input[name=\"ville\"]").val("");
$(".city_content_input").append("<div class=\"all-city\"><div class=\"p-city-container\"><p class=\"p-input\">"+input
+"</p><a class=\"delete-input-city\" onclick=\"delete_func(this)\" href=\"#\">x</a></div></div>");
}, 500);
}
}
});
|
// Variables
var firstNumber = "";
var secondNumber = "";
var countSymbol = 0;
var symbol = "";
// Field Input
var fieldInput = document.querySelector(".field_for_input");
// Buttons
var numberButton = document.querySelectorAll(".numberBtn");
var symbolButton = document.querySelectorAll(".symbolBtn");
var resultButton = document.querySelector(".resultBtn");
var clearButton = document.querySelector(".clearBtn");
var _loop_1 = function (i) {
numberButton[i].addEventListener("click", function (e) {
if (fieldInput.value === "Введите первое число") {
fieldInput.value = numberButton[i].textContent;
}
else {
fieldInput.value += numberButton[i].textContent;
}
});
};
for (var i = 0; i < numberButton.length; i++) {
_loop_1(i);
}
var _loop_2 = function (i) {
symbolButton[i].addEventListener("click", function (e) {
countSymbol += 1;
if (fieldInput.value === "") {
fieldInput.value = "Введите первое число";
}
else if (fieldInput.value.length > 0 && countSymbol > 0) {
firstNumber = fieldInput.value;
fieldInput.value = "";
symbol = symbolButton[i].textContent;
for (var i_1 = 0; i_1 < symbolButton.length; i_1++) {
symbolButton[i_1].disabled = true;
}
}
});
};
for (var i = 0; i < symbolButton.length; i++) {
_loop_2(i);
}
resultButton.addEventListener("click", function (e) {
secondNumber = Number(fieldInput.value);
firstNumber = Number(firstNumber);
var actions = new Map()
.set("+", firstNumber + secondNumber)
.set("-", firstNumber - secondNumber)
.set("/", firstNumber / secondNumber)
.set("*", firstNumber * secondNumber);
(function disbledNumberSymbol() {
for (var i = 0; i < numberButton.length; i++) {
numberButton[i].disabled = true;
}
for (var i = 0; i < symbolButton.length; i++) {
symbolButton[i].disabled = true;
}
resultButton.disabled = true;
})();
return (fieldInput.value = actions.get(symbol));
});
clearButton.addEventListener("click", function (e) {
fieldInput.value = "";
for (var i = 0; i < numberButton.length; i++) {
numberButton[i].disabled = false;
}
for (var i = 0; i < symbolButton.length; i++) {
symbolButton[i].disabled = false;
}
resultButton.disabled = false;
});
|
import React, { Component } from 'react'
import BarChartHierarchy from "./BarChartHierarchy.js";
export default class BarchartHierarchyWrapper extends Component {
constructor(props) {
super(props);
this.laref = React.createRef();
this.state = {
bh: null
}
}
componentDidUpdate() {
console.log("update")
//this.state.bh.update(this.props.data);
}
componentDidMount() {
const bh = BarChartHierarchy(this.laref.current, this.props.addCityToTable);
bh.update(this.props.data);
this.setState({ bh: bh });
}
render() {
return (
<div>
<div className="BarchartHierarchyWrapper">
<div ref={this.laref}></div>
</div>
</div>
)
}
}
|
import React, { Component } from "react";
import styled, { css, keyframes } from "react-emotion";
import Shade from "../Shade/Shade";
class NotificationModal extends Component {
state = {
isNotificationOn: false
};
handleNotification = () => {
this.setState({
isNotificationOn: !this.state.isNotificationOn
});
};
render() {
const slideIn = keyframes`
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
`;
const Container = styled("div")`
background-color: #fff;
border-radius: 10px;
-webkit-box-shadow: 0px 2px 6px -2px rgba(10, 21, 60, 1);
-moz-box-shadow: 0px 2px 6px -2px rgba(10, 21, 60, 1);
box-shadow: 0px 2px 6px -2px rgba(10, 21, 60, 1);
display: flex;
padding: 5%;
flex-direction: column;
z-index: 100;
animation: ${slideIn} 0.5s ease-in;
`;
const Center = css`
display: flex;
justify-content: center;
align-items: center;
`;
const Text = styled("p")``;
const redPlease = css`
color: #eb5757;
font-weight: 700;
`;
return (
<Shade className={Center} onClick={this.props.onClick}>
{this.state.isNotificationOn ? (
<Container>
<p>Le notifiche sono attivate</p>
<p className={redPlease} onClick={this.handleNotification}>
DISATTIVA LE NOTIFICHE
</p>
</Container>
) : (
<Container>
<p>Rimani aggiornato sulle attività di Alture360</p>
<p className={redPlease} onClick={this.handleNotification}>
ATTIVA LE NOTIFICHE
</p>
</Container>
)}
</Shade>
);
}
}
export default NotificationModal;
|
$(function(){
//随机四位验证码
function validateCode(){
var _code=[];
var m=0;
for(var i=0;i<36;i++){
if(i<=9){
_code[i]=i;
}else{
_code[i]=String.fromCharCode("a".charCodeAt(0)+m);
m++;
}
}
return ""+_code[Math.floor(Math.random()*_code.length)]+_code[Math.floor(Math.random()*_code.length)]+_code[Math.floor(Math.random()*_code.length)]+_code[Math.floor(Math.random()*_code.length)];
}
$("#yzh").text(validateCode());
$("#shua").click(function(){$("#yzh").text(validateCode())});
$("#pwd3").blur(function(){
if($("#yzh").text()==$(this).val()){
_flag4=1;
$("#dc4").html("输入正确");
}else{
$("#dc4").html("输入错误");
_flag4=0;
}
});
//手机验证
$("#busPhone").blur(function () {
var re=/^1[3|4|5|7|8]\d{9}$/;
if(!re.test($(this).val().trim()) && $(this).val().length > 0){
$(this).next().css('display', 'inline-block').html("<s></s>手机格式不正确");
$(this).focus();
}else{
validate($(this));
}
});
$("#submit").click(function() {
var strActionName="Mer_UpdatePassWord";
var arrActionParam = {
"OldPassword":"123456",
"Password":"123456",
"WaiterID":"8f689e23401f4da7bc6dde63e7de0178"
};
var strActionParam = JSON.stringify(arrActionParam);
var strRequest = GetVisitData(strActionName, strActionParam);
var datSubmit = { strRequest: strRequest };
$.ajax({
url: jsgDataUrl+jsgDataGate,
type: 'post',
dataType: 'json',
data: datSubmit,
timeout : ajaxTimeout,
async: true,
beforeSend: function () {
},
success: function (objResult,textStatus) {
if(objResult.Result == 1){
alert(objResult.Message);
}else{
//alert("输入信息不完整");
}
},
error: function () {
},
complete : function(XMLHttpRequest,status){ //请求完成后最终执行参数
if(status=='timeout'){
alert("请求超时");
}
}
})
});
})
|
/*
* vim: ts=4:sw=4:expandtab
*/
(function () {
'use strict';
window.Whisper = window.Whisper || {};
var URL_REGEX = /(^|[\s\n]|<br\/?>)((?:https?|ftp):\/\/[\-A-Z0-9\u00A0-\uD7FF\uE000-\uFDCF\uFDF0-\uFFFD+\u0026\u2019@#\/%?=()~_|!:,.;]*[\-A-Z0-9+\u0026@#\/%=~()_|])/gi;
var ErrorIconView = Whisper.View.extend({
templateName: 'error-icon',
className: 'error-icon-container',
initialize: function() {
if (this.model.name === 'UnregisteredUserError') {
this.$el.addClass('unregistered-user-error');
}
}
});
var NetworkErrorView = Whisper.View.extend({
tagName: 'span',
className: 'hasRetry',
templateName: 'hasRetry',
render_attributes: {
messageNotSent: i18n('messageNotSent'),
resend: i18n('resend')
}
});
Whisper.MessageView = Whisper.View.extend({
tagName: 'li',
templateName: 'message',
initialize: function() {
this.listenTo(this.model, 'change:errors', this.onErrorsChanged);
this.listenTo(this.model, 'change:body', this.render);
this.listenTo(this.model, 'change:delivered', this.renderDelivered);
this.listenTo(this.model, 'change', this.renderSent);
this.listenTo(this.model, 'change:flags change:group_update', this.renderControl);
this.listenTo(this.model, 'destroy', this.remove);
this.listenTo(this.model, 'pending', this.renderPending);
this.listenTo(this.model, 'done', this.renderDone);
this.timeStampView = new Whisper.ExtendedTimestampView();
},
events: {
'click .retry': 'retryMessage',
'click .error-icon': 'select',
'click .timestamp': 'select',
'click .status': 'select',
'click .error-message': 'select'
},
retryMessage: function() {
var retrys = _.filter(this.model.get('errors'), function(e) {
return (e.name === 'MessageError' ||
e.name === 'OutgoingMessageError' ||
e.name === 'SendMessageNetworkError');
});
_.map(retrys, 'number').forEach(function(number) {
this.model.resend(number);
}.bind(this));
},
select: function(e) {
this.$el.trigger('select', {message: this.model});
e.stopPropagation();
},
className: function() {
return ['entry', this.model.get('type')].join(' ');
},
renderPending: function() {
this.$el.addClass('pending');
},
renderDone: function() {
this.$el.removeClass('pending');
},
renderSent: function() {
if (this.model.isOutgoing()) {
this.$el.toggleClass('sent', !!this.model.get('sent'));
}
},
renderDelivered: function() {
if (this.model.get('delivered')) { this.$el.addClass('delivered'); }
},
onErrorsChanged: function() {
if (this.model.isIncoming()) {
this.render();
} else {
this.renderErrors();
}
},
renderErrors: function() {
var errors = this.model.get('errors');
if (_.size(errors) > 0) {
if (this.model.isIncoming()) {
this.$('.content').text(this.model.getDescription()).addClass('error-message');
}
var view = new ErrorIconView({ model: errors[0] });
view.render().$el.appendTo(this.$('.bubble'));
} else {
this.$('.error-icon-container').remove();
}
if (this.model.hasNetworkError()) {
this.$('.meta').prepend(new NetworkErrorView().render().el);
} else {
this.$('.meta .hasRetry').remove();
}
},
renderControl: function() {
if (this.model.isEndSession() || this.model.isGroupUpdate()) {
this.$el.addClass('control');
this.$('.content').text(this.model.getDescription());
} else {
this.$el.removeClass('control');
}
},
render: function() {
var contact = this.model.isIncoming() ? this.model.getContact() : null;
this.$el.html(
Mustache.render(_.result(this, 'template', ''), {
message: this.model.get('body'),
timestamp: this.model.get('sent_at'),
sender: (contact && contact.getTitle()) || '',
avatar: (contact && contact.getAvatar()),
}, this.render_partials())
);
this.timeStampView.setElement(this.$('.timestamp'));
this.timeStampView.update();
this.renderControl();
twemoji.parse(this.el, {
attributes: function(icon, variant) {
var colon = emoji_util.get_colon_from_unicode(icon);
if (colon) {
return {title: ":" + colon + ":"};
} else {
return {};
}
},
base: '/images/twemoji/',
size: 16
});
var content = this.$('.content');
var escaped = content.html();
content.html(escaped.replace(/\n/g, '<br>').replace(URL_REGEX, "$1<a href='$2' target='_blank'>$2</a>"));
this.renderSent();
this.renderDelivered();
this.renderErrors();
this.loadAttachments();
return this;
},
loadAttachments: function() {
this.model.get('attachments').forEach(function(attachment) {
var view = new Whisper.AttachmentView({ model: attachment });
this.listenTo(view, 'update', function() {
this.trigger('beforeChangeHeight');
this.$('.attachments').append(view.el);
this.trigger('afterChangeHeight');
});
view.render();
}.bind(this));
}
});
})();
|
/*global module */
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: {
production: ['prebuilt']
},
copy: {
production: {
files: [{
expand: true,
src: [
'editable.html',
'readonly.html',
'index.html',
'quink.html',
'quink/js/lib/require.js',
'quink/plugins/**',
'quink/resources/**',
'!quink/resources/css/**',
'quink/pluginadapters/**'
],
dest: 'prebuilt'
}]
}
},
requirejs: {
production: {
options: {
baseUrl: 'quink/js',
mainConfigFile: 'quink/js/main.js',
name: 'main',
include: 'ext/PluginAdapterContext',
out: 'prebuilt/quink/js/main.js'
}
}
},
mkdir: {
production: {
options: {
create: ['prebuilt/quink/js']
}
}
},
cssmin: {
production: {
src: 'quink/resources/css/quink.css',
dest: 'prebuilt/quink/resources/css/quink.css'
}
},
uglify: {
production: {
files: {
'prebuilt/quink.js': ['quink.js']
}
}
}
});
grunt.loadNpmTasks('grunt-mkdir');
grunt.loadNpmTasks('grunt-css');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask('default', ['clean', 'copy', 'mkdir', 'requirejs', 'cssmin', 'uglify']);
};
|
import {
addCarRows,
retrieveCarId,
populateEditCarForm,
retrieveCarForm,
cleanTable,
} from './uiHelpers';
import {
getAllCars,
getCarById,
addCar
} from './API/carsApi.double';
import { getAllCarsWithAxios, getCarByIdWithAxios, addCarWithAxios, } from './API/carsApiWithAxios';
import { getAllCarsWithFetch, getCarByIdWithFetch, addCarWithFetch } from './API/carsApiWithFetch'
import { authenticate } from './API/authApi';
document.addEventListener('DOMContentLoaded', () => {
let authToken = '';
///////////////////////////
// Authentication //
///////////////////////////
const createTokenBtn = document.getElementById('createToken');
const clearTokenBtn = document.getElementById('clearToken');
createTokenBtn.addEventListener('click', event => {
const userpassword = {
username: 'admin',
password: 'admin'
};
authenticate(userpassword).then(({ access_token }) => {
authToken = access_token;
}).catch(console.warn)
});
clearTokenBtn.addEventListener('click', event => {
authToken = '';
});
///////////////////////////
// Load data with fetch //
///////////////////////////
const buttonLoadCarsFetch = document.getElementById('loadcarsfetch');
const buttonLoadCarFetch = document.getElementById('loadcarfetch');
const buttonAddCarFetch = document.getElementById('addfetch');
buttonLoadCarsFetch.addEventListener('click', (event) => {
event.stopPropagation();
cleanTable('cars-table');
getAllCarsWithFetch(authToken).then(readBodyAsJson).then(allCarsSuccessHandlerFetch).catch(errorHandler);
});
buttonLoadCarFetch.addEventListener('click', (event) => {
event.stopPropagation();
const carId = retrieveCarId();
getCarByIdWithFetch(carId, authToken).then(readBodyAsJson).then(singleCarSuccessHandlerFetch).catch(errorHandler);
});
buttonAddCarFetch.addEventListener('click', (event) => {
event.stopPropagation();
event.preventDefault();
const car = retrieveCarForm();
addCarWithFetch(car, authToken).then(_ => {
buttonLoadCarsFetch.click();
});
});
///////////////////////////
// Load data with axios //
///////////////////////////
const buttonLoadCarsAxios = document.getElementById('loadcarsaxios');
const buttonLoadCarAxios = document.getElementById('loadcaraxios');
const buttonAddCarAxios = document.getElementById('addaxios');
buttonLoadCarsAxios.addEventListener('click', (event) => {
event.stopPropagation();
cleanTable('cars-table');
getAllCarsWithAxios(authToken).then(allCarsSuccessHandlerAxios).catch(errorHandler);
});
buttonLoadCarAxios.addEventListener('click', (event) => {
event.stopPropagation();
const carId = retrieveCarId();
getCarByIdWithAxios(carId, authToken).then(singleCarSuccessHandlerAxios).catch(errorHandler);
});
buttonAddCarAxios.addEventListener('click', (event) => {
event.stopPropagation();
event.preventDefault();
const car = retrieveCarForm();
addCarWithAxios(car, authToken).then(_ => {
buttonLoadCarsAxios.click();
});
});
///////////////////////////
// Load data by default //
///////////////////////////
const buttonLoadCars = document.getElementById('loadcars');
const buttonLoadCar = document.getElementById('loadcar');
const buttonAddCar = document.getElementById('add');
buttonLoadCars.addEventListener('click', (event) => {
event.stopPropagation();
cleanTable('cars-table');
getAllCars().then((result) => {
addCarRows(result, 'cars-table');
});
});
buttonLoadCar.addEventListener('click', (event) => {
event.stopPropagation();
const carId = retrieveCarId();
getCarById(carId)
.then((r) => populateEditCarForm(r));
});
buttonAddCar.addEventListener('click', (event) => {
event.stopPropagation();
event.preventDefault();
const car = retrieveCarForm();
addCar(car)
.then((_) => {
cleanTable('cars-table');
return getAllCars();
})
.then((result) => {
addCarRows(result, 'cars-table');
});
});
});
// Axios handlers
const allCarsSuccessHandlerAxios = ({ data }) => {
addCarRows(data, 'cars-table');
}
const singleCarSuccessHandlerAxios = ({ data }) => {
populateEditCarForm(data);
}
// Fetch handlers
const allCarsSuccessHandlerFetch = (data) => {
addCarRows(data, 'cars-table');
}
const singleCarSuccessHandlerFetch = (data) => {
populateEditCarForm(data);
}
const readBodyAsJson = (response) => response.json();
// Error handler
const errorHandler = (err) => {
alert(err);
return [];
}
|
import Link from 'next/link';
const navbarStyle = {
color:'#61698F',
fontFamily: 'Poppins',
fontSize: '1rem'
}
const leftStyle = {
display: 'inline-block',
textAlign: 'left',
float: 'left',
fontWeight: 600
};
const rightStyle = {
display: 'inline-block',
textAlign: 'right',
float: 'right'
};
const linkStyle = {
color:'#61698F',
textDecoration: 'none',
marginRight: 15
};
const hrStyle = {
color:'#dedede',
borderTop: '2px solid'
};
const BlogNavbar = () => (
<div style={navbarStyle}>
<div style={leftStyle}>
Gejr's blog
</div>
<div style={rightStyle}>
<Link href='/'>
<a style={linkStyle}>Home</a>
</Link>
<Link href='/about'>
<a style={linkStyle}>About</a>
</Link>
<Link href='/blog'>
<a style={linkStyle}>Blog</a>
</Link>
</div>
<br />
<hr style={hrStyle}/>
</div>
);
export default BlogNavbar;
|
module.exports = (req, res, next) => {
//if(req.user)
if (!req.user) {
return res.redirect('/login?redirect=/'+process.env.ADMIN_SLUG);
}else if(req.user.levelFlag != "superadmin" && (typeof process.env.ALLOWALLUSERINADMIN == "undefined" || !process.env.ALLOWALLUSERINADMIN)){
return res.redirect(process.env.PUBLIC_URL);
}else if((!req.user || req.user.levelFlag != "superadmin" ) && (typeof process.env.ALLOWALLUSERINADMIN != "undefined" || process.env.ALLOWALLUSERINADMIN)){
if(req.method == "POST"){
res.send({});
return
}
}
next();
}
|
// Xumak Colombia
// Alejandro Sosa
$('.recent-work').parallax({imageSrc: 'images/bg/bg-parralax-1.1.jpg'});
$('.blog-home').parallax({imageSrc: 'images/bg/bg-parralax-2.jpg'});
$('#testimonialSlider').lightSlider({
gallery: true,
item: 1,
loop: true,
slideMargin: 0,
thumbItem: 14
});
$(document).ready(function(){
//Check to see if the window is top if not then display button
$(window).scroll(function(){
if ($(this).scrollTop() > 100) {
$('.scrollToTop').fadeIn();
} else {
$('.scrollToTop').fadeOut();
}
});
//Click event to scroll to top
$('.scrollToTop').click(function(){
$('html, body').animate({scrollTop : 0},800);
return false;
});
});
|
import styled from 'styled-components';
const FormActions = styled.div`
width: 100%;
margin-top: 8px;
margin-bottom: 8px;
& > button {
margin-right: 8px;
}
`;
export const FormActionsDisplay = styled.div`
margin-left: 6px;
margin-top: 8px;
width: 100%;
display: flex;
height: 31px;
& > button {
margin-right: 8px;
}
`;
export default FormActions;
|
import * as R from 'ramda'
/**
* @typedef {function} Lens - A lens bound to a getter & setter
* @example
* const myLens = R.lens(
* x => x.myKey,
* myValue => myObject => R.assoc('myKey', myValue, myObject)
* )
*/
const eq = R.curry((a, b)=> R.equals(a, b))
//-- Lens utility functions to save some keystrokes =D
export const lensEq = lens => value => obj => eq(value, R.view(lens, obj))
export const eqLenses = lens => a => b => eq(R.view(lens, a), R.view(lens, b))
/**
* @func mapLens - Like `R.over`, but the modifier function accepts the
* entire Object/Array/Anything (not just the focused value)
*
*/
export const mapLens = lens => fn => obj =>
R.set(
lens,
fn(
R.view(lens, obj),
obj
),
obj
)
export const uniqByLens = lens => R.uniqBy( R.view(lens) )
export const findByLens = lens => value =>
R.find( lensEq(lens)(value) )
export const filterByLens = lens => value =>
R.filter( lensEq(lens)(value) )
export const sortByLens = lens =>
R.sortBy( R.view(lens) )
//-- Common Lenses (id, name, etc)
export const idLens = R.lensPath(['id'])
export const viewId = R.view(idLens)
export const uniqById = uniqByLens(idLens)
export const findById = id => findByLens(idLens)(id)
export const nameLens = R.lensPath(['name'])
export const viewName = R.view(nameLens)
export const sortOrderLens = R.lensPath(['sortOrder'])
|
dojo.provide("dojo._base.NodeList");
dojo.require("dojo._base.lang");
dojo.require("dojo._base.array");
(function(){
var d = dojo;
var tnl = function(arr){
// decorate an array to make it look like a NodeList
arr.constructor = dojo.NodeList;
dojo._mixin(arr, dojo.NodeList.prototype);
return arr;
}
var _mapIntoDojo = function(func, alwaysThis){
// returns a function which, when executed in the scope of its caller,
// applies the passed arguments to a particular dojo.* function (named
// in func) and aggregates the returns. if alwaysThis is true, it
// always returns the scope object and not the collected returns from
// the Dojo method
return function(){
var _a = arguments;
var aa = d._toArray(_a, 0, [null]);
var s = this.map(function(i){
aa[0] = i;
return d[func].apply(d, aa);
});
return (alwaysThis || ( (_a.length > 1) || !d.isString(_a[0]) )) ? this : s; // String||dojo.NodeList
}
};
dojo.NodeList = function(){
// summary:
// dojo.NodeList is as subclass of Array which adds syntactic
// sugar for chaining, common iteration operations, animation,
// and node manipulation. NodeLists are most often returned as
// the result of dojo.query() calls.
// example:
// create a node list from a node
// | new dojo.NodeList(dojo.byId("foo"));
return tnl(Array.apply(null, arguments));
}
dojo.NodeList._wrap = tnl;
dojo.extend(dojo.NodeList, {
// http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array#Methods
// FIXME: handle return values for #3244
// http://trac.dojotoolkit.org/ticket/3244
// FIXME:
// need to wrap or implement:
// join (perhaps w/ innerHTML/outerHTML overload for toString() of items?)
// reduce
// reduceRight
slice: function(/*===== begin, end =====*/){
// summary:
// Returns a new NodeList, maintaining this one in place
// description:
// This method behaves exactly like the Array.slice method
// with the caveat that it returns a dojo.NodeList and not a
// raw Array. For more details, see:
// http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:slice
// begin: Integer
// Can be a positive or negative integer, with positive
// integers noting the offset to begin at, and negative
// integers denoting an offset from the end (i.e., to the left
// of the end)
// end: Integer?
// Optional parameter to describe what position relative to
// the NodeList's zero index to end the slice at. Like begin,
// can be positive or negative.
var a = d._toArray(arguments);
return tnl(a.slice.apply(this, a));
},
splice: function(/*===== index, howmany, item =====*/){
// summary:
// Returns a new NodeList, manipulating this NodeList based on
// the arguments passed, potentially splicing in new elements
// at an offset, optionally deleting elements
// description:
// This method behaves exactly like the Array.splice method
// with the caveat that it returns a dojo.NodeList and not a
// raw Array. For more details, see:
// <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:splice>
// index: Integer
// begin can be a positive or negative integer, with positive
// integers noting the offset to begin at, and negative
// integers denoting an offset from the end (i.e., to the left
// of the end)
// howmany: Integer?
// Optional parameter to describe what position relative to
// the NodeList's zero index to end the slice at. Like begin,
// can be positive or negative.
// item: Object...?
// Any number of optional parameters may be passed in to be
// spliced into the NodeList
// returns:
// dojo.NodeList
var a = d._toArray(arguments);
return tnl(a.splice.apply(this, a));
},
concat: function(/*===== item =====*/){
// summary:
// Returns a new NodeList comprised of items in this NodeList
// as well as items passed in as parameters
// description:
// This method behaves exactly like the Array.concat method
// with the caveat that it returns a dojo.NodeList and not a
// raw Array. For more details, see:
// <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:concat>
// item: Object...?
// Any number of optional parameters may be passed in to be
// spliced into the NodeList
// returns:
// dojo.NodeList
var a = d._toArray(arguments, 0, [this]);
return tnl(a.concat.apply([], a));
},
indexOf: function(/*Object*/ value, /*Integer?*/ fromIndex){
// summary:
// see dojo.indexOf(). The primary difference is that the acted-on
// array is implicitly this NodeList
// value:
// The value to search for.
// fromIndex:
// The loction to start searching from. Optional. Defaults to 0.
// description:
// For more details on the behavior of indexOf, see:
// <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:indexOf>
// returns:
// Positive Integer or 0 for a match, -1 of not found.
return d.indexOf(this, value, fromIndex); // Integer
},
lastIndexOf: function(/*===== value, fromIndex =====*/){
// summary:
// see dojo.lastIndexOf(). The primary difference is that the
// acted-on array is implicitly this NodeList
// description:
// For more details on the behavior of lastIndexOf, see:
// <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:lastIndexOf>
// value: Object
// The value to search for.
// fromIndex: Integer?
// The loction to start searching from. Optional. Defaults to 0.
// returns:
// Positive Integer or 0 for a match, -1 of not found.
return d.lastIndexOf.apply(d, d._toArray(arguments, 0, [this])); // Integer
},
every: function(/*Function*/callback, /*Object?*/thisObject){
// summary:
// see `dojo.every()` and:
// <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:every>
// Takes the same structure of arguments and returns as
// dojo.every() with the caveat that the passed array is
// implicitly this NodeList
return d.every(this, callback, thisObject); // Boolean
},
some: function(/*Function*/callback, /*Object?*/thisObject){
// summary:
// see dojo.some() and:
// http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:some
// Takes the same structure of arguments and returns as
// dojo.some() with the caveat that the passed array is
// implicitly this NodeList
return d.some(this, callback, thisObject); // Boolean
},
map: function(/*Function*/ func, /*Function?*/ obj){
// summary:
// see dojo.map(). The primary difference is that the acted-on
// array is implicitly this NodeList and the return is a
// dojo.NodeList (a subclass of Array)
return d.map(this, func, obj, d.NodeList); // dojo.NodeList
},
forEach: function(callback, thisObj){
// summary:
// see dojo.forEach(). The primary difference is that the acted-on
// array is implicitly this NodeList
d.forEach(this, callback, thisObj);
// non-standard return to allow easier chaining
return this; // dojo.NodeList
},
// custom methods
coords: function(){
// summary:
// Returns the box objects all elements in a node list as
// an Array (*not* a NodeList)
return d.map(this, d.coords); // Array
},
/*=====
attr: function(property, value){
// summary:
// gets or sets the DOM attribute for every element in the
// NodeList
// property: String
// the attribute to get/set
// value: String?
// optional. The value to set the property to
// returns:
// if no value is passed, the result is an array of attribute values
// If a value is passed, the return is this NodeList
return; // dojo.NodeList
return; // Array
},
style: function(property, value){
// summary:
// gets or sets the CSS property for every element in the NodeList
// property: String
// the CSS property to get/set, in JavaScript notation
// ("lineHieght" instead of "line-height")
// value: String?
// optional. The value to set the property to
// returns:
// if no value is passed, the result is an array of strings.
// If a value is passed, the return is this NodeList
return; // dojo.NodeList
return; // Array
},
addClass: function(className){
// summary:
// adds the specified class to every node in the list
// className: String
// the CSS class to add
return; // dojo.NodeList
},
removeClass: function(className){
// summary:
// removes the specified class from every node in the list
// className: String
// the CSS class to add
// returns:
// dojo.NodeList, this list
return; // dojo.NodeList
},
toggleClass: function(className, condition){
// summary:
// Adds a class to node if not present, or removes if present.
// Pass a boolean condition if you want to explicitly add or remove.
// condition: Boolean?
// If passed, true means to add the class, false means to remove.
// className: String
// the CSS class to add
return; // dojo.NodeList
},
connect: function(methodName, objOrFunc, funcName){
// summary:
// attach event handlers to every item of the NodeList. Uses dojo.connect()
// so event properties are normalized
// methodName: String
// the name of the method to attach to. For DOM events, this should be
// the lower-case name of the event
// objOrFunc: Object|Function|String
// if 2 arguments are passed (methodName, objOrFunc), objOrFunc should
// reference a function or be the name of the function in the global
// namespace to attach. If 3 arguments are provided
// (methodName, objOrFunc, funcName), objOrFunc must be the scope to
// locate the bound function in
// funcName: String?
// optional. A string naming the function in objOrFunc to bind to the
// event. May also be a function reference.
// example:
// add an onclick handler to every button on the page
// | dojo.query("div:nth-child(odd)").connect("onclick", function(e){
// | console.debug("clicked!");
// | });
// example:
// attach foo.bar() to every odd div's onmouseover
// | dojo.query("div:nth-child(odd)").connect("onmouseover", foo, "bar");
},
=====*/
attr: _mapIntoDojo("attr"),
style: _mapIntoDojo("style"),
addClass: _mapIntoDojo("addClass", true),
removeClass: _mapIntoDojo("removeClass", true),
toggleClass: _mapIntoDojo("toggleClass", true),
connect: _mapIntoDojo("connect", true),
// FIXME: connectPublisher()? connectRunOnce()?
place: function(/*String||Node*/ queryOrNode, /*String*/ position){
// summary:
// places elements of this node list relative to the first element matched
// by queryOrNode. Returns the original NodeList.
// queryOrNode:
// may be a string representing any valid CSS3 selector or a DOM node.
// In the selector case, only the first matching element will be used
// for relative positioning.
// position:
// can be one of:
// * "last"||"end" (default)
// * "first||"start"
// * "before"
// * "after"
// or an offset in the childNodes property
var item = d.query(queryOrNode)[0];
return this.forEach(function(i){ d.place(i, item, position); }); // dojo.NodeList
},
orphan: function(/*String?*/ simpleFilter){
// summary:
// removes elements in this list that match the simple
// filter from their parents and returns them as a new
// NodeList.
// simpleFilter:
// single-expression CSS filter
// returns:
// `dojo.NodeList` containing the orpahned elements
return (simpleFilter ? d._filterQueryResult(this, simpleFilter) : this). // dojo.NodeList
forEach("if(item.parentNode){ item.parentNode.removeChild(item); }");
},
adopt: function(/*String||Array||DomNode*/ queryOrListOrNode, /*String?*/ position){
// summary:
// places any/all elements in queryOrListOrNode at a
// position relative to the first element in this list.
// Returns a dojo.NodeList of the adopted elements.
// queryOrListOrNode:
// a DOM node or a query string or a query result.
// Represents the nodes to be adopted relative to the
// first element of this NodeList.
// position:
// can be one of:
// * "last"||"end" (default)
// * "first||"start"
// * "before"
// * "after"
// or an offset in the childNodes property
var item = this[0];
return d.query(queryOrListOrNode).forEach(function(ai){ // dojo.NodeList
d.place(ai, item, position || "last");
});
},
// FIXME: do we need this?
query: function(/*String*/ queryStr){
// summary:
// Returns a new, flattened NodeList. Elements of the new list
// satisfy the passed query but use elements of the
// current NodeList as query roots.
if(!queryStr){ return this; }
// FIXME: probably slow
// FIXME: use map?
var ret = d.NodeList();
this.forEach(function(item){
// FIXME: why would we ever get undefined here?
ret = ret.concat(d.query(queryStr, item).filter(function(subItem){ return (subItem !== undefined); }));
});
return ret; // dojo.NodeList
},
filter: function(/*String*/ simpleQuery){
// summary:
// "masks" the built-in javascript filter() method to support
// passing a simple string filter in addition to supporting
// filtering function objects.
// example:
// "regular" JS filter syntax as exposed in dojo.filter:
// | dojo.query("*").filter(function(item){
// | // highlight every paragraph
// | return (item.nodeName == "p");
// | }).styles("backgroundColor", "yellow");
// example:
// the same filtering using a CSS selector
// | dojo.query("*").filter("p").styles("backgroundColor", "yellow");
var items = this;
var _a = arguments;
var r = d.NodeList();
var rp = function(t){
if(t !== undefined){
r.push(t);
}
}
if(d.isString(simpleQuery)){
items = d._filterQueryResult(this, _a[0]);
if(_a.length == 1){
// if we only got a string query, pass back the filtered results
return items; // dojo.NodeList
}
// if we got a callback, run it over the filtered items
_a.shift();
}
// handle the (callback, [thisObject]) case
d.forEach(d.filter(items, _a[0], _a[1]), rp);
return r; // dojo.NodeList
},
/*
// FIXME: should this be "copyTo" and include parenting info?
clone: function(){
// summary:
// creates node clones of each element of this list
// and returns a new list containing the clones
},
*/
addContent: function(/*String*/ content, /*String||Integer?*/ position){
// summary:
// add a node or some HTML as a string to every item in the list.
// Returns the original list.
// description:
// a copy of the HTML content is added to each item in the
// list, with an optional position argument. If no position
// argument is provided, the content is appended to the end of
// each item.
// content:
// the HTML in string format to add at position to every item
// position:
// can be one of:
// * "last"||"end" (default)
// * "first||"start"
// * "before"
// * "after"
// or an offset in the childNodes property
// example:
// appends content to the end if the position is ommitted
// | dojo.query("h3 > p").addContent("hey there!");
// example:
// add something to the front of each element that has a "thinger" property:
// | dojo.query("[thinger]").addContent("...", "first");
// example:
// adds a header before each element of the list
// | dojo.query(".note").addContent("<h4>NOTE:</h4>", "before");
var ta = d.doc.createElement("span");
if(d.isString(content)){
ta.innerHTML = content;
}else{
ta.appendChild(content);
}
if(position === undefined){
position = "last";
}
var ct = (position == "first" || position == "after") ? "lastChild" : "firstChild";
this.forEach(function(item){
var tn = ta.cloneNode(true);
while(tn[ct]){
d.place(tn[ct], item, position);
}
});
return this; // dojo.NodeList
},
empty: function(){
// summary:
// clears all content from each node in the list
return this.forEach("item.innerHTML='';"); // dojo.NodeList
// FIXME: should we be checking for and/or disposing of widgets below these nodes?
},
instantiate: function(/*String|Object*/ declaredClass, /*Object?*/ properties){
// summary:
// Create a new instance of a specified class, using the
// specified properties and each node in the nodeList as a
// srcNodeRef
//
var c = d.isFunction(declaredClass) ? declaredClass : d.getObject(declaredClass);
return this.forEach(function(i){
new c(properties||{},i);
}) // dojo.NodeList
},
at: function(/*===== index =====*/){
// summary:
// Returns a new NodeList comprised of items in this NodeList
// at the given index or indices.
// index: Integer...
// One or more 0-based indices of items in the current NodeList.
// returns:
// dojo.NodeList
var nl = new dojo.NodeList();
dojo.forEach(arguments, function(i) { if(this[i]) { nl.push(this[i]); } }, this);
return nl; // dojo.NodeList
}
});
// syntactic sugar for DOM events
d.forEach([
"blur", "focus", "click", "keydown", "keypress", "keyup", "mousedown",
"mouseenter", "mouseleave", "mousemove", "mouseout", "mouseover",
"mouseup", "submit", "load", "error"
], function(evt){
var _oe = "on"+evt;
d.NodeList.prototype[_oe] = function(a, b){
return this.connect(_oe, a, b);
}
// FIXME: should these events trigger publishes?
/*
return (a ? this.connect(_oe, a, b) :
this.forEach(function(n){
// FIXME:
// listeners get buried by
// addEventListener and can't be dug back
// out to be triggered externally.
// see:
// http://developer.mozilla.org/en/docs/DOM:element
console.debug(n, evt, _oe);
// FIXME: need synthetic event support!
var _e = { target: n, faux: true, type: evt };
// dojo._event_listener._synthesizeEvent({}, { target: n, faux: true, type: evt });
try{ n[evt](_e); }catch(e){ console.debug(e); }
try{ n[_oe](_e); }catch(e){ console.debug(e); }
})
);
}
*/
}
);
})();
|
const express = require('express');
const app = express();
app.get('/', function (req, res) {
res.send("hello express")
})
app.get('/mmm', function (req, res) {
res.send("hello from my pc")
}).listen(4500);
|
import React, { Component } from 'react';
import { env } from '#store';
import { autorun } from 'mobx';
import { observer } from 'mobx-react';
import ace from 'brace';
import 'brace/keybinding/vim';
import 'brace/mode/javascript';
import 'brace/theme/tomorrow';
// container for copied text
const textarea = document.body.appendChild(document.createElement('textarea'));
textarea.style.left = '-999px';
textarea.style.position = 'absolute';
const uuid = (() => {
let count = 0;
return () => (++count).toString(36);
})();
@observer
export class Editor extends Component {
id = uuid();
onRef = (node) => {
if (node) {
this.editor = ace.edit(this.id);
this.editor.session.setUseWorker(false)
this.editor.setTheme('ace/theme/tomorrow');
this.editor.getSession().setMode('ace/mode/javascript');
this.editor.$blockScrolling = Infinity;
this.editor.setShowPrintMargin(false);
this.editor.setHighlightActiveLine(false);
this.editor.setShowFoldWidgets(false);
this.editor.renderer.setScrollMargin(10, 10, 10, 10);
this.editor.setOptions({
fontSize: '14px',
maxLines: Infinity,
wrap: true,
});
this.setVim(env.editor.vimMode);
ace.config.loadModule('ace/keyboard/vim', (module) => {
var VimApi = module.CodeMirror.Vim;
VimApi.defineEx('write', 'w', (cm, input) => {
this.save();
});
VimApi.defineEx('copy', 'c', (cm, input) => {
textarea.value = this.editor.getValue();
textarea.select();
document.execCommand('copy');
textarea.value = '';
});
});
}
};
state = {
sureDelete: false,
ok: false,
};
setText = (text) => {
const pos = this.editor.getCursorPosition();
this.editor.setValue(text);
this.editor.clearSelection();
this.editor.moveCursorToPosition(pos);
};
setVim = (bool) => {
this.editor.setKeyboardHandler(bool ? 'ace/keyboard/vim' : null);
};
toggleVim = (e) => {
env.editor.vimMode = !env.editor.vimMode;
this.setVim(env.editor.vimMode);
};
componentWillMount() {
this.disposer = autorun(() => {
const { command } = env.editor;
this.editor &&
this.setText(env.editor.command);
});
}
componentDidMount() {
env.getCommand(this.props.command);
}
componentWillUnmount() {
this.disposer && this.disposer();
}
save = () => {
env.setCommand(this.props.command, this.editor.getValue());
this.setState({ok: true});
setTimeout(() => {
this.setState({ok: false});
}, 500);
};
delete = () => {
if (this.state.sureDelete) {
env.deleteCommand(this.props.command);
this.props.delete();
}
else {
this.setState({sureDelete: true});
}
};
toggleStar = () => {
env.setConfig(this.props.command, {starred: !env.editor.starred});
};
toggleLock = () => {
env.setConfig(this.props.command, {locked: !env.editor.locked});
};
render() {
const { vimMode, locked, starred } = env.editor;
const { admin } = env;
const { sureDelete, ok } = this.state;
return (
<div className="editor">
<div className="flex items-stretch items-grow buttons">
<input
type="text"
disabled
defaultValue={this.props.command}
/>
<button
type="button"
onClick={this.save}
disabled={locked && !admin}
>
{ok ? 'ok' : 'save'}
</button>
<button
type="button"
disabled={!admin}
onClick={this.toggleLock}
>
{locked ? 'unlock' : 'lock'}
</button>
<button
type="button"
disabled={!admin}
onClick={this.toggleStar}
>
{starred ? 'unstar' : 'star'}
</button>
<button
type="button"
onClick={this.delete}
disabled={locked && !admin}
>
{sureDelete ? 'for real?' : 'delete'}
</button>
<button type="button" onClick={this.toggleVim}>
{!vimMode ? 'vim keys' : 'normal keys'}
</button>
</div>
<div id={this.id} ref={this.onRef}/>
</div>
);
}
}
|
import baseService from './baseService';
const todoService = baseService('todo');
export default todoService;
|
/**
* Created by dell-pc on 2017/6/27.
*/
var arr = [12,23,45];
//arr.show = function(){
// //console.log(this);
// console.log(this.length);
//};
function show(){
console.log(this.length);
}
show();
//arr.show();
//var obj = new Object();
//obj.aaa = 12;
//obj.show=function(){
// console.log(this.aaa);
//}
//obj.show();
//创建对象
//字面量表示
var obj = {
name:'zhangsan',
sex:'nan',
age:30,
eat:function(){
console.log(this.age);
}
}
//工厂模式 必须返回,需要显式创建对象,不需要new,每个对象都有自己的一套函数,极其浪费
function createPerson(name,sex,age){
var obj = new Object();
obj.name = name;
obj.sex = sex;
obj.age = age;
obj.eat = function(){
console.log(this.age);
};
return obj;
}
//构造函数模式 不返回,不需要显式创建对象,需要new,每个对象都有自己的一套函数,极其浪费
function Person(name,sex,age){
this.name = name;
this.sex = sex;
this.age = age;
this.eat = function(){
console.log(this.age);
};
}
var p1 = new Person('lili','nan',20);
var p2 = new Person('riri','nv',19);
console.log(p1.eat === p2.eat);
var p3 = createPerson('lili','nan',20);
var p4 = createPerson('riri','nv',19);
console.log(p3.eat === p4.eat);
|
export const DESCRIPTION =
'Прочитайте предлагаемые утверждения. Оцените степень влияния каждого фактора на Ваш спортивный результат во время соревнований. Поставьте напротив фактора отметку в ячейке, отражающей степень его влияния.';
export const QUESTIONS = [
{
id: 0,
title: 'Предшествующие плохие тренировочные и соревновательные результаты'
},
{
id: 1,
title: 'Конфликты с тренером, товарищами по команде или в семье'
},
{
id: 2,
title: 'Положение фаворита перед соревнованиями'
},
{
id: 3,
title: 'Плохой сон за день или за несколько дней до старта'
},
{
id: 4,
title: 'Плохое оснащение соревнований'
},
{
id: 5,
title: 'Предыдущие неудачи'
},
{
id: 6,
title: 'Завышенные требования'
},
{
id: 7,
title: 'Длительный переезд к месту соревнований'
},
{
id: 8,
title: 'Постоянные мысли о необходимости выполнения поставленной задачи'
},
{
id: 9,
title: 'Незнакомый противник'
},
{
id: 10,
title: 'Предшествующие поражения от данного противника'
},
{
id: 11,
title: 'Неудачи на старте'
},
{
id: 12,
title: 'Необъективное судейство'
},
{
id: 13,
title: 'Отсрочка старта'
},
{
id: 14,
title: 'Упреки во время соревнования'
},
{
id: 15,
title: 'Повышенное волнение'
},
{
id: 16,
title: 'Значительное превосходство соперника'
},
{
id: 17,
title: 'Неожиданно высокие результаты соперника'
},
{
id: 18,
title: 'Зрительные, акустические и тактильные помехи'
},
{
id: 19,
title: 'Реакция зрителей'
},
{
id: 20,
title: 'Плохое физическое самочувствие'
},
{
id: 21,
title: 'Болевой финишный синдром, страх смерти'
}
];
export const STRESS_FACTORS_SAVE_INTERPRETATION = `athleteTests/StressFactorsQuiz/STRESS_FACTORS_SAVE_INTERPRETATION`;
export const STRESS_FACTORS_SAVE_INTERPRETATION_ERROR = `athleteTests/StressFactorsQuiz/STRESS_FACTORS_SAVE_INTERPRETATION_ERROR`;
export const STRESS_FACTORS_SAVE_INTERPRETATION_SUCCESS = `athleteTests/StressFactorsQuiz/STRESS_FACTORS_SAVE_INTERPRETATION_SUCCESS`;
|
import config from '../../lib/config';
import Helpers from '../../lib/Helpers';
export default class Header {
static render() {
}
}
|
function solve(args) {
let arr = args;
let [day, month, year] = args;
let date = new Date(year, month, day);
date.setMonth(date.getMonth() - 1);
date.setDate(0);
console.log(date.getDate());
}
solve([17, 3, 2002]);
|
const net = require('net');
const debug = require('debug')('conn:');
const defaultIdelTimeout = 3 * 60 * 1000 - 5 * 1000;
function loop() {}
class Connection {
get defaultOptions() {
return {
keepAlive: true,
idleTimeout: defaultIdelTimeout,
};
}
get destroyed() {
return this.socket.destroyed;
}
constructor(options = {}) {
this.options = Object.assign({}, this.defaultOptions, options);
this.socket = null;
this.ready = false;
this.writeCacheData = null;
this.successCall = loop;
this.failCall = loop;
this.contentLength = 0;
this.chunked = false;
this.bodySize = 0;
this.data = ''; // received data
this.dataCount = 0; // received data count
this.connect();
}
connect() {
this.socket = new net.Socket();
this.socket.setTimeout(this.options.idleTimeout);
this.socket.setKeepAlive(this.options.keepAlive);
this.socket.connect(this.options.port, this.options.host);
this.socket.setEncoding('utf8');
this.socket
.on('lookup', () => {
// Emitted after resolving the hostname but before connecting. Not applicable to Unix sockets.
debug('socket event -> lookup');
})
.on('connect', () => {
// Emitted when a socket connection is successfully established.
debug('socket event -> connect');
})
.on('ready', () => {
// Emitted when a socket is ready to be used.
debug('socket event -> ready');
this.ready = true;
if (this.writeCacheData) {
this.write(this.writeCacheData);
this.writeCacheData = null;
}
})
.on('data', chunk => {
// Emitted when data is received.
debug('socket event -> data');
this.dataCount++;
this.data += chunk;
if (this.dataCount === 1) {
const contentLengthIndex = chunk.indexOf('Content-Length: ');
this.chunked = contentLengthIndex === -1;
if (!this.chunked) {
this.contentLength = parseInt(chunk.slice(contentLengthIndex + 16, contentLengthIndex + 26).toString());
const headerTailIndex = chunk.indexOf('\r\n\r\n');
this.bodySize += Buffer.byteLength(chunk) - headerTailIndex - 4;
}
} else {
if (!this.chunked) {
this.bodySize += Buffer.byteLength(chunk);
}
}
const zeroIndex = chunk.lastIndexOf('\r\n0');
if ((this.bodySize && this.bodySize >= this.contentLength) || zeroIndex > -1) {
this.successCall(this.data);
this.release();
}
})
.on('timeout', () => {
// Emitted if the socket times out from inactivity. This is only to notify that the socket has been idle.
// The user must manually close the connection.
debug('socket event -> timeout');
this.socket.end();
})
.on('drain', () => {
// Emitted when the write buffer becomes empty. Can be used to throttle uploads.
debug('socket event -> drain');
})
.on('end', () => {
// Emitted when the other end of the socket sends a FIN packet, thus ending the readable side of the socket.
debug('socket event -> end');
})
.on('error', err => {
// Emitted when an error occurs. The 'close' event will be called directly following this event.
debug('socket event -> error');
this.failCall(err);
})
.on('close', () => {
// Emitted once the socket is fully closed.
// The argument hadError is a boolean which says if the socket was closed due to a transmission error.
debug('socket event -> close');
this.ready = false;
this.release();
if (!this.socket.destroyed) {
this.socket.destroy();
}
});
}
release() {
this.writeCacheData = null;
this.successCall = loop;
this.failCall = loop;
this.contentLength = 0;
this.chunked = false;
this.bodySize = 0;
this.data = '';
this.dataCount = 0;
}
send(data, successCall, failCall) {
this.successCall = successCall;
this.failCall = failCall;
debug('socket ready status check');
if (this.ready) {
this.write(data);
} else {
debug('data temporary cache');
this.writeCacheData = data;
}
}
write(data) {
debug('socket start send');
const result = this.socket.write(data, 'utf8', function(err) {
debug('socket data is finally written out');
});
debug('socket write call result:', result);
if (!result) {
}
}
}
module.exports = Connection;
|
const path = require('path');
const express = require('express');
const DB = require('../core/database');
const router = express.Router();
router.get('/', (request, response, next) => {
DB.all('SELECT * FROM users', (err, row) => {
if (err) return console.error(err);
console.log(row);
response.render('users', {users: row});
})
});
module.exports = router;
|
const webpack = require('webpack');
const merge = require('webpack-merge');
const path = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin')
var baseConfig = {
mode: 'production',
output: {
path: path.resolve(__dirname + '/dist/')
},
module: {
rules: [
{
test:/\.vue$/,
loader: 'vue-loader'
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options:{
presets: ['@babel/preset-env']
}
}
},
{
test:/\.css$/,
use:[
'vue-style-loader',
'css-loader'
]
}
],
},
plugins: [
new VueLoaderPlugin(),
],
externals: {
BButton: 'BButton',
BTooltip: 'BTooltip',
BIconArrowRight: 'BIconArrowRight',
BIconArrowLeft: 'BIconArrowLeft',
}
};
module.exports = [
merge(
baseConfig,
{
entry: path.resolve(__dirname + '/src/plugin.js'),
output: {
filename: 'flipping-stepper.min.js',
libraryTarget: 'window',
library: 'FlippingStepper'
}
}
),
merge(
baseConfig,
{
entry: path.resolve(__dirname + '/src/FlippingStepper.vue'),
output: {
filename: 'flipping-stepper.js',
libraryTarget: 'umd',
library: 'flipping-stepper',
umdNamedDefine: true
}
}
)
];
|
const url = new URL('http://localhost:8081/player-lobby', self.location.origin).href
/**
* Listen for push event. Show notification if the page is not in focus
*/
self.addEventListener('push', event => {
let job = event.data.json()
let promiseChain = getMatchingWindowClient().then(windowClient => {
if (windowClient === null || !windowClient.focused) {
return self.registration.showNotification('Ny mostander funnet!',
{
'body': 'Du spiller mot: ' + job.opponent + ' med ' + job.colour + ' brikker!',
'icon': './notificationIcon.jpg',
'vibrate': [500] // Not available in Android Oreo or higher.
})
}
})
event.waitUntil(promiseChain)
})
/**
* adapted from https://developers.google.com/web/fundamentals/push-notifications/common-notification-patterns
*
* Listen for notification click event. Focus the website if it is open, else open it.
*/
self.addEventListener('notificationclick', event => {
event.waitUntil(getMatchingWindowClient().then(matchingClient => {
if (matchingClient) {
return matchingClient.focus()
} else {
return self.clients.openWindow(url)
}
}))
})
/**
* adapted from https://developers.google.com/web/fundamentals/push-notifications/common-notification-patterns
*
* Finds and returns the window client that matches the website.
* @returns {Promise<ReadonlyArray<Client>>}.
*/
async function getMatchingWindowClient() {
let matchingClient = null
return self.clients.matchAll({
type: 'window',
includeUncontrolled: true
}).then((windowClients) => {
let i = 0
while (i < windowClients.length) {
const windowClient = windowClients[i]
if (windowClient.url === url) {
matchingClient = windowClient
}
i++
}
return matchingClient
})
}
|
//for
// 1) Declarar una variable
// 2) Condición(Expresiones)
//Incrementar,Disminuir
/*for(let numeroExDeMiCrush= 7;numeroExDeMiCrush == 0; //False
numeroExDeMiCrush--){
console.log('ES CAN DA LO ',numeroExDeMiCrush);numeroExDeMiCrush--;
}*/
/*for(let numeroExDeMiCrush= 7;numeroExDeMiCrush > 0;
numeroExDeMiCrush--){
console.log('ES CAN DA LO ',numeroExDeMiCrush);
}*/
/*for(let numeroExDeMiCrush= 0;numeroExDeMiCrush <7 ;
numeroExDeMiCrush++){
console.log('ES CAN DA LO ',numeroExDeMiCrush);} */
for (var numeroExDeMiCrush = 0; numeroExDeMiCrush <= 6; numeroExDeMiCrush++) {
console.log('ES CAN DA LO ', numeroExDeMiCrush);
}
//ARREGLOS
// Representacion de un vector
// 1 elemento (variable const numero = 1)
// Conjunto del mismo elementos([1,2,3,4,5,6,7])
// conjunto de diferentes elementos ([1,"abc",true])
var arregloNumeros = [1, 2, 3, 4, 5];
//const arregloNumeros = [1,2,3,4,5,6] queremos agregar
//Función(Push)
// Si existe una funcion elinmutable puede cambiar
//lET REASIGNAR
arregloNumeros.push(6);
console.log('arreglo Numeros', arregloNumeros);
arregloNumeros.pop();
console.log('arreglo de Numeros', arregloNumeros);
//Acceder a cada elemento del arreglo por el indice
var indiceElementoUno = 0;
arregloNumeros[indiceElementoUno];
arregloNumeros[0];
var indiceElementoCinco = 4;
arregloNumeros[indiceElementoCinco];
arregloNumeros[4];
//Acceder al elemento 5
// INDIE
//[1,2,3,4,5,]
// 0 1 2 3 4
//indice
//console.log(arregloNumeros[4]);
console.log(arregloNumeros[indiceElementoCinco]);
// Crear arreglo de 5 elementos
// Cada 2 elemento 1 0 un 0
// Ejmp[0,0,1,1,0]
// Exista al menos un elemento 1
//ej[0,0,0,1] valido
Math.floor(Math.random() * 2);
//
// Arreglo
// 1) Elementos
// 2) Indices(0 index based) --> Posicion
// 3) Logitud -># Elementos
//console.log(arregloNumeros.length);
// For
// let tamaño = arregloNumeros.length
// tamaño >0
//--
/*for(let tamaño=arregloNumeros.length; tamaño > 0 ;
tamaño --){
console.log('ES CAN ',tamaño);}*/
|
(function () {
angular.module('myApp')
.controller('EditTodoModalController', EditTodoModalController)
.factory('editTodoModalService', function ($uibModal) {
function editTodoModal(todoObj, cb) {
var modalInstance = $uibModal.open({
restrict: "E",
templateUrl: './app/components/modal/editTodo.Modal.html',
controller: 'EditTodoModalController',
controllerAs: 'ctrl',
resolve: {
todoObj: function () {
return angular.copy(todoObj);
},
cb: function () {
return cb
}
}
});
modalInstance.result
.then(function (result) {
result.cb(result);
})
.catch(handleError);
function handleError(err) {
console.log(err);
}
}
return {
editTodoModal: editTodoModal
}
});
EditTodoModalController.$inject = ['$scope', '$uibModalInstance', 'todoObj', 'cb'];
function EditTodoModalController($scope, $uibModalInstance, todoObj, cb) {
var ctrl = this;
ctrl.todoObj = todoObj;
ctrl.todoObj.cb = cb;
// date & time picker
{
$scope.dt = (ctrl.todoObj.todo.dueDate)? new Date(ctrl.todoObj.todo.dueDate) : null;
$scope.open = function() {
$scope.status.opened = true;
};
$scope.status = {
opened: false
};
$scope.getDayClass = function(date, mode) {
if (mode === 'day') {
var dayToCheck = new Date(date).setHours(0,0,0,0);
for (var i=0;i<$scope.events.length;i++){
var currentDay = new Date($scope.events[i].date).setHours(0,0,0,0);
if (dayToCheck === currentDay) {
return $scope.events[i].status;
}
}
}
return '';
};
}
ctrl.select = function (e) {
e.target.setSelectionRange(0, e.target.value.length);
};
ctrl.deleteTodo = function () {
ctrl.todoObj.operation = 'delete';
$uibModalInstance.close(ctrl.todoObj);
};
ctrl.save = function () {
ctrl.todoObj.todo.dueDate = $scope.dt;
ctrl.todoObj.operation = 'save';
$uibModalInstance.close(ctrl.todoObj);
};
ctrl.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
}
})();
|
import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
const zeroPad = n => {
if (n < 10) {
return n = `0${n}`;
}
return n.toString();
};
const getDateByGtmHourOffset = gtmHourOffset => {
const now = new Date();
const timeOffset = now.getTimezoneOffset();
return new Date(now.getTime() + timeOffset * 60 * 1000 + gtmHourOffset * 60 * 60 * 1000);
};
const formatDate = (date) => {
const hh = date.getHours();
const mm = date.getMinutes();
const ss = date.getSeconds();
return `${zeroPad(hh)}:${zeroPad(mm)}:${zeroPad(ss)}`;
};
function WatchesItem({
id,
name,
timeZone,
onRemove
}) {
const [time, setTime] = useState(formatDate(getDateByGtmHourOffset(timeZone)));
const handleRemoveClick = () => {
onRemove(id);
};
useEffect(() => {
const intervalId = setInterval(() => {
setTime(formatDate(getDateByGtmHourOffset(timeZone)));
}, 1000);
return () => {
if (intervalId) {
clearInterval(intervalId);
}
};
});
return (
<div className="Watches-item">
<div>
<h5>
{name}
{' '}
<small>(GTM{timeZone > 0 ? `+${timeZone}` : timeZone})</small>
</h5>
<button
className="Watches-itemRemove"
type="button"
onClick={handleRemoveClick}
>
×
</button>
</div>
<p>{time}</p>
</div>
);
}
WatchesItem.propTypes = {
id: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
timeZone: PropTypes.number.isRequired,
onRemove: PropTypes.func
};
WatchesItem.defaultProps = {
onRemove: () => null
};
export default WatchesItem;
|
jQuery.fn.selectBox = function(options){
var params = {
url:"sysadmin/queryChSelDict_dict_item.action",
code:null,
query:"",
valueId:null,
textId:null
};
var itemIdLd=options.query;
var sourceSelect = jQuery(this);
sourceSelect.attr('code',options.code);
var check_wi='148';
if(options.width!=undefined&&options.width!=null&&options.width!=""){
check_wi=options.width;
}
sourceSelect.unbind('mouseover');//移除事件,以避免事件冲突
sourceSelect.css('width',check_wi);//设置宽度,也可以在此增加class样式
var newwidth_select=sourceSelect.css('width').substring(0,sourceSelect.css('width').length-2);//取出目前的宽度
sourceSelect.css('width',parseInt(newwidth_select)+7);//在原宽度上再增加2像素
if(options.code!=undefined||options.code!=null||options.code!=""){//code不为空时将其加载到select的属性中
sourceSelect.attr('code',options.code);
}
var selectLength=sourceSelect.find('option').length;//取出目前下拉菜单中的数据条数
/**
* 设计思路
* select中无数据时需要默认写上字典的第一个数据,之后绑定事件,当鼠标滑过时才加载数据(通常这一条数据为空行)
* select只有一条数据时绑定触发事件,不加载数据
* select中有多条数据时清空数据,判断第一条如果是空行则保留, 之后绑定事件
* 如果code为空则不进行操作
*/
if(options.code==undefined||options.code==null||options.code==""){//未填写code 表示不需要加载字典
return ;
}
if(selectLength>0){//多条记录
var option=sourceSelect.find('option').val();//取出第一条记录
sourceSelect.empty();//取出第一条记录后清除select中的数据,以便于加载新的值
if(option==''){//如果第一条值是空白,那么继续保持该状态
sourceSelect.append("<option></option>");
}
sourceSelect.bind('mouseover',function(){
clickSelectBoxFunction(sourceSelect,options,itemIdLd);
});
return ;//多条数据直接绑定事件,不加载数据
}
if (options)
{
jQuery.extend(params, options);
}
if(params.query==undefined||params.query==null||params.query==''){
params.query='';
}
if(params.code!=undefined&¶ms.code!=null&¶ms.code!=""&&selectLength==0){//当select中无数据时才加载一条
$.ajax({
type: "POST",
url:"sysadmin/queryChSelDict_dict_item.action",
async: false,
data: {dict_code:params.code,superId:params.query},
dataType:"json",
timeout:1000,
success: function(result){
sourceSelect.append("<option value='"+result.ldata[0].fact_value+"' item='"+result.ldata[0].item_id+"'>"+result.ldata[0].display_name+"</option>");
sourceSelect.bind('mouseover',function(){//绑定事件
clickSelectBoxFunction(sourceSelect,options,itemIdLd);
});
}
});
}
}
function clickSelectBoxFunction(obj,options,itemIdLd){
var roptions = obj.find('option').length;
if(roptions>1){//大于1条记录则不操作,只有select为空或者1条记录时才加载数据,否则视为已经增加了事件
return ;
}
if(itemIdLd==undefined||itemIdLd==null||itemIdLd==''){
itemIdLd='';
}else{
alert(itemIdLd);
}
if(options.code!=undefined&&options.code!=null&&options.code!=""){
$.ajax({
type: "POST",
url:"sysadmin/queryChSelDict_dict_item.action",
async: false,
data: {dict_code:options.code,query_simplepin:options.query,superId:itemIdLd},
dataType:"json",
timeout:1000,
success: function(result){
var i=0;
var lfvalue='';//首先读取出当前字典的值与title
var lftitle='';
var lfselect='';
if(obj.find('option').val()!=''){//当第一条不为空时清空数据后才加载数据
lfvalue=obj.find('option').val();
lftitle=obj.find('option').attr('title');
obj.empty();
}
for( i=0;i<result.ldata.length;i++){
if(result.ldata[i].fact_value==lfvalue||result.ldata[i].display_name==lftitle){//当数据与默认值相同时设定为selected
lfselect="selected='selected'";
}
obj.append("<option value='"+result.ldata[i].fact_value+"' item='"+result.ldata[i].item_id+"' title='"+result.ldata[i].display_name+"'"+lfselect+">"+result.ldata[i].display_name+"</option>");
lfselect="";//使用之后清空值
}
}
});
}
obj.unbind('mouseover');//移除事件,以避免事件冲突
}
jQuery.fn.setValue = function(text){//setValue与setText可以走同一个方法
var sourceSelect = jQuery(this);
findValue(sourceSelect,text);
}
jQuery.fn.setText = function(text){
var sourceSelect = jQuery(this);
findValue(sourceSelect,text);
}
function findValue(sourceSelect,text){
var roptions = sourceSelect.find('option').length;//首先判断条数
if(roptions<=1){//当小于或等于1条记录时判定为尚未加载数据
var code=sourceSelect.attr('code');//取出该下拉菜单的字典项//通常进行定位时都是有code的,所以下面就不判断code是否存在了
sourceSelect.empty();//定位时清空数据,只要定位的一条数据
$.ajax({
type: "POST",
url:"sysadmin/queryChSelDict_dict_item.action",
async: false,
data: {dict_code:code},
dataType:"json",
timeout:1000,
success: function(result){
var i=0;
for(i=0;i<result.ldata.length;i++){
if(result.ldata[i].fact_value==text||result.ldata[i].display_name==text){//字典值或者显示名称与传来的值相等时写到页面上,只写这一条 其他的点击才加载
sourceSelect.append("<option value='"+result.ldata[i].fact_value+"' item='"+result.ldata[i].item_id+"' title='"+result.ldata[i].display_name+"'>"+result.ldata[i].display_name+"</option>");
sourceSelect.bind('mouseover',function(){//绑定事件
clickSelectBoxFunction(sourceSelect,options,itemIdLd);
});
}
}
}
});
}else{//大于1时判定为已经加载数据,直接定位到该数据
obj.find('option').each(function(r){//循环每一条数据
var $option=obj.find('option').eq(r);
if($option.val()==text||$option.attr('title')==text){//当找到这条数据时设为选中
$option.attr('selected','selected');
}
});
}
}
jQuery.fn.selectBoxhylb = function(options){
var selData;
var params = {
url:"sysadmin/querySelDicthylb_dict_item.action",
state:"",
code:null,
order:0,
query:"",
width: "150px"
//selValue:"",
//selText:""
};
var sourceSelect = jQuery(this);
if (options)
{
jQuery.extend(params, options);
}
sourceSelect.width(params.width);
if(params.code!=undefined && params.code!=null && params.code!=""){
selData = {dict_code:params.code,query_simplepin:params.query,orderBySib_order:params.order};
}else{
selData = {dataxml:sXML};
}
var flength=sourceSelect.find("option").length;
sourceSelect.empty();
if(flength!=0){//默认第一行有数据,当做其为空白行
sourceSelect.append("<option></option>");
}
if(params.state==undefined || params.state==null || params.state==""){//行业类别不多,可以直接加载
$.ajax({
type: "POST",
url: params.url,
async: false,
data: selData,
dataType:"json",
timeout:1000,
success: function(result){
for( var h=0;h<result.ldata.length;h++){
sourceSelect.append("<option value='"+result.ldata[h].fact_value+"' title='"+result.ldata[h].display_name+"'>"+result.ldata[h].display_name+"</option>");
}
}
});
}else{
sourceSelect.combobox(params);
}
if(sourceSelect.find("option").length<=1){
sourceSelect.setAttr("readonly",true);
}
}
|
import firebase from 'firebase'
var firebaseConfig = {
apiKey: "AIzaSyB8uLuYPuMbldRWc-ctTBEUwPS8CET7mN8",
authDomain: "photo-gallery00001.firebaseapp.com",
projectId: "photo-gallery00001",
storageBucket: "photo-gallery00001.appspot.com",
messagingSenderId: "772105277078",
appId: "1:772105277078:web:e7a9d6de60c213bc333cb7",
measurementId: "G-4HRJY2RJSJ"
};
firebase.initializeApp(firebaseConfig);
export default firebase;
|
import { driverService } from '../../../backend/drivers/DriverService';
const LOAD_DRIVERS = 'LOAD_DRIVERS';
const SET_DRIVERS = 'SET_DRIVERS';
const SET_DRIVERS_ERROR = 'SET_DRIVERS_ERROR';
const CLEAR_DRIVERS = 'CLEAR_DRIVERS';
const CREATE_DRIVER = 'CREATE_DRIVER';
const REMOVE_DRIVER = 'REMOVE_DRIVER';
const SET_DRIVERS_LOADING = 'SET_DRIVERS_LOADING';
const FINISH_DRIVERS_LOADING = 'FINISH_DRIVERS_LOADING';
export const driverActions = {
loadDrivers: () => {
return {
type: LOAD_DRIVERS
}
},
setDrivers: driversList => {
return {
type: SET_DRIVERS,
payload: { driversList }
};
},
clearDrivers: () => {
return {
type: CLEAR_DRIVERS
};
},
setDriversLoading: () => {
return {
type: SET_DRIVERS_LOADING
};
},
finishDriversLoading: () => {
return {
type: FINISH_DRIVERS_LOADING
};
},
setDriversError: (errorMessage) => {
return {
type: SET_DRIVERS_ERROR,
payload: {
errorMessage
}
}
}
};
export const driversReducer = {
[SET_DRIVERS](state = {}, action) {
const { driversList } = action.payload;
return {
...state,
driversList
};
},
[CLEAR_DRIVERS](state = {}) {
return {
...state,
driversList: []
};
},
[SET_DRIVERS_LOADING](state = {}) {
return {
...state,
isLoading: true
};
},
[FINISH_DRIVERS_LOADING](state = {}) {
return {
...state,
isLoading: false
};
},
[SET_DRIVERS_ERROR](state = {}, action) {
const { errorMessage } = action.payload;
return {
...state,
errorMessage
};
}
};
export const driversLogic = [
{
type: LOAD_DRIVERS,
cancelType: 'ABORT',
latest: true,
process({ getState, action }, dispatch, done) {
dispatch(driverActions.setDriversLoading());
driverService
.fetchAll()
.then(drivers => {
dispatch(driverActions.setDrivers(drivers));
dispatch(driverActions.finishDriversLoading());
done();
})
.catch(err => {
dispatch(driverActions.finishDriversLoading());
done();
});
}
}
];
|
import * as React from "react";
import { action } from "@storybook/addon-actions";
import { withKnobs, boolean, text } from "@storybook/addon-knobs";
import Button from ".";
export default {
title: "Components/Button",
component: Button,
decorators: [withKnobs],
};
export const Default = () => (
<Button
text={text("Text", "Button Text")}
disabled={boolean("Disabled", false)}
onClick={action("onClick")}
/>
);
|
import React, { Component } from "react";
import { StyleSheet, View, Text, Image, TouchableOpacity, TextInput, TouchableHighlightBase } from "react-native";
import DropDownPicker from 'react-native-dropdown-picker';
import { ceil } from "react-native-reanimated";
class ShareRegister extends Component {
constructor({ props }) {
super(props);
const handleSubmit = () => {
}
this.state = {
yearOpen: false,
monthOpen: false,
dayOpen: false,
endYearOpen: false,
endMonthOpen: false,
endDayOpen: false,
accountOpen: false
}
this.setValue = this.setValue.bind(this);
}
setOpen(open) {
this.setState({
open
});
}
setValue(callback) {
this.setState(state => ({
value: callback(state.value)
}));
}
setItems(callback) {
this.setState(state => ({
items: callback(state.items)
}));
}
render() {
const { yearOpen, monthOpen, dayOpen, endYearOpen, endMonthOpen, endDayOpen, accountOpen} = this.state;
return (
<View style={styles.container}>
<View style={styles.modifyBtnView}>
<TouchableOpacity style={styles.modifyStyle}>
<Text style={styles.modifyText}>
수정
</Text>
</TouchableOpacity>
</View>
<View style={styles.bodyView}>
<View style={styles.contentView}>
<View style={styles.titleView}>
<Text style={styles.titleText}>
서비스 시작
</Text>
<Text style={styles.titleText}>
서비스 종료
</Text>
<Text style={styles.titleText}>
사진 첨부
</Text>
<Text style={styles.titleText}>
계좌
</Text>
<Text style={styles.titleText}>
등록번호
</Text>
</View>
<View style={styles.dropView}>
<View style={styles.startView}>
<DropDownPicker
containerStyle={{width: '38%', }}
placeholder='년도'
items={[
{ label: '2021', value: '1'},
{ label: '2022', value: '2', selected:true }
]}
open={yearOpen}
onOpen = {() => {this.setState({ yearOpen: true })}}
onClose={() => this.setState({ yearOpen: false })}
onChangeItem={item => {
this.setState({
selected: item.value
});
}}
/>
<DropDownPicker
containerStyle={{width: '32%', }}
placeholder='월'
items={[
{ label: '08', value: '1'},
{ label: '09', value: '2'},
{ label: '10', value: '3'}
]}
open={monthOpen}
onOpen = {() => {this.setState({ monthOpen: true })}}
onClose={() => this.setState({ monthOpen: false })}
/>
<DropDownPicker
containerStyle={{width: '32%', }}
placeholder='일'
items={[
{ label: '08', value: '1'},
{ label: '09', value: '2'},
{ label: '10', value: '3'}
]}
open={dayOpen}
onOpen = {() => {this.setState({ dayOpen: true })}}
onClose={() => this.setState({ dayOpen: false })}
/>
</View>
<View style={styles.endView}>
<DropDownPicker
containerStyle={{width: '38%', }}
placeholder='년도'
items={[
{ label: '2021', value: '1'},
{ label: '2022', value: '2', selected:true }
]}
open={endYearOpen}
onOpen = {() => {this.setState({ endYearOpen: true })}}
onClose={() => this.setState({ endYearOpen: false })}
onChangeItem={item => {
this.setState({
selected: item.value
});
}}
/>
<DropDownPicker
containerStyle={{width: '32%', }}
placeholder='월'
items={[
{ label: '08', value: '1'},
{ label: '09', value: '2'},
{ label: '10', value: '3'}
]}
open={endMonthOpen}
onOpen = {() => {this.setState({ endMonthOpen: true })}}
onClose={() => this.setState({ endMonthOpen: false })}
/>
<DropDownPicker
containerStyle={{width: '32%', }}
placeholder='일'
items={[
{ label: '08', value: '1'},
{ label: '09', value: '2'},
{ label: '10', value: '3'}
]}
open={endDayOpen}
onOpen = {() => {this.setState({ endDayOpen: true })}}
onClose={() => this.setState({ endDayOpen: false })}
/>
</View>
<View style={styles.picView}>
<View style={styles.picTextView}>
<Text style={styles.picText}>
파일명
</Text>
</View>
<View style={styles.picBtnView}>
<TouchableOpacity style={styles.picBtnStyle}>
<Text style={styles.picBtnText}>
첨부
</Text>
</TouchableOpacity>
</View>
</View>
<View style={styles.accountView}>
<View style={styles.accountDropView}>
<DropDownPicker
placeholder='은행'
items={[
{ label: '농협', value: '1'},
{ label: '신한', value: '2'},
{ label: '카카오', value: '3'}
]}
open={accountOpen}
onOpen = {() => {this.setState({ accountOpen: true })}}
onClose={() => this.setState({ accountOpen: false })}
/>
</View>
<View style={styles.accountNumView}>
<TextInput style={styles.accountNumTextInput}
placeholder='계좌번호 입력'
>
</TextInput>
</View>
</View>
<View style={styles.registerNumView}>
<Text style={styles.registerNumText}>
#100000
</Text>
</View>
</View>
</View>
<View style={styles.alertView}>
<Text>
• 쉐어링 서비스 시작, 종료일을 선택해주세요.{"\n"}
• 반드시 본인의 킥보드 사진을 등록해주시기 바랍니다. {"\n"}
• 수익금을 수령할 계좌번호를 정확히 입력해주세요.
</Text>
</View>
<View style={styles.btnView}>
<TouchableOpacity style={styles.confirmBtn}>
<Text style={styles.confirmText}>
쉐어링 서비스 등록
</Text>
</TouchableOpacity>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "flex-end",
backgroundColor: "#f9e6e9",
},
modifyBtnView: {
flex: 0.3,
flexDirection: 'row-reverse',
alignItems: 'center'
},
bodyView: {
flex: 3.7,
paddingTop: 40,
paddingBottom: 40,
paddingLeft: 30,
paddingRight: 30,
},
contentView: {
flex: 2,
flexDirection: 'row',
},
alertView: {
flex: 1.7,
paddingTop: '5%',
justifyContent: 'center'
},
btnView: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
modifyStyle: {
borderWidth: 1,
borderRadius: 40,
width: '20%',
height: '55%',
justifyContent: 'center',
alignItems: 'center',
marginRight: '5%'
},
modifyText: {
fontSize: 16
},
titleView: {
flex: 0.85,
alignItems: 'center',
},
titleText: {
fontSize: 18,
marginBottom: '15%',
marginTop: '17%'
},
dropView: {
flex: 2.15,
},
confirmBtn: {
borderWidth: 1,
borderRadius: 40,
backgroundColor: "pink",
borderColor: "pink",
width: "65%",
height: '40%',
alignItems: "center",
justifyContent: "center"
},
confirmText: {
fontSize: 23,
color: "white"
},
dropDownStyle: {
borderRadius: 0,
},
startView: {
flex:1,
flexDirection: 'row',
zIndex:3
},
endView: {
flex:1,
flexDirection: 'row',
zIndex: 2
},
picView: {
flex:1,
flexDirection: 'row'
},
picTextView: {
flex: 2,
justifyContent: 'center',
alignItems: 'center'
},
picText: {
fontSize: 16
},
picBtnView: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
picBtnStyle: {
borderWidth: 1,
justifyContent: 'center',
alignItems: 'center',
width: '80%',
height: '40%'
},
picBtnText: {
fontSize: 16
},
accountView: {
flex: 1,
flexDirection: 'row',
zIndex: 1
},
accountDropView: {
flex: 1
},
accountNumView: {
flex: 2,
justifyContent: 'center',
alignItems: 'center',
},
accountNumTextInput: {
borderBottomWidth: 1,
width: '95%',
fontSize: 16
},
registerNumView: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
registerNumText: {
fontSize: 16,
marginBottom: '5%'
}
})
export default ShareRegister;
|
import {arr, num} from 'types';
export default function dec(increment = 1) {
return function innerDec(n) {
return num(n) - num(increment);
};
};
|
//Yelp API authorization
var auth = {
consumerKey: '8L0N5Y4Y_5nWgpDtuTkohQ',
consumerSecret: 'iFNnSoNi7GEdTww73caLQvsKf3Y',
accessToken: 'tTEdjH2VZaIZas2ioc-ex72kEHxHEpir',
accessTokenSecret: 'PJ5AjTZKwL8Jp-5LM686Czm39hU',
serviceProvider: {
signatureMethod: 'HMAC-SHA1'
}
};
//Initial data for this project
var initlocation = [{
name: 'Salute',
location: {
lat: 41.765559,
lng: -72.675989,
}
}, {
name: 'Firebox Restaurant',
location: {
lat: 41.762332,
lng: -72.686888,
}
}, {
name: 'ON20',
location: {
lat: 41.7659452,
lng: -72.669071,
}
}, {
name: 'The Capital Grille',
location: {
lat: 41.762998,
lng: -72.670809,
}
}, {
name: "Peppercorn's Grill",
location: {
lat: 41.760349,
lng: -72.675408,
}
}, {
name: 'Ichiban',
location: {
lat: 41.7667179,
lng: -72.7119986,
}
}, {
name: "Carbone's Ristorante",
location: {
lat: 41.732369,
lng: -72.674121,
}
}, {
name: "Fleming's Prime Steakhouse",
location: {
lat: 41.7601688,
lng: -72.7437346,
}
}];
var map;
var infowindow;
//This will initialize the Google Map
/**
* @description: Initialize the Google Map
* @returns null
*/
function initMap() {
'use strict';
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 41.76034899999998,
lng: -72.67540800000003
},
zoom: 13
});
infowindow = new google.maps.InfoWindow();
var myModel = new ViewModel();
ko.applyBindings(myModel);
//responsive code to ensure Google Map is
//always re-centered if re-sized.
google.maps.event.addDomListener(window, 'resize', function() {
var center = map.getCenter();
google.maps.event.trigger(map, 'resize');
map.setCenter(center);
});
$(window).resize(function() {
if ($(window).width() < 600)
myModel.showMenuIcon(true);
else
myModel.showMenuIcon(false);
});
if ($(window).width() < 600)
myModel.showMenuIcon(true);
else
myModel.showMenuIcon(false);
}
/**
* @description: Error Handler for Google Map API call
* @returns null
*/
function mapErrorHandler() {
document.getElementById("map").innerHTML = "<b>Google Map is not available at this time. Please try again later.</b>";
}
/**
* @description: Model section
*/
var LocationSpot = function(data) {
'use strict';
this.name = ko.observable(data.name);
this.location = ko.observable(data.location);
this.selected = ko.observable(false);
// creating the Google marker and making it as part of this model
var mapmarker = new google.maps.Marker({
position: data.location,
title: data.name,
map: map
});
mapmarker.addListener('click', (function(thisCopy) {
return function() {
thisCopy.displayYelpInfo();
};
})(this));
this.marker = mapmarker;
};
/**
* @description Asynchronous API call to Yelp and display in infowindow
* @returns null
*/
LocationSpot.prototype.displayYelpInfo = function() {
'use strict';
// "this" is the current instance inside this function
var self = this;
//Yelp requires OAuth authentication. Use oauth.js and sha1.js to
//authenticate using the token provided by Yelp.
var accessor = {
consumerSecret: auth.consumerSecret,
tokenSecret: auth.accessTokenSecret
};
var location = self.location().lat + ',' + self.location().lng;
var parameters = [];
parameters.push(['term', self.name()]);
parameters.push(['ll', location]);
parameters.push(['callback', 'cb']);
parameters.push(['oauth_consumer_key', auth.consumerKey]);
parameters.push(['oauth_consumer_secret', auth.consumerSecret]);
parameters.push(['oauth_token', auth.accessToken]);
parameters.push(['oauth_signature_method', 'HMAC-SHA1']);
var message = {
'action': 'http://api.yelp.com/v2/search',
'method': 'GET',
'parameters': parameters
};
var htmlcontent = '';
OAuth.setTimestampAndNonce(message);
OAuth.SignatureMethod.sign(message, accessor);
var parameterMap = OAuth.getParameterMap(message.parameters);
map.panTo(self.location());
//use global infowindow variable so that there's only 1 instance of infowindow open at a time.
if (infowindow) {
infowindow.close();
}
infowindow.setContent('Loading...');
infowindow.open(map, self.marker);
$.ajax({
'url': message.action,
'data': parameterMap,
'dataType': 'jsonp',
'cache': true
}).done(function(data) {
htmlcontent = '<a href="' + data.businesses[0].url + '" target="_blank"><h4 style="margin:0;">' + data.businesses[0].name + '</h4></a>';
htmlcontent += '<img src="' + data.businesses[0].rating_img_url + '" alt="Yelp Rating" height="17" width="84"> ' + data.businesses[0].review_count + ' Yelp Reviews <br>';
htmlcontent += data.businesses[0].location.display_address[0] + '<br>' + data.businesses[0].location.display_address[2] + '<br>' + data.businesses[0].display_phone;
infowindow.setContent(htmlcontent);
}).fail(function(jqXHR, textStatus) {
infowindow.setContent('Error loading Yelp review.');
});
self.selectMarker();
infowindow.addListener('closeclick', function() {
self.unselectMarker();
});
//will automatically close all infowindow, animation and highlight if click anywhere in the map
google.maps.event.addListener(map, 'click', function() {
if (infowindow) {
infowindow.close();
self.unselectMarker();
}
});
//will automatically stop the animation and unhighlight the item from list view after 3 bounce (700ms per bounce)
window.setTimeout(function() {
self.unselectMarker();
}, 2100); //
};
/**
* @description: LocationSpot selectMarker method will bounce the marker and highlight the item from the list view
* @returns null
*/
LocationSpot.prototype.selectMarker = function() {
// "this" is the current instance inside this function
var self = this;
self.marker.setAnimation(google.maps.Animation.BOUNCE);
self.selected(true);
};
/**
* @description: this will stop the animation and unhighlight the item from the list view
* @returns null
*/
LocationSpot.prototype.unselectMarker = function() {
// "this" is the current instance inside this function
var self = this;
self.marker.setAnimation(null);
self.selected(false);
};
/**
* @description: ViewModel section
*/
var ViewModel = function() {
'use strict';
var self = this;
self.locationList = ko.observableArray([]);
self.showMenuIcon = ko.observable(false);
//Load the default data into observablearray.
initlocation.forEach(function(data) {
self.locationList.push(new LocationSpot(data));
});
//Create a filtereddata based on the search query.
//will make the marker visible or not based on the search query.
self.query = ko.observable('');
self.filtereddata = ko.computed(function() {
var filter = self.query().toLowerCase();
if (!filter) {
self.locationList().forEach(function(data) {
if (data.hasOwnProperty('marker')) {
data.marker.setVisible(true);
}
});
return self.locationList();
} else {
return ko.utils.arrayFilter(self.locationList(), function(item) {
if (item.name().toLowerCase().indexOf(filter) !== -1) {
item.marker.setVisible(true);
return true;
} else {
item.marker.setVisible(false);
return false;
}
});
}
});
// this will be called by the data-bind click event if the list item is clicked
self.clickListitem = function(data) {
//var infowindow = new google.maps.InfoWindow;
data.displayYelpInfo();
};
self.clickMain = function(data) {
var drawer = document.querySelector('#drawer');
drawer.classList.remove('open');
};
self.clickMenu = function(data, e) {
var drawer = document.querySelector('#drawer');
drawer.classList.toggle('open');
e.stopPropagation();
};
};
|
// var BCLS_learning_paths = (function (window, document) {
// var thisWindow = window,
// learning_path_wrapper = document.createElement('nav'),
// learning_path_item,
// span,
// shortLink = document.querySelector('link[rel="shortlink"]'),
// nodePath = shortLink.getAttribute('href'),
// thisNode = nodePath.substring(nodePath.lastIndexOf('/') + 1),
// body = document.querySelector('body'),
// surveyDiv = document.getElementById('surveyDiv');
// if (learning_path) {
// var i,
// iMax = learning_path.length,
// item,
// h4,
// a;
// learning_path_wrapper.classList.add('learning-path-wrapper');
// h4 = document.createElement('h4');
// h4.textContent = 'Learning Path';
// learning_path_wrapper.appendChild(h4);
// for (i = 0; i < iMax; i++) {
// item = learning_path[i];
// learning_path_item = document.createElement('div');
// learning_path_item.classList.add('learning-path-item');
// learning_path_wrapper.appendChild(learning_path_item);
// if (thisNode === item.node) {
// learning_path_item.classList.add('selected');
// learning_path_item.textContent = item.title;
// } else {
// a = document.createElement('a');
// a.setAttribute('href', '/node/' + item.node);
// a.textContent = item.title;
// learning_path_item.appendChild(a);
// }
// if (i < (iMax - 1)) {
// span = document.createElement('span');
// span.classList.add('learning-path');
// span.textContent = '|';
// learning_path_wrapper.appendChild(span);
// }
// }
// body.appendChild(learning_path_wrapper);
// }
// thisWindow.addEventListener('resize', function () {
// if (window.innerWidth < 1300) {
// learning_path_wrapper.setAttribute('style', 'visibility:hidden');
// if (surveyDiv) {
// surveyDiv.setAttribute('style', 'visibility:hidden');
// }
// } else {
// learning_path_wrapper.removeAttribute('style');
// if (surveyDiv) {
// surveyDiv.removeAttribute('style');
// }
// }
// });
// })(window, document);
|
var _ = require('underscore');
// Visits every state per continent and attaches to the state a class
// representing the continent the state pertains to.
function set_continents() {
// Organize each country into a set of geographic locations. Each country
// belongs in at most one category, as the classes are unable to magically
// hybridize.
var continents = {
africa: [
'ag', 'ao', 'bc', 'bn', 'by', 'cd', 'cf', 'cg',
'cm', 'cn', 'ct', 'cv', 'dj', 'eg', 'ek', 'er',
'et', 'ga', 'gb', 'gh', 'gv', 'iv', 'ke', 'li',
'lt', 'ly', 'ma', 'mi', 'ml', 'mo', 'mp', 'mr',
'mz', 'ng', 'ni', 'od', 'pu', 'rw', 'se', 'sf',
'sg', 'sh', 'sl', 'so', 'su', 'to', 'tp', 'ts',
'tz', 'ug', 'uv', 'wa', 'wi', 'wz', 'za', 'zi'
],
central_asia: [
'kg', 'kz', 'rs', 'ti', 'tx', 'uz'
],
south_asia: [
'af', 'bg', 'bt', 'ce', 'in', 'mv', 'np', 'pk'
],
east_asia: [
'bm', 'bx', 'cb', 'ch', 'id', 'ja', 'kn', 'ks', 'la',
'mg', 'my', 'pp', 'rp', 'sn', 'th', 'tt', 'tw', 'vm'
],
europe: [
'al', 'an', 'au', 'be', 'bk', 'bo', 'bu', 'cy', 'da',
'ei', 'en', 'ez', 'fi', 'fo', 'fr', 'gi', 'gk', 'gm',
'gr', 'hr', 'hu', 'ic', 'im', 'it', 'je', 'lg', 'lh',
'lo', 'ls', 'lu', 'md', 'mj', 'mk', 'mn', 'mt', 'nl',
'no', 'pl', 'po', 'ri', 'ro', 'si', 'sm', 'sp', 'sw',
'sz', 'uk', 'up'
],
middle_east: [
'ae', 'aj', 'am', 'ba', 'gg', 'gz', 'ir', 'is', 'iz',
'jo', 'ku', 'le', 'mu', 'qa', 'sa', 'sy', 'tu', 'we',
'ym'
],
north_america: [
'bd', 'ca', 'gl', 'mx', 'sb', 'us'
],
central_america: [
'aa', 'ac', 'av', 'bb', 'bf', 'bh', 'cj', 'cs',
'cu', 'do', 'dr', 'es', 'gj', 'gt', 'ha', 'ho',
'jm', 'mh', 'nu', 'pm', 'rn', 'rq', 'sc', 'st',
'tb', 'td', 'tk', 'vc', 'vi', 'vq'
],
south_america: [
'ar', 'bl', 'br', 'ci', 'co', 'ec', 'fg', 'fk',
'gy', 'ns', 'pa', 'pe', 'uy', 've'
],
// Oceania //
oceania: [
'aq', 'as', 'bp', 'cq', 'cw', 'fj', 'fm', 'fp',
'gq', 'kr', 'nc', 'ne', 'nh', 'nr', 'nz', 'pc',
'ps', 'rm', 'tn', 'tv', 'wf', 'ws'
]
};
// Loop through all the countries and add the continent id to each
// country's svg element
_(continents).each(function (countries, continent) {
_(countries).each(function (country) {
$('#' + country).attr({
'class': country + ' ' + continent
});
});
});
}
set_continents();
|
export const YOUTUBE_API_KEY = 'AIzaSyB3rCpN08ZRMfnjExT6_FJ45bqauDEhbsA';
|
var realm = require("realm-js")
var mongo = require('mongodb');
var Promise = require("promise");
var Connection;
var MONGO_DB_NAME = 'editor_test';
var MONGO_URI = 'mongodb://localhost:27017/' + MONGO_DB_NAME
if (process.env.MONGO_PORT_27017_TCP_ADDR) {
MONGO_URI = 'mongodb://' + process.env.MONGO_PORT_27017_TCP_ADDR + ':' + process.env.MONGO_PORT_27017_TCP_PORT + '/' +
MONGO_DB_NAME
}
// Resolving connection
realm.service("$realmMongoConnection", function() {
return new Promise(function(resolve, reject) {
if (Connection) {
return resolve(Connection);
}
console.log("connecting", MONGO_URI)
mongo.MongoClient.connect(MONGO_URI, {
server: {
auto_reconnect: true
}
}, function(err, _db) {
if (err) {
return reject(err);
}
Connection = _db;
return resolve(Connection);
})
})
});
|
describe('initialize', () => {
test('Should warn if interactionLoaded method not found', () => {
console.warn = jest.fn().mockName('console.warn')
require('./')
expect(console.warn).toBeCalledWith('interactionLoaded callback is not defined')
})
})
|
function get_content() {
$.getScript(media_url+'js/aux/date.js');
$.getScript(media_url+'js/aux/journeys.js');
var meses=['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'];
var owner_id="";
$.post('partials/invoicing_driver', function(template, textStatus, xhr) {
$('#accordion_wait').html('<div class="waiting"><i class="fa fa-cog fa-spin"></i></div>');
$('#main').html(template);
$.getJSON(api_url+'drivers/get?callback=?', '', function(data2){
if(data2.status=='success'){
owner_id=data2.data.owner_profile.id;
}else{
super_error('Data failure');
}
$.getJSON(api_url+'invoices/list_by_owner?callback=?&owner_id='+owner_id, '', function(data3){
if(data3.status=='success'){
var panelA=$('<div><h4>Facturas Taxible Servicios: </h4></div>').attr('id','invoicing_accordion_invoices');
$('#invoicing_accordion').append(panelA);
var panelB=$('<div><h4>Autofacturas: </h4></div>').attr('id','invoicing_accordion_autoinvoices');
$('#invoicing_accordion').append(panelB);
panelA.hide();
panelB.hide();
for(var i=0; i<data3.data.invoices.length; i++){
panelA.show();
var panel=$('<div></div>').attr('class','panel panel-default'); $('#invoicing_accordion_invoices').append(panel);
var heading=$('<div></div>').attr('class','panel-heading panel-heading-invoice invoice-padding');
panel.append(heading);
var div_h4=$('<div></div>').attr('class','responsive-title margin_yes col-md-9');
var title=$('<h4></h4>').attr('class','panel-title');
div_h4.append(title);
heading.append(div_h4);
var toggle=$('<span></span>').attr({'class':'accordion-toggle','data-toggle':'collapse', 'data-parent':'#invoicing_accordion'}).text(meses[data3.data.invoices[i].month-1]+' '+data3.data.invoices[i].year+' - '+data3.data.invoices[i].num_invoice_complete+' - '+data3.data.invoices[i].amount+' '+data3.data.invoices[i].currency_delgation);
title.append(toggle);
var button_div=$('<div></div>').attr({'class':'responsive-button col-md-2'})
var location = "location.href=\""+data3.data.invoices[i].url_pdf+"\"";
var button=$('<button></button>').attr({'onclick':location, 'type':'button', 'class':'responsive-btn btn btn-default'}).text('Descargar en PDF');
button_div.append(button);
heading.append(button_div);
}
for(var i=0; i<data3.data.autoinvoices.length; i++){
panelB.show();
var panel=$('<div></div>').attr('class','panel panel-default'); $('#invoicing_accordion_autoinvoices').append(panel);
var heading=$('<div></div>').attr('class','panel-heading panel-heading-invoice invoice-padding');
panel.append(heading);
var div_h4=$('<div></div>').attr('class','responsive-title margin_yes col-md-9');
var title=$('<h4></h4>').attr('class','panel-title');
div_h4.append(title);
heading.append(div_h4);
var toggle=$('<span></span>').attr({'class':'accordion-toggle','data-toggle':'collapse', 'data-parent':'#invoicing_accordion'}).text(meses[data3.data.autoinvoices[i].month-1]+' '+data3.data.autoinvoices[i].year+' - '+data3.data.autoinvoices[i].num_invoice_complete+' - '+data3.data.autoinvoices[i].amount+' '+data3.data.autoinvoices[i].currency_delgation);
title.append(toggle);
var button_div=$('<div></div>').attr({'class':'responsive-button col-md-2'})
var location = "location.href=\""+data3.data.autoinvoices[i].url_pdf+"\"";
var button=$('<button></button>').attr({'onclick':location, 'type':'button', 'class':'responsive-btn btn btn-default'}).text('Descargar en PDF');
button_div.append(button);
heading.append(button_div);
}
}else super_error('Data failure');
if(data3.data.invoices.length==0 && data3.data.autoinvoices.length==0){
var panel=$('<div></div>').attr('class','panel panel-default'); $('#invoicing_accordion').append(panel);
var heading=$('<div></div>').attr('class','panel-heading panel-heading-invoice');
panel.append(heading);
var title=$('<h4></h4>').attr('class','panel-title');
heading.append(title);
var toggle=$('<span></span>').attr({'class':'accordion-toggle','data-toggle':'collapse', 'data-parent':'#invoicing_accordion'}).text('No existen facturas');
title.append(toggle);
}
});
});
});
$('#accordion_wait').hide();
}
|
const app =getApp()
Page({
data: {
show: false,
status: 1,
date: '请选择月份',
month: null,
payable_salary: null,
real_salary: null,
deductions: null,
borrowing: null,
accident_insurance: null,
taxes: null,
subsidies: null,
status: null
},
goToPage: function () {
// wx.navigateTo({
// url: '/pages/shaixuan/index?type=gongzitiao'
// })
},
selectDate(e) {
let str = e.detail.value.split('-')
this.setData({
date: str[0] + '年' + str[1] + '月',
month: e.detail.value
})
app.fun.post('/user/salaryDetail', {
send_month: this.data.month
}).then((res) => {
if (res.result) {
this.setData({
show: true,
payable_salary: res.result.payable_salary,
real_salary: res.result.real_salary,
deductions: res.result.deductions,
borrowing: res.result.borrowing,
accident_insurance: res.result.accident_insurance,
taxes: res.result.taxes,
subsidies: res.result.subsidies,
status: res.result.status
})
}
})
}
})
|
module.exports = {
devServer: {
proxy: {
'*': {
target:'http://47.92.173.68/',
ws:true,
changOrigin:true,
pathRewrite:{
// '^/renren-security':'/renren-security'
}
}
}
}
};
|
var confirmBooking = document.getElementById("confirm-booking");
if (confirmBooking) {
var loading = document.getElementById("loading");
var confirmView = document.getElementById("confirm-view");
confirmBooking.addEventListener("click", (event) => {
confirmView.classList.add("hidden");
loading.classList.remove("hidden");
confirmBooking.classList.add("hidden");
});
}
|
export default class CountdownTimer {
constructor({ selector, targetDate }) {
this.targetDate = new Date(targetDate);
this.daysSpan = document.querySelector(
`${selector} .value[data-value="days"]`,
);
this.hoursSpan = document.querySelector(
`${selector} .value[data-value="hours"]`,
);
this.minutesSpan = document.querySelector(
`${selector} .value[data-value="mins"]`,
);
this.secondsSpan = document.querySelector(
`${selector} .value[data-value="secs"]`,
);
}
padtime(value) {
return value.toString().padStart(2, '0');
}
countDowm() {
const currentTime = new Date();
this.getTimeComponents(currentTime);
// console.log(currentTime);
}
showTime() {
setInterval(() => this.countDowm(), 1000);
}
getTimeComponents(currentTime) {
const time = this.targetDate - currentTime;
this.secondsSpan.textContent = this.padtime(Math.floor((time / 1000) % 60));
this.minutesSpan.textContent = this.padtime(
Math.floor((time / 1000 / 60) % 60),
);
this.hoursSpan.textContent = this.padtime(
Math.floor((time / (1000 * 60 * 60)) % 24),
);
this.daysSpan.textContent = this.padtime(
Math.floor(time / (1000 * 60 * 60 * 24)),
);
}
}
|
const exp = require('express')
const cors = require('cors');
const app = exp();
app.use(cors())
app.get('/getInput', (req,res) => {
res.send(req.query);
})
app.listen(9000)
console.log('listening')
|
import Ember from 'ember';
export default Ember.Route.extend({
i18n: Ember.inject.service(),
init(){
//this.controller.set("title-list",this.get('i18n').t('category.list-product.list-all-products-of'));
},
model(params){
if(params.category_id){
//GET to api/products/?filter[products][status]=A&filter[categories][categoryId]=3&sort[products][productName]=asc
return this.get('store').query('product', {
filter: {
categories:{
categoryId: params.category_id
},
products:{
status: 'A'
},
},
sort:{
products:{
productName: 'asc'
}
}
});
}
}
});
|
module.exports = (sequelize, DataTypes) => {
const Merchant = sequelize.define('Merchant', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
username: {
type: DataTypes.STRING,
unique: true
},
email: {
type: DataTypes.STRING,
unique: true
},
password: DataTypes.STRING,
firstname: DataTypes.STRING,
lastname: DataTypes.STRING,
address: DataTypes.TEXT,
province: DataTypes.STRING,
postcode: DataTypes.STRING,
mobile: DataTypes.STRING,
remember_token: {
type: DataTypes.STRING,
allowNull: true
},
createdAt: DataTypes.DATE,
updatedAt: DataTypes.DATE,
deletedAt: DataTypes.DATE
})
Merchant.associate = function(models) {
// models.Merchant.hasMany(models.Item, {foreignKey: 'merchantId'})
// models.Merchant.hasMany(models.Shipping, {foreignKey: 'merchantId'})
// models.Merchant.hasMany(models.Order, {foreignKey: 'merchantId'})
// models.Merchant.hasMany(models.Confirm_Payment, {foreignKey: 'merchantId'})
}
return Merchant
}
|
import Page from "../../components/page";
import dialogs from "../../components/dialogs";
import constants from "../../constants";
import tag from 'html-tag-js';
import gen from "../../components/gen";
export default function themeSettings() {
const page = Page(strings.theme);
const settingsList = tag('div', {
className: 'main list'
});
actionStack.push({
id: 'settings-theme',
action: page.hide
});
page.onhide = function () {
actionStack.remove('settings-theme');
};
const values = appSettings.value;
const settingsOptions = [{
key: 'editor',
text: strings['editor theme'],
subText: values.editorTheme.split('/').slice(-1)[0].replace(/_/g, ' '),
},
{
key: 'app',
text: strings['app theme'],
subText: values.appTheme
}
];
gen.listItems(settingsList, settingsOptions, changeSetting);
function changeSetting() {
const editor = editorManager.editor;
const themeList = [];
constants.themeList.map(theme => {
themeList.push([theme, theme.replace(/_/g, ' ')]);
});
switch (this.key) {
case 'editor':
dialogs.select(this.text, themeList, {
default: values.editorTheme.split('/').slice(-1)[0]
}).then(res => {
const theme = `ace/theme/` + res;
if (editor) editor.setTheme(theme);
appSettings.value.editorTheme = theme;
appSettings.update();
this.changeSubText(res.replace(/_/g, ' '));
});
break;
case 'app':
dialogs.select(this.text, [
'default', 'light', 'dark'
], {
default: appSettings.value.appTheme
})
.then(res => {
if (res === 'dark' && /(free)$/.test(BuildInfo.packageName)) {
window.open('https://play.google.com/store/apps/details?id=com.foxdebug.acode', '_system');
return;
}
appSettings.value.appTheme = res;
appSettings.update();
window.restoreTheme();
this.changeSubText(res);
});
break;
default:
break;
}
}
page.appendChild(settingsList);
document.body.append(page);
}
|
console.log('adicionando arquivo pelo site');
|
function englishLevelsQuery() {
return 'SELECT * FROM english_lvl';
}
function locationQuery() {
return 'SELECT * FROM location';
}
function skillsQuery() {
return 'SELECT * FROM skills';
} /* LIMIT 20*/
function candidateStatusesQuery() {
return 'SELECT * FROM candidate_status';
}
function otherSkillsQuery() {
return 'SELECT * FROM other_skills';
}
function vacancyStatusesQuery() {
return 'SELECT * FROM vacancy_status';
}
module.exports = {
englishLevelsQuery,
locationQuery,
skillsQuery,
candidateStatusesQuery,
otherSkillsQuery,
vacancyStatusesQuery,
};
|
import Ember from 'ember';
import redux from 'redux';
import reducers from '../reducers/index';
import enhancers from '../enhancers/index';
import middlewareConfig from '../middleware/index';
const { assert, isArray } = Ember;
// Handle "classic" middleware exports (i.e. an array), as well as the hash option
const extractMiddlewareConfig = (mc) => {
assert(
'Middleware must either be an array, or a hash containing a `middleware` property',
isArray(mc) || mc.middleware
);
return isArray(mc) ? { middleware: mc } : mc;
}
// Destructure the middleware array and the setup thunk into two different variables
const { middleware, setup = () => {} } = extractMiddlewareConfig(middlewareConfig);
var { createStore, applyMiddleware, combineReducers, compose } = redux;
var createStoreWithMiddleware = compose(applyMiddleware(...middleware), enhancers)(createStore);
export default Ember.Service.extend({
init() {
const reducer = typeof reducers === 'function' ? reducers : combineReducers(reducers);
this.store = createStoreWithMiddleware(reducer);
setup(this.store);
this._super(...arguments);
},
getState() {
return this.store.getState();
},
dispatch(action) {
return this.store.dispatch(action);
},
subscribe(func) {
return this.store.subscribe(func);
},
replaceReducer(nextReducer) {
return this.store.replaceReducer(nextReducer);
}
});
|
import './App.css';
import Header from './Components/Header/Header';
import Title from './Components/Title/title';
import Filter from './Components/Main-body/Filter/Filters';
import Expert from './Components/Main-body/Experts/Expert';
function App() {
return (
<div className="App">
<Header />
<div className="App-body">
<Title />
<div className="Content">
<Filter />
<Expert />
</div>
</div>
</div>
);
}
export default App;
|
let _ = require('lodash');
module.exports = function () {
let def = require("./app.json"),
rs = _.cloneDeep(def),
env = process.env.NODE_ENV ? process.env.NODE_ENV : 'development';
if (env !== 'development') {
if (def[env]) {
rs.db = def[env].db;
}
}
rs['production'] && delete rs['production'];
rs['test'] && delete rs['test'];
rs.path = {
views: `${__dirname}/../${rs.views}/`,
models: `${__dirname}/../${rs.models}/`,
logs: `${__dirname}/../${rs.logs}/`,
public: `${__dirname}/../${rs.public}/`,
resource: `${__dirname}/../${rs.resource}`
};
return rs;
}();
|
import React from 'react';
import Payment from './';
import { createMemoryHistory } from 'history'
import { Router } from 'react-router-dom'
import Routes from '../index'
import { render, cleanup, screen, fireEvent, waitFor, findByLabelText, wait } from '../../test-utils'
beforeAll(cleanup)
describe('<Payment />', () => {
it('renders Loading', () => {
const { getByText } = render(<Payment />)
const linkElement = getByText(/carregando.../i)
expect(linkElement).toBeInTheDocument()
})
it('renders Component after Loading', async () => {
const { getByTestId } = render(<Payment />)
await waitFor(() => {
expect(getByTestId('payment')).toBeInTheDocument()
})
})
it('Send Form data', async () => {
const history = createMemoryHistory()
const { getByText, getByTestId, queryByTestId } = render(
<Router history={history}>
<Payment />
</Router>
)
await waitFor(() => getByTestId('form'));
const form = getByTestId('form')
const cardNumber = getByTestId('input-cardNumber')
const cardName = getByTestId('input-cardName')
const cardExpiress = getByTestId('input-cardExpiress')
const cvv = getByTestId('input-cvv')
const button = getByText(/FINALIZAR O PEDIDO/i);
await wait(() => fireEvent.change(cardNumber, { target: { value: '12344567890987654' } }))
await wait(() => fireEvent.change(cardName, { target: { value: 'Meu Nome' } }))
await wait(() => fireEvent.change(cardExpiress, { target: { value: '12/2021' } }))
await wait(() => fireEvent.change(cvv, { target: { value: '123' } }))
await wait(() => fireEvent.click(button))
expect(queryByTestId("input-error")).toBe(null);
})
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.