text
stringlengths 7
3.69M
|
|---|
export const data = [
{
name: 'Jan',
"Active users": 1500,
},
{
name: 'Feb',
"Active users": 1800,
},
{
name: 'Mar',
"Active users": 2300,
},
{
name: 'April',
"Active users": 2800,
},
{
name: 'May',
"Active users": 4250,
},
{
name: 'Jun',
"Active users": 4000,
},
{
name: 'July',
"Active users": 4000,
},
{
name: 'Aug',
"Active users": 4000,
},
{
name: 'Sep',
"Active users": 2500,
},
{
name: 'Oct',
"Active users": 5000,
},
{
name: 'Nov',
"Active users": 1520,
},
{
name: 'Dec',
"Active users": 9055,
}
];
export const UserRows = [
{
id: 1,
userName: "John gathuita",
avatar: "https://lh3.googleusercontent.com/ogw/ADea4I5Zmq8Da4GL7w1Bi0NPQTomAbVrc6oMrn_pZiEugw=s32-c-mo",
email: "jon@mail.com",
status: "active",
transaction: "ksh. 1200"
},
{
id: 2,
userName: "Kennedy Muia",
avatar: "https://lh3.googleusercontent.com/ogw/ADea4I5Zmq8Da4GL7w1Bi0NPQTomAbVrc6oMrn_pZiEugw=s32-c-mo",
email: "ken@mail.com",
status: "active",
transaction: "ksh. 2000"
},
{
id: 3,
userName: "Kevin Saiyalel",
avatar: "https://lh3.googleusercontent.com/ogw/ADea4I5Zmq8Da4GL7w1Bi0NPQTomAbVrc6oMrn_pZiEugw=s32-c-mo",
email: "kev@mail.com",
status: "active",
transaction: "ksh. 800"
},
{
id: 4,
userName: "Brandon Leiyan",
avatar: "https://lh3.googleusercontent.com/ogw/ADea4I5Zmq8Da4GL7w1Bi0NPQTomAbVrc6oMrn_pZiEugw=s32-c-mo",
email: "brandon@mail.com",
status: "active",
transaction: "ksh. 2500"
},
{
id: 5,
userName: "Brandon Leiyan",
avatar: "https://lh3.googleusercontent.com/ogw/ADea4I5Zmq8Da4GL7w1Bi0NPQTomAbVrc6oMrn_pZiEugw=s32-c-mo",
email: "brandon@mail.com",
status: "active",
transaction: "ksh. 2500"
},
{
id: 6,
userName: "Brandon Leiyan",
avatar: "https://lh3.googleusercontent.com/ogw/ADea4I5Zmq8Da4GL7w1Bi0NPQTomAbVrc6oMrn_pZiEugw=s32-c-mo",
email: "brandon@mail.com",
status: "active",
transaction: "ksh. 2500"
},
{
id: 7,
userName: "Brandon Leiyan",
avatar: "https://lh3.googleusercontent.com/ogw/ADea4I5Zmq8Da4GL7w1Bi0NPQTomAbVrc6oMrn_pZiEugw=s32-c-mo",
email: "brandon@mail.com",
status: "active",
transaction: "ksh. 2500"
},
{
id: 8,
userName: "Brandon Leiyan",
avatar: "https://lh3.googleusercontent.com/ogw/ADea4I5Zmq8Da4GL7w1Bi0NPQTomAbVrc6oMrn_pZiEugw=s32-c-mo",
email: "brandon@mail.com",
status: "active",
transaction: "ksh. 2500"
},
];
|
/**
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.provide('audioCat.state.editMode.SectionSplitMode');
goog.require('audioCat.state.command.SplitSectionCommand');
goog.require('audioCat.state.editMode.EditMode');
goog.require('audioCat.state.editMode.EditModeName');
/**
* The edit mode in which the user can split sections.
* @param {!audioCat.ui.window.ScrollResizeManager} scrollResizeManager
* Manages and responds to resizing and scrolling.
* @param {!audioCat.state.command.CommandManager} commandManager Manages the
* history of commands, thus allowing for undo/redo.
* @param {!audioCat.utility.IdGenerator} idGenerator Generates IDs unique
* throughout the application.
* @constructor
* @extends {audioCat.state.editMode.EditMode}
*/
audioCat.state.editMode.SectionSplitMode = function(
scrollResizeManager,
commandManager,
idGenerator) {
goog.base(this, audioCat.state.editMode.EditModeName.SPLIT_SECTION);
/**
* Manages and responds to resizing and scrolling.
* @private {!audioCat.ui.window.ScrollResizeManager}
*/
this.scrollResizeManager_ = scrollResizeManager;
/**
* Manages the history of commands.
* @private {!audioCat.state.command.CommandManager}
*/
this.commandManager_ = commandManager;
/**
* Generates IDs unique throughout the application.
* @private {!audioCat.utility.IdGenerator}
*/
this.idGenerator_ = idGenerator;
/**
* A list of selected sections.
* @private {!Array.<!audioCat.state.Section>}
*/
this.selectedSections_ = [];
};
goog.inherits(
audioCat.state.editMode.SectionSplitMode, audioCat.state.editMode.EditMode);
/**
* Splits a section at a certain time into the section. Issues a command for it.
* Only splits a section if the clip happens to be big enough.
* @param {audioCat.state.Section} section The section to split.
* @param {number} splitTime The time in seconds into the section to split.
*/
audioCat.state.editMode.SectionSplitMode.prototype.splitSection =
function(section, splitTime) {
var accumulatedClipTime = 0;
var numberOfClips = section.getNumberOfClips();
var clipIndex = 0;
var clip;
var clipDuration;
var sampleRate = section.getSampleRate();
// Multiply by playback rate to account for variation in speed.
splitTime *= section.getPlaybackRate();
while (accumulatedClipTime <= splitTime) {
clip = section.getClipAtIndex(clipIndex);
if (!clip) {
// The clip could be undefined if the user keeps splitting the section
// into tiny chunks.
break;
}
clipDuration = (clip.getRightSampleBound() - clip.getBeginSampleIndex()) /
sampleRate;
accumulatedClipTime += clipDuration;
++clipIndex;
}
--clipIndex;
if (clip) {
// Sometimes, if the user eratically splits a section into very minute
// slices, the clip could be undefined. Then, don't split it.
var sectionBeginTime = section.getBeginTime();
var clipSplitBeginSampleIndex = clip.getBeginSampleIndex();
var clipSplitIntoSampleIndexDelta = Math.round(splitTime * sampleRate);
var audioChest = section.getAudioChest();
var sectionName = section.getName();
var playbackRate = section.getPlaybackRate();
var idGenerator = this.idGenerator_;
var newSection1 = new audioCat.state.Section(
idGenerator, audioChest, sectionName + ' 1', sectionBeginTime,
undefined, undefined, playbackRate);
// Add all the initial unsplit clips into the first new section.
for (var i = 0; i < clipIndex; ++i) {
newSection1.addClip(section.getClipAtIndex(i));
}
// Create a new clip.
var splitClipSplitSampleLocation =
clipSplitBeginSampleIndex + clipSplitIntoSampleIndexDelta;
newSection1.addClip(new audioCat.state.Clip(
idGenerator, clipSplitBeginSampleIndex, splitClipSplitSampleLocation));
var newSection2 = new audioCat.state.Section(
idGenerator, audioChest, sectionName + ' 2',
sectionBeginTime + newSection1.getDuration(), undefined, undefined,
playbackRate);
newSection2.addClip(new audioCat.state.Clip(
idGenerator, splitClipSplitSampleLocation, clip.getRightSampleBound()));
for (var i = clipIndex + 1; i < numberOfClips; ++i) {
newSection2.addClip(section.getClipAtIndex(i));
}
this.commandManager_.enqueueCommand(
new audioCat.state.command.SplitSectionCommand(
this.scrollResizeManager_,
section,
newSection1,
newSection2,
this.idGenerator_));
}
};
|
/* eslint-disable no-useless-constructor */
/* eslint-disable no-unused-vars */
import React, { Component } from "react";
class Footer extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="footer">
<span>
<span className="pendingTasks"></span>{" "}
{this.props.total !== 0 ? (
<p>pending tasks</p>
) : (
<p>You don't have pending tasks</p>
)}
</span>
<button className="footer-button" onClick={this.props.clearAll}>
Clear All
</button>
</div>
);
}
}
export default Footer;
|
/**
* Created by timothy on 27/05/16.
*/
function P3 (hook) {
this.D3 = d3.select("."+hook);
this.width = 0;
this.height = 0;
this.backgroundColour = d3.rgb(0, 0, 0);
this.fillColour = d3.rgb(0,0,0);
this.shapes = {};
}
P3.prototype = {
constructor: P3,
resize:function (x,y) {
this.D3.attr("width", x).attr("height", y);
this.width = x;
this.height = y; },
background:function (r,g,b) {
this.backgroundColour = d3.rgb(r,g,b);
this.D3.append("rect").attr("x",0).attr("y",0).attr("width", this.width).attr("height", this.height).attr("fill", this.backgroundColour);
},
fill : function(r,g,b) {
this.fillColour = d3.rgb(r,g,b);
},
rect: function(w,h,x,y,mode) {
if (mode == "centre") {
px = (x) - w / 2;
py = (y) - h / 2;
} else {
px = x;
py = y;
}
rect = this.D3.append("rect").attr("x", px).attr("y", py).attr("width", w).attr("height", h).attr("fill", this.fill);
var newPos = this.shapes.push(rect);
return newPos;
},
mousemove: function(func) {
this.D3.on('mousemove', function() {
console.log(this.D3.node());
this.mouseX = d3.mouse(this.D3.node())[0];
this.mouseY = d3.mouse(this.D3.node())[1];
func();
}.bind(this))}
};
|
import serverless from 'serverless-http'
import Koa from 'koa';
import Router from 'koa-router';
import bodyParser from 'koa-bodyparser';
const app = new Koa();
const router = new Router();
router.get('/', (ctx) => {
ctx.body = {"Message": "Hello World!!!!"};
});
app.use(bodyParser());
app.use(router.routes());
app.use(router.allowedMethods());
// app.listen(process.env.PORT, () => {
// console.log("Listening to PORT " + process.env.PORT);
// });
export const handler = serverless(app);
|
"use strict";
var React = require("react-native");
var { StyleSheet } = React;
module.exports = StyleSheet.create({
quizButton: {
margin: 5,
flex: 1,
borderRadius: 1,
backgroundColor: "#20B573",
alignItems: "center",
alignSelf: "stretch",
justifyContent: "center",
flexDirection: "column",
height: 50,
},
fullWidthButtonText: {
fontSize: 22,
color: "white",
},
backgroundImage: {
flex: 1,
resizeMode: "cover" // or 'stretch'
},
modalContent: {
backgroundColor: "white",
padding: 22,
justifyContent: "center",
alignItems: "center",
borderRadius: 4,
borderColor: "rgba(0, 0, 0, 0.1)"
}
});
|
import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { color, space, typography, compose } from 'styled-system';
import { createPropTypes } from '@styled-system/prop-types';
import { deprecate } from '../../helpers/propTypes';
const system = compose(color, space, typography);
const Styledlink = styled.a`
${system}
${props => {
if (props.disabled) {
return `
&, &:visited {
opacity: 0.6;
color: ${props.theme.colors.gray['900']};
pointer-events: none;
}
`;
}
}}
`;
const UnstyledLink = React.forwardRef(function UnstyledLink(props, ref) {
const {
children,
to,
title,
Component,
component,
as,
external,
onClick,
role,
disabled,
tabIndex,
...rest
} = props;
const WrapperComponent = as || component || Component;
const linkTitle = external && !title ? 'Opens in a new tab' : title;
const linkRole = role ? role : !!onClick ? 'button' : null;
const disabledAttributes = {
'aria-disabled': disabled,
disabled,
tabIndex: disabled ? '-1' : tabIndex,
onClick: disabled ? () => false : onClick,
};
if (to && !WrapperComponent) {
return (
<Styledlink
as="a"
href={to}
target={external ? '_blank' : ''}
rel={external ? 'noopener noreferrer' : ''}
title={linkTitle}
onClick={onClick}
role={role}
ref={ref}
{...rest}
{...disabledAttributes}
>
{children}
</Styledlink>
);
}
if (WrapperComponent) {
return (
<Styledlink
as={WrapperComponent}
onClick={onClick}
ref={ref}
role={role}
title={linkTitle}
to={to}
{...rest}
{...disabledAttributes}
>
{children}
</Styledlink>
);
}
return (
<Styledlink
as="a"
title={linkTitle}
role={linkRole}
onClick={onClick}
ref={ref}
{...rest}
{...disabledAttributes}
>
{children}
</Styledlink>
);
});
UnstyledLink.displayName = 'UnstyledLink';
UnstyledLink.propTypes = {
to: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
disabled: PropTypes.bool,
title: PropTypes.string,
external: PropTypes.bool,
component: deprecate(PropTypes.elementType, 'Use "as" instead'),
Component: deprecate(PropTypes.elementType, 'Use "as" instead'),
as: PropTypes.elementType,
children: PropTypes.node,
onClick: PropTypes.func,
role: PropTypes.string,
tabIndex: PropTypes.string,
...createPropTypes(color.propNames),
...createPropTypes(space.propNames),
...createPropTypes(typography.propNames),
};
export default UnstyledLink;
|
$(document).ready(function() {
// Catalog menu
$('#j-catalog__button').on('click', function() {
$('#j-catalog__nav.j-offcanvas').addClass('j-offcanvas--open');
});
// Page menu
$('#j-page__button').on('click', function() {
$('#j-page__nav.j-offcanvas').addClass('j-offcanvas--open');
});
$('#j-page__nav .level-1.parent > a').on('click', function(event) {
event.preventDefault();
});
/*if ($(window).width() <= 1024) {
$('#j-page__nav .level-1.parent > a').on('click', function(event) {
event.preventDefault();
});
}*/
// No click to tel
if ($(window).width() > 1024) {
$('a[href^="tel"]').on('click', function(event) {
event.preventDefault();
});
}
// Hidden offcanvas
$('.j-offcanvas').on('click', function() {
$('.j-offcanvas').removeClass('j-offcanvas--open');
});
$('.j-offcanvas__menu').on('click', function(event) {
event.stopPropagation();
});
});
|
// eslint-disable-next-line camelcase
import jwt_decode from 'jwt-decode';
export const isAuthenticated = () => {
const token = window.localStorage.getItem('access_token');
let decoded;
if (token) {
decoded = jwt_decode(token);
return new Date(decoded.exp * 1000) > new Date();
}
return false;
};
export const getBearerToken = () => ({
headers: {
Authorization: `Bearer ${window.localStorage.getItem('access_token')}`,
},
});
|
export const REQUEST_TYPE = {
CREDIT: "CREDIT",
DEBIT: "DEBIT"
};
export const REFERENCE_TYPE = {
purchaseOrder: {
value: "PURCHASE_ORDER",
display: "PO"
},
invoice: {
value: "INVOICE",
display: "Invoice"
},
others: {
value: "OTHERS",
display: "Others"
}
};
|
var Clapp = require('../modules/clapp-discord');
var jsonfile = require('jsonfile-promised');
var rpg = require('../rpg/player.js');
var playerDB = __dirname + "/../rpg/db/players.json";
module.exports = new Clapp.Command({
name: "rpg",
desc: "Plays the RPG game",
fn: (argv, context) => {
// This output will be redirected to your app's onReply function
if(argv.args.action == "mine") return mine(context.msg.author.username);
//TODO: change json object to have just Username: player not array
if(argv.flags.create) return create(context.msg.author.username);
if(argv.flags.info) return info(context.msg.author.username);
if(argv.flags.restart) return restart(context.msg.author.username);
return "Nothing happens";
},
args: [
{
name: 'action',
desc: 'Does the specified action',
type: 'string',
required: false,
default: ''
}
],
flags: [//adventure,skills,inventory,lvl-up
{
name: 'create',
desc: 'Create a new character',
alias: 'c',
type: 'boolean',
default: false
},
{
name: 'info',
desc: 'See your character\'s info',
alias: '?',
type: 'boolean',
default: false
},
{
name: 'restart',
desc: 'Delete your character from the database',
alias: 'r',
type: 'boolean',
default: false
}
]
});
function mine(name){
return jsonfile.readFile(playerDB).then((obj) => {
if(obj == undefined) return "There is no json created yet";
if(!hasPlayer(obj.players, name)) return "Player has not been created";
var plr = getPlayer(obj.players, name);
plr.gold += 10;
updatePlayer(obj, plr);
return "Went Mining and earned 10 gold";
}).catch((err) => {
console.log(err);
});
}
function create(name){
return jsonfile.readFile(playerDB).then((obj) => {
if(obj == undefined) return "There is no json created yet";
if(hasPlayer(obj.players, name)) return "Player already created";
var plr = new rpg.Player(name);
obj.players.push(plr);
jsonfile.writeFile(playerDB, obj).catch((err) => {
console.log(err);
});
return "Player Created: " + plr.toString();
}).catch((err) => {
console.log(err);
});
}
function info(name){
return jsonfile.readFile(playerDB).then((obj) => {
if(obj == undefined) return "There is no json created yet";
if(!hasPlayer(obj.players, name)) return "Player has not been created";
var plr = getPlayer(obj.players, name);
return plr.toString();
//return "Player: " + rpg.Player.prototype.toString().call(plr);
}).catch((err) => {
console.log(err);
});
}
function restart(name){
return jsonfile.readFile(playerDB).then((obj) => {
if(obj == undefined) return "There is no json created yet";
if(!hasPlayer(obj.players, name)) return "Player has not been created";
var plr = getPlayer(obj.players, name);
if(plr.restart == true){
var newPlayer = new rpg.Player(name);
updatePlayer(obj, newPlayer);
return "Player restarted";
}else{
plr.restart = true;
updatePlayer(obj, plr);
setTimeout(function(){
plr.restart = false;
updatePlayer(obj, plr);
}, 1000 * 60 * 1);
return "1min to !restart again to restart player";
}
}).catch((err) => {
console.log(err);
});
}
function hasPlayer(array, name){
var found = false;
array.forEach(function(element) {
if(element.name === name){
found = true;
}
});
return found;
}
function getPlayer(array, name){
var plr = {};
array.forEach(function(element) {
if(element.name === name){
plr = Object.assign(new rpg.Player(""), element);
}
});
return plr;
}
function updatePlayer(obj, player){
if(!hasPlayer(obj.players, player.name)) return;
obj.players.splice(obj.players.indexOf(getPlayer(obj.players, player.name)));
obj.players.push(player);
jsonfile.writeFile(playerDB, obj).catch((err) => {
console.log(err);
});
}
var rand = function(min, max) {
return Math.random() * (max - min) + min;
};
/**
* Usage
* var list = ['javascript', 'php', 'ruby', 'python'];
* var weight = [0.5, 0.2, 0.2, 0.1];
* var random_item = getRandomItem(list, weight);
*/
var getRandomItem = function(list, weight) {
var total_weight = weight.reduce(function (prev, cur, i, arr) {
return prev + cur;
});
var random_num = rand(0, total_weight);
var weight_sum = 0;
//console.log(random_num)
for (var i = 0; i < list.length; i++) {
weight_sum += weight[i];
weight_sum = +weight_sum.toFixed(2);
if (random_num <= weight_sum) {
return list[i];
}
}
};
|
/**PC导航**/
$(function(){
$('.language').mouseenter(function(){
var $this = $(this);
$this
.find('.nf-ol')
.css('display', 'block')
.addClass('animated-fast fadeInUpMenu')
}).mouseleave(function(){
var $this = $(this);
$this
.find('.nf-ol')
.css('display', 'none')
.removeClass('animated-fast fadeInUpMenu');
});
});
$(function(){
$('.pc-nav li').mouseenter(function(){
var $this = $(this);
$this
.find('.dropdown')
.css('display', 'block')
.addClass('animated-fast fadeInUpMenu')
}).mouseleave(function(){
var $this = $(this);
$this
.find('.dropdown')
.css('display', 'none')
.removeClass('animated-fast fadeInUpMenu');
});
});
/*******手机端点击弹出导航********/
$(function(){
$('.menubtn').click(function(){//给d1绑定一个点击事件;
/*这个判断的意义是,如果d2是隐藏的,那么让它显示出来,并将d1的文本内容替换成收起,
如果是显示的,那么就隐藏它并将d1的文本内容替换为展开;*/
if($('.menu').is(':hidden'))
{
$('.menu').slideDown('slow');
$(this).addClass("o");
}else{
$('.menu').slideUp('slow');
$(this).removeClass("o");
}
});
});
/*下拉*/
$(function() {
var Accordion = function(el, multiple) {
this.el = el || {};
this.multiple = multiple || false;
// Variables privadas
var links = this.el.find('.menu-list li a');
// Evento
links.on('click', {el: this.el, multiple: this.multiple}, this.dropdown)
}
Accordion.prototype.dropdown = function(e) {
var $el = e.data.el;
$this = $(this),
$next = $this.next();
$next.slideToggle();
$this.parent().toggleClass('open');
if (!e.data.multiple) {
$el.find('.dropdown').not($next).slideUp().parent().removeClass('open');
};
}
var accordion = new Accordion($('#menu'), false);
});
|
/*global LocalCache, appVersion */
describe('app-version', function() {
beforeEach(function() {
this.originalTime = appVersion.loadTime;
this.originalConfig = exports.config.configRefreshRate;
exports.config.configRefreshRate = 5 * 60 * 1000;
this.originalStarted = Backbone.history.started;
Backbone.history.started = true;
this.stub(Backbone.history, 'loadUrl');
this.stub(LocalCache, 'store');
this.resetSpy = this.spy();
exports.bind('cache-reset', this.resetSpy);
});
afterEach(function() {
if (this.originalTime) {
appVersion.loadTime = this.originalTime;
}
Backbone.history.started = this.originalStarted;
exports.config.configRefreshRate = this.originalConfig;
exports.unbind('cache-reset', this.resetSpy);
});
describe('#isPopulated', function() {
it('should return false with no loadTime', function() {
var original = appVersion.loadTime;
delete appVersion.loadTime;
expect(appVersion.isPopulated()).to.be.false;
if (original) {
appVersion.loadTime = original;
}
});
it('should return false if expired', function() {
appVersion.loadTime = Date.now();
this.clock.tick(exports.config.configRefreshRate);
expect(appVersion.isPopulated()).to.be.false;
});
it('should return true if config is invalid', function() {
appVersion.loadTime = Date.now();
this.clock.tick(1);
exports.config.configRefreshRate = 'foo';
expect(appVersion.isPopulated()).to.be.false;
});
it('should return true if refresh is a string', function() {
exports.config.configRefreshRate = '100';
appVersion.loadTime = Date.now();
this.clock.tick(99);
expect(appVersion.isPopulated()).to.be.true;
});
it('should return true if refresh is 0 string', function() {
exports.config.configRefreshRate = '0';
appVersion.loadTime = Date.now();
this.clock.tick(99);
expect(appVersion.isPopulated()).to.be.true;
});
it('should not triger under 5 minutes', function() {
exports.config.configRefreshRate = '100';
appVersion.loadTime = Date.now();
this.clock.tick(5 * 60 * 1000 - 1);
expect(appVersion.isPopulated()).to.be.true;
});
it('should return true if not expired', function() {
appVersion.loadTime = Date.now();
this.clock.tick(exports.config.configRefreshRate - 1);
expect(appVersion.isPopulated()).to.be.true;
});
it('should return true if expiration is disabled', function() {
appVersion.loadTime = Date.now();
exports.config.configRefreshRate = 0;
this.clock.tick(1000);
expect(appVersion.isPopulated()).to.be.true;
exports.config.configRefreshRate = undefined;
this.clock.tick(1000);
expect(appVersion.isPopulated()).to.be.true;
});
});
describe('cache-reset', function() {
it('should trigger on changed value', function() {
this.stub(LocalCache, 'get', function() { return '1234'; });
appVersion.set('clearClientCache', '1234', {silent: true});
appVersion.set('clearClientCache', '1234');
expect(this.resetSpy).to.not.have.been.called;
expect(LocalCache.store).to.not.have.been.called;
appVersion.set('clearClientCache', '12345');
expect(this.resetSpy).to.have.been.calledOnce;
expect(LocalCache.store).to.have.been.calledOnce;
});
it('should cause url load', function() {
var fragment = 'foo';
this.stub(Backbone.history, 'getFragment', function() { return fragment; });
Backbone.history.started = false;
exports.trigger('cache-reset');
expect(Backbone.history.loadUrl).to.not.have.been.called;
Backbone.history.started = true;
exports.trigger('cache-reset');
expect(Backbone.history.loadUrl).to.have.been.calledOnce;
fragment = 'checkout/place';
exports.trigger('cache-reset');
expect(Backbone.history.loadUrl).to.have.been.calledOnce;
fragment = 'photo/bar';
exports.trigger('cache-reset');
expect(Backbone.history.loadUrl).to.have.been.calledOnce;
});
});
});
|
/*$('.header_menu_item').hover(function(){
$(this).fadeTo('1000', 0.8); //
},function(){
$(this).fadeTo('1000', 1.0); //
});*/
//alert('aae');
|
/**
* Title.js
* @author Huy Vo
*/
import React, {Component } from 'react';
import './Title.css';
import Tabs from './tabs/Tabs';
import TimeTab from './tabs/TimeTab';
import DateTab from './tabs/DateTab';
import SearchBar from './Search';
class Title extends Component {
constructor(props){
super(props);
this.state = {
title: this.props.title
};
}
tabs(){
return [<DateTab/>, <TimeTab/>]
}
render(){
return (
<div id="title_container">
<SearchBar/>
<h1 id="title_header">
{this.state.title}
</h1>
<Tabs tabs={this.tabs()}/>
</div>
);
}
}
export default Title;
|
const path = require('path');
const spawn = require('cross-spawn');
const fs = require('fs');
const fse = require('fs-extra');
const chalk = require('chalk');
const ProgressBar = require('progress');
const { name:CLI_NAME } = require('../../package.json');
const { writeFile, findYarn, emptyDirectory, confirm } = require('../utils/utils');
const { CORE_PATH_PREFIX, CORE_IGNORE_LIST, TS_CORE_IGNORE_LIST, CORE_NAME, CORE_TYPE } = require('../utils/constants');
const yarn = findYarn();
const sep = path.sep;
const globalPackagePath = __dirname.split(sep).slice(0, -3);
const innerPackagePath = globalPackagePath.concat([CLI_NAME, 'node_modules']);
const useInner = fs.readdirSync(innerPackagePath.join(sep)).includes(CORE_NAME.webpack);
const packagePath = useInner ? innerPackagePath.join(sep) : globalPackagePath.join(sep);
const coreConfig = {
name: CORE_NAME.webpack,
path: path.resolve(packagePath, CORE_NAME.webpack),
type: CORE_TYPE.default,
}
function init(dirname, cmd) {
emptyDirectory(dirname, function (empty) {
if (empty) {
create(dirname, cmd);
} else {
confirm(chalk.red('Directory is not empty, continue? [y/N] '), function (ok) {
if (ok) {
process.stdin.destroy();
create(dirname, cmd);
} else {
console.error('Aborting.');
return;
}
});
}
})
}
async function create(dirname, cmd) {
const { install = true, ts = false, rollup = false } = cmd;
const destPath = path.resolve(dirname);
if (ts) {
coreConfig.type = CORE_TYPE.ts;
}
if (rollup) {
coreConfig.path = path.resolve(packagePath, CORE_NAME.rollup);
}
await updateCore();
await copyCore(destPath);
if (install) {
spawn(yarn, ['install', '--cwd', path.resolve(destPath)], { stdio: 'inherit' });
}
}
function updateCore() {
return new Promise((resolve, reject) => {
const updateBar = new ProgressBar(`${chalk.blue('Updating rainypack:')} [:bar] :percent`, {
complete: '=',
incomplete: '-',
total: 30,
});
const updateProcess = spawn(yarn, ['upgrade', coreConfig.name]);
const timer = setInterval(function (){
updateBar.tick();
if (updateBar.curr === 28) {
clearInterval(timer);
}
}, 200);
updateProcess.on('exit', () => {
updateBar.tick(30);
clearInterval(timer)
resolve();
});
updateProcess.on('error', err => reject(err));
})
}
function copyCore(destPath) {
const appName = destPath.split(sep).pop();
const defaultCorePath = `${coreConfig.path}/lib`;
const tsCorePath = `${coreConfig.path}/ts`;
const ignoreList = coreConfig.type === 'ts' ? [...CORE_IGNORE_LIST, ...TS_CORE_IGNORE_LIST] : CORE_IGNORE_LIST;
const appPkgPath = coreConfig.type === 'ts' ? `${tsCorePath}/package.json` : `${defaultCorePath}/package.json`;
let list = fs.readdirSync(defaultCorePath)
.filter(f => !ignoreList.includes(f))
.map(f => `${CORE_PATH_PREFIX.default}/${f}`);
if (coreConfig.type === 'ts') {
const tsList = fs.readdirSync(tsCorePath)
.filter(f => !CORE_IGNORE_LIST.map(f => `${CORE_PATH_PREFIX.ts}/${f}`).includes(f))
.map(f => `${CORE_PATH_PREFIX.ts}/${f}`);
list = list.concat(tsList);
}
console.log(chalk.green('Initial rainypack...'))
return new Promise((resolve, reject) => {
setTimeout(function () {
Promise.all(list.map(file => {
const destFileName = file.replace(/(lib|ts)\//, '');
return fse.copy(`${coreConfig.path}/${file}`, `${destPath}/${destFileName}`)
.then(() => console.log(chalk.green(`create: ${destPath}${sep}${destFileName}`)))
}))
.then(() => {
const appPkg = require(appPkgPath);
appPkg.name = appName;
appPkg.description = appName;
appPkg.author = '';
writeFile(`${destPath}${sep}package.json`, JSON.stringify(appPkg, null, 2));
resolve();
})
.catch(err => reject(err));
}, 500)
})
}
module.exports = init;
|
export default {
// websocket实例
ws: null, //websocket实例
init (config, onMessage, onError) {
if (!this.ws) {
this.ws = new WebSocket(`ws://localhost:3000/${config.user.id}`)
}
this.ws.onmessage = event => {
console.log('前端收到了message', event.data)
let message = JSON.parse(event.data)
onMessage && onMessage(message)
}
this.ws.onerror = error => {
onError && onError(error)
}
this.ws.onclose = () => {
this.ws = null
}
},
send (message) {
this.ws.send(JSON.stringify(message))
}
}
|
/**
* @author Jon Jouret
*/
jQuery.sap.declare("controls.RoundedTile");
jQuery.sap.includeStyleSheet("controls/roundedTile.css");
jQuery.sap.require("sap.m.StandardTile");
sap.m.StandardTile.extend("controls.RoundedTile", {
metadata : {
properties : {
// Icon color property with default value to standard UI5 blue
iconColor : {
type : "string",
defaultValue : "#007cc0"
},
// Background color property with default value to white
bgColor : {
type : "string",
defaultValue : "rgb(255, 255, 255)"
},
// Border color property with default value to standard UI5 blue
borderColor : {
type : "string",
defaultValue : "#007cc0"
}
}
}
});
|
let count = parseInt(prompt("Enter a number to count down"));
for (let i = count; i >= 0; i--) {
document.write(i + ",");
}
|
/*
* backpack-node-sass
*
* Copyright 2018-2021 Skyscanner Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eslint-disable no-console */
const fs = require('fs');
const util = require('util');
const { argv } = require('yargs');
const ora = require('ora');
const sass = require('node-sass');
const chokidar = require('chokidar');
const importer = require('node-sass-tilde-importer');
const functions = require('bpk-mixins/sass-functions.js');
const getCssFileName = (name) => name.replace(/\.scss/, '.css');
const renderSass = util.promisify(sass.render);
const writeFile = util.promisify(fs.writeFile);
const unlinkFile = util.promisify(fs.unlink);
const compileSass = async (file, spinner) => {
const cssFileName = getCssFileName(file);
try {
const result = await renderSass({
file,
importer,
functions,
outputStyle: 'compressed',
});
let prefixedContents;
if (argv.prefixComment) {
try {
const comment = `/*
${argv.prefixComment.replace(/^/gm, ' * ')}
*/`;
prefixedContents = [comment, result.css].join('\n');
} catch (err) {
console.error('There was an error processing the argument.');
console.error(err);
}
}
await writeFile(cssFileName, prefixedContents || result.css);
spinner.succeed(`Compiled: ${cssFileName}`);
} catch (e) {
spinner.fail(`Failed: ${cssFileName}`);
console.error();
console.error(e);
console.error();
}
};
const spinner = ora('Starting watcher...').start();
chokidar
.watch(
[
'**/*.scss',
'!**/_*.scss',
'!**/node_modules',
'!**/bpk-foundations-web/tokens/**',
'!**/bpk-tokens/tokens/**',
],
{
ignoreInitial: true,
followSymlinks: false,
},
)
.on('ready', () => spinner.succeed('Ready for changes'))
.on('add', async (file) => {
spinner.start(`Added: ${file}`);
await compileSass(file, spinner);
})
.on('change', async (file) => {
spinner.start(`Changed: ${file}`);
await compileSass(file, spinner);
})
.on('unlink', async (file) => {
spinner.start(`Removed: ${file}`);
const cssFileName = getCssFileName(file);
try {
await unlinkFile(cssFileName);
spinner.succeed(`Removed: ${cssFileName}`);
} catch (e) {
spinner.fail(`Failed: Unable to cleanup ${cssFileName}`);
console.error();
console.error(e);
console.error();
}
});
|
import React, { Component } from "react";
import { api } from "../../services/ApiConfig";
import PodContainer from "../shared/PodContainer";
import "../../styles/Pods.css";
class Pods extends Component {
constructor(props) {
super(props);
this.state = {
pods: []
};
}
componentDidMount() {
this.fetchPods();
}
fetchPods = async () => {
try {
const pods = await api.get("/NespressoPodList");
this.setState({ pods: pods.data });
} catch (error) {
console.log(error);
}
};
render() {
const renderPods = this.state.pods.map((pod, i) => {
return (
<div key={i}>
<PodContainer handlePodInfo={this.handlePodInfo} key={i} obj={pod} />
</div>
);
});
return (
<div className="podscontainer">
<p className="select">
Select A Pod To View It's Caffeine Levels. <br></br>
<br></br>
<br></br>If You Have A Pod To Add, Please Select 'Add Pod' From The
Menu Above
</p>
<div className="allpods">{renderPods}</div>
</div>
);
}
}
export default Pods;
|
import React from 'react'
import PropTypes from 'prop-types'
import {connect} from 'react-redux'
const MainUsers = (props)=> {
return(
<div>
<p>User Dashboard</p>
{props.children}
</div>
)
}
MainUsers.propTypes = {
children : PropTypes.element.isRequired
}
const mapStateToProps = state => ({
})
export default connect(mapStateToProps, {})(React.memo(MainUsers))
|
const pool = require('../db/index')
module.exports = class User{
constructor({username, email, password}){
this.username = username
this.email = email
this.password = password
}
async save(){
const user = await pool.query(
'INSERT INTO USERS (username, email, password, created) ' +
'VALUES ($1, $2, $3, $4)',
[this.username, this.email, this.password, new Date()]
)
}
static createModel(candidate){
return {
id: candidate.id,
username: candidate.username,
email: candidate.email,
password: candidate.password
}
}
static async findOne({id, email}){
let candidate;
if(id){
candidate = await pool.query('SELECT * FROM users WHERE id=$1 FETCH FIRST ROW ONLY', [id])
}else if(email){
candidate = await pool.query('SELECT * FROM users WHERE email=$1 FETCH FIRST ROW ONLY', [email])
}
else{
return null
}
if(candidate.rowCount === 0) return null
return this.createModel(candidate.rows[0])
}
static async exists({email}){
return (await pool.query('SELECT 1 FROM users WHERE email= $1', [email])).rowCount > 0
}
}
|
var foo = 'bad single quotes';
|
var escapeGhosts = function(ghosts, target) {
let curr = [0,0];
while ((curr[0] !== target[0] && curr[1] !== target[1]) ) {
if (target[0] > curr[0]) {
curr = [curr[0]+1, curr[1]];
} else if (target[0] < curr[0]) {
curr = [curr[0]-1, curr[1]]
} else if (target[1] > curr[1]) {
curr = [curr[0], curr[1]+1]
} else {
curr = [curr[0], curr[1]-1]
}
ghosts.forEach(ghost => {
})
}
};
|
import React, { useState } from "react";
import "react-datepicker/dist/react-datepicker.css";
import Modal2 from "../../modal"
import "../../Dashboardcard.css"
const Custom = () => {
const [startDate, setStartDate] = useState(new Date());
return (
<div>
<div className=" grid grid-flow-col pr-60">
<div className="max-w-8xl mx-auto " style={{ width: "165%" }}>
<div
className=" bg-white shadow overflow-hidden py-3 px-12 relative lg:w-full "
style={{ height: "100%" }}
>
<br />
<br />
<div className=" flex justify-end">
<div className="">
<button
className="group rounded text-white p-2 btn hover-blue"
style={{ width:"130px", fontSize: "17px" }}
>
<div className="grid grid-flow-col auto-cols-max ">
<svg
class="w-6 h-6"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 6v6m0 0v6m0-6h6m-6 0H6"
></path>
</svg>
<div >
Add New
</div>
</div>
</button>
</div>
</div>
<div>
<br />
<br />
<div className="grid grid-flow-col auto-cols-auto ">
<div className="text-gray-600 pr-28 px-3">
<tr className=" text-gray-600 text-xs">
<span>NAME</span>
</tr>
</div>
<div className="text-gray-600 pr-28 px-3">
<tr className=" text-gray-600 text-xs">
<span>POSITION</span>
</tr>
</div>
<div className="text-gray-600">
<tr className=" text-gray-600 text-xs ">
<span> ADDED </span>
</tr>
</div>
</div>
<hr />
</div>
<br />
<div>
<br />
<br />
<div className="grid grid-flow-col auto-cols-auto ">
<div className="text-gray-600 py-4 pr-28">
<tr className=" text-gray-600 text-sm">
<span>Draft filter</span>
</tr>
</div>
<div className="text-gray-600 py-4 pr-28 ">
<tr className=" text-gray-600 text-sm ">
<span> June 1 2021</span>
</tr>
</div>
<div>
<a href="#" className="flex py-2 ">
<span className=" text-blue-600 p-2 text-sm bg-blue-100 ">
<svg
xmlns="http://www.w3.org/2000/svg"
width="19"
height="17"
viewBox="0 0 19 17"
>
<g
fill="none"
fill-rule="evenodd"
stroke="#006AFF"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="1.2"
>
<path d="M4.911 15.438H2.875A1.875 1.875 0 0 1 1 13.562V2.876C1 1.839 1.84 1 2.875 1h9.187c1.036 0 1.875.84 1.875 1.875v1.286M4.844 5.219h5.25M4.844 8.219h3.75M4.844 11.219H6.53M10.319 15.585l-1.861.318.317-1.861a2.733 2.733 0 0 1 .761-1.472l5.6-5.6a1.593 1.593 0 1 1 2.254 2.254l-5.6 5.6c-.4.4-.914.666-1.471.761z" />
</g>
</svg>
</span>
<span
className=" pt-2 pr-3 text-sm bg-blue-100"
style={{ color: "#006AFF" }}
>
Edit
</span>
</a>
</div>
</div>
<hr />
</div>
<br />
</div>
<br />
<p>
<span style={{ paddingLeft: "35%", paddingTop: "5%" }}>
<span className="icon" style={{ alignItems: "center" }}>
<svg
className="w-5 h-5 "
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
></path>
</svg>
</span>
<span className="text text-sm pl-4">
Learn more about <b>Custom filters</b>
</span>
</span>
</p>
<div>
<div
className="grid grid-flow-col auto-cols-max "
style={{ paddingLeft: "29%", paddingTop: "1%" }}
>
<a href="#" className="pr-3">
<span className="icon" style={{ alignItems: "center" }}>
<svg
className="w-4 h-4"
fill="none"
stroke="#3388FF"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"
/>
</svg>
</span>
<span
className="text text-xs pl-3 "
style={{ color: "#3388FF" }}
>
Read the Guide
</span>
</a>
<span
className="text text-sm pl-3 "
style={{ color: "#3388FF" }}
>
<Modal2
msg={['Custom filters are another way to guide your customers toward the content','they"re interested in.','We suggest using difficulty, video length, or levels (beginner, intermediate,','advanced).', ]}
name="Take a tour"/>
</span>
<a href="#" className="pr-3">
<span className="icon" style={{ alignItems: "center" }}>
<svg
className="w-4 h-4"
fill="none"
stroke="#3388FF"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"
/>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
</span>
<span
className="text text-xs pl-3 "
style={{ color: "#3388FF" }}
>
Watch a video
</span>
</a>
</div>
</div>
</div>
</div>
</div>
);
};
export default Custom;
|
const nock = require('nock');
const configCoinApi = require('../../../config').common.braveNewCoinApi;
const coinObjects = require('../objects/crypto_coins');
exports.mockGetCoinOK = (params, responseCoin = coinObjects.coinApiTickerBTC) => {
nock(configCoinApi.endpoint)
.get(`/${configCoinApi.routes.ticker}`)
.query(params)
.reply(200, responseCoin);
};
exports.mockGetCoinNotFound = () => {
nock(configCoinApi.endpoint)
.get(`/${configCoinApi.routes.ticker}`)
.query({ coin: 'ABDCEFG' })
.reply(200, coinObjects.coinApiTickerNotFound);
};
exports.mockGetCoinFailure = () => {
nock(configCoinApi.endpoint)
.get(`/${configCoinApi.routes.ticker}`)
.query({ coin: 'BTC', show: 'USD' })
.replyWithError('Connection refused, request time out');
};
exports.mulipleMockGetCoinOK = () => {
this.mockGetCoinOK({ coin: 'BTC', show: 'USD' }, coinObjects.coinApiTickerBTC);
this.mockGetCoinOK({ coin: 'LTC', show: 'USD' }, coinObjects.coinApiTickerLTC);
this.mockGetCoinOK({ coin: 'ETH', show: 'USD' }, coinObjects.coinApiTickerETH);
this.mockGetCoinOK({ coin: 'ZEC', show: 'USD' }, coinObjects.coinApiTickerZEC);
this.mockGetCoinOK({ coin: 'XRP', show: 'USD' }, coinObjects.coinApiTickerXRP);
};
|
import React from "react";
import "./About.css";
import { selectDarkmode, setDarkMode } from "./features/userSlice";
import { useDispatch, useSelector } from "react-redux";
function About() {
const darkmode = useSelector(selectDarkmode);
return (
<div className="about">
<h1 className={darkmode === true ? "darkAbout__header" : "about__header"}>
Covid-19 Pandemic
</h1>
<div className="aboutContainer">
<div className="aboutContainer__left">
<p className="aboutInfo">
Coronavirus disease (COVID-19) is an infectious disease caused by a
newly discovered coronavirus. <br />
<br />
Most people infected with the COVID-19 virus will experience mild to
moderate respiratory illness and recover without requiring special
treatment. Older people, and those with underlying medical problems
like cardiovascular disease, diabetes, chronic respiratory disease,
and cancer are more likely to develop serious illness.
<br />
<br />
The best way to prevent and slow down transmission is to be well
informed about the COVID-19 virus, the disease it causes and how it
spreads. Protect yourself and others from infection by washing your
hands or using an alcohol based rub frequently and not touching your
face.
<br />
<br />
The COVID-19 virus spreads primarily through droplets of saliva or
discharge from the nose when an infected person coughs or sneezes,
so it’s important that you also practice respiratory etiquette (for
example, by coughing into a flexed elbow).{" "}
</p>
</div>
<div className="aboutContainer__right">
<img className="aboutPic" src="/images/Covid-19.jpeg" alt="" />{" "}
</div>
</div>
<h2
className={
darkmode === true
? "darkAbout__Prevention aboutMeasure"
: "about__Prevention aboutMeasure"
}
>
Measures to prevent Covid-19
</h2>
<div className="containerPrevent">
<div className="containerPrevent__left">
<p>
Protect yourself and others around you by knowing the facts and
taking appropriate precautions. Follow advice provided by your local
health authority. To prevent the spread of COVID-19:
<br />
<br />
<ul>
<li>
Clean your hands often. Use soap and water, or an alcohol-based
hand rub.
</li>
<br />
<li>
Maintain a safe distance from anyone who is coughing or
sneezing.
</li>
<br />
<li>Wear a mask when physical distancing is not possible.</li>
<br />
<li>Don’t touch your eyes, nose or mouth.</li>
<br />
<li>
{" "}
Cover your nose and mouth with your bent elbow or a tissue when
you cough or sneeze.{" "}
</li>
<br />
<li>Stay home if you feel unwell.</li>
<br />
<li>
If you have a fever, cough and difficulty breathing, seek
medical attention.
</li>
<br />
</ul>
Calling in advance allows your healthcare provider to quickly direct
you to the right health facility. This protects you, and prevents
the spread of viruses and other infections. Masks Masks can help
prevent the spread of the virus from the person wearing the mask to
others. Masks alone do not protect against COVID-19, and should be
combined with physical distancing and hand hygiene. Follow the
advice provided by your local health authority.
</p>
</div>
<div className="containerPrevent__right">
<img
className="imagePrevention"
src="/images/Prevention.jpeg"
alt=""
/>{" "}
</div>
</div>
</div>
);
}
export default About;
|
import { attachChildren } from "./render/attachChildren"
import { createTreeNode } from "./render/prepareRenderComponent"
import { screenRouter } from "./render/screenRouter"
import { createStateManager } from "./state/stateManager"
import { getAppIdFromPath } from "./render/getAppId"
export const createApp = ({
componentLibraries,
frontendDefinition,
window,
}) => {
let routeTo
let currentUrl
let screenStateManager
const onScreenSlotRendered = screenSlotNode => {
const onScreenSelected = (screen, url) => {
const stateManager = createStateManager({
componentLibraries,
onScreenSlotRendered: () => {},
routeTo,
})
const getAttachChildrenParams = attachChildrenParams(stateManager)
screenSlotNode.props._children = [screen.props]
const initialiseChildParams = getAttachChildrenParams(screenSlotNode)
attachChildren(initialiseChildParams)(screenSlotNode.rootElement, {
hydrate: true,
force: true,
})
if (screenStateManager) screenStateManager.destroy()
screenStateManager = stateManager
currentUrl = url
}
routeTo = screenRouter({
screens: frontendDefinition.screens,
onScreenSelected,
window,
})
const fallbackPath = window.location.pathname.replace(
getAppIdFromPath(),
""
)
routeTo(currentUrl || fallbackPath)
}
const attachChildrenParams = stateManager => {
const getInitialiseParams = treeNode => ({
componentLibraries,
treeNode,
onScreenSlotRendered,
setupState: stateManager.setup,
})
return getInitialiseParams
}
let rootTreeNode
const pageStateManager = createStateManager({
componentLibraries,
onScreenSlotRendered,
// seems weird, but the routeTo variable may not be available at this point
routeTo: url => routeTo(url),
})
const initialisePage = (page, target, urlPath) => {
currentUrl = urlPath
rootTreeNode = createTreeNode()
rootTreeNode.props = {
_children: [page.props],
}
const getInitialiseParams = attachChildrenParams(pageStateManager)
const initChildParams = getInitialiseParams(rootTreeNode)
attachChildren(initChildParams)(target, {
hydrate: true,
force: true,
})
return rootTreeNode
}
return {
initialisePage,
screenStore: () => screenStateManager.store,
pageStore: () => pageStateManager.store,
routeTo: () => routeTo,
rootNode: () => rootTreeNode,
}
}
|
import auth from '@/auth/authService';
export default {
isUserLoggedIn: () => localStorage.getItem('userInfo') && auth.isAuthenticated()
};
|
var table=null;
$(function(){
table = $('#blog_table_id').dataTable();
getAllBlog();
});
function getAllBlog(){
$.ajax({
contentType : "application/json",
processData : true,
url : 'getBlog.html',
type : "GET",
dataType : "json",
cache : false,
async : true,
success : function(response){
table.fnClearTable();
$.each(response.data,function(index,row){
addRow(row);
});
}
});
}
function addRow(row){
//var str=(row.blogMeta).replace(/(<([^>]+)>)/ig,"").trunc(50);
//var tgs='<div class="pop-div"><a href="javascript:void(0)" class="pop-div" data-html=true data-trigger="focus" data-toggle="popover" title="Description" data-content=\''+row.blogMeta+'\'></a></div>';
table.fnAddData({
"0":(row.title!=null && row.title!="null">0)?row.title:'N/A',
"1":(row.date!=null &&row.date!="null">0)?row.date:'N/A',
"2":(row.user!=null && row.user!="null">0)?row.user:'N/A',
"3":(row.content!=null && row.content!="null">0)?row.content:'N/A',
//"4":('<div class="pop-div"><a href="javascript:void(0)" class="pop-div" data-html=true data-trigger="focus" data-toggle="popover" title="Description" data-content=\''+row.blogMeta+'\'></a></div>'),
"4":(row.blogMeta!=null && row.blogMeta!="null">0)?row.blogMeta:'N/A',
"5": "<input type='submit' value= 'edit' class='edit btn btn-sm btn-primary' blogid='"+row.id+"' title=\""+row.title+"\"" +
" date=\""+row.date+"\"user=\""+row.user+"\"content=\""+row.content+"\"blogMeta=\""+row.blogMeta+"\">",
"6": "<input type='submit' value= 'delete' class='delete btn btn-sm btn-danger' blogid='"+row.id+"' name=\""+row.title+"\" />"
});
}
function getCategory(){
$.ajax({
contentType: "application/json",
processData : true,
async : false,
url : "getCategory.html",
type : "GET",
success : function(response) {
if (response.status!=0)
{
$("#catId").empty();
$.each(response.data,function(index,value){
$("#catId").append('<option value = '+value.id+'>'+value.name+'</option>');
});
}
else
alert("error");
},
error : function(request, status, thrownError) {
}
});
}
$("body").on("click",".edit",function(){
getCategory();
$('#btnSaveUser').hide();
$('#update_id').show();
var id=$(this).attr("blogid");
var blogedittitle=$(this).attr("title");
var blogeditcat=$(this).attr("catid");
var blogeditcontent=$(this).attr("content");
$("#blog_id").val(id);
$("#title").val(blogedittitle);
$("#catId option[value='"+ blogeditcat +"']").attr("selected", "selected");
//$("#").val();
$("#content").val(blogeditcontent);
$('#blog_modal').modal({backdrop:true});
});
$("body").on("click","#btnSaveUser",function(){
var id=$("#blog_id").val();
var title=$("#title").val();
//var date=$("#date").val();
var content=$("#content").val();
var catid=$("#catId").val();
var blogObj={};
blogObj.id=id;
blogObj.title=title;
blogObj.content=content;
blogObj.catid=catid;
//updateBlog(blogObj);
saveBlog(blogObj);
$('#blog_modal').modal("hide");
});
$("body").on("click","#update_id",function(){
var id=$("#blog_id").val();
var title=$("#title").val();
//var date=$("#date").val();
var content=$("#content").val();
var catid=$("#catId").val();
var blogObj={};
if(id!="" || id!=null || id.length>0){
blogObj.id=id;
}
blogObj.title=title;
blogObj.content=content;
blogObj.catid=catid;
//updateBlog(blogObj);
saveBlog(blogObj);
$('#blog_modal').modal("hide");
});
function saveBlog(blogObj)
{
$.ajax({
contentType : "application/json",
processData : true,
url : 'addBlog.html',
type : "POST",
dataType : "json",
cache : false,
async : true,
data : JSON.stringify(blogObj),
success : function(response){
if(response.status==1){
getAllBlog();
}else{
alert("Blog not update or save. ");
}
}
});
}
$("body").on("click",".addnewblog",function(){
$('#btnSaveUser').show();
$('#update_id').hide();
getCategory();
$("#blog_id").val("");
$("#title").val("");
//$("#catId").val("");
$("#content").val("");
$('#btnSaveUser').val("save");
$('#blog_modal').modal({backdrop:true});
});
$("body").on("click",".delete",function(){
var blog_id=$(this).attr("blogid");
$("#blog_id").val(blog_id);
$('#delete_blog_modal').modal({backdrop:true});
});
$("body").on("click","#btndeleteblog",function(){
var blog_id=$("#blog_id").val();
deleteBlog(blog_id);
$('#delete_blog_modal').modal("hide");
});
function deleteBlog(id) {
$.ajax({
contentType: "application/json",
processData : true,
data : {id : id},
async : false,
url : "deleteBlog.html",
type : "GET",
success : function(response) {
if (response.status!=0)
{
window.location.reload(true);
}
else
alert("error");
},
error : function(request, status, thrownError) {
}
});
}
|
import { createSlice } from '@reduxjs/toolkit';
const initialState = {
uId: null,
email: '',
photoURL: '',
displayName: '',
isAuthenticated: false,
userType: 'player'
}
export const userSlice = createSlice({
name: 'user',
initialState,
reducers: { // methods to update our state
userSignIn: (state, action) => {
state.uId = action.payload.uid;
state.email = action.payload.email;
state.isAuthenticated = true;
}
}
})
export const { userSignIn } = userSlice.actions;
export default userSlice.reducer; //exporting the reducer as userReducer to add to our store.
|
export default class MyMap {
constructor() {
this.world = new World({element: document.querySelector('#my_map')});
return this.world;
}
}
|
import React from 'react';
const MatchRate = props => (
<div style={{backgroundSize: 'cover', width: '100%', height: '750px'}}>
<h1 className="display-4 indigo-text text-darken-4" style={{padding:"0px 0px 200px 40px"}}>MATCH RATE</h1>
<p className="lead indigo-text text-darken-4" style={{padding:"0px 25px 0px 40px"}}>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<br/>
</div>
);
export default MatchRate;
|
import React from 'react'
import ProductSummary from './productSummary'
function ProductList({products}) {
return (
<div className="container">
<div className="row row-cols-4">
{products && products.map(product=>{
return(
<div className="cell small-3" key={product.id}>
<ProductSummary product={product}/>
</div>
)
})}
</div>
</div>
)
}
export default ProductList
|
import React from "react";
import { ScrollView, StyleSheet, Text, View } from "react-native";
import { useTeams } from "../../contexts/TeamsContext";
import { useTheme } from "../../contexts/ThemeContext";
import { getListStyles } from "./Styles";
const TeamsResults = () => {
const {teams, addNewTeam} = useTeams()
const {colors} = useTheme()
const listStyles = getListStyles(colors)
const styles = getStyles(colors)
return (
<View style={{marginTop: 20}}>
<View style={listStyles.headerRow}>
<Text style={styles.headerText}>Name</Text>
<Text style={styles.headerText}>Wins</Text>
<Text style={styles.headerText}>Losses</Text>
</View>
<ScrollView style={styles.teamsBoard}>
{teams.sort((f, s) => s.wins - f.wins || f.losses - s.losses).map(x => (
<View key={x.id} style={listStyles.bodyRow}>
<Text style={styles.nameText}>{x.name}</Text>
<Text style={styles.winsText}>{x.wins}</Text>
<Text style={styles.lossesText}>{x.losses}</Text>
</View>
))}
</ScrollView>
</View>
)
}
export default TeamsResults
const getStyles = (colors) => {
return StyleSheet.create({
headerText: {
fontSize: 18,
fontWeight: "bold",
color: colors.lightTextColor
},
nameText: {
width: "20%",
fontSize: 18,
fontWeight: "bold",
textAlign: "left",
color: colors.darkTextColor
},
winsText: {
width: "20%",
textAlign: "right",
color: colors.secondaryColor
},
lossesText: {
width: "20%",
textAlign: "right",
color: colors.primaryColor
},
teamsBoard: {
height: "70%"
}
})
}
|
import React, { Component } from 'react';
import './App.css';
import Home from './Component/Home/Home';
import Skills from './Component/Skills/Skills';
import Works from './Component/Works/Works';
import Form from './Component/Form/Form';
import Navbar from './Component/Navbar/Navbar';
import { Route} from 'react-router-dom';
import Footer from './Component/Footer/Footer';
import Services from './Component/Services/Services';
class App extends Component {
render() {
return (
<div className="App">
<Navbar/>
<Route path='/' exact component={Home}/>
<Route path='/skills' exact component={Skills}/>
<Route path='/services' exact component={Services}/>
<Route path='/works' exact component={Works}/>
<Route path='/form' exact component={Form}/>
<Footer/>
</div>
);
}
}
export default App;
|
const express = require('express');
const router = express.Router()
const Members = require('../../controllers/members.controller');
router.post('/', (req, res) => {
console.log('POST /members/');
Members.create(req, res);
});
router.put('/', (req, res) => {
console.log('PUT /members/');
Members.update(req, res);
})
router.get('/get/group/:groupId(\d+)', (req, res) => {
console.log('GET /members/get/group/' + req.params.groupId);
Members.findInGroup(req, res);
})
router.get('/get/:id(\d+)', (req, res) => {
console.log('GET /members/get/' + req.params.id);
Members.findOne(req, res);
})
router.get('/get', (req, res) => {
console.log('GET /members/get');
Members.getAll(req, res);
});
router.delete('/delete/:id(\d+)', (req, res) => {
console.log('DELETE /members/' + req.params.id);
Members.delete(req, res);
})
module.exports = router;
|
class Calculator {
constructor(aimString) {
this.aimString = aimString
this.aimArray = aimString.split(' ')
this.signStack = []
this.numStack = []
}
/**
* 调用该方法获得计算结果
*/
calculate() {
this.inputSignAndNum()
// 当数字栈只有一个数字时,那就是结果
while (this.numStack.length !== 1) {
const calculateTwoNumResult = this.calculateTwoNum()
this.numStack.push(calculateTwoNumResult)
}
return this.numStack.pop()
}
/**
* 将数字和符号分别入栈
*/
inputSignAndNum() {
for (const i of this.aimArray) {
const currFloat = parseFloat(i)
// 判断是数字还是符号
if (!isNaN(currFloat)) {
this.numStack.push(currFloat)
continue
}
const whetherHigher = this.priority(i, this.signStack[this.signStack.length - 1])
// 判断是否是高优先级符号
// 对于高优先级符号,先计算栈顶部符号和栈顶部的两个数字,将结果入数字栈
// 再将符号入栈
if (i !== ')' && whetherHigher) {
const calculateTwoNumResult = this.calculateTwoNum()
this.numStack.push(calculateTwoNumResult)
this.signStack.push(i)
continue
}
// 对于非高优先级符号,且不是结束括号,直接入栈
if (i !== ')') {
this.signStack.push(i)
} else {
// 对于结束括号,先计算结果,并入数字栈
// 再将起始括号去除
this.numStack.push(this.calculateTwoNum())
this.signStack.pop()
}
}
}
calculateTwoNum() {
const secondNum = this.numStack.pop()
const firstNum = this.numStack.pop()
const neededSign = this.signStack.pop()
let result = 0.0
switch (neededSign) {
case '*':
result = firstNum * secondNum
break
case '/':
result = firstNum / secondNum
break
case '+':
result = firstNum + secondNum
break
case '-':
result = firstNum - secondNum
break
default:
break
}
return result
}
priority(firstChar, secondChar) {
// 执行加法运算
if (firstChar === '+' && secondChar === '+') return false
if (firstChar === '+' && secondChar === '-') return false
if (firstChar === '+' && secondChar === '*') return true
if (firstChar === '+' && secondChar === '/') return true
// 执行减法运算
if (firstChar === '-' && secondChar === '+') return false
if (firstChar === '-' && secondChar === '-') return false
if (firstChar === '-' && secondChar === '*') return true
if (firstChar === '-' && secondChar === '/') return true
// 执行乘法运算
if (firstChar === '*' && secondChar === '+') return false
if (firstChar === '*' && secondChar === '-') return false
if (firstChar === '*' && secondChar === '*') return false
if (firstChar === '*' && secondChar === '/') return false
// 执行除法运算
if (firstChar === '/' && secondChar === '+') return false
if (firstChar === '/' && secondChar === '-') return false
if (firstChar === '/' && secondChar === '*') return false
if (firstChar === '/' && secondChar === '/') return false
if (firstChar === '(') return false
}
}
const test = '1 + 2 * 3 + 3 / ( 3 - 2 )'
const calculator = new Calculator(test)
const result = calculator.calculate()
console.log(result)
|
var searchData=
[
['elementwisemultiplication',['elementWiseMultiplication',['../classVector3D.html#aa464747455b93d84f15856493692cf04',1,'Vector3D']]],
['elementwisepower',['elementWisePower',['../classVector3D.html#a0006a0a729d3d99259024cdcb354eb5d',1,'Vector3D']]],
['empty',['empty',['../classFixedSizeStack.html#a6271318779d6b69768a28a5675fa9136',1,'FixedSizeStack']]],
['enable_5finterpolation',['enable_interpolation',['../classTriangle.html#a1a81c94f82103c8f1b81e006d8b03356',1,'Triangle']]],
['equals_5fabout',['equals_about',['../namespaceutility.html#a48a4f01e19bee62fd4f16da19255abeb',1,'utility']]]
];
|
// Copyright (c) 2017, Lewin Villar and contributors
// For license information, please see license.txt
frappe.ui.form.on('Paciente', {
refresh: function(frm) {
//El usuario solo puede agregar la ARS al crear el paciente, luego solo las ARS pueden modificar estos campos
if (!frm.doc.__islocal){
frm.set_df_property("nss","read_only",1)
frm.set_df_property("ars","read_only",1)
}
// Filtro solo para ver las ARS
frm.set_query("ars", function() {
return {
"filters": {
"tipo": "ARS"
}
}
});
},
fecha_de_nacimiento: function(frm){
var today = frappe.datetime.get_today()
var f_nacimiento = moment(frm.doc.fecha_de_nacimiento, "YYYY-MM-DD")
// let make the diff
var edad = moment(today, "YYYY-MM-DD").diff(f_nacimiento, 'years')
frm.set_value("edad", edad)
},
validate: function(frm){
//Validar que si alguno de los dos tiene data, el otro tambien
if(frm.doc.ars || frm.doc.nss){
frm.set_df_property("nss","reqd",1)
frm.set_df_property("ars","reqd",1)
}
fields = ["dir_calle","dir_edificio","dir_numero","dir_apartamento","dir_sector","dir_provincia"]
$.each(fields,function(key1, val1){
if (frm.get_field(val1).value){
$.each(fields,function(key2, val2){
frm.set_df_property(val2, "reqd", 1)
})
return
}
})
if (frm.doc.sexo == "-"){
frappe.msgprint("Debes seleccionar el sexo del Paciente!")
frappe.validated = false
return
}
},
primer_nombre: function(frm) {
if (frm.doc.primer_nombre)
frm.set_value("primer_nombre", frm.doc.primer_nombre.trim().toUpperCase())
frm.trigger("nombre_completo")
},
segundo_nombre: function(frm) {
if (frm.doc.segundo_nombre)
frm.set_value("segundo_nombre", frm.doc.segundo_nombre.trim().toUpperCase())
frm.trigger("nombre_completo")
},
apellido_materno: function(frm) {
if (frm.doc.apellido_materno)
frm.set_value("apellido_materno", frm.doc.apellido_materno.trim().toUpperCase())
frm.trigger("nombre_completo")
},
apellido_paterno: function(frm) {
if (frm.doc.apellido_paterno)
frm.set_value("apellido_paterno", frm.doc.apellido_paterno.trim().toUpperCase())
frm.trigger("nombre_completo")
},
nombre_completo: function(frm) {
//Limpiamos el campo para garantizar integridad
frm.doc.nombre_completo = ""
if (frm.doc.primer_nombre){
frm.doc.nombre_completo = frm.doc.primer_nombre
if (frm.doc.segundo_nombre)
frm.doc.nombre_completo += " "+frm.doc.segundo_nombre
if (frm.doc.apellido_paterno)
frm.doc.nombre_completo += " "+frm.doc.apellido_paterno
if (frm.doc.apellido_materno)
frm.doc.nombre_completo += " "+frm.doc.apellido_materno
}
refresh_field("nombre_completo")
},
cedula_pasaporte: function(frm){
frm.set_value("cedula_pasaporte", mask_ced_pas_rnc(frm.doc.cedula_pasaporte))
},
correo_electronico: function(frm){
if(frm.doc.correo_electronico && !valida_correo(frm.doc.correo_electronico)){
frm.set_value("correo_electronico", "")
frappe.msgprint("El correo electronico ingresado no es valido!")
}
},
dir_calle: function(frm) {
if (frm.doc.dir_calle)
frm.set_value("dir_calle", frm.doc.dir_calle.trim().toUpperCase())
},
dir_edificio: function(frm) {
if (frm.doc.dir_edificio)
frm.set_value("dir_edificio", frm.doc.dir_edificio.trim().toUpperCase())
},
dir_apartamento: function(frm) {
if (frm.doc.dir_apartamento)
frm.set_value("dir_apartamento", frm.doc.dir_apartamento.trim().toUpperCase())
},
dir_sector: function(frm) {
if (frm.doc.dir_sector)
frm.set_value("dir_sector", frm.doc.dir_sector.trim().toUpperCase())
}
});
frappe.ui.form.on("Telefonos", {
telefono: function(frm, cdt, cdn){
var row = locals[cdt][cdn];
frappe.model.set_value(cdt, cdn, "telefono", mask_phone(row.telefono));
}
})
function mask_ced_pas_rnc(input)
{
input = input.trim().replace(/-/g,"")
if (input.length == 11)
return ("{0}{1}{2}-{3}{4}{5}{6}{7}{8}{9}-{10}".format(input));
if (input.length == 9)
return ("{0}-{1}{2}-{3}{4}{5}{6}{7}-{8}".format(input));
return input
}
function mask_phone(phone)
{
var pattern = new RegExp("((^[0-9]{3})[0-9]{3}[0-9]{4})$");
var pattern1 = new RegExp("([(][0-9]{3}[)] [0-9]{3}-[0-9]{4})$");
var pattern2 = new RegExp("([(][0-9]{3}[)][0-9]{3}-[0-9]{4})$");
if(pattern.test(phone))
return ("({0}{1}{2}) {3}{4}{5}-{6}{7}{8}{9}".format(phone));
else if(pattern1.test(phone))
return phone;
else if(pattern2.test(phone))
return ("{0}{1}{2}{3}{4} {5}{6}{7}{8}{9}{10}{11}{12}".format(phone));
}
function valida_correo(email) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
|
cc.Class({
extends: cc.Component,
properties: {
},
// use this for initialization
onLoad: function () {
this.node.setPosition(cc.p(0,0));
this.menuState = 'DOWN';
//监听列表探入弹出事件
this.node.on('move-up',this.moveUp,this);
this.node.on('move-down',this.moveDown,this);
//this.audio = this.node.getComponent(cc.AudioSource);
this.skillsContent = cc.find('view/content_skills',this.node);
this.friendsContent = cc.find('view/content_friends',this.node);
this.friends_pkContent = cc.find('view/content_pk',this.node);
this.storeContent = cc.find('view/content_store',this.node);
this.scrollView = this.node.getComponent(cc.ScrollView);
},
moveUp:function(){
this.node.stopAllActions();
var moveup = cc.moveTo(0.2,cc.p(0,300));
this.node.runAction(moveup);
this.menuState = 'UP';
//this.audio.play('tab_change');
},
moveDown:function(){
this.node.stopAllActions();
var movedown = cc.moveTo(0.2,cc.p(0,0));
this.node.runAction(movedown);
this.menuState = 'DOWN';
//this.audio.play('window_close');
},
showSkills: function(){
this.skillsContent.active = true;
this.friendsContent.active = false;
this.friends_pkContent.active = false;
this.storeContent.active = false;
this.scrollView.content = this.skillsContent;
},
showFriends : function () {
this.skillsContent.active = false;
this.friendsContent.active = true;
this.storeContent.active = false;
this.friends_pkContent.active = false;
this.scrollView.content = this.friendsContent;
},
showFriends_pk : function () {
this.skillsContent.active = false;
this.friendsContent.active = false;
this.friends_pkContent.active = true;
this.storeContent.active = false;
this.scrollView.content = this.friends_pkContent;
},
showStore : function () {
this.skillsContent.active = false;
this.friendsContent.active = false;
this.friends_pkContent.active = false;
this.storeContent.active = true;
this.scrollView.content = this.storeContent;
}
});
|
'use strict';
import chalk from 'chalk';
import Website from './app/http/server';
import Install from './app/libraries/install/check';
class Application
{
constructor ()
{
const status = new Install;
Application.environment();
if (!status.completed)
{
Application.console();
new Website;
}
}
static environment ()
{
global.home = __dirname;
global.crash = false;
global.start = Date.now();
}
static console ()
{
process.stdout.write("\x1B[2J");
console.log(
chalk.bgRed.bold(
" " + "\n" +
" " + "\n" +
" xHabbo Two " + "\n" +
" Developed by LeChris " + "\n" +
" " + "\n" +
" " + "\n"
)
+ chalk.bgYellow(
" " + "\n" +
" " + "\n" +
" Database " + "\n" +
" Plus Emulator Ready " + "\n" +
" " + "\n" +
" "
)
);
}
static crash ()
{
global.crash = true;
}
}
export default Application;
|
// Dependencies
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import ListItem from './ListItem/ListItem'
/**
* The List component, a collection of list items.
* @type {Class}
*/
class List extends Component {
/**
* Map over the items provided as props and render a ListItem component for
* each.
* @return {Object} The rendered collection of list items.
*/
renderListItems() {
const {
listItems,
} = this.props
return listItems.map(item =>
(
<li key={item.tmdbID || item.id}>
<ListItem
item={item}
/>
</li>
))
}
/**
* Render the list.
* @return {Object} The rendered component.
*/
render() {
return (
<div className={`${this.props.className} c-list`}>
<ul className="u-unstyled-list">
{this.renderListItems()}
</ul>
</div>
)
}
}
export default List
/**
* Define the property types.
* @type {Object}
*/
List.propTypes = {
className: PropTypes.string,
listItems: PropTypes.array,
}
/**
* Define the default values for the property types.
* @type {Object}
*/
List.defaultProps = {
className: '',
listItems: [],
}
|
import React from 'react';
import 'bootstrap/dist/css/bootstrap.css';
import '../../index.css';
import '../../App.css';
import Search from '../../components/search/search';
class Home extends React.Component {
render() {
return (
<div className="container container-news">
<div className="row">
<div >
<h1> Search News</h1>
<div className="spacer-24"></div>
<h6 className="font-weight-100"> Search through millions of articles from over 30,000 large and small news sources and blogs.</h6>
<h6 className="font-weight-100"> This includes breaking news as well as lesser articles.</h6>
<div className="spacer-24"></div>
<Search></Search>
</div>
</div>
</div>
);
}
}
export default Home;
|
const User = require('../../../models/user');
const { TransformObject } = require('./merge');
const bcrypt = require('bcryptjs');
exports.changePassword = async args => {
try {
const user = await User.findById(args.userId);
user.password = await bcrypt.hash(args.password, 12);
await user.save();
return TransformObject(user);
} catch (e) {
throw e;
}
};
|
import ReactDom from 'react-dom';
import React from 'react';
export class Counter extends React.Component{
constructor(props) {
super(props);
this.state = {counter: 0};
this.incrementCounter = this.incrementCounter.bind(this);
}
render() {
return (
<button onClick={this.incrementCounter}> Counter : {this.state.counter}</button>
);
}
incrementCounter() {
this.setState(function(state, props) {
return {
counter: state.counter + 1
};
});
}
}
|
var commonNavInfo={
"referurl":document.referrer, // 上一跳url
"nuseragent":navigator.userAgent, // 浏览器属性
"nplatform":navigator.platform, // 系统平台
"resolution":window.screen.width+"x"+window.screen.height, // 屏幕分辨率
"colorpepth":window.screen.colorDepth, // 颜色质量
"checkFlash":checkePlugs('Shockwave Flash'), // 是否有flash插件
"pluginsNum":navigator.plugins.length, // 插件数量
"pluginsName":getPluginName(), // 插件名称
"cookieId":"", // cookieId
"ipAddress":"", // ip地址
"token":"" // 登录服务器返回的token
};
$(function(){
getIps();
// console.log(commonNavInfo);
});
//获取插件所有的名称
function getPluginName() {
var info = "";
var plugins = navigator.plugins;
if (plugins.length > 0) {
for (i = 0; i < navigator.plugins.length; i++) {
info += navigator.plugins[i].name + ";";
}
}
return info;
}
//检查是否安装了某插件,如果安装了返回版本号
function checkePlugs(pluginname) {
var f = "-"
var plugins = navigator.plugins;
if (plugins.length > 0) {
for (i = 0; i < navigator.plugins.length; i++) {
if (navigator.plugins[i].name.indexOf(pluginname) >= 0) {
f = navigator.plugins[i].description.split(pluginname)[1];
return f;
break;
}
}
}
return false;
}
//判断是否IE
function isIe() {
var i = navigator.userAgent.toLowerCase().indexOf("msie");
return i >= 0;
}
//判断是否firefox
function isFireFox() {
var i = navigator.userAgent.toLowerCase().indexOf("firefox");
return i >= 0;
}
function getIps() {
var url = 'http://chaxun.1616.net/s.php?type=ip&output=json&callback=?&_='+Math.random();
$.getJSON(url, function(data){
commonNavInfo.ipAddress=data.Ip;
// $("#allPCInfo").html("显示:IP【"+data.Ip+"】 地址【"+data.Isp+"】 浏览器【"+data.Browser+"】 系统【"+data.OS+"】");
});
}
|
const { v4: uuid } = require("uuid");
const { Router } = require("express");
const storage = require("../storage/placesStorage");
const authMiddleware = require("../middleware/auth.middleware")
const router = Router();
router.get("/", async (req, res, next) => {
const list = storage.listAll()
res.json(list);
});
router.get("/:id", async (req, res, next) => {
const item = await storage.getById(req.params["id"]);
console.log(req.query)
res.status(item ? 200 : 404).json(
item ? item : {
statusCode: 404,
}
);
});
router.put("raiting/:idplaces/:idplace", authMiddleware, async (req, res, next) => {
const { body } = req;
const idPlace = req.params["idplace"]
const places = await storage.getById(req.params["idplaces"]);
const place = places.places.filter((place) => +place.id === +idPlace)[0]
place.voted.push(body.login)
place.scores += body.rating
place.rating = place.voted.length === 1 ? body.rating : place.scores / place.voted.length
const newBody = await storage.update({
...body,
id: req.params.id,
idUser
});
console.log(newBody)
res.json(newBody);
});
module.exports = router;
|
const Conference = {};
// attendeeWebApi의 가짜 버전. 진짜와 메서드는 같지만 전체적으로 클라이언트 측 코드만 있다.
Conference.fakeAttendeeWebApi = function () {
const attendees = []; // 가짜 데이터베이스 테이블
return {
// 서버에 attendee를 POST 전송하는 척 한다.
// attendee 사본(마치 서버에서 새 버전을 조회해오는 것처럼)으로
// 귀결되는 프라미스를 반환하고, 귀결 시점에 이 레코드에는
// 데이터베이스에서 할당된 PK(attendeeId)l가 들어있을 것이다.
// 프라미스를 버려야 하는 테스트라면 스파이를 이용하자
post(attendee) {
return new Promise(function (resolve, reject) {
// 5 밀리 초에 불과하지만,
// setTimeout은 프라미스 귀결을 다음 차례로 지연한다.
setTimeout(function pretendPostingToServer() {
const copyOfAttendee = attendee.copy();
copyOfAttendee.setId(attendees.length + 1);
attendees.push(copyOfAttendee);
resolve(copyOfAttendee);
}, 5);
});
},
// 전체 참가자에 대한 프라미스를 반환한다.
// 이 프라미스는 반드시 귀결되지만, 필요하면 테스트 코등에서 스파이를 심을 수 있다
getAll() {
return new Promise(function (resolve, reject) {
// setTimeout은 실제 조건을 흉내 내기 위해
// post 보다 지연 시간이 짧다
setTimeout(function pretendToGetAllFromServer() {
const copies = attendees.map((attendee) => attendee.copy());
resolve(copies);
}, 1);
});
},
};
};
export default Conference;
|
import React from "react";
import API from "../utils/API";
export default function SearchItem(props) {
function saveBook(props) {
API.saveBook({
title: props.title,
authors: props.authors[0],
description: props.description,
image: props.image,
link: props.link
})
.then(alert("Book Saved"))
.catch(err => console.log(err));
}
return (
<li className="list-group-item">
<div className="row">
<h5 className="col-lg-6 col-md-12 float-left" >{props.title}</h5>
<a href={props.link} rel="noreferrer noopener" target="_blank" className="col-lg-2 col-md-2 col-sm-auto border btn btn-light float-right" role="button">View</a>
<button id={props.id} className="col-lg-2 col-md-2 col-sm-auto border btn btn-light float-right" onClick={() => saveBook(props)} tabIndex="0">Save Book</button>
</div>
<div className="row">
<p className="col-12">{props.authors}</p>
</div>
<div className="row">
<img className="col-md-4 col-sm-12 img-fluid" src={props.image} alt={props.title} />
<p className="col-md-8 col-sm-12">{props.description}</p>
</div>
</li>
);
}
|
var toolsLanguage = '';
function smallAlertWindow(position, status, desc) {
const Toast = Swal.mixin({
toast: true,
position: position,
showConfirmButton: false,
timer: 10000
});
Toast.fire({
type: status,
title: desc
})
initPage();
}
function smallAlertWindowSuccessful() {
smallAlertWindow('top', 'success',
'Congratulations, the operation is successful ●ω●');
}
function smallAlertWindowFailure() {
smallAlertWindow('top', 'error',
'Sorry, the operation failed, please try again ●^●');
}
function smallAlertWindowWithMessage(message) {
Swal.fire({
type: message.alertWindowType,
title: message.title,
position:'top',
customClass: 'customLayoutForDevice',
html: message.html
})
initPage();
}
function doPost(url, params, doSuccess, doFailure) {
$.ajax({
type: "POST",
url: url,
contentType: 'application/json',
data: JSON.stringify(params),
success: function (response) {
if (response) {
if (response.success) {
doSuccess(response.result);
} else {
let message = toolsLanguage === 'CN' ? response.messageCn
: response.messageEn;
smallAlertWindow('top', 'error',
'Sorry, the operation failed, please try again ●^● . '
+ response.retCode + '-' + response.errCode +
"-" + message);
}
}
},
error: function (response) {
doFailure(response);
}
})
}
function doGet(url, doSuccess, doFailure) {
$.ajax({
method: "GET",
url: url,
success: function (response) {
doSuccess(response);
},
error: function (response) {
doFailure(response);
}
})
}
function chooseLanguage(language) {
$("#settingsLanguageVal").val(language);
$("#settingsLanguageBtn").html(language)
}
function changeToolsVersion(version) {
$("#toolsVersion").val(version);
$("#toolsVersionBtn").html("V" + version)
}
function showLog(logSwitch) {
$("#settingsLogVal").val(logSwitch);
if (logSwitch == '0') {
$("#settingsLogBtn").html("ON")
} else {
$("#settingsLogBtn").html("OFF")
}
}
function initPage() {
doPost('/api/crm-x/getUserInfo/v1', {fingerprint: fingerprint},
function (res) {
let ops = res.userOperations;
if (ops && ops.length > 0) {
for (let i = 0; i < ops.length; i++) {
$("#operationClickCount" + ops[i].operation).html(
ops[i].clickCount);
}
}
toolsLanguage = res.userInfo.language;
if (res.userInfo.language === 'EN') {
let opNameArr = $(".opName");
let opDescArr = $(".opDesc");
for (let i = 0; i < opNameArr.size(); i++) {
opNameArr.eq(i).html(opNameArr.eq(i).attr("opnameen"))
opDescArr.eq(i).html(opDescArr.eq(i).attr("opdescen"))
}
} else {
let opNameArr = $(".opName");
let opDescArr = $(".opDesc");
for (let i = 0; i < opNameArr.size(); i++) {
opNameArr.eq(i).html(opNameArr.eq(i).attr("opnamecn"))
opDescArr.eq(i).html(opDescArr.eq(i).attr("opdesccn"))
}
}
// let createDate = date('Y-m-d H:i:s', '' + res.userInfo.createTime
// / 1000);
fillLogArea(res.logs, res.userInfo);
}, function () {
smallAlertWindow('top', 'error',
'Sorry , initializing the page failed !');
})
}
function numberAddOne(operationId) {
$("#operationClickCount" + operationId).html(parseInt(
$("#operationClickCount" + operationId).html()) + 1)
$("#userOperationClickCount" + operationId).html(parseInt(
$("#userOperationClickCount" + operationId).html())
+ 1)
}
function recordClickEvent(operationId) {
numberAddOne(operationId);
doPost("/api/crm-x/recordClickEven/v1",
{fingerprint: fingerprint, operation: operationId}
, function () {
}, function () {
smallAlertWindowFailure();
}
)
}
function fillLogArea(logs, userInfo) {
if (userInfo.showLog == '1') {
$("#logArea").css("display", "none")
} else {
$("#logArea").css("display", "block")
}
$("#logList").empty();
for (let i = 0; i < logs.length; i++) {
let log = logs[i];
let opName = log.opNameCn;
let remark = log.remarkCn;
let className = 'selfLog';
let user = log.fingerprint;
if (userInfo.language === 'EN') {
opName = log.opNameEn;
remark = log.remarkEn;
}
let createDate = date('Y-m-d H:i:s', '' + log.createTime / 1000);
if (log.fingerprint != fingerprint) {
className = 'otherLog';
}
if (log.nickName) {
user = log.nickName;
}
$("#logList").append(
$("<li class='" + className + "'>[" + createDate + "] [" + opName
+ "] [" + user + "] " + remark + "</li>"))
}
}
function saveSettings(params) {
doPost("/api/crm-x/saveSettings/v1", params
, function () {
initPage();
smallAlertWindow('top', 'success', 'Your work has been saved');
}, function () {
smallAlertWindowFailure();
}
)
}
function saveProfile(params) {
doPost('/api/crm-x/saveProfile/v1', params, function () {
initPage();
smallAlertWindow('top', 'success', 'Your work has been saved');
}, function () {
smallAlertWindowFailure();
})
}
function doOperation(operationId, executeMethod, configs) {
recordClickEvent(operationId);
if (!executeMethod || executeMethod == '' || executeMethod == 'null') {
eval("stepProcess(" + operationId + "," + configs + ")");
} else {
eval(executeMethod + "(" + operationId + "," + configs + ")");
}
}
function buildParams(operationId, propertyName, params, extraParams) {
let finalParams = {
operation: operationId,
fingerprint: fingerprint
};
$.extend(finalParams, extraParams);
for (let i = 0; i < propertyName.length; i++) {
finalParams[propertyName[i]] = params[i];
}
return finalParams;
}
function getValidators(validatorsName, tip) {
if (validatorsName === 'validate_is_empty') {
return (value) => {
return new Promise((resolve) => {
if (value === '') {
resolve(tip)
} else {
resolve()
}
})
}
} else if (validatorsName === 'validate_is_password') {
return (value) => {
return new Promise((resolve) => {
if (value === '' || value.length < 4 || value.length > 30) {
resolve(tip)
} else {
resolve()
}
})
}
} else if (validatorsName === 'validate_is_amount') {
return (value) => {
return new Promise((resolve) => {
if (value === '' || value > 20 || value < 1) {
resolve(tip)
} else {
resolve()
}
})
}
}
return null;
}
function stepProcess(operationId, configs) {
let config;
if (toolsLanguage === 'CN') {
config = configs.cn;
} else {
config = configs.en;
}
let queue = [];
let progressSteps = [];
for (let i = 0; i < config.queue.length; i++) {
progressSteps.push(i + 1);
let baseJson = {
inputAutoTrim: true
};
baseJson["inputValidator"] = getValidators(configs.basic.validators[i],
config.swal.tips[i])
let finalJson = $.extend({}, baseJson, config.queue[i]);
queue.push(finalJson);
}
Swal.mixin({
input: config.swal.input,
confirmButtonText: config.swal.confirmButtonText,
showCancelButton: true,
reverseButtons: true,
padding: '2rem',
position: 'top',
customClass: 'customLayout',
progressSteps: progressSteps
}).queue(queue).then((result) => {
if (result.value) {
doPost(configs.basic.url,
buildParams(operationId, configs.basic.args, result.value,
configs.basic.defaultArgs),
function (result) {
if (result) {
smallAlertWindowWithMessage(result)
} else {
smallAlertWindowSuccessful();
}
}, smallAlertWindowFailure
);
}
})
}
function operation_100(operationId, configs) {
let config;
if (toolsLanguage === 'CN') {
config = configs.cn;
} else {
config = configs.en;
}
doPost(configs.basic.url, {fingerprint: fingerprint},
function (userInfo) {
Swal.fire({
title: config.swal.title,
padding: config.swal.padding,
position: config.swal.position,
customClass: config.swal.customClass,
html:
'<form class="form-horizontal">'
+ ' <div class="form-group" style="margin-top:20px;">'
+ ' <label class="col-sm-4 control-label">'
+ config.template[0] + '</label>'
+ ' <input type="hidden" id="settingsLanguageVal" value="'
+ userInfo.language + '"/>'
+ ' <div class="col-sm-8">'
+ ' <div class="input-group-btn">'
+ ' <button type="button" id="settingsLanguageBtn" class="btn btn-default dropdown-toggle"'
+ ' style="width:100%;" data-toggle="dropdown" aria-haspopup="true"'
+ ' aria-expanded="false">'
+ ' ' + userInfo.language + ''
+ ' </button>'
+ ' <ul class="dropdown-menu" style="width:100%;text-align:center!important;">'
+ ' <li><a href="#" onclick="chooseLanguage(\'CN\')">CN</a></li>'
+ ' <li><a href="#" onclick="chooseLanguage(\'EN\')">EN</a></li>'
+ ' </ul>'
+ ' </div>'
+ ' </div>'
+ ' </div>'
+ ''
+ ' <div class="form-group">'
+ ' <label class="col-sm-4 control-label">'
+ config.template[1] + '</label>'
+ ' <input type="hidden" id="settingsLogVal" value="'
+ userInfo.showLog + '"/>'
+ ' <div class="col-sm-8">'
+ ' <div class="input-group-btn">'
+ ' <button type="button" id="settingsLogBtn" class="btn btn-default dropdown-toggle"'
+ ' style="width:100%;" data-toggle="dropdown" aria-haspopup="true"'
+ ' aria-expanded="false">'
+ ' ' + ((userInfo.showLog == '0') ? 'ON'
: 'OFF') + ''
+ ' </button>'
+ ' <ul class="dropdown-menu" style="width:100%;text-align:center!important;">'
+ ' <li><a href="#" onclick="showLog(\'0\')">ON</a></li>'
+ ' <li><a href="#" onclick="showLog(\'1\')">OFF</a></li>'
+ ' </ul>'
+ ' </div>'
+ ' </div>'
+ ' </div>'
+ ' <div class="form-group">'
+ ' <label class="col-sm-4 control-label">'
+ config.template[2] + '</label>'
+ ' <input type="hidden" id="toolsVersion" value="'
+ userInfo.version + '"/>'
+ ' <div class="col-sm-8">'
+ ' <div class="input-group-btn dropup">'
+ ' <button type="button" id="toolsVersionBtn" class="btn btn-default dropdown-toggle"'
+ ' style="width:100%;" data-toggle="dropdown" aria-haspopup="true"'
+ ' aria-expanded="false">'
+ ' V' + userInfo.version + ''
+ ' </button>'
+ ' <ul class="dropdown-menu" style="width:100%;text-align:center!important;">'
+ ' <li><a href="#" onclick="changeToolsVersion(\'1\')">V1</a></li>'
+ ' <li><a href="#" onclick="changeToolsVersion(\'2\')">V2</a></li>'
+ ' </ul>'
+ ' </div>'
+ ' </div>'
+ ' </div>'
+ '</form>',
focusConfirm: true,
showCancelButton: true,
reverseButtons: true,
confirmButtonText: config.swal.confirmButtonText,
preConfirm: () => {
return [$("#settingsLanguageVal").val(),
$("#settingsLogVal").val(), $("#toolsVersion").val()]
}
}).then((result) => {
if (result.value) {
let finalParams = {
fingerprint: fingerprint,
operation: operationId
};
for (let i = 0; i < configs.basic.args.length; i++) {
finalParams[configs.basic.args[i]] = result.value[i];
}
saveSettings(finalParams)
}
})
})
}
function operation_101(operationId, configs) {
let config;
if (toolsLanguage === 'CN') {
config = configs.cn;
} else {
config = configs.en;
}
doPost(configs.basic.url, {fingerprint: fingerprint},
function (userInfo) {
Swal.fire({
title: config.swal.title,
padding: config.swal.padding,
position: config.swal.position,
customClass: config.swal.customClass,
html:
'<form class="form-horizontal">'
+ ' <div class="form-group" style="margin-top:20px;">'
+ ' <label for="profileFingerprint" class="col-sm-4 control-label">'
+ config.template[0] + '</label>'
+ ' <div class="col-sm-8">'
+ ' <input type="text" readonly="true" class="form-control" value="'
+ userInfo.fingerprint + '" id="profileFingerprint"/>'
+ ' </div>'
+ ' </div>'
+ ' <div class="form-group">'
+ ' <label for="profileNickname" class="col-sm-4 control-label">'
+ config.template[1] + '</label>'
+ ' <div class="col-sm-8">'
+ ' <input type="text" class="form-control" value="'
+ userInfo.nickName
+ '" id="profileNickname" placeholder="Input your nickname"/>'
+ ' </div>'
+ ' </div>'
+ ' <div class="form-group">'
+ ' <label for="profileRegisterDate" class="col-sm-4 control-label">'
+ config.template[2] + '</label>'
+ ' <div class="col-sm-8">'
+ ' <input type="text" readonly="true" value="'
+ date('Y-m-d H:i:s', '' + userInfo.createTime / 1000)
+ '" class="form-control" id="profileRegisterDate" />'
+ ' </div>'
+ ' </div>'
+ ' <div class="form-group">'
+ ' <label for="profileScore" class="col-sm-4 control-label">'
+ config.template[3] + '</label>'
+ ' <div class="col-sm-8">'
+ ' <input type="text" readonly="true" value="'
+ userInfo.score
+ '" class="form-control" id="profileScore" />'
+ ' </div>'
+ ' </div>'
+ '</form>',
focusConfirm: true,
showCancelButton: true,
reverseButtons: true,
confirmButtonText: config.swal.confirmButtonText,
preConfirm: () => {
return [$("#profileNickname").val()]
}
}).then((result) => {
if (result.value) {
let finalParams = {
fingerprint: fingerprint,
operation: operationId
};
for (let i = 0; i < configs.basic.args.length; i++) {
finalParams[configs.basic.args[i]] = result.value[i];
}
saveProfile(finalParams)
}
})
})
}
function operation_12(operationId, configs) {
let config;
if (toolsLanguage === 'CN') {
config = configs.cn;
} else {
config = configs.en;
}
doPost(configs.basic.url, {fingerprint: fingerprint},
function (userInfo) {
Swal.fire({
title: config.swal.title,
padding: config.swal.padding,
position: config.swal.position,
customClass: 'customLayoutForNotification',
html:
'<div>'
+ ' <div class="input-group">'
+ ' <div class="input-group-btn">'
+ ' <button type="button" id="notificationDesc" class="btn btn-default dropdown-toggle"'
+ ' style="width:250px;" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">'
+ ' Normal origin purchase<span class="caret" style="margin-left:2px;"></span>'
+ ' </button>'
+ ' <ul class="dropdown-menu">'
+ ' <li><a href="#" class="fetchTemplate" onclick="fetchTemplate(1,this)">Normal origin'
+ ' purchase</a></li>'
+ ' <li><a href="#" class="fetchTemplate" onclick="fetchTemplate(2,this)">Renewal origin'
+ ' purchase</a></li>'
+ ' <li><a href="#" class="fetchTemplate" onclick="fetchTemplate(3,this)">Renewal subscription'
+ ' purchase</a></li>'
+ ' <li role="separator" class="divider"></li>'
+ ' <li><a href="#" class="fetchTemplate" onclick="fetchTemplate(4,this)">Refund</a></li>'
+ ' <li role="separator" class="divider"></li>'
+ ' <li><a href="#" class="fetchTemplate" onclick="fetchTemplate(5,this)">Charge back</a></li>'
+ ' <li role="separator" class="divider"></li>'
+ ' <li><a href="#" class="fetchTemplate" onclick="fetchTemplate(6,this)">Rebilling'
+ ' cancelled</a></li>'
+ ' <li><a href="#" class="fetchTemplate" onclick="fetchTemplate(7,this)">Rebilling cancelled by'
+ ' charge back</a></li>'
+ ' <li><a href="#" class="fetchTemplate" onclick="fetchTemplate(8,this)">Rebilling cancelled by'
+ ' notpossible</a></li>'
+ ' <li><a href="#" class="fetchTemplate" onclick="fetchTemplate(9,this)">Rebilling cancelled by'
+ ' refund</a></li>'
+ ' <li><a href="#" class="fetchTemplate" onclick="fetchTemplate(10,this)">Rebilling cancelled'
+ ' by requseted</a></li>'
+ ' <li><a href="#" class="fetchTemplate" onclick="fetchTemplate(11,this)">Rebilling cancelled'
+ ' by TCA</a></li>'
+ ' <li><a href="#" class="fetchTemplate" onclick="fetchTemplate(12,this)">Rebilling cancelled'
+ ' by TDL</a></li>'
+ ''
+ ' </ul>'
+ ' </div>'
+ ' <input type="hidden" id="templateIndex" value="1"/>'
+ ' <input type="number" class="form-control" placeholder="Invoice ID" id="invoiceId"/>'
+ ' <div class="input-group-btn">'
+ ' <a type="button" class="btn btn-default"'
+ ' onclick="replaceInvoiceId()">Swap'
+ ' </a>'
+ ' </div>'
+ ' </div>'
+ ' <textarea id="notification" rows="35" cols="78" style="resize:none;font-size:13px;margin-top:20px;"></textarea>'
+ '</div>',
focusConfirm: true,
showCancelButton: true,
reverseButtons: true,
confirmButtonText: config.swal.confirmButtonText,
preConfirm: () => {
return [$("#profileNickname").val()]
}
}).then((result) => {
if (result.value) {
let finalParams = {
fingerprint: fingerprint,
operation: operationId
};
for (let i = 0; i < configs.basic.args.length; i++) {
finalParams[configs.basic.args[i]] = result.value[i];
}
doSendNotification();
}
})
})
}
function operation_13(operationId, configs) {
let config;
if (toolsLanguage === 'CN') {
config = configs.cn;
} else {
config = configs.en;
}
doPost(configs.basic.url, {fingerprint: fingerprint},
function (userInfo) {
Swal.fire({
title: config.swal.title,
padding: config.swal.padding,
position: config.swal.position,
customClass: 'customLayoutForNotification',
html:'<div>'
+ '<div style="float:right;margin-bottom:10px;">'
+ '<form class="form-inline">'
+ ' <div class="form-group">'
+ ' <label class="sr-only" for="invoiceIdForEditRenewal">originOrderIdForEditRenewal</label>'
+ ' <input type="number" class="form-control" id="invoiceIdForEditRenewal"'
+ ' placeholder="Invoice ID"/>'
+ ' </div>'
+ ' <div class="form-group">'
+ ' <label class="sr-only" for="originOrderIdForEditRenewal">originOrderIdForEditRenewal</label>'
+ ' <input type="number" class="form-control" id="originOrderIdForEditRenewal"'
+ ' placeholder="Origin order ID"/>'
+ ' </div>'
+ ' <a class="btn btn-default" onclick="return doSearchRenewal()">Search</a>'
+ '</form>'
+ '</div>'
+ '<div>'
+ '<form class="form-horizontal">'
+ ' <input type="hidden" id="renewalId"/>'
+ ' <div class="form-group">'
+ ' <label for="originOrderID" class="col-sm-3 control-label">OriginOrderID</label>'
+ ' <div class="col-sm-9">'
+ ' <input type="text" class="form-control" id="originOrderID" readonly="readonly" placeholder="Origin order ID"/>'
+ ' </div>'
+ ' </div>'
+ ' <div class="form-group">'
+ ' <label for="subscriptionId" class="col-sm-3 control-label">SubscriptionId</label>'
+ ' <div class="col-sm-9">'
+ ' <input type="text" class="form-control" id="subscriptionId" placeholder="Subscription ID"/>'
+ ' </div>'
+ ' </div>'
+ ' <div class="form-group">'
+ ' <label for="nextPaymentDate" class="col-sm-3 control-label">NextPaymentDate</label>'
+ ' <div class="col-sm-9">'
+ ' <input type="text" class="form-control" id="nextPaymentDate"'
+ ' placeholder="Next payment date"/>'
+ ' </div>'
+ ' </div>'
+ ' <div class="form-group">'
+ ' <label for="invoiceExpireDate" class="col-sm-3 control-label">InvoiceExpireDate</label>'
+ ' <div class="col-sm-9">'
+ ' <input type="text" class="form-control" id="invoiceExpireDate"'
+ ' placeholder="Invoice expire date"/>'
+ ' </div>'
+ ' </div>'
+ ' <div class="form-group">'
+ ' <label for="renewalStatus" class="col-sm-3 control-label">RenewalStatus</label>'
+ ' <div class="col-sm-9">'
+ ' <input type="number" class="form-control" id="renewalStatus" placeholder="Renewal status"/>'
+ ' </div>'
+ ' </div>'
+ '</form>'
+ '</div>'
+ '</div>',
focusConfirm: true,
showCancelButton: true,
reverseButtons: true,
confirmButtonText: config.swal.confirmButtonText,
preConfirm: () => {
return [$("#profileNickname").val()]
}
}).then((result) => {
if (result.value) {
let finalParams = {
fingerprint: fingerprint,
operation: operationId
};
for (let i = 0; i < configs.basic.args.length; i++) {
finalParams[configs.basic.args[i]] = result.value[i];
}
doEditRenewal();
}
})
})
}
function formatJson(txt, compress/*是否为压缩模式*/) {/* 格式化JSON源码(对象转换为JSON文本) */
var indentChar = ' ';
if (/^\s*$/.test(txt)) {
alert('数据为空,无法格式化! ');
return;
}
try {
var data = eval('(' + txt + ')');
}
catch (e) {
alert('数据源语法错误,格式化失败! 错误信息: ' + e.description, 'err');
return;
}
;
var draw = [], last = false, This = this, line = compress ? '' : '',
nodeCount = 0, maxDepth = 0;
var notify = function (name, value, isLast, indent/*缩进*/, formObj) {
nodeCount++;
/*节点计数*/
for (var i = 0, tab = ''; i < indent; i++) {
tab += indentChar;
}
/* 缩进HTML */
tab = compress ? '' : tab;
/*压缩模式忽略缩进*/
maxDepth = ++indent;
/*缩进递增并记录*/
if (value && value.constructor == Array) {/*处理数组*/
draw.push(tab + (formObj ? ('"' + name + '":') : '') + '[' + line);
/*缩进'[' 然后换行*/
for (var i = 0; i < value.length; i++) {
notify(i, value[i], i == value.length - 1, indent, false);
}
draw.push(tab + ']' + (isLast ? line : (',' + line)));
/*缩进']'换行,若非尾元素则添加逗号*/
} else if (value && typeof value == 'object') {/*处理对象*/
draw.push(tab + (formObj ? ('"' + name + '":') : '') + '{' + line);
/*缩进'{' 然后换行*/
var len = 0, i = 0;
for (var key in value) {
len++;
}
for (var key in value) {
notify(key, value[key], ++i == len, indent,
true);
}
draw.push(tab + '}' + (isLast ? line : (',' + line)));
/*缩进'}'换行,若非尾元素则添加逗号*/
} else {
if (typeof value == 'string') {
value = '"' + value + '"';
}
draw.push(tab + (formObj ? ('"' + name + '":') : '') + value
+ (isLast ? '' : ',') + line);
}
;
};
var isLast = true, indent = 0;
notify('', data, isLast, indent, false);
return draw.join('');
}
|
var courses
var currentResults = []
var selected = []
var classSched = []
function main() {
// /*called when body loads*/
// scheduler.init('scheduler_here', new Date(), "week");
// loadData()
// $('#dropdown').find('a').click(function(e) {
// $('#semester').text(this.innerHTML);
// $('#semester').append('<span class="caret"></span>');
// });
// $("#search").on("keydown", function(e) {
// if (e.keyCode === 13) {
// //checks whether the pressed key is "Enter"
// search();
// }
// });
// $(":checkbox").mouseup(function() {
// $(this).blur();
// })
scheduler.config.repeat_date = "%m/%d/%Y";
scheduler.config.include_end_by = true;
scheduler.config.start_on_monday = false;
/*called when body loads*/
scheduler.init('scheduler_here', new Date(), "week");
scheduler.config.repeat_precise = true;
loadData()
$('#dropdown').find('a').click(function(e) {
$('#semester').text(this.innerHTML);
$('#semester').append('<span class="caret"></span>');
});
$("#search").on("keydown", function(e) {
if (e.keyCode === 13) {
//checks whether the pressed key is "Enter"
search();
}
});
$(":checkbox").mouseup(function() {
$(this).blur();
})
//Changes***
createEvent("MWF Course", "09:30", "10:20", "MWF");
createEvent("TTH Course", "12:30", "16:20", "TTH");
}
function timeConvert(str) {
var p = str.split(':'),
s = 0,
m = 1;
while (p.length > 0) {
s += m * parseInt(p.pop(), 10);
m *= 60;
}
return s;
}
function createEvent(course_name, start_time, end_time, repeat) {
var sd = "01/17/2017 "
var ed = "05/30/2017 "
var el = 60 * (timeConvert(end_time) - timeConvert(start_time))
var repNums
switch (repeat) {
case "MWF":
repNums = "1,3,5"
break;
case "TTH":
repNums = "2,4"
break;
case "F":
repNums = "5"
break;
case "W":
repNums = "3"
break;
case "M":
repNums = "1"
break;
case "T":
repNums = "2"
break;
case "TH":
repNums = "4"
break;
case "MW":
repNums = "1,3"
break;
default:
repNums = ""
}
classSched.push({
id: classSched.length + 1,
text: course_name,
start_date: sd + start_time + ":" + "00",
end_date: ed + end_time + ":" + "00",
event_length: el,
event_pid: "0",
rec_type: "week_1___" + repNums
});
//console.log(classSched)
scheduler.parse(classSched, "json"); //takes the name and format of the data source
}
//Changes***
function loadData() {
var campuses = ['Bryn_Mawr', 'Haverford', 'Swarthmore'];
var semesters = ['Fall_2015', 'Fall_2016', 'Spring_2016', 'Spring_2017'];
courses = {};
var urlStub = 'https://raw.githubusercontent.com/keikun555/triCoCourseSearch/master/data/';
//formats to json of campuses of semesters of courses
for (campus in campuses) {
var cam = {};
for (semester in semesters) {
//gets data from url, for every semester for every campus
url = urlStub + campuses[campus] + "/" + semesters[semester] + ".json";
sem = $.parseJSON($.ajax({
url: url,
async: false,
success: function(data) {}
})["responseText"]);
cam[semesters[semester]] = sem;
}
courses[campuses[campus]] = cam;
}
console.log(courses)
}
function find(searchText, semester, campuses) {
/*given string, chosen semester, and chosen campuses, return list of courses within conditions*/
var options = {
shouldSort: true,
threshold: 0.6,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: [
"Course Title",
"Registration ID",
"Room Location"
]
};
list = []
for (campus in campuses) {
tempList = courses[campuses[campus]][semester].reduce(function(L, element) {
return L.concat(element);
}, [])
for (course in tempList) {
list.push(tempList[course]); //creating master list to search from
}
}
//search the list
var fuse = new Fuse(list, options)
return fuse.search(searchText)
//
// result = [];
// for (campus in campuses) {
// result.push(courses[campuses[campus]][semester].filter(function(course) {
// values = []
// for (element in course) {
// values.push(course[element])
// }
// for (word in searchText) {
// for (value in values) {
// if (values[value].toLowerCase().includes(searchText[word].toLowerCase())) {
// return true
// }
// }
// }
// return false
// }));
// }
// result = result.reduce(function(list, campus) {
// return list.concat(campus);
// }, []);
// return result
}
function search() {
var table = document.getElementById("table");
var tableHeader = '<thead><tr><th style="text-align: center;">Course Name</th><th style="text-align: center;">Registration ID</th><th style="text-align: center;">Course Number</th><th style="text-align: center;">Time Offered</th><th style="text-align: center;">Instructor</th><th style="text-align: center;">Campus</th></tr></thead>'
searchText = document.getElementById("search").value.trim() //.split(' ');
//if nothing in searchText, shows all courses in given campus and semester
semester = document.getElementById('semester').textContent.split(' ');
if (semester[0] === 'Select') {
//if no semester is selected, choose most recent one
semester = $('#dropdown').find('a').first().text().split(' ');
}
semester = semester.reverse().join('_');
allcampuses = ["brynmawr", "haverford", "swarthmore"];
campuses = allcampuses.filter(function(campus) {
return ($('#' + campus).attr('aria-pressed') === 'true');
});
if (campuses.length <= 0) {
//if no campuses are selected, choose all campuses
campuses = allcampuses
}
if (campuses.includes('brynmawr')) {
campuses[campuses.indexOf('brynmawr')] = 'Bryn_Mawr';
}
for (campus in campuses) {
campuses[campus] = campuses[campus].charAt(0).toUpperCase() + campuses[campus].slice(1);
}
result = find(searchText, semester, campuses);
currentResults = result
$(table).html(tableHeader)
if (result.length > 0) {
for (course in result) {
var name = result[course]['Course Title'];
var id = result[course]['Registration ID'];
var num = result[course]['CRN'];
var time = result[course]['Time And Days'].split(', ').join(',').split(',').join('<br>');
var prof = result[course]['Instructor'].split(', ').join(',').split(',').join(', ');
var camp = result[course]['Campus'].split('_').join(' ');
var row;
if (camp === "Swarthmore") {
row = `<tbody><tr class='t' onclick='cSwap(this)' data-toggle="buttons-toggle"><td height="50">${name}</td><td>${id}</td><td>${num}</td><td>${time}</td><td>${prof}</td><td>${camp}</td></tr></tbody>`
$(table).append(row);
} else if (camp === "Haverford") {
row = `<tbody><tr class='t' onclick='cSwap(this)' data-toggle="buttons-toggle"><td height="50">${name}</td><td>${id}</td><td>${num}</td><td>${time}</td><td>${prof}</td><td>${camp}</td></tr></tbody>`
$(table).append(row);
} else {
row = `<tbody><tr class='t' onclick='cSwap(this)' data-toggle="buttons-toggle"><td height="50">${name}</td><td>${id}</td><td>${num}</td><td>${time}</td><td>${prof}</td><td>${camp}</td></tr></tbody>`
$(table).append(row);
}
}
} else {
$(table).html('<div class="alert alert-warning"><strong>No classes found!</strong></div>')
}
}
function update(checkbox) {
course = currentResults[checkbox.id]
if ($(checkbox).attr('aria-pressed') === "false") {
selected.push(course)
index = courses[course["Campus"]][course["Semester"]].indexOf(course)
if (index > -1) {
courses[course["Campus"]][course["Semester"]].splice(index, 1)
}
//console.log(`Added ${course["Course Title"]} (${course["Campus"]}) to selected`)
} else if ($(checkbox).attr('aria-pressed') === "true") {
courses[course["Campus"]][course["Semester"]].push(course)
index = selected.indexOf(course)
if (index > -1) {
selected.splice(index, 1)
}
//console.log(`Removed ${course["Course Title"]} (${course["Campus"]}) from selected`)
}
}
function cSwap(row){
if (row.className == "t")
row.className = "t2";
else if (row.className == "t2")
row.className = "t";
}
/* used for debugging
function get_type(thing) {
if (thing === null) return "[object Null]"; // special case
return Object.prototype.toString.call(thing);
}
*/
|
import { fromJS } from 'immutable'
import { createReducer } from 'bypass/utils/index'
import * as actions from '../constants/orders'
const initialState = fromJS({
orders: [],
total: 0,
perpage: 30,
timeout: 1800,
checkTimeout: 0,
detail: {
checkTimeout: 0,
cards: [],
},
})
export default createReducer(initialState, {
[actions.load]: (state, { data, count, offset, perpage, timeout, check_timeout }) => {
const orders = offset > 0 ? state.get('orders').concat(data) : data
return state.merge(fromJS({
offset,
perpage,
timeout,
orders,
total: parseInt(count, 10),
checkTimeout: check_timeout,
}))
},
[actions.select]: (state, { row }) => {
const index = state.get('orders')
.findIndex(item => item.get('order_id') === row.get('order_id'))
if (index !== -1) {
const updated = state.setIn(['orders', index, 'selected'], !row.get('selected'))
return updated.set(
'hasSelected',
updated.get('orders')
.some(item => item.get('selected'))
)
}
return state
},
[actions.selectAll]: state => {
const selected = !state.get('allSelected')
return state.set('orders', state.get('orders').map(card => card.set('selected', selected)))
.set('allSelected', selected)
.set('hasSelected', selected)
},
[actions.loadOrder]: (state, { data, check_timeout, show }) => {
const cards = show === '0' ? data.filter(card => card.returned != 3) : data // eslint-disable-line eqeqeq
return state.mergeIn(['order'], fromJS({
checkTimeout: check_timeout,
total: cards.length,
cards,
}))
},
})
|
import React from 'react';
import "./css/Books.css"
import {BooksData} from './booksData';
import {BooksLists} from './booksList';
// Making a Booklists component
const Books = () => {
return (
<section className='section__app__books'>
{BooksData.map( (book) => {
return (
<BooksLists key={book.id} {...book} />
)
})}
</section>
)
}
export default Books;
|
export * from "./IntroItem";
|
import Vue from 'vue'
import Router from 'vue-router'
import ShoppingMall from '@/components/pages/ShoppingMall'
import Register from '@/components/pages/Register'
import Login from '@/components/pages/Login'
import Collects from '@/components/pages/Collects'
import Goods from '@/components/pages/goods'
import CategoryList from '@/components/pages/CategoryList'
import Cart from '@/components/pages/Cart'
import Main from '@/components/pages/Main'
import Member from '@/components/pages/Member'
import Search from '@/components/pages/Search'
import Order from '@/components/pages/Order'
import HistoryTrail from '@/components/pages/HistoryTrail'
Vue.use(Router)
export default new Router({
routes: [
{path:'/main',name:'Main',component:Main,
children:[
{path:'/',name:'ShoppingMall',component:ShoppingMall},
{path:'/CategoryList',name:'CategoryList',component:CategoryList},
{path:'/Cart',name:'Cart',component:Cart},
{path:'/Member',name:'Member',component:Member},
{path:'/search',name:'Search',component:Search},
]
},
{path:'/register',name:'Register',component:Register},
{path:'/order',name:'Order',component:Order},
{path:'/login',name:'Login',component:Login},
{path:'/collects',name:'Collects',component:Collects},
{path:'/historyTrail',name:'HistoryTrail',component:HistoryTrail},
{path:'/goods',name:'Goods',component:Goods},
{path: "*", redirect: "/main"}
]
})
|
const EventEmitter = require('events');
const amqp = require('amqplib/callback_api');
// -----------------------------------------------------------------------------
// Private functions
// -----------------------------------------------------------------------------
function messagePreHandler(callback, msg, channel) {
callback(msg, (err) => {
if (err) {
channel.reject(msg, true);
} else {
channel.ack(msg);
}
});
}
// -----------------------------------------------------------------------------
// Class definition
// -----------------------------------------------------------------------------
class RabbitMQClient extends EventEmitter {
constructor(url, prefetch) {
super();
this.url = url;
this.amqpConn = null;
this.receiveChannel = null;
this.pubChannel = null;
this.offlinePubQueue = [];
this.offlineDepth = 0;
this.prefetch = prefetch;
}
connect() {
let clazz = this;
amqp.connect(clazz.url, function (err, conn) {
if (err) {
console.error('[AMQP]', err.message);
return setTimeout(() => {
clazz.connect(clazz.url);
}, 3000);
}
conn.on('error', function (conErr) {
if (conErr.message !== 'Connection closing') {
console.error('[AMQP] conn error', conErr.message);
return setTimeout(() => {
clazz.connect();
}, 3000);
}
});
conn.on('close', function () {
console.error('[AMQP] reconnecting');
return setTimeout(() => {
clazz.connect();
}, 3000);
});
clazz.amqpConn = conn;
clazz.createPublishChannel(() => {
clazz.createReceiveChannel(() => {
clazz.emit('connected');
});
});
});
}
createPublishChannel(next) {
let clazz = this;
clazz.amqpConn.createConfirmChannel(function (err, ch) {
if (err) {
clazz.amqpConn.close();
clazz.amqpConn = null;
return;
}
ch.on('error', function (chanErr) {
console.error('[AMQP] channel error', chanErr.message);
});
ch.on('close', function () {
console.log('[AMQP] channel closed');
});
clazz.pubChannel = ch;
next();
function publishOneOfflineMessage() {
if (clazz.offlineDepth > 10) {
console.log('Too many offline messages. Throttling back...');
return;
}
if (clazz.pubChannel && clazz.offlinePubQueue && clazz.offlinePubQueue.length > 0) {
let m = clazz.offlinePubQueue.shift();
if (m) {
clazz.publish(m[0], m[1]);
clazz.offlineDepth++;
publishOneOfflineMessage();
}
}
}
setInterval(function () {
if (clazz.offlinePubQueue && clazz.offlinePubQueue.length > 0) {
console.log(clazz.offlinePubQueue.length + ' messages in offline queue');
}
clazz.offlineDepth = 0;
publishOneOfflineMessage();
}, 5000);
});
}
createReceiveChannel(next) {
let clazz = this;
clazz.amqpConn.createChannel(function (err, ch) {
if (err) {
clazz.amqpConn.close();
clazz.amqpConn = null;
return;
}
ch.on('error', function (chanErr) {
console.error('[AMQP] channel error', chanErr.message);
});
ch.on('close', function () {
console.log('[AMQP] channel closed');
});
ch.prefetch(clazz.prefetch);
clazz.receiveChannel = ch;
next();
});
}
subscribe(queueName, callback) {
let clazz = this;
const options = {
noAck: false
};
clazz.receiveChannel.assertQueue(queueName, { durable: true }, (err) => {
if (err) {
clazz.amqpConn.close();
clazz.amqpConn = null;
return;
}
clazz.receiveChannel.consume(queueName, (msg) => { messagePreHandler(callback, msg, clazz.receiveChannel); }, options);
});
}
publish(queueName, message, callback) {
let clazz = this;
if (clazz.pubChannel) {
try {
clazz.pubChannel.publish('', queueName, message, { persistent: true }, (err) => {
if (err) {
console.error('[AMQP] publish', err);
clazz.offlinePubQueue.push([queueName, message]);
if (clazz.pubChannel && clazz.pubChannel.connection) {
clazz.pubChannel.connection.close();
}
clazz.pubChannel = null;
if (callback) {
callback(err);
}
} else if (callback) {
callback();
}
});
} catch (e) {
console.error('[AMQP] publish', e.message);
clazz.offlinePubQueue.push([queueName, message]);
if (clazz.pubChannel && clazz.pubChannel.connection) {
clazz.pubChannel.connection.close();
}
clazz.pubChannel = null;
if (callback) {
callback(e);
}
}
} else {
clazz.offlinePubQueue.push([queueName, message]);
if (callback) {
callback();
}
}
}
}
module.exports = RabbitMQClient;
|
'use strict';
const getDropdownOpen = (target) => {
while (!target.classList.contains('nav-dropdown-button')) {
target = target.parentElement;
if (!target) {
return undefined;
}
}
return target;
};
window.onclick = (event) => {
const button = getDropdownOpen(event.target);
if (button) {
const target = button.getAttribute('data-target');
document.getElementById(target).classList.toggle('show');
return;
}
if (event.target.classList.contains('nav-dropdown') ||
event.target.classList.contains('mobile-nav-dropdown')) {
return;
}
const dropdowns = document.querySelectorAll('.nav-dropdown,.mobile-nav-dropdown');
for (let i = 0; i < dropdowns.length; i++) {
const openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
};
function getErrorLogElement() {
return document.querySelector('#error_log') || (() => {
const element = document.createElement('textarea');
element.id = 'error_log';
element.style.width = '100%';
element.style.position = 'fixed';
element.style.bottom = '0';
element.style['z-index'] = '100';
element.style.background = '#ddd';
element.style.color = 'red';
document.body.appendChild(element);
return element;
})();
}
window.onerror = function(msg, file, line, column, err) {
getErrorLogElement().value += (err && err.stack) || `${msg}
at ${file}:${line}:${column}`;
};
|
import { defineConfig } from 'vite'
import semver from 'semver'
import envCompatible from 'vite-plugin-env-compatible'
import htmlTemplate from 'vite-plugin-html-template'
import vueCli, { cssLoaderCompat } from 'vite-plugin-vue-cli'
import mpa from 'vite-plugin-mpa'
import Checker from 'vite-plugin-checker'
import { VlsChecker } from 'vite-plugin-checker-vls'
import eslintPlugin from 'vite-plugin-eslint'
import path from 'path'
import chalk from 'chalk'
import styleImport from 'vite-plugin-style-import'
const resolve = (p) => path.resolve(process.cwd(), p)
process.env.NODE_ENV = process.env.NODE_ENV || 'development'
// vue.config.js
let vueConfig = {}
try {
vueConfig = require(resolve('vue.config.js')) || {}
} catch (e) {
if (process.env.VITE_DEBUG) {
console.error(chalk.redBright(e))
}
}
let vueVersion = 2
try {
const Vue = require('vue')
vueVersion = semver.major(Vue.version)
} catch (e) {}
const pluginOptions = vueConfig.pluginOptions || {}
const viteOptions = pluginOptions.vite || {}
const optimizeDeps = viteOptions.optimizeDeps || {}
const extraPlugins = viteOptions.plugins || []
const vitePluginVue2Options = viteOptions.vitePluginVue2Options || {}
const vitePluginVue3Options = viteOptions.vitePluginVue3Options || {}
const useMPA = Boolean(vueConfig.pages)
const overlay = (() => {
if (typeof vueConfig === 'undefined') {
return true
}
if (typeof vueConfig.devServer === 'undefined') {
return true
}
if (typeof vueConfig.devServer.overlay === 'undefined') {
return true
}
if (typeof vueConfig.devServer.overlay === 'boolean') {
return vueConfig.devServer.overlay !== false
} else {
return (
vueConfig.devServer.overlay.warnings !== false || vueConfig.devServer.overlay.errors !== false
)
}
})()
/**
* @see {@link https://vitejs.dev/config/}
*/
export default defineConfig({
plugins: [
envCompatible(),
styleImport({
libs: [
{
libraryName: 'vant',
esModule: true,
resolveStyle: (name) => `vant/es/${name}/style`,
},
],
}),
viteOptions.cssLoaderCompat !== false ? cssLoaderCompat() : undefined,
vueCli(),
// lazyload plugin for vue-template-compiler mismatch errors.
vueVersion === 2
? require('vite-plugin-vue2')['createVuePlugin'](vitePluginVue2Options)
: [
require('@vitejs/plugin-vue')(),
vitePluginVue3Options.jsx
? require('@vitejs/plugin-vue-jsx')(vitePluginVue3Options.jsx)
: undefined,
],
useMPA ? mpa() : undefined,
// auto infer pages if needed.
viteOptions.disabledHtmlTemplate
? undefined
: htmlTemplate(vueConfig.pages ? { pages: vueConfig.pages } : undefined),
// since vue-cli have type-checker by default(but use webpack plugin instead of vls).
// viteOptions.disabledTypeChecker
// ? undefined
// : Checker(
// vueVersion === 2
// ? /* temporarily enabled for development */ process.env.NODE_ENV === 'development'
// ? {
// overlay,
// vls: VlsChecker(/** advanced VLS options */),
// }
// : undefined
// : process.env.NODE_ENV === 'development'
// ? {
// overlay,
// vueTsc: true,
// }
// : undefined,
// ),
// vue-cli enable eslint-loader by lintOnSave.
viteOptions.disabledLint
? undefined
: /* temporarily enabled for development */ process.env.NODE_ENV === 'development'
? eslintPlugin({
/**
* deal with some virtual module like react/refresh or windicss.
* @see {@link https://github.com/gxmari007/vite-plugin-eslint/issues/1}
*/
include: 'src/**/*.{vue,js,jsx,ts,tsx}',
fix:true
})
: undefined,
// ...extraPlugins,
],
optimizeDeps: {
...optimizeDeps,
/**
* vite auto scan html files and rollupOptions.input but vite-plugin-html-template cannot enforce pre.
* set explicit entries here. main.{js,ts} is the default vue-cli entries.
*/
entries: ['**/main.{js,ts}', ...(optimizeDeps.entries || [])],
},
})
|
'use strict';
const got = require('got');
const cheerio = require('cheerio');
const table = require('columnify');
const chalk = require('chalk');
const wrap = require('wordwrap')(90);
const open = require('open');
const SEARCH_URL = {
js: 'JavaScript/Reference/Global_Objects',
css: 'CSS'
};
const getBaseUrl = locale => `https://developer.mozilla.org/${locale}/docs/Web`;
const format = (markup, url) => {
const $ = cheerio.load(markup);
const title = $('#wiki-document-head h1').text();
const method = title.split('.').pop();
const methodWithoutParens = method.replace(/\(\)/, '');
const description = $('#wikiArticle > p')
.filter((index, element) => $(element).text().length !== 0)
.first()
.text()
.replace(title, chalk.bold(title))
.replace(method, chalk.bold(method));
const usage = $('#Syntax')
.next('pre')
.text()
.trim()
.split(/\n/)
.map((line, index) => {
return `\t${index} | ${line}\n`;
})
.join('')
.replace(new RegExp(methodWithoutParens, 'gim'), chalk.underline(methodWithoutParens));
const api = [];
console.log(`\n${chalk.bold(title)}`);
console.log(`\n${wrap(description)}\n`);
if (/[a-z]/.test(usage)) {
console.log(`${usage}\n`);
}
$('#wikiArticle').children('dl').children('dt')
.has('code')
.each((index, element) => {
const $element = $(element);
const term = $element.text();
const $definition = $element.next('dd');
if ($definition.has('dl').length === 0) {
api.push({
term: chalk.bold(term),
definition: $definition.text().replace(new RegExp(term, 'gim'), chalk.bold(term))
});
api.push({
term: '',
definition: ''
});
} else {
api.push({
term: chalk.bold(term),
definition: $definition.text().substr(0, $definition.text().search('\n'))
});
$definition.children('dl').children('dt').each((subIndex, subElement) => {
const $subElement = $(subElement);
const subTerm = $subElement.text();
const subDefinition = $subElement
.next('dd')
.text()
.replace(new RegExp(subTerm, 'gim'), chalk.underline(subTerm));
api.push({
term: `..${chalk.underline(subTerm)}`,
definition: `..${subDefinition}`
});
});
api.push({
term: '',
definition: ''
});
}
});
console.log(table(api, {
showHeaders: false,
config: {
term: {
minWidth: 15
},
definition: {
maxWidth: 65
}
}
}));
console.log(`${chalk.dim(url)}`);
};
const fetch = (keyword, language, shouldOpen, locale) => {
const baseUrl = getBaseUrl(locale);
const parts = keyword.replace(/prototype\./, '').split('.');
const url = `${baseUrl}/${SEARCH_URL[language]}/${parts[0]}/${parts[1] || ''}`;
const options = {
headers: {
'user-agent': 'https://github.com/rafaelrinaldi/mdn'
}
};
if (shouldOpen) {
return new Promise(resolve => {
resolve(open(url));
});
}
return got(url, options)
.then(response => {
format(response.body, url);
})
.catch(error => {
if (error.statusCode === 404) {
console.error(`"${keyword}" not found for language "${language}"`);
} else {
console.error(error.stack);
}
process.exit(1);
});
};
module.exports = options => fetch(
options.keyword,
options.language,
options.shouldOpen,
options.locale
);
|
import Vue from 'vue'
import VueRouter from 'vue-router'
import {viewList} from './view.List'
Vue.use(VueRouter); //router-link router-view
const routes = new VueRouter({
mode: 'history',
routes:[
{
path:'/',
redirect:'/index/home'
},
{
path:'/index',
beforeEnter(to,from,next){
let token = window.localStorage.getItem('token');
if(token && token.split('.').length === 3){
next();
}else{
routes.replace('/login');
}
},
component:()=>import('@/views/Index/index.vue'),
children:[
{
path:'home',
component:()=>import('@/views/Index/components/index.vue')
},
{
path:'/index',
redirect:'/index/home'
},
...viewList
]
},
{
path:'/login',
component:()=>import('@/views/Login/index.vue')
},
{
path:'/registry',
component:()=>import('@/views/Registry/index.vue')
}
]
})
export default routes;
|
var collide = function(obj1, obj2){
if (obj1.position.x<obj2.position.x+118 && obj1.position.x>obj2.position.x && obj1.position.y<obj2.position.y && obj1.position.y>obj2.position.y-49){
return true
}else
return false
}
|
// import { StoreCustomer } from './storecustomer';
var shopper = new StoreCustomer('Oscar', 'Negrete');
shopper.showName();
|
import firebase from 'firebase';
require('@firebase/firestore')
var firebaseConfig = {
apiKey: "AIzaSyA8GHtSRTRMU6SpWYd_z_qqCOvaN0JmpC4",
authDomain: "shantanu-17232.firebaseapp.com",
databaseURL: "https://shantanu-17232.firebaseio.com",
projectId: "shantanu-17232",
storageBucket: "shantanu-17232.appspot.com",
messagingSenderId: "970871607884",
appId: "1:970871607884:web:6a9b6e1ed2fd57c23bdae9"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
export default firebase.firestore();
|
import { from, of } from 'rxjs';
import {
tap,
catchError,
map,
switchMap,
ignoreElements
} from 'rxjs/operators';
import { ofType } from 'redux-observable';
import { LOGIN_SUBMITED, LOGIN_SUCCESS, LOGOUT } from './loginConstants';
import { loginUser } from './loginService';
import { loginFailAction, loginSuccessAction } from './loginActions';
import { loadQuestionsAction } from '../question/questionActions';
export const loginSuccessEpic = action$ => {
return action$.pipe(
ofType(LOGIN_SUCCESS),
map(() => loadQuestionsAction())
);
};
export const logoutEpic = action$ => {
return action$.pipe(
ofType(LOGOUT),
tap(() => {
localStorage.setItem('authedUser', JSON.stringify(null));
}),
ignoreElements()
);
};
export const loginEpic = action$ => {
return action$.pipe(
ofType(LOGIN_SUBMITED),
switchMap(({ login: { username, password } }) => {
const user = loginUser(username, password);
const ob$ = from(user);
return ob$.pipe(
map(user => loginSuccessAction(user)),
catchError(error =>
of(error).pipe(map(error => loginFailAction(error)))
)
);
})
);
};
|
import http from '../services/http';
import { users_list, users_delete, users_add, users_details, users_edit } from "../utils/endpoints";
export function getUsersData(data) {
return new Promise((resolve, reject) => {
http.Request("get", users_list, null)
.then(response => resolve(response) )
.catch(error => reject(error));
});
}
export function deleteUserData(data) {
return new Promise((resolve, reject) => {
http.Request("delete", users_delete + data.data.id, null)
.then(response => resolve(response) )
.catch(error => reject(error));
});
}
export function addUserData(data) {
return new Promise((resolve, reject) => {
http.Request(data.data.id ? "put" : "post", data.data.id ? users_edit + data.data.id : users_add, data.data)
.then(response => resolve(response) )
.catch(error => reject(error));
});
}
export function getUserRow(data) {
return new Promise((resolve, reject) => {
http.Request("get", users_details + data.data.id, null)
.then(response => resolve(response) )
.catch(error => reject(error));
});
}
|
import { curry } from "../curry/curry"
import { pipe } from "../pipe/pipe"
const _maxBy = (_fn, source) => {
const fn = Array.isArray(_fn) ? pipe(..._fn) : _fn
if (source.length === 0) {
return undefined
}
const result = {
item: source[0],
value: fn.call(null, source[0]),
}
for (let i = 1, length = source.length; i < length; i++) {
if (result.value < fn.call(null, source[i])) {
result.item = source[i]
result.value = fn.call(null, result.item)
}
}
return result.item
}
/**
* Find the maximum value in a source array
*
* @param {number[]} source Array of numbers
*
* @returns {number}
*
* @name max
* @tag Array
* @signature (source: Number[]): Number
* @signature (fn: Function, source: Number[]): Number
*
* @example
* max([-1, 1, 10, 3])
* // => 10
*
* const fn = element => (new Date(element.time))
* const source = [
* { time: "2018-05-15T11:20:07.754110Z" },
* { time: "2018-06-11T09:01:54.337344Z" },
* { time: "2018-06-08T08:26:12.711071Z" },
* ]
* max(fn, source)
* // => {time: "2018-06-11T09:01:54.337344Z"}
*/
export const max = source => {
if (source.length === 0) {
return undefined
}
let [maxValue] = source
for (let i = 0, length = source.length; i < length; i++) {
if (maxValue < source[i]) {
maxValue = source[i]
}
}
return maxValue
}
export const maxBy = curry(_maxBy)
|
import Todo from "./component/Todo";
function App() {
return (
<div>
<h1>My Todos</h1>
<Todo text="Learn React from scratch" />
<Todo text="Master React" />
<Todo text="Explore React course" />
</div>
);
}
export default App;
|
let y = 4;
for (let i = 1; i <= 10; i++){
console.log(y)
y+=3
}
|
const wallet = {
namespaced: true,
state: {
accounts: [],
activeAccount: null,
balance: null,
mutations: null,
receiveAddress: null,
walletBalance: null,
walletPassword: null,
unlocked: false
},
mutations: {
SET_ACCOUNTS(state, accounts) {
state.accounts = accounts;
},
SET_ACTIVE_ACCOUNT(state, accountUUID) {
state.activeAccount = accountUUID;
},
SET_BALANCE(state, balance) {
state.balance = balance;
},
SET_MUTATIONS(state, mutations) {
state.mutations = mutations;
},
SET_RECEIVE_ADDRESS(state, receiveAddress) {
state.receiveAddress = receiveAddress;
},
SET_WALLET_BALANCE(state, walletBalance) {
state.walletBalance = walletBalance;
},
SET_WALLET_PASSWORD(state, password) {
state.walletPassword = password;
},
SET_UNLOCKED(state, unlocked) {
state.unlocked = unlocked;
},
SET_WALLET(state, payload) {
// batch update state properties from payload
for (const [key, value] of Object.entries(payload)) {
state[key] = value;
}
}
},
actions: {
SET_ACCOUNT_NAME({ state, commit }, payload) {
let accounts = [...state.accounts];
let account = accounts.find(x => x.UUID === payload.accountUUID);
account.label = payload.newAccountName;
commit("SET_ACCOUNTS", accounts);
},
SET_ACCOUNTS({ commit }, accounts) {
commit("SET_ACCOUNTS", accounts);
},
SET_ACTIVE_ACCOUNT({ commit }, accountUUID) {
// clear mutations and receive address
commit("SET_RECEIVE_ADDRESS", { receiveAddress: "" });
commit("SET_ACTIVE_ACCOUNT", accountUUID);
commit("SET_MUTATIONS", { mutations: null });
},
SET_BALANCE({ commit }, new_balance) {
commit("SET_BALANCE", new_balance);
},
SET_MUTATIONS({ commit }, mutations) {
commit("SET_MUTATIONS", mutations);
},
SET_RECEIVE_ADDRESS({ commit }, receiveAddress) {
commit("SET_RECEIVE_ADDRESS", receiveAddress);
},
SET_WALLET_BALANCE({ commit }, walletBalance) {
commit("SET_WALLET_BALANCE", walletBalance);
},
SET_WALLET_PASSWORD({ commit }, password) {
commit("SET_WALLET_PASSWORD", password);
},
SET_UNLOCKED({ commit }, unlocked) {
commit("SET_UNLOCKED", unlocked);
},
SET_WALLET({ commit }, payload) {
commit("SET_WALLET", payload);
}
},
getters: {
totalBalance: state => {
let balance = state.walletBalance;
if (balance === undefined || balance === null) return null;
return balance.availableIncludingLocked + balance.unconfirmedIncludingLocked + balance.immatureIncludingLocked;
},
lockedBalance: state => {
let balance = state.walletBalance;
if (balance === undefined || balance === null) return null;
return balance.totalLocked;
},
spendableBalance: state => {
let balance = state.walletBalance;
if (balance === undefined || balance === null) return null;
return balance.availableExcludingLocked;
},
pendingBalance: state => {
let balance = state.walletBalance;
if (balance === undefined || balance === null) return null;
return balance.unconfirmedExcludingLocked;
},
immatureBalance: state => {
let balance = state.walletBalance;
if (balance === undefined || balance === null) return null;
return balance.immatureIncludingLocked;
},
accounts: state => {
return state.accounts
.filter(x => x.state === "Normal")
.sort((a, b) => {
const labelA = a.label.toUpperCase();
const labelB = b.label.toUpperCase();
let comparison = 0;
if (labelA > labelB) {
comparison = 1;
} else if (labelA < labelB) {
comparison = -1;
}
return comparison;
});
},
account: state => {
return state.accounts.find(x => x.UUID === state.activeAccount);
},
miningAccount: state => {
return state.accounts.find(x => x.type === "Mining" && x.state === "Normal"); // this will retrieve the first account of type Mining
}
}
};
export default wallet;
|
function Order(customerName, date, orderId, orderDetails) {
var _customerName = customerName;
var _date = date;
var _oid = orderId;
var _orderDetails = orderDetails;
this.getCustomerName = function () {
return _customerName;
}
this.getOrderDate = function () {
return _date;
}
this.getOrderId = function () {
return _oid;
}
this.getOrderDetails = function () {
return _orderDetails;
}
this.setCustomerName = function (customerName) {
_customerName = customerName;
}
this.setOrderDate = function (orderDate) {
_date = orderDate;
}
this.setOrderId = function (orderID) {
_oid = orderID;
}
this.setOrerDetails = function (orderDetails) {
_orderDetails = orderDetails;
}
}
|
onmessage = function (e) {
//pelota.postMessage(e.data);
//pelota.postMessage(e.data[0]);
detectarColision(e.data[0],e.data[1],e.data[2]);
};
function detectarColision(pared,pelota,canvas){
var width = 20, height = 150;
var parx, pary;
for (let i = 0; i <2; i++) {
if(i == 0){
parx = pared.p1x;
pary = pared.p1y;
}else{
parx = pared.p2x;
pary = pared.p2y;
}
let x = Math.sqrt(Math.pow(pelota.px - parx, 2));
let y = Math.sqrt(Math.pow(pelota.py - pary, 2));
if (x - pelota.prad - width <= 0)
if (y - pelota.prad - height <= 0) {
console.log("COLISION 1" + pelota.pdx);
pelota.pdx = -pelota.pdx;
}
}
console.log("PDX1 " + pelota.pdx);
console.log("PDY1 " + pelota.pdy);
if (pelota.py + pelota.prad > canvas.cH || pelota.py - pelota.prad < 0){
//pelota.dy = -pelota.dy;
pelota.pdy = -pelota.pdy;
console.log("COLISION 2 " + pelota.pdy);
}
if (pelota.px + pelota.prad > canvas.cW || pelota.px - pelota.prad < 0){
//pelota.dx = -pelota.dx;
pelota.pdx = -pelota.pdx;
console.log("COLISION 3 " + pelota.pdx);
}
console.log("PDX2 " + pelota.pdx);
console.log("PDY2 " + pelota.pdy);;
this.postMessage([pelota.pdx,pelota.pdy]);
}
|
import moment from 'moment';
import ramda from 'ramda';
import tenures from './tenures';
const { memoize } = ramda;
function convert(...args) {
let duration, units;
if (args.length === 3) {
const start = args[0];
const end = args[1];
units = args[2];
duration = durationFromStartAndEnd(start, end);
} else {
units = args[1];
duration = Number(args[0]);
if (Number.isNaN(duration)) {
throw new Error("Duration argument must be a number");
}
}
const unitsDuration = durationForUnits(units);
return duration / unitsDuration;
}
function durationForUnits(units) {
if (typeof tenures[units] !== 'object') {
throw new Error('Could not find units from source data');
}
const start = moment(tenures[units].start);
const end = moment(tenures[units].end);
return durationFromStartAndEnd(start, end);
}
function durationFromStartAndEnd(start, end) {
start = moment(start);
end = moment(end);
if (!start.isValid() || !end.isValid()) {
throw new Error('Start or End are invalid when handled by moment');
}
const duration = moment.duration(end.diff(start));
return duration.asMilliseconds();
}
export default memoize(convert);
|
$(document).ready(function() {
$("#dob").datepicker({
dateFormate : 'yy/mm/dd',
changeMonth : 'true',
changeYear : 'true',
yearRange : '-100y:c+nn',
maxDate : '-1d'
});
});
/*
* $(document).ready(function() { $('#terms').change(function(){
* $('#submit').prop('disabled',false); }); });
*/
/*
* $(document).ready(function(){ $('#terms').click(function(){
* if($('#terms').is(':checked')){ $('#submit').prop('disabled',false);
*
* }else{ $('#submit').prop('disabled',true);
* } });
*
* });
*/
$(document).ready(function() {
$('#reset').click(function() {
// location.reload(true);
document.getElementById("name").value = " ";
document.getElementById("gender").innerHTML.checked = false;
document.getElementById("contact").value = " ";
document.getElementById("email").value = " ";
document.getElementById("address").value = " ";
document.getElementById("dob").value = " ";
document.getElementById("experience").value = " ";
document.getElementById("techKnown").innerHTML.checked = false;
});
});
|
const fs = require('fs');
exports.deleteFile = (filePath) => {
fs.unlink(filePath, (err) => {
if (err) {
console.log('Erro while deleting ' + filePath);
throw (err);
}
console.log('Deleted file: ' + filePath);
});
}
|
// 1D ensemble spaghetti plots
function spaghettiPlots(where, type, ratio, data) {
d3.select(where).selectAll("*").remove();
var w = 1600 * ratio;
var h = 800 * 0.23;
var that = this;
var svg = d3.select(where).append("svg")
.attr("preserveAspectRatio", "none")
.attr("viewBox", "0 0 " + w + " " + h);
var max = [];
for (var i=0; i<data.length; i++) {
max[i] = findMax(data[i], 1);
}
var maxPeak = Math.ceil(d3.max(max) * 100) / 100;
// console.log(max);
// console.log(d3.max(max));
// console.log(maxPeak);
// type
var title = svg.append("text")
.attr("x", 35 + (w - 35) / 2)
.attr("y", 15)
.style("fill", "black")
.style("font-size", 18)
.style("text-anchor", "middle")
.text(type);
// x/y-axis
var xAxis = svg.append("line")
.attr("x1", 30)
.attr("y1", h - 14)
.attr("x2", w)
.attr("y2", h - 14)
.style("stroke", "black")
.style("stroke-width", 2);
var yAxis = svg.append("line")
.attr("x1", 34)
.attr("y1", 5)
.attr("x2", 34)
.attr("y2", h - 14)
.style("stroke", "black")
.style("stroke-width", 2);
// x/y labels
var xLabel = svg.append("text")
.attr("x", 30)
.attr("y", h - 2)
.style("fill", "black")
.style("font-size", 12)
.style("text-anchor", "middle")
.text("0");
var xLabel = svg.append("text")
.attr("x", 30 + (w - 30) / 2)
.attr("y", h - 2)
.style("fill", "black")
.style("font-size", 12)
.style("text-anchor", "middle")
.text((data[0].length-1) / 2);
var xLabel = svg.append("text")
.attr("x", w)
.attr("y", h - 2)
.style("fill", "black")
.style("font-size", 12)
.style("text-anchor", "end")
.text(data[0].length-1);
var yLabel = svg.append("text")
.attr("x", 30)
.attr("y", 10 + (h- 20) / 2)
.style("fill", "black")
.style("font-size", 12)
.style("text-anchor", "end")
.text(maxPeak / 2);
var yLabel = svg.append("text")
.attr("x", 30)
.attr("y", 10)
.style("fill", "black")
.style("font-size", 12)
.style("text-anchor", "end")
.text(maxPeak);
//
var xScale = d3.scaleLinear()
.domain([0, data[0].length])
.range([35, w]);
var yScale = d3.scaleLinear()
.domain([0, maxPeak])
.range([h - 15, 5]);
var pathFunc = d3.line()
.x(function(d, i) {return xScale(i)})
.y(function(d, i) {return yScale(d)});
/**************************************************/
var spaghettiPath = [];
for (var i=0; i<data.length; i++) {
var group = svg.append("g").attr("id", "run"+i);
for (var j=0; j<TimeSteps; j++) {
var groupTime = group.append("g").attr("class", "time"+j);
var prob = [];
for (var k=0; k<data[i].length; k++) {
prob.push(+d3.values(data[i][k])[j+1]);
}
var color = d3.hsl(runHSL[i][0], 0.25 + (runHSL[i][1] - 0.25) * j / (TimeSteps-1), 0.75 - (0.75 - runHSL[i][2]) * j / (TimeSteps - 1));
spaghettiPath.push({run:i, time: j, probPath: prob, colorPath: color});
// var path = groupTime.append("path")
// .attr("d", pathFunc(prob))
// .style("fill", "none")
// // .style("stroke", runColor[i])
// .style("stroke", color)
// .style("stroke-width", 1)
// .style("opacity", 0.6)
// .on("mouseover", function() {
// console.log(i);
// });
}
}
//
// console.log(spaghettiPath);
var path = svg.selectAll("path")
.data(spaghettiPath)
.enter()
.append("path")
.attr("id", (d) => {
return "run"+d.run;
})
.attr("d", (d) => {
return pathFunc(d.probPath);
})
.style("fill", "none")
.style("stroke", (d) => {
return d.colorPath;
})
.style("stroke-width", 1)
.style("opacity", 0.6)
.on("mouseover", (d) => {
console.log(d.run);
});
this.update = function(runID, checked) {
for (var i=0; i<data.length; i++) {
if (runID === runFolder[i]) {
// console.log(runID);
// console.log(d3.selectAll("#run"+i));
if (checked) {
d3.select(where).selectAll("#run"+i).style("display", "initial");
} else {
d3.select(where).selectAll("#run"+i).style("display", "none");
}
}
}
}
}
|
import React from 'react'
import { useSelector } from 'react-redux'
import "./App.css"
import Navbar from './Routes/Navbar'
import Route from './Routes/Route'
import Sidebar from './Routes/Sidebar'
const App = () => {
const {auth } = useSelector(state => state.auth)
console.log(auth)
return (
<div className="App" >
{!auth ? <Navbar /> : <Sidebar/>}
<Route />
{/* <div style={{minHeight:'300px'}}></div> */}
{/* <h1>hi</h1> */}
</div>
)
}
export default App
|
import React, { Component } from 'react';
import '../Assets/css/grayscale.css';
class matchs extends Component {
constructor(){
super();
this.state = {
matchs:[]
};
}
componentDidMount(){
fetch("http://api.football-data.org/v1/competitions/"+this.props.match.params.id+"/fixtures?matchday=8")
.then(res => res.json())
.then(res => {
this.setState({
matchs: res.fixtures
});
})
.catch(error => {
console.log('error dude, desolé');
})
}
render () {
return (
<div>
<header className="ligues">
<div className="intro-body">
<div className="container">
<div className="row">
<div className="col-lg-8 mx-auto">
<h1 className="brand-heading">Ligues Football</h1>
<a href="" className="btn btn-circle js-scroll-trigger">
<i className="fa fa-angle-double-down animated"></i>
</a>
</div>
</div>
</div>
</div>
</header>
<h1>Les matchs de la ligue</h1>
<div className="row">
{this.state.matchs.map(function(p, index){
var date = new Date(p.date);
var elapsed = date.getFullYear()+"-"+date.getMonth()+"-"+date.getDay();
return(
<div className="col-md-6">
<div class="card margine">
<div className="row">
<div className="col-md-12 noir">
{elapsed}
</div>
</div>
<div className="row centered">
<div className="col-md-4 noir">
{p.homeTeamName}
</div>
<div className="col-md-4 noir">
<h4> {p.result.goalsHomeTeam} - {p.result.goalsAwayTeam}</h4>
</div>
<div className="col-md-4 noir">
{p.awayTeamName}
</div>
</div>
<div className="row centered">
<div className="col-md-12 noir">
{p.status}
</div>
</div>
</div>
</div>
);
})}
</div>
</div>
);
}
}
export default matchs;
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const centroSchema = new Schema({
nombre: String,
codigoPostal: Number,
fechaAlta: {
type: String,
required: false
},
fechaBaja: {
type: String,
required: false
},
activo:{
type: String,
enum: ["Activo", "Inactivo"],
default: "Inactivo"
},
ventas:[],
ventasUsuario:[],
usuarios:[{
type:Schema.Types.ObjectId,
ref:"User"
}],
brand:{
type:Schema.Types.ObjectId,
ref:"Brand"
},
zona:{
type:Schema.Types.ObjectId,
ref:"Zona"
}
},{
timestamps: {
createdAt: 'created_at',
updatedAt: 'updated_at'
}
});
module.exports = mongoose.model('CentroConsumo', centroSchema);
// UN CENTRO DE CONSUMO ES FACIL DE DEFINIR, ES UN CENTRO EN DONDE SE REGISTRAN VENTAS D ELAS MARCAS QUE NUESTROS BRANDS NECESITAN VENDER
// EN SI ESTE MODELO SE CREO PARA QUE LOS USUARIOS ELIJAN EL CENTRO DE CONSUMO EN EL QUE TRABAJAN
// LA IDEA ERA AGRUPAR LOS USUARIOS DENTRO DE ESTE CENTRO DE CONSUMO PERO VIMOS MEJOR SOLO UBICAR QUE USUARIOS TRABAJAN EN QUE LUGAR
// MEDIANTE UNA BUSQUEDA DEL CENTRO DE CONSUMO QUE TIENEN EN SU PERFIL O MODELO DE USUARIO.
// UN CENTRO DE CONSUMO ES GENERAL PARA TODOS, ES DECIR CUALQUIER USUARIO PUEDE DEICR QUE TRABAJA EN TL¡AL CENTRO DE CONSUMO.
|
if ( typeof(_effect) == "undefined") { var _effect = []; }
_effect["arrow"] = function( a, b ) {
this.scene = a;
this.clear = b;
this.speed = 10;
this.p = new BABYLON.ParticleSystem("particles", 2000, scene);
//this.p.particleTexture = new BABYLON.Texture("content/shot.png", scene);
this.p.particleTexture = this.scene._loadTexture( "content/shot.png" );
this.p.emitter = new BABYLON.Vector3(0, 0, 0);
this.p.direction1 = new BABYLON.Vector3(0, 10, 0);
this.p.direction2 = this.p.direction1;
this.p.minEmitBox = new BABYLON.Vector3(0, 0, 0);
this.p.maxEmitBox = new BABYLON.Vector3(0, 0, 0);
this.p.color1 = new BABYLON.Color4(1, 1, 0, 1);
this.p.color2 = new BABYLON.Color4(1, 1, 0, 1);
this.p.colorDead = new BABYLON.Color4(0, 0, 0, 0.0);
this.p.minSize = 0.75;
this.p.maxSize = 0.75;
this.p.minLifeTime = (1/this.speed)/this.scene.game_tickrate;
this.p.maxLifeTime = this.p.minLifeTime;
this.p.emitRate = 50;
this.p.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
this.p.gravity = new BABYLON.Vector3(0, 0, 0);
this.p.minAngularSpeed = 0;
this.p.maxAngularSpeed = 0;
this.p.targetStopDuration = 0.1;
this.p.minEmitPower = this.speed*this.scene.game_tickrate;
this.p.maxEmitPower = this.p.minEmitPower;
this.p.updateSpeed = 0.01;
this.cur = 0;
this.lifeTime = 1000;
this.run = false;
this.lastrun = -1;
}
_effect["arrow"].prototype.start = function( a ) {
var time = (new Date().getTime());
if ( time > this.cur ) {
this.cur = time+this.lifeTime
this.p.emitter = new BABYLON.Vector3(a.p1.x, a.p1.y, a.p1.z);
this.p.direction1 = new BABYLON.Vector3( a.p2.x-a.p1.x, a.p2.y-a.p1.y, a.p2.z-a.p1.z );
this.p.direction2 = this.p.direction1;
this.p.color1 = new BABYLON.Color4(((a.t==0)?0:1), ((a.t==0)?1:0), 0, 1);
this.p.color2 = new BABYLON.Color4(((a.t==0)?0:1), ((a.t==0)?1:0), 0, 1);
this.p.minLifeTime = (1/this.speed)/this.scene.game_tickrate;
this.p.maxLifeTime = this.p.minLifeTime;
this.p.minEmitPower = this.speed*this.scene.game_tickrate;
this.p.maxEmitPower = this.p.minEmitPower;
this.p.start();
this.run = true;
return (true);
}
return (false);
}
_effect["arrow"].prototype.stop = function( ) {
if ( this.run == true ) {
this.lastrun = this.time+(this.lifeTime*2);
this.run = false;
}
if ( this.time > this.lastrun && this.lastrun != -1 ) {
this.scene.loadEffect.load[this.clear[0]][this.clear[1]] = null;
this.lastrun = -1
}
}
_effect["arrow"].prototype.think = function() {
this.time = (new Date().getTime());
if ( this.time < this.cur ) {
// NONE
} else {
this.stop();
}
}
|
import React from 'react'
import { mount, shallow } from 'enzyme'
import { Home } from './Home'
describe('Home Component', () => {
it('should render a loader when the query is in progress', () => {
const mockProps = {
data: {
loading: true,
},
}
const component = mount(<Home {...mockProps} />)
expect(component.find('.c-loader').exists()).toBe(true)
expect(component.find('.c-auth-form').exists()).toBe(false)
})
it('should render a login form when there is no logged in user', () => {
const mockProps = {
data: {
loading: false,
user: null,
},
}
const component = shallow(<Home {...mockProps} />)
expect(component.find('.c-loader').exists()).toBe(false)
expect(component.debug().toString().indexOf('Login')).not.toBe(-1)
})
it('should render a list when there is a logged in user', () => {
const mockProps = {
data: {
loading: false,
user: {
id: '1',
email: 'test@test.com',
},
},
}
const component = shallow(<Home {...mockProps} />)
expect(component.find('.o-loader').exists()).toBe(false)
expect(component.debug().toString().indexOf('Login')).toBe(-1)
expect(component.find('Route').exists()).toBe(true)
})
})
|
import Snake from './snake.js';
import SnakeFood from './snakeFood.js';
import FeedingGround from './feedingGround.js';
const canvas = document.getElementById('snake_canvas');
const fg = new FeedingGround(canvas.width, canvas.height);
const reset = document.getElementById('reset-box');
if (fg.playing){
fg.start(canvas);
}
reset.addEventListener('click', restart);
function restart() {
fg.snake.alive = true;
fg.snake.eaten = '';
fg.playing = true;
fg.start(canvas);
reset.style.zIndex = -1;
}
window.addEventListener('keydown', keyPressed);
function keyPressed(e) {
let code = e.keyCode;
if (code === 37) {
fg.snake.move = 'left';
fg.snake.direction(-0.3, 0, 'left');
} else if (code === 38) {
fg.snake.move = 'up';
fg.snake.direction(0, -0.3, 'up');
} else if (code === 39) {
fg.snake.move = 'right';
fg.snake.direction(0.3, 0, 'right');
} else if (code === 40) {
fg.snake.move = 'down';
fg.snake.direction(0, 0.3, 'down');
} else if (code === 32) {
fg.playing = !fg.playing;
}
}
|
/*
Use webpack -p to compress output.js
*/
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
module.exports = {
mode:'development',
entry: {
main: [
'babel-polyfill',
'./public/src/main.js',
]
},
output: {
path: path.resolve(__dirname, 'public/dist/'),
/* publicPath -> add path to url prefix*/
//publicPath: '../public/dist/',
filename: '[name].js',
publicPath: 'http://localhost:3001/dist/'
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.styl(us)?$/,
use: [
'vue-style-loader',
'css-loader',
'stylus-loader'
]
},
{
test: /\.styl$/,
loader:'stylus-loader'
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /\.(scss|sass)$/,
loader: ExtractTextPlugin.extract({
use:
[
{loader: "css-loader"},
{loader:'resolve-url-loader'},
{
loader: "sass-loader",
options:{
sourceMap:true,
}
}
],
})
},
{
test: /\.(jpe?g|gif|png|svg)$/,
loader: 'file-loader',
options:{
emitFile:false,
name:"[path][name].[ext]"
}
}
]
},
resolve: {
extensions: ['.js', '.vue'],
alias: {
'vue': 'vue/dist/vue.js', // developement mode
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify("production")
}
}),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
Tether: 'tether'
}),
new ExtractTextPlugin({
publicPath: './public/dist/',
filename: 'main.css'
}),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new VueLoaderPlugin()
]
}
|
import styled from "styled-components";
export default styled.div`
margin-top: 20px;
padding-top: 10px;
.cmt {
position: relative;
background-color: #f1f1f1;
padding: 10px 15px 30px;
margin-bottom: 10px;
border-radius: 6px;
.cmt-time {
position: absolute;
right: 8px;
bottom: 8px;
opacity: 0.7;
font-size: 12px;
}
}
`;
|
import axios from 'axios';
import { ROOT_URL } from '../helpers/constants';
// Action Types
// ==================
export const LOGIN = 'LOGIN';
export const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
export const LOGIN_FAILURE = 'LOGIN_FAILURE';
export function login(access_token) {
const request = axios({
method: 'post',
data: access_token,
url: `${ROOT_URL}/facebook-login`,
headers : { 'Content-Type': 'application/octet-stream' }
})
return {
type: LOGIN,
payload: request
}
}
export function loginSuccess(access_token) {
return {
type: LOGIN_SUCCESS,
payload: access_token
}
}
export function loginFailure(error) {
return {
type: LOGIN_FAILURE,
payload: error
}
}
|
import React from "react";
import {ageFromDOB} from "../helpers/helpers"
import '../css/Profile.css';
const Profile = ({ user }) => {
if (!user) return "loading...";
return (
<div className="profile-detail">
<h2>{user.fullName}</h2>
<p><strong>Age:</strong> {ageFromDOB(new Date(user.dob))}</p>
<h3>About Me</h3>
<p>{user.aboutMe}</p>
<div>
<h3>Points</h3>
<p>{user.noOfPoints}</p>
</div>
</div>
);
};
export default Profile;
|
import React from 'react';
import ReactDOM from 'react-dom';
import Table from './table.js';
import User from './user.js';
import {App} from './app.js';
export default class ClickedUser extends React.Component {
constructor(props){
super(props);
this.state={
user: null
};
}
componentWillReceiveProps(nextProps){
this.setState({
user: nextProps.user
});
console.log("ClickedUser props received");
}
render(){
if (this.state.user)
{
var userTmp = this.state.user.map(function(item, index){
return(<p>{item}</p>);
})
}
else var userTmp = null;
return(<div className='clicked-user'>
{userTmp}
</div>);
}
}
|
if (!OC.Encryption) {
OC.Encryption = {};
}
OC.Encryption.msg = {
start: function (selector, msg) {
var spinner = '<img src="' + OC.imagePath('core', 'loading-small.gif') + '">';
$(selector)
.html(msg + ' ' + spinner)
.removeClass('success')
.removeClass('error')
.stop(true, true)
.show();
},
finished: function (selector, data) {
if (data.status === "success") {
$(selector).html(data.data.message)
.addClass('success')
.stop(true, true)
.delay(3000);
} else {
$(selector).html(data.data.message).addClass('error');
}
}
};
|
const test = require('tape');
const elo = require('./elo.js');
test('Testing elo', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof elo === 'function', 'elo is a Function');
t.deepEqual(elo([1200, 1200]), [1216, 1184], "Standard 1v1s");
t.deepEqual(elo([1200, 1200], 64), [1232, 1168]), "Standard 1v1s";
t.deepEqual(elo([1200, 1200, 1200, 1200]).map(Math.round), [1246, 1215, 1185, 1154], "4 player FFA, all same rank");
//t.deepEqual(elo(args..), 'Expected');
//t.equal(elo(args..), 'Expected');
//t.false(elo(args..), 'Expected');
//t.throws(elo(args..), 'Expected');
t.end();
});
|
moveOneWord = (input, many) => {
let word = input.split(" ");
let count = 0;
if (many == 1) {
return 0;
}
for (let a = 0; a <= many - 1; a++) {
if (a == many - 1) {
count++;
} else {
count = count + (word[a].length + 1);
}
}
return count;
};
reverseOneWord = (input, many) => {
let word = input.split(" ");
return word;
};
cursorer = words => {
let getCodes = words.split(" ")[0];
let moveWord = 1;
for (let initMove = 1; initMove <= getCodes.length; initMove++) {
if (getCodes[initMove] == "w") {
moveWord++;
}
}
let finalCount = 1;
for (let init = 0; init <= getCodes.length - 1; init++) {
if (getCodes[init] == "l") {
finalCount++;
} else if (getCodes[init] == "h") {
finalCount--;
} else if (getCodes[init] == "w") {
finalCount = moveOneWord(words, moveWord) + finalCount;
} else if (getCodes[init] == "b") {
// TODO
}
}
return finalCount;
};
console.log(cursorer("ll aku mau hidup seribu tahun lagi"));
console.log(cursorer("h robohnya surau kami"));
console.log(cursorer("wh kaki yang terhormat"));
|
import React from 'react';
const ProductList = (props) => {
const listOfProducts = props.dataList.map(appn => {
return (
<div className="col-md-5 float-left card mb-1 mr-2" key={appn.id}>
<div className="figure">
<div className="row">
<div className="col-4">
<img className="img-thumbnail" alt={appn.name} src={appn.imageUrl} height="200px" width="200px" style={{ float: "left", margin: "5px" }} />
</div>
<div className="col-8" >
<button className="close" id={appn.id} onClick={props.change}>X</button>
<span className="card-body">
<h4> Product Name : {appn.name}</h4>
<p> Product Type : {appn.type}</p>
<p> Product Price : {appn.price} $</p>
<p> Product Quantity : {appn.quantity}</p>
<p> Payment Mode : {appn.payment}</p>
<p> Cities : <ul><li>{appn.city}</li> </ul>
</p>
</span>
</div>
</div>
</div>
</div>
);
})
return <div>{listOfProducts}</div>;
}
export default ProductList;
|
//index.js
//获取应用实例
const app = getApp()
Page({
data: {
// 页面配置
winWidth: 0,
winHeight: 0,
// tab切换
currentTab: 0,
isHideLoadMore: false,
hasRefesh: false,
hidden: false,
taobaodata: [],
taobaopage: 1,
pinduoduodata: [],
pinduoduopage: 1
},
onLoad: function(options) {
var that = this;
wx.getSystemInfo({
success: function(res) {
that.setData({
winWidth: res.windowWidth,
winHeight: res.windowHeight
});
}
});
that.taobaocollection();
},
onShow: function () {
this.taobaocollection();
},
// 滑动切换tab
bindChange: function(e) {
var that = this;
that.setData({
currentTab: e.detail.current
});
var tabindexs = e.detail.current;
// console.log(tabindexs);
if (tabindexs == 0) {
that.taobaocollection();
} else if (tabindexs == 1) {
that.pinduoduocollection();
}
},
// 点击tab切换
swichNav: function(e) {
var that = this;
if (this.data.currentTab === e.target.dataset.current) {
return false;
} else {
that.setData({
currentTab: e.target.dataset.current
})
var tabindex = e.target.dataset.current;
// console.log(tabindex);
if (tabindex == 0) {
that.taobaocollection();
} else if (tabindex == 1) {
that.pinduoduocollection();
}
}
},
//淘宝收藏商品
taobaocollection: function(e) {
var that = this;
wx.request({
url: app.globalData.taobaocollectionurl,
data: {
userId: app.globalData.userId,
page: 1,
},
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: 'POST',
dataType: '',
success: function(res) {
// console.log(res)
that.setData({
taobaodata: res.data.result,
hidden: true
})
},
fail: function(res) {
console.log(res)
},
})
},
//淘宝收藏商品上拉加载更多
taobaoloadMore: function(e) {
setTimeout(() => {
// console.log('加载更多')
var that = this;
wx.request({
url: app.globalData.taobaocollectionurl,
data: {
userId: app.globalData.userId,
page: ++that.data.taobaopage,
},
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: 'POST',
dataType: '',
success: function(res) {
// console.log(res)
if (res.statusCode == 200) {
// console.log(res.data.result)
that.setData({
taobaodata: that.data.taobaodata.concat(res.data.result),
isHideLoadMore: false,
hidden: true,
hasRefesh: false,
});
}
console.log(that.data.taobaopage)
},
fail: function(res) {
console.log(res)
}
})
}, 1000)
},
//淘宝收藏商品下拉刷新
taobaorefesh: function() {
var that = this;
that.setData({
hasRefesh: true,
});
wx.request({
url: app.globalData.taobaocollectionurl,
data: {
userId: app.globalData.userId,
page: 1,
},
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: 'POST',
dataType: '',
success: function(res) {
if (res.statusCode == 200) {
var PIC = res.data.result;
that.setData({
taobaodata: PIC,
taobaopage: 1,
hasRefesh: false,
hidden: true,
});
}
}
})
},
//收藏商品点击跳转到商品详情
bindViewTap: function (e) {
var productId = e.currentTarget.dataset.id;
wx.navigateTo({
url: '../pagedetail/pagedetail?productId=' + productId
});
},
bindgooddel:function(e){
var productId = e.currentTarget.dataset.id;
// console.log(productId)
var that = this;
wx.request({
url: app.globalData.taobaodelcollectionurl,
data: {
userId: app.globalData.userId,
productIds: productId,
},
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: 'POST',
dataType: '',
success: function (res) {
// console.log(res)
wx.showToast({
title: res.data.message,
icon: 'succes',
duration: 2000,
mask: true
})
that.taobaocollection();
},
fail: function (res) {
console.log(res)
},
})
},
pinduoduocollection:function(){
console.log("拼多多商品收藏")
}
})
|
// THEME
function Theme(id, nom, nomVo){
this.id = id;
this.nom = nom;
this.nomVo = nomVo;
this.caracBonuses = new Map();
this.themeCompetences = new Map();
}
Theme.prototype.addThemeCaracBonus = function(nom, value){
this.caracBonuses.set(nom, value);
}
Theme.prototype.addThemeCompetence = function(nom){
this.themeCompetences.set(nom, true);
}
Theme.prototype.printJson = function(json){
var theme = json.startObjet("theme");
theme.writeParam("id", this.id);
theme.writeParam("vf", this.nom);
theme.writeParam("vo", this.nomVo);
var caracTab = theme.writeParamTab("caracBonuses");
for(var [caracName, caracValue] of this.caracBonuses){
caracTab.writeSeparator();
var caracBonus = json.startObjet("caracteristique");
caracBonus.writeParam('nom', caracName);
caracBonus.writeParam('valeur', caracValue);
caracBonus.endObjet();
}
caracTab.endTab();
var compTab = theme.writeParamTab("competences");
for(var [compName, comp] of this.themeCompetences){
compTab.writeSeparator();
json.writeQuoted(compName);
}
compTab.endTab();
theme.endObjet();
}
function themeFromJson(themeNode){
var theme = new Theme(themeNode['id'], themeNode['vf'], themeNode['vo']);
this.themeCompetences = [];
themeNode['caracBonuses']
.map(caracNode => elementFromJson(caracNode))
.forEach(carac => theme.addThemeCaracBonus(carac.nom, carac.valeur));
if(themeNode['competences'] != undefined) {
themeNode['competences']
.forEach(competence => theme.addThemeCompetence(competence));
}
return theme;
}
|
import cookies from './util.cookies'
const util = {
cookies
}
/**
* 初始化顶部菜单
* @param {用户菜单} menu
*/
util.initHeaderMenu = function (menu) {
return getMenu(menu)
}
/**
* 生成随机len位数字
*/
util.randomLenNum = function (len, date) {
let random = ''
random = Math.ceil(Math.random() * 100000000000000).toString().substr(0, typeof len === 'number' ? len : 4)
if (date) random = random + Date.now()
return random
}
/**
* @description 更新标题
* @param {String} title 标题
*/
util.title = function (titleText) {
const processTitle = process.env.VUE_APP_TITLE || 'D2Admin'
window.document.title = `${processTitle}${titleText ? ` | ${titleText}` : ''}`
}
export default util
|
import React from 'react'
import './ForkMe.css'
export default function ForkMe(props) {
return (
<span id='forkongithub'>
<a href='https://github.com/BrandonDyer64/Memory-Game' target='_blank'>
Fork me on GitHub
</a>
</span>
)
}
|
//requis: PhantomJS + Serveur Apache qui héberge le fichier generate.php
//CLI: ./phantomjs client.js
//Système de snapshot pour le projet TMN
//github:nicolastrognot
var url_tmn = "[PRIVATE]/generate.php";
var private_key = "[PRIVATE]";
var page_l = require('webpage').create();
var page_p = require('webpage').create();
page_p.viewportSize = {
width: 1080,
height: 740
};
page_l.open(url_tmn + '?pk=' + private_key + '&m=l', function(status) {
var lines = page_l.plainText.split("efee505537fdf2556a91fd6af850cc5a60e176ee");
var page_preview = require('webpage').create();
page_preview.open(url_tmn + '?pk=' + private_key + '&m=p&url=' + encodeURIComponent(lines[1]) + '&id=' + encodeURIComponent(lines[0]) + '&lang=' + encodeURIComponent(lines[2]) + '&from_name=' + encodeURIComponent(lines[3]), function(status) {
console.log("Status: " + status);
});
page_p.open(url_tmn + '?pk=' + private_key + '&m=p&url=' + encodeURIComponent(lines[1]) + '&id=' + encodeURIComponent(lines[0]) + '&lang=' + encodeURIComponent(lines[2]) + '&from_name=' + encodeURIComponent(lines[3]), function(status) {
var page_s = require('webpage').create(),
server = url_tmn + '?pk=' + private_key + '&m=s',
data = 'b64=' + encodeURIComponent(page_p.renderBase64('PNG')) + '&id=' + lines[0];
page_s.open(server, 'post', data, function (status) {
if (status !== 'success') {
console.log('Unable to post!');
} else {
console.log(page_s.content);
}
phantom.exit();
});
});
});
|
import styled from "styled-components";
const FeedCardStyled = styled.div`
border-radius: 2%;
box-shadow: 1px 1px 2px grey;
.card-infos {
h2 {
font-size: 20px;
font-weight: 700;
}
h2, p {
padding: 10px 25px;
text-align: left;
}
}
`
export default FeedCardStyled
|
document.addEventListener("DOMContentLoaded", showSubFilter);
function showSubFilter() {
console.log("CLICK PÅ KNAP");
if (window.innerWidth <= 1239){
console.log("jeg hedder EDAMAMAMA")
document.querySelector(".genre_tekst").addEventListener("click", showMusikMenu);
document.querySelector(".venues_tekst").addEventListener("click", showVenuesMenu);
//sub filter
document.querySelector(".tema_musik").addEventListener("click", show_sub_musik);
document.querySelector(".tema_film").addEventListener("click", show_sub_film);
document.querySelector(".tema_ord").addEventListener("click", show_sub_ord);
document.querySelector(".tema_scenekunst").addEventListener("click", show_sub_scenekunst);
document.querySelector(".tema_andet").addEventListener("click", show_sub_andet);
document.querySelectorAll(".event_genre").forEach(knap => {
knap.addEventListener("click", lukAlleSub)
})
document.querySelectorAll(".event_venue").forEach(knap => {
knap.addEventListener("click", lukAlleSub)
})
}
else {
document.querySelector(".tema_musik").addEventListener("click", show_sub_musik);
document.querySelector(".tema_film").addEventListener("click", show_sub_film);
document.querySelector(".tema_ord").addEventListener("click", show_sub_ord);
document.querySelector(".tema_scenekunst").addEventListener("click", show_sub_scenekunst);
document.querySelector(".tema_andet").addEventListener("click", show_sub_andet);
}
}
function showMusikMenu() {
console.log("Hvis musik menu");
document.querySelector(".venues_block").style.display = "none";
let a = document.querySelector(".genre_block");
if (a.style.display === "none") {
a.style.display = "block";
} else {
a.style.display = "none";
}
}
function showVenuesMenu() {
console.log("Hvis venues menu");
document.querySelector(".genre_block").style.display = "none";
let a = document.querySelector(".venues_block");
if (a.style.display === "none") {
a.style.display = "block";
} else {
a.style.display = "none";
}
}
function show_sub_musik() {
console.log("show musik sub");
let a = document.querySelector(".musik_filter");
if (a.style.display === "none") {
a.style.display = "block";
} else {
a.style.display = "none";
}
}
function show_sub_film() {
console.log("show film sub");
let a = document.querySelector(".film_filter");
if (a.style.display === "none") {
a.style.display = "block";
} else {
a.style.display = "none";
}
}
function show_sub_ord() {
console.log("show ord sub");
let a = document.querySelector(".ord_filter");
if (a.style.display === "none") {
a.style.display = "block";
} else {
a.style.display = "none";
}
}
function show_sub_scenekunst() {
console.log("show scenekunst sub");
let a = document.querySelector(".scenekunst_filter");
if (a.style.display === "none") {
a.style.display = "block";
} else {
a.style.display = "none";
}
}
function show_sub_andet() {
console.log("show andet sub");
let a = document.querySelector(".andet_filter");
if (a.style.display === "none") {
a.style.display = "block";
} else {
a.style.display = "none";
}
}
function lukAlleSub(){
document.querySelector(".venues_block").style.display = "none";
document.querySelector(".genre_block").style.display = "none";
}
|
const bcrypt = require('bcrypt');
const mongoose = require('mongoose');
const supertest = require('supertest');
const app = require('../app');
const Tournament = require('../models/tournament');
const User = require('../models/user');
const api = supertest(app);
const testUsername = 'testuser';
const testPassword = 'sekret';
const initialTournaments = [
{
name: 'Tournament1',
players: [],
playerPools: [],
teams: []
},
{
name: 'Tournament2',
players: [],
playerPools: [],
teams: []
}
];
var testUser;
var token;
beforeAll(async () => {
await User.deleteMany({});
const passwordHash = await bcrypt.hash(testPassword, 10);
const user = new User({
username: testUsername,
name: 'Teemu Testaaja',
passwordHash
});
await user.save();
testUser = user;
const loginResponse = await api.post('/api/login')
.send({ username: 'testuser', password: testPassword });
token = loginResponse.body.token;
});
beforeEach(async () => {
await Tournament.deleteMany({});
for (const tournament of initialTournaments) {
const newTournament = new Tournament({
...tournament,
user: testUser._id
});
const savedTournament = await newTournament.save();
tournament.id = savedTournament.id;
}
testUser.tournaments = initialTournaments.map(tournament => tournament._id);
await testUser.save();
});
afterAll(() => {
mongoose.connection.close();
});
describe('when there is initially tournaments in database', () => {
test('tournaments are returned as json', async () => {
await api
.get('/api/tournaments')
.set('Authorization', 'Bearer ' + token)
.expect(200)
.expect('Content-Type', /application\/json/);
});
test('response with matching number of items is received', async () => {
const response = await api
.get('/api/tournaments')
.set('Authorization', 'Bearer ' + token);
expect(response.body).toHaveLength(initialTournaments.length);
});
test('adding new tournament stores it correctly', async () => {
const newTournament = {
name: 'Tournament3',
players: [],
playerPools: [],
teams: []
};
const postResponse = await api
.post('/api/tournaments/')
.set('Authorization', 'Bearer ' + token)
.send(newTournament);
const getResponse = await api
.get('/api/tournaments')
.set('Authorization', 'Bearer ' + token);
expect(getResponse.body).toHaveLength(initialTournaments.length + 1);
expect(getResponse.body).toContainEqual(postResponse.body);
});
test('deleting tournament removes it correctly', async () => {
await api
.delete(`/api/tournaments/${initialTournaments[0].id}`)
.set('Authorization', 'Bearer ' + token);
const getResponse = await api
.get('/api/tournaments')
.set('Authorization', 'Bearer ' + token);
expect(getResponse.body).toHaveLength(initialTournaments.length - 1);
expect(getResponse.body).not.toContainEqual(initialTournaments[0]);
});
test('updating tournament updates it correctly', async () => {
const updatedTournament = {
...initialTournaments[0],
name: 'UpdatedTournament'
};
const putResponse = await api
.put(`/api/tournaments/${initialTournaments[0].id}`)
.set('Authorization', 'Bearer ' + token);
const getResponse = await api
.get(`/api/tournaments/${initialTournaments[0].id}`)
.set('Authorization', 'Bearer ' + token);
expect(putResponse.body).toEqual(getResponse.body);
});
});
describe('correct status code is returned when', () => {
test('requesting all tournaments', async () => {
await api
.get('/api/tournaments')
.set('Authorization', 'Bearer ' + token)
.expect(200);
});
test('requesting tournament with id that is found', async () => {
await api
.get(`/api/tournaments/${initialTournaments[0].id}`)
.set('Authorization', 'Bearer ' + token)
.expect(200);
});
test('requesting tournament with id that isn\'t found', async () => {
await api
.get('/api/tournaments/5f1888da1015da0f08ff23bb')
.set('Authorization', 'Bearer ' + token)
.expect(404);
});
test('requesting tournament with id that isn\'t valid', async () => {
await api
.get('/api/tournaments/abbaacdc')
.set('Authorization', 'Bearer ' + token)
.expect(400);
});
test('adding new tournament', async () => {
const newTournament = {
name: 'Tournament3',
players: [],
playerPools: [],
teams: []
};
await api
.post('/api/tournaments/')
.set('Authorization', 'Bearer ' + token)
.send(newTournament)
.expect(201);
});
test('deleting tournament that is found', async () => {
await api
.delete(`/api/tournaments/${initialTournaments[0].id}`)
.set('Authorization', 'Bearer ' + token)
.expect(204);
});
test('deleting tournament that isn\'t found', async () => {
await api
.delete('/api/tournaments/5f1888da1015da0f08ff23bb')
.set('Authorization', 'Bearer ' + token)
.expect(401);
});
test('deleting tournament with id that isn\'t valid', async () => {
await api
.delete('/api/tournaments/abbaacdc')
.set('Authorization', 'Bearer ' + token)
.expect(400);
});
test('updating tournament that is found', async () => {
const updatedTournament = {
...initialTournaments[0],
name: 'UpdatedTournament'
};
await api
.put(`/api/tournaments/${initialTournaments[0].id}`)
.set('Authorization', 'Bearer ' + token)
.send(updatedTournament)
.expect(200);
});
test('updating tournament that isn\'t found', async () => {
const updatedTournament = {
...initialTournaments[0],
name: 'UpdatedTournament',
id: '5f1888da1015da0f08ff23bb'
};
await api
.put('/api/tournaments/5f1888da1015da0f08ff23bb')
.set('Authorization', 'Bearer ' + token)
.send(updatedTournament)
.expect(401);
});
test('updating tournament with id that isn\'t valid', async () => {
const updatedTournament = {
...initialTournaments[0],
name: 'UpdatedTournament',
id: '5f1888da1015da0f08ff23bb'
};
await api
.put('/api/tournaments/5f1888da1015da0f08ff23bb')
.set('Authorization', 'Bearer ' + token)
.send(updatedTournament)
.expect(401);
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.