text stringlengths 7 3.69M |
|---|
const User = require('../../users/model/User')
module.exports = {
method: 'POST',
path: '/api/users/privilege',
options: {
handler: async (request, h) => {
const privilege = request.payload.privilege
const user = await User.findOne({ldap_username: request.payload.ldap_username})
if (privilege === 'admin') {
user.admin = request.payload.value
}
if (privilege === 'moderator') {
user.moderator = request.payload.value
}
user.save()
return { message: `Changed ${user.ldap_username}'s ${privilege} privilege to ${user[privilege]}`}
},
auth: {
strategy: 'jwt',
scope: ['admin']
},
description: 'Change user\' privilege',
notes: 'Changes user\'s privilege',
tags: ['api', 'user', 'admin']
}
} |
let Injector = (function() {
let instancia = undefined;
class Injector {
constructor() {
if(!instancia) {
this._$ = document.querySelector.bind(document);
this._deps = new Map();
instancia = this;
}
return instancia;
}
registraClasse(classe) {
this._deps.set(classe.name, classe);
console.log(`[${classe.name}]: classe registrada`);
}
registraInstancia(id, instancia) {
this._deps.set(id, instancia);
console.log(`[${id}]: instancia registrada`);
}
criarInstancia(classe) {
console.log(`[${classe.name}]: verificando dependências para criação`)
var deps = [];
if(classe.inject) {
console.log(`[${classe.name}]: possui as dependências ${classe.inject.join(',')}`);
console.log(`[${classe.name}]: resolvendo dependências`);
deps = classe.inject.map(dep => this.buscaInstancia(dep));
console.log(`[${classe.name}]: dependências resolvidas`)
} else {
console.log(`[${classe.name}] NÃO possui dependências`);
}
var instancia = Reflect.construct(classe, deps);
console.log(`[${classe.name}]: criado com sucesso`);
return instancia;
}
buscaInstancia(id) {
var dep = this._deps.get(id) || this._$(id);
if(!dep) throw new Error(`Dependência "${id}" não registrada`);
if(this._precisaInstanciar(dep)) {
console.log(`[${id}]: precisa instanciar`);
dep = this.criarInstancia(dep);
}
return dep;
}
_precisaInstanciar(dep) {
return dep.toString().startsWith('class');
}
}
return Injector;
})();
|
// https://leetcode.com/problems/add-two-numbers/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
// Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
// Output: 7 -> 0 -> 8
// Explanation: 342 + 465 = 807.
function ListNode(val) {
this.val = val;
this.next = null;
}
const exampleList1 = new ListNode(2);
exampleList1.next = new ListNode(4);
exampleList1.next.next = new ListNode(3);
const exampleList2 = new ListNode(5);
exampleList2.next = new ListNode(6);
exampleList2.next.next = new ListNode(4);
var addTwoNumbers = function(l1, l2) {
if (l1 === null && l2 === null) return null;
if (l1 === null) return l2;
if (l2 === null) return l1;
let remainder = 0;
let sumOfDigits = l1.val + l2.val; // 7
let revisedSum = sumOfDigits; // 7
if (sumOfDigits > 9) {
remainder = 1;
revisedSum = sumOfDigits - 10;
}
const summedList = new ListNode(revisedSum); // 7
let nextNodeInSummedList = summedList;
let latestNodeInL1 = l1.next; // 4
let latestNodeInL2 = l2.next; // 6
while (latestNodeInL1 !== null && latestNodeInL2 !== null) {
sumOfDigits = latestNodeInL1.val + latestNodeInL2.val + remainder; // 8
revisedSum = sumOfDigits; // 8
if (sumOfDigits > 9) {
remainder = 1; // 1
revisedSum = sumOfDigits - 10; // 0
} else {
remainder = 0; // 0
}
nextNodeInSummedList.next = new ListNode(revisedSum); // 8
latestNodeInL1 = latestNodeInL1.next; // null
latestNodeInL2 = latestNodeInL2.next; // null
nextNodeInSummedList = nextNodeInSummedList.next;
}
let remainingList = latestNodeInL1 === null ? latestNodeInL2 : latestNodeInL1;
while (remainingList !== null) {
sumOfDigits = remainingList.val + remainder;
revisedSum = sumOfDigits;
if (sumOfDigits > 9) {
remainder = 1;
revisedSum = sumOfDigits - 10;
} else {
remainder = 0;
}
nextNodeInSummedList = new ListNode(revisedSum);
remainingList = remainingList.next;
nextNodeInSummedList = nextNodeInSummedList.next;
}
if (remainder > 0) {
nextNodeInSummedList.val = 1;
}
return summedList;
};
console.log(addTwoNumbers(exampleList1, exampleList2));
|
const { devServer, ...webpackParams } = require("./webpack.config");
module.exports = {
...webpackParams,
output:{
...webpackParams.output,
publicPath: "/react-starter/"
},
mode: "production"
}; |
import React,{useState,useEffect} from "react";
import OneCard from "./oneCard";
import database from "./firebaseConfig";
export default function Cards() {
const [cardArr,setCardArr]= useState([]);
async function chapterFetch () {
const res = await database.collection('Curriculim').get();
const data = res.docs.map( (el)=>el.data())
console.log(data)
setCardArr([...data])
};
useEffect(() => {
chapterFetch();
}, [])
function renderCard() {
const allCards = cardArr.map(function(card, index) {
return <OneCard card={card} key={index} />;
});
return allCards;
};
return (
<div className="card">
<div>{renderCard()}</div>
</div>
);
}
|
(function(shoptet) {
function getElements() {
return document.querySelectorAll('.btn-cofidis');
}
function setMinPayment(el, minPayment) {
el.querySelector('b').textContent = minPayment;
el.classList.remove('hidden');
}
function calculator($newPriceHolder, $cofidis) {
var newPrice = parseFloat($newPriceHolder.text().replace(/[^\d,.-]/g, ''));
$cofidis.attr(
'data-url',
$cofidis.attr('data-url').replace(/(cenaZbozi=)(.+)(&idObchodu)/, '$1' + newPrice + '$3')
);
}
function handleClick(e) {
e.preventDefault();
var url = e.currentTarget.dataset.url;
window.open(url, 'iPlatba', 'width=770,height=650,menubar=no,toolbar=no');
}
function addCalculatorListeners() {
var cofidisCalculatorLinks = document.querySelectorAll('.js-cofidis-open');
for (var i = 0; i < cofidisCalculatorLinks.length; i++) {
cofidisCalculatorLinks[i].removeEventListener('click', shoptet.cofidis.handleClick);
cofidisCalculatorLinks[i].addEventListener('click', shoptet.cofidis.handleClick);
}
}
document.addEventListener('DOMContentLoaded', function() {
shoptet.cofidis.addCalculatorListeners();
var elements = shoptet.cofidis.getElements();
var successCallback = function(response) {
var index = response.getFromPayload('index');
var minPayment = response.getFromPayload('minPayment');
if (minPayment) {
shoptet.cofidis.setMinPayment(elements[index], minPayment);
}
};
for (var i = 0; i < elements.length; i++) {
var minPayment = parseInt(elements[i].getAttribute('data-minpay'));
if (minPayment) {
shoptet.cofidis.setMinPayment(elements[i], minPayment);
} else {
shoptet.ajax.makeAjaxRequest(
'/action/Iplatba/GetMinPayment/',
shoptet.ajax.requestTypes.post,
{
price: parseInt(elements[i].getAttribute('data-price')),
index: i
},
{
'success': successCallback
},
{
'X-Shoptet-XHR': 'Shoptet_Coo7ai'
}
)
}
}
});
document.addEventListener('ShoptetDOMContentLoaded', function() {
shoptet.cofidis.addCalculatorListeners();
});
shoptet.cofidis = shoptet.cofidis || {};
shoptet.scripts.libs.cofidis.forEach(function(fnName) {
var fn = eval(fnName);
shoptet.scripts.registerFunction(fn, 'cofidis');
});
})(shoptet);
|
var routes = require("../routes/index");
var diaryDays = require("../routes/api/entries");
var foods = require("../routes/api/foods");
var favourites = require("../routes/api/favourites");
function initialise(app) {
app.use("/", routes);
app.use("/api/diaryEntries/", diaryDays);
app.use("/api/foods/", foods);
app.use("/api/favourites/", favourites);
}
module.exports = initialise; |
// const redis = require('redis');
const asyncRedis = require("async-redis");
const redisClient = asyncRedis.createClient()
redisClient.on('error', (err) => {
console.log('redis err: ', err)
})
module.exports = redisClient; |
import tokens from "@paprika/tokens";
import { POSITIONS } from "./CollapsibleCard";
export default function getBorderRadius(position, isCollapsed, isHeader) {
const isInAGroup = position !== null;
const isExpanded = !isCollapsed;
const innerBorderRadius = tokens.card.borderRadius; // 6px
const outerBorderRadius = "7px";
if (isInAGroup) {
if (position === POSITIONS.FIRST) {
return `${innerBorderRadius} ${innerBorderRadius} 0 0`;
}
if (position === POSITIONS.MIDDLE) {
return `unset`;
}
if (position === POSITIONS.LAST) {
if (isCollapsed) {
return `0 0 ${innerBorderRadius} ${innerBorderRadius}`;
}
return `unset`;
}
} else if (isExpanded && isHeader) {
return `${innerBorderRadius} ${innerBorderRadius} 0 0`;
}
if (isHeader) {
return innerBorderRadius;
}
return outerBorderRadius;
}
|
const REGEX = /grid/;
export default {
'transition': REGEX,
'transition-property': REGEX,
};
|
const express = require('express');
const port = 3000;
const bp = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
// SERVER APP CONSTRUCTION
const app = express();
app.use(cors());
app.use(bp.json());
app.get('/bugs', (req, res) => {
// console.log('new get req in progress' + Object.keys(req));
BugModel.find((err, bugs) => {
if (err) {
res.send(err);
} else {
res.send(bugs);
}
})
});
// idnum to be incremented and decremented on create/delete
var idnum = 6;
app.post('/bugs', (req, res) => {
// console.log('new post req in progress: ' + req.body)
idnum++;
const newBug = new BugModel({
description: req.body.description,
reporter: req.body.reporter,
assignment: req.body.assignment
})
newBug.save((err, newBug)=> {
if (err) {
res.sendStatus(err);
} else {
res.send(newBug, 201)
}
})
})
app.listen(port, () => console.log(`Server is listening on port ${port}`));
//SCHEMA CONSTRUCTION
const BugSchema = new mongoose.Schema({
id: Number,
description: String,
reporter: String,
creationTime: { type: Date, default: Date.now },
assignment: String,
threatLevel: String
})
mongoose.connect('mongodb://localhost:27017/bugs', {useNewUrlParser: true, useUnifiedTopology: true});
const db = mongoose.connection;
db.on('error', () => console.log('connection error'));
db.once('open', () => {
`Connected to DB!`
})
const BugModel = mongoose.model('Bugs', BugSchema)
|
var path = require('path'),
gulp = require('gulp'),
plugins = require("gulp-load-plugins")({
pattern: ['gulp-*', 'gulp.*'],
replaceString: /\bgulp[\-.]/
});
var template = require('lodash').template;
var runSequence = require('run-sequence'),
pkg = require('./package.json'),
dirs = pkg['dir-configs'];
gulp.task('clean', function (done) {
require('del')([
template('<%= dist %>', dirs)
], done);
});
gulp.task('copy', function(done) {
runSequence(
['copy:main.css', 'copy:misc', 'copy:normalize'],
'html',
done);
});
gulp.task('copy:main.css', function () {
var banner = '/*! ' + pkg.name + ' v' + pkg.version +
' | ' + pkg.license.type + ' License' +
' | ' + pkg.homepage + ' */\n\n';
return gulp.src(template('<%= src %>/css/main.css', dirs))
.pipe(plugins.header(banner))
.pipe(gulp.dest(template('<%= dist %>/css', dirs)));
});
gulp.task('copy:misc', function () {
return gulp.src([
// Copy all files
template('<%= src %>/**/*', dirs),
// Exclude the following files
// (other tasks will handle the copying of these files)
template('!<%= src %>/css/main.scss', dirs)
], {
// Include hidden files by default
dot: true
})
.pipe(gulp.dest(template('<%= dist %>', dirs)))
.pipe(plugins.connect.reload());
});
gulp.task('copy:normalize', function () {
return gulp.src('node_modules/normalize.css/normalize.css')
.pipe(gulp.dest(template('<%= dist %>/css', dirs)));
});
gulp.task('css', function() {
gulp.src('src/css/main.scss')
.pipe(plugins.rubySass())
.pipe(plugins.autoprefixer())
.on('error', function (err) { console.log(err.message); })
.pipe(gulp.dest(template('<%= src %>/css', dirs)))
.pipe(plugins.notify('Finished Styles'));
});
gulp.task('js', function () {
return gulp.src([
'node_modules/jquery/dist/jquery.js',
'node_modules/slick-carousel/slick/slick.min.js',
'src/js/vendor/prettyphoto.min.js',
'src/js/vendor/localscroll.min.js',
'src/js/main.js',
])
.pipe(plugins.concat('main.min.js'))
.pipe(plugins.uglify())
.pipe(gulp.dest(template('<%= src %>/js', dirs)))
.pipe(plugins.notify('Finished Javascript'));
});
gulp.task('html', function () {
gulp.src(template('<%= dist %>/index.html', dirs))
.pipe(plugins.connect.reload());
});
gulp.task('connect', function() {
plugins.connect.server({
root: 'dist',
livereload: true
});
});
gulp.task('build', function (done) {
runSequence(
'clean',
['css', 'js'],
'copy',
done);
});
gulp.task('watch', ['connect'], function () {
gulp.watch(template('<%= src %>/css/main.scss', dirs), ['build']);
gulp.watch(template('<%= src %>/js/main.js', dirs), ['build']);
});
gulp.task('default', ['watch']); |
// todo: import Highcharts as a local module
import highchartsMore from 'highcharts/highcharts-more.js';
highchartsMore(Highcharts);
import exporting from 'highcharts/highcharts-more.js';
exporting(Highcharts);
import offlineExporting from 'highcharts/highcharts-more.js';
offlineExporting(Highcharts);
import './dist/lasp-highstock.js';
import './dist/lasp-highstock.css'; |
// ** React Imports
import { useState, useEffect } from "react"
import { useParams, Link } from "react-router-dom"
// ** Store & Actions
import { useSelector, useDispatch } from "react-redux"
// ** Third Party Components
import { User, Info, Share2 } from "react-feather"
// ** React Import
import InputPasswordToggle from "@components/input-password-toggle"
// ** Custom Components
import Sidebar from "@components/sidebar"
import Select from "react-select"
import Uppy from "@uppy/core"
const XHRUpload = require("@uppy/xhr-upload")
import SunEditor from "suneditor-react"
import "suneditor/dist/css/suneditor.min.css"
import { DragDrop } from "@uppy/react"
// ** Utils
import { getImageUser } from "@utils"
import Flatpickr from "react-flatpickr"
import "@styles/react/libs/flatpickr/flatpickr.scss"
// ** Third Party Components
import classnames from "classnames"
import {
Button,
FormGroup,
Label,
Card,
CardBody,
Form,
Input,
Nav,
NavItem,
NavLink,
ListGroup,
TabContent,
ListGroupItem,
Badge,
TabPane,
Alert,
Col,
Row
} from "reactstrap"
import { useForm, Controller } from "react-hook-form"
// ** Store & Actions
import {
addItem,
addImage,
udpateItem,
getAllTypes,
getAllStatuses,
getItem
} from "../store/action"
// ** Styles
import "@styles/react/apps/app-general.scss"
const ItemEdit = (props) => {
// ** States & Vars
const store = useSelector((state) => state.subjects)
const stores = useSelector((state) => state.subjects)
const { id } = useParams()
const dispatch = useDispatch()
// const { id } = useParams()
const baseUrl = "http://localhost:3000/api/"
const [name, setName] = useState("")
const [sigla, setSigla] = useState("")
const [agreement, setAgreement] = useState(null)
const [activeTab, setActiveTab] = useState(1)
const [directorAcad, setdirectorAcad] = useState(null)
const [coordinatorAcad, setCoordinatorAcad] = useState(null)
const [startDate, setStartDate] = useState(new Date())
const [endDate, setEndDate] = useState(new Date())
const [startDateDefault, setStartDateDefault] = useState(new Date())
const [endDateDefault, setEndDateDefault] = useState(new Date())
const [price, setPrice] = useState(0)
const [period, setPeriod] = useState(0)
const [year, setYear] = useState(0)
const [description, setDescription] = useState("")
const [studentProfile, setStudentProfile] = useState("")
const [title, setTitle] = useState("")
const [versions, setVersions] = useState([])
const { register, errors, handleSubmit, control, trigger } = useForm({
defaultValues: { dob: new Date() }
})
useEffect(() => {
setVersions(store.versions)
}, [dispatch, store.versions])
useEffect(() => {
if (!!store.selectedItem) {
dispatch(getAllVersions(id))
// setId(store.selectedItem._id)
setName(store.selectedItem.name)
setSigla(store.selectedItem.sigla)
if (!!store.selectedItem.agreement) {
setAgreement({
value: store.selectedItem.agreement.id,
label: store.selectedItem.agreement.name,
id: store.selectedItem.agreement._id
})
}
if (!!store.selectedItem.directorAcad) {
setdirectorAcad({
value: store.selectedItem.directorAcad._id,
label: store.selectedItem.directorAcad.name,
id: store.selectedItem.directorAcad._id
})
}
if (!!store.selectedItem.coordinatorAcad) {
setCoordinatorAcad({
value: store.selectedItem.coordinatorAcad._id,
label: store.selectedItem.coordinatorAcad.name,
id: store.selectedItem.coordinatorAcad._id
})
}
setStartDate(store.selectedItem.startDate)
setEndDate(store.selectedItem.endDate)
setPrice(store.selectedItem.price)
setPeriod(store.selectedItem.period)
setYear(store.selectedItem.year)
setDescription(store.selectedItem.description)
setStudentProfile(store.selectedItem.studentProfile)
setTitle(store.selectedItem.title)
} else {
// setId(0)
setSigla("")
setName("")
setdirectorAcad("")
setCoordinatorAcad("")
setStartDate(new Date())
setEndDate(new Date())
setPrice("")
setPeriod("")
setYear("")
setDescription("")
setStudentProfile("")
setTitle("")
}
}, [dispatch, store.selectedItem])
// ** Store Vars
const addVersionMethod = (val) => {
dispatch(
addVersion({
id
})
)
}
const getAggrement = (val) => {
if (val.length > 3) {
dispatch(
getAllAggrements({
q: val
})
)
}
}
const selectAggrement = (val) => {
getAggrement(val)
}
const selectedItemAggrement = (val) => {
console.log(val)
setAgreement(val)
}
const selectUser = (val) => {
}
const selectedItemDirectorAcad = (val) => {
setdirectorAcad(val)
}
const selectedItemCoordinatorAcad = (val) => {
setCoordinatorAcad(val)
}
const checkDisabled = () => {
let disabled = false
if (agreement === null) {
disabled = true
}
return disabled
}
const toggle = (values) => {
setActiveTab(values)
}
// ** Vars
// ** Function to handle form submit
const onSubmit = (values) => {
values["agreement"] = agreement._id
values["directorAcad"] = directorAcad._id
values["coordinatorAcad"] = coordinatorAcad._id
values["startDate"] = startDate
values["endDate"] = endDate
values["description"] = description
values["studentProfile"] = studentProfile
values["id"] = id
if (id === 0) {
dispatch(addItem(values))
} else {
dispatch(udpateItem(values, props))
}
}
const versionsStore = useSelector((state) => state.versions)
// ** Function to toggle tabs
// ** Function to get user on mount
useEffect(() => {
setActiveTab("1")
setVersions([])
setVersions((versions) => versions.concat({ name: "version", index: 1 }))
setVersions((versions) => versions.concat({ name: "version", index: 2 }))
setVersions((versions) => versions.concat({ name: "version", index: 3 }))
dispatch(getItem(id))
}, [dispatch])
return stores.selectedItem !== null && stores.selectedItem !== undefined ? (
<Row className="app-user-edit">
<Col sm="12">
<Card>
<CardBody className="pt-2">
<Nav pills>
<NavItem>
<NavLink active={activeTab === "1"} onClick={() => toggle("1")}>
<span className="align-middle d-none d-sm-block">
Información
</span>
</NavLink>
</NavItem>
<NavLink active={activeTab === "2"} onClick={() => toggle("2")}>
<span className="align-middle d-none d-sm-block">
Versiones
</span>
</NavLink>
</Nav>
<TabContent activeTab={activeTab}>
<TabPane tabId="1">
<Card>
<CardBody>
<Form onSubmit={handleSubmit(onSubmit)} autoComplete="off">
<FormGroup>
<Label for="lastName">
Nombre <span className="text-danger">*</span>
</Label>
<Input
name="name"
id="name"
autoComplete={0}
defaultValue={name}
placeholder="Ingresar el nombre"
innerRef={register({ required: true })}
className={classnames({
"is-invalid": errors["lastName"]
})}
/>
</FormGroup>
<Row>
<Col>
<FormGroup>
<Label for="directorAcad">Director Acad:</Label>
<Select
isClearable
value={directorAcad}
options={store.people}
onInputChange={selectUser}
onChange={selectedItemDirectorAcad}
name="directorAcad"
id="directorAcad"
innerRef={register({ required: true })}
className={classnames({
"is-invalid": errors["directorAcad"]
})}
/>
</FormGroup>
</Col>
<Col>
<FormGroup>
<Label for="coordinatorAcad">
Coordinador Acad:
</Label>
<Select
isClearable
value={coordinatorAcad}
options={store.people}
onInputChange={selectUser}
onChange={selectedItemCoordinatorAcad}
name="coordinatorAcad"
id="coordinatorAcad"
innerRef={register({ required: true })}
className={classnames({
"is-invalid": errors["coordinatorAcad"]
})}
/>
</FormGroup>
</Col>
<Col>
<FormGroup>
<Label for="price">
Precio Total:
<span className="text-danger">*</span>
</Label>
<Input
name="price"
id="price"
autoComplete={0}
defaultValue={price}
placeholder="Ingresar el precio"
innerRef={register({ required: true })}
className={classnames({
"is-invalid": errors["price"]
})}
/>
</FormGroup>
</Col>
</Row>
<Row>
<Col>
<FormGroup>
<Label for="price">Nota de aprobación</Label>
<Input
name="price"
id="price"
autoComplete={0}
defaultValue={0}
placeholder="Ingresar el precio"
innerRef={register({ required: true })}
className={classnames({
"is-invalid": errors["price"]
})}
/>
</FormGroup>
</Col>
<Col>
<FormGroup>
<Label for="price">Número de asignaturas</Label>
<Input
name="price"
id="price"
autoComplete={0}
defaultValue={0}
placeholder="Ingresar el precio"
innerRef={register({ required: true })}
className={classnames({
"is-invalid": errors["price"]
})}
/>
</FormGroup>
</Col>
<Col>
<FormGroup>
<Label for="directorAcad">Universidad</Label>
<Select
isClearable
value={""}
options={store.people}
onInputChange={selectUser}
onChange={selectedItemDirectorAcad}
name="directorAcad"
id="directorAcad"
innerRef={register({ required: true })}
className={classnames({
"is-invalid": errors["directorAcad"]
})}
/>
</FormGroup>
</Col>
<Col className="p-2">
<Button.Ripple
tag="label"
className="mr-50 cursor-pointer"
color="primary"
outline
>
Reglamento
<Input
type="file"
name="file"
id="uploadImg"
hidden
/>
</Button.Ripple>
</Col>
<Col className="p-2">
<Button.Ripple
tag="label"
className="mr-50 cursor-pointer"
color="primary"
outline
>
Brochure
<Input
type="file"
name="file"
id="uploadImg"
hidden
/>
</Button.Ripple>
</Col>
</Row>
<FormGroup>
<Label for="title">
Titulación: <span className="text-danger">*</span>
</Label>
{title && (
<SunEditor
name="title"
setOptions={{
height: 300,
buttonList: [
[
"font",
"align",
"fontSize",
"table",
"textStyle",
"align"
],
["image"]
]
}}
id="title"
autoComplete={0}
defaultValue={title}
placeholder="Ingresar el título"
innerRef={register({ required: true })}
onChange={setTitle}
className={classnames({
"is-invalid": errors["title"]
})}
/>
)}
{!title && (
<SunEditor
setOptions={{
buttonList: [
[
"font",
"align",
"fontSize",
"table",
"textStyle",
"align"
],
["image"]
],
height: 300
}}
name="title"
id="title"
autoComplete={0}
defaultValue={""}
placeholder="Ingresar el título"
innerRef={register({ required: true })}
onChange={setTitle}
className={classnames({
"is-invalid": errors["title"]
})}
/>
)}
</FormGroup>
<FormGroup>
<Label for="description">
Descripción <span className="text-danger">*</span>
</Label>
{description && (
<SunEditor
setOptions={{
height: 300,
buttonList: [
[
"font",
"align",
"fontSize",
"table",
"textStyle",
"align"
],
["image"]
]
}}
name="description"
id="description"
autoComplete={0}
defaultValue={description}
placeholder="Ingresar la descripción"
innerRef={register({ required: true })}
onChange={setDescription}
className={classnames({
"is-invalid": errors["description"]
})}
/>
)}
{!description && (
<SunEditor
setOptions={{
height: 300,
buttonList: [
[
"font",
"align",
"fontSize",
"table",
"textStyle",
"align"
],
["image"]
]
}}
name="description"
id="description"
autoComplete={0}
defaultValue={""}
placeholder="Ingresar la descripción"
innerRef={register({ required: true })}
onChange={setDescription}
className={classnames({
"is-invalid": errors["description"]
})}
/>
)}
</FormGroup>
<FormGroup>
<Label for="studentProfile">
Perfil Estudiante:{" "}
<span className="text-danger">*</span>
</Label>
{studentProfile && (
<SunEditor
setOptions={{
height: 300,
buttonList: [
[
"font",
"align",
"fontSize",
"table",
"textStyle",
"align"
],
["image"]
]
}}
name="studentProfile"
id="studentProfile"
autoComplete={0}
defaultValue={studentProfile}
onChange={setStudentProfile}
type="textarea"
placeholder="Ingresar el perfil del estudiante"
innerRef={register({ required: true })}
className={classnames({
"is-invalid": errors["studentProfile"]
})}
/>
)}
{!studentProfile && (
<SunEditor
setOptions={{
height: 300,
buttonList: [
[
"font",
"align",
"fontSize",
"table",
"textStyle",
"align"
],
["image"]
]
}}
name="studentProfile"
id="studentProfile"
autoComplete={0}
defaultValue={""}
onChange={setStudentProfile}
type="textarea"
placeholder="Ingresar el perfil del estudiante"
innerRef={register({ required: true })}
className={classnames({
"is-invalid": errors["studentProfile"]
})}
/>
)}
</FormGroup>
<FormGroup>
<Label for="studentProfile">Observaciones</Label>
{studentProfile && (
<SunEditor
setOptions={{
height: 300,
buttonList: [
[
"font",
"align",
"fontSize",
"table",
"textStyle",
"align"
],
["image"]
]
}}
name="studentProfile"
id="studentProfile"
autoComplete={0}
defaultValue={studentProfile}
onChange={setStudentProfile}
type="textarea"
placeholder="Ingresar el perfil del estudiante"
innerRef={register({ required: true })}
className={classnames({
"is-invalid": errors["studentProfile"]
})}
/>
)}
{!studentProfile && (
<SunEditor
setOptions={{
height: 300,
buttonList: [
[
"font",
"align",
"fontSize",
"table",
"textStyle",
"align"
],
["image"]
]
}}
name="studentProfile"
id="studentProfile"
autoComplete={0}
defaultValue={""}
onChange={setStudentProfile}
type="textarea"
placeholder="Ingresar el perfil del estudiante"
innerRef={register({ required: true })}
className={classnames({
"is-invalid": errors["studentProfile"]
})}
/>
)}
</FormGroup>
<Row>
<Col>
<Button
type="submit"
className="mr-1"
color="primary"
disabled={checkDisabled()}
>
Guardar
</Button>
<Button type="reset" color="secondary" outline>
Cancelar
</Button>
</Col>
</Row>
</Form>
</CardBody>
</Card>
</TabPane>
</TabContent>
</CardBody>
</Card>
</Col>
</Row>
) : (
<Alert color="danger">
<h4 className="alert-heading">Item not found</h4>
<div className="alert-body">
El item con el id : {id} no existe, por favor buscalo en :{" "}
<Link to="/apps/user/list">la lista de items</Link>
</div>
</Alert>
)
}
export default ItemEdit
|
export const START = "START";
|
function postDelete() {
const postDelete = document.querySelector('#postDelete');
if (confirm("게시물을 삭제하시겠습니까?") == true){ //확인
postDelete.submit();
} else{ //취소
return ;
}
} |
// DECLARATIONS
// Initial parameters
var dilutionFactor = 2;
var dilutionPoints = 10;
var targetVolume = 100;
var stockConc = 10;
var adjStockConc = 10;
// Output arrays
var arrTargetConcs = [];
var arrDispenseVols = [];
var arrDmsoVols = [];
var arrAdjStockConcs = [];
// MAIN SCRIPT
// Create target concentrations array
for (i=0;i<dilutionPoints;i++) {
arrTargetConcs[i] = stockConc / Math.pow(2,i);
}
// Create dispense volume list
for (i=0;i<dilutionPoints;i++) {
findSuitableDispenseVol(i);
}
//console.log(arrDispenseVols);
//console.log(arrAdjStockConcs);
// FUNCTIONS
// Recursive function to find best dispense volume
function findSuitableDispenseVol (ctr) {
var adjFactor = adjStockConc / stockConc; //factor that multiplies the dispense volume to a value that can be divisible by 2.5
var adjTargetVolume = targetVolume / adjFactor;
var tempDispenseVol = +((adjTargetVolume / Math.pow(2,ctr)).toFixed(2));
if (tempDispenseVol % 2.5 === 0) {
arrDispenseVols[ctr] = tempDispenseVol;
arrAdjStockConcs[ctr] = adjStockConc;
} else {
adjStockConc = adjStockConc / 10;
findSuitableDispenseVol(ctr);
}
}
// Find closest number to n divisible by m
// Only works with positive numbers, but that's nbd
function findClosestNumber(n,m) {
var q, n1, n2;
q = n / m;
n1 = m * Math.floor(q);
n2 = m * Math.ceil(q);
if (Math.abs(n-n1) < Math.abs(n-n2)) {
return n1;
} else {
return n2;
}
}
console.log(findClosestNumber(16.25,2.5)); |
import tabs from "./tabs";
function product() {
let radio1 = document.querySelector(".form__checkbox-button"),
radio2 = document.querySelector(".form__checkbox-button--multi"),
radio1Dropdown = document.querySelector(".form__dropdown"),
radio2Dropdown = document.querySelector(".form__dropdown--multi");
if (radio1Dropdown) {
function show(radioDrop1, radioDrop2, activeClass) {
radioDrop1.classList.add(activeClass);
radioDrop2.classList.remove(activeClass);
}
radio1.addEventListener("change", () => {
show(radio1Dropdown, radio2Dropdown, "form__dropdown--show");
});
radio2.addEventListener("change", () => {
show(radio2Dropdown, radio1Dropdown, "form__dropdown--show");
});
tabs({
button: ".product__tab-button",
content: ".product__tab-content",
activeClass: ".product__tab-button--active",
noContentAlert: ".nothing-find",
tabToShow: 0,
animate: true
});
}
}
export default product; |
var resetpass=(function(){
var $oldpass,$newpass,$confirmpass,oldpass_val,newpass_val,confirmpass_val;
//Cache DOM
$oldpass=$(".txtoldpassword");
$newpass=$(".txtnewpassword");
$confirmpass=$(".txtconfirmpassword");
$submit_btn= $('#submit');
pass_val = $oldpass.val();
newpass_val = $newpass.val();
confirmpass_val = $confirmpass.val();
//Binding events
$('#modal1').on('show.bs.modal', modalShownEvent);
$oldpass.focusout(validateOldPass);
$newpass.focusout(validateNewPass);
$confirmpass.focusout(validateconfirmPass);
$submit_btn.click(function(e){
e.preventDefault();
changePassword(pass_val,newpass_val,confirmpass_val);
});
//Functions - sandbox
function modalShownEvent() {
$oldpass.val("")
.css("background-color","")
.focus();
$newpass.val("")
.css("background-color","");
$confirmpass.val("")
.css("background-color","");
}
function validateOldPass() {
pass_val = $(this).val();
if (pass_val === "") {
$(this).focus()
.css("background-color", "#ffb3b3");
} else {
$(this).css("background-color", "");
}
}
function validateNewPass() {
newpass_val = $(this).val();
if (newpass_val === "") {
$(this).focus()
.css("background-color", "#ffb3b3");
} else {
$(this).css("background-color", "");
}
}
function validateconfirmPass() {
confirmpass_val = $(this).val();
newpass_val = $newpass.val();
if (confirmpass_val === "") {
$(this).focus()
.css("background-color", "#ffb3b3");
}else {
$(this).css("background-color", "");
checkPassEquality(newpass_val,confirmpass_val);
}
}
function checkPassEquality(newpass_val,confirmpass_val){
if (confirmpass_val != newpass_val) {
$newpass.focus()
.val("")
.css("background-color", "#ffb3b3");
$confirmpass.val("")
.css("background-color", "#ffb3b3");
return false;
}else{
$newpass.css("background-color","");
$confirmpass.css("background-color", "");
return true;
}
}
function changePassword(pass,npass,cpass) {
if(arguments.length != 3){
console.log("Enter valid numbers of arguments..");
return false;
}else {
var ans=checkPassEquality(npass,cpass);
if(ans == false ){
console.log("New password and confirm passeord should be same.");
return false;
}
}
if (pass === "" || npass === "" || cpass === "") {
$('.success1').css('display', 'block').html("<img src=\"../Resource/Image/error.png\" alt=\"error\" style=\"width: 5%\"><font color='red'><b>Fill all the details..</b></font>").delay(1000).fadeOut();
console.log("Enter all details...");
} else {
$('.ajaxprogress1').show();
changePassAjaxCall(pass,npass,cpass);
}
}
function changePassAjaxCall(pass,npass,cpass){
$.ajax({
type : "PUT",
url : "changepassword",
data : "passoldpassword=" + pass + "&passnewpassword=" + npass + "&passnewrepassword=" + cpass,
success : function(datas) {
$oldpass.val("");
$newpass.val("");
$confirmpass.val("");
$('.ajaxprogress1').hide();
$('.success1').css('display','block')
.html(datas)
.delay(1000)
.fadeOut();
var start_str=datas.search("<b>");
var end_str=datas.search("</b>");
var str=datas.slice(start_str+3,end_str);
console.log(str);
},
error : function(e) {
alert("Error in change password..");
}
});
}
return{
changePassword : changePassword,
};
})()
|
/*
Gradebook from Names and Scores
I worked on this challenge with Timur Catakli.
This challenge took me 1.5 hours.
You will work with the following two variables. The first, students, holds the names of four students.
The second, scores, holds groups of test scores. The relative positions of elements within the two
variables match (i.e., 'Joseph' is the first element in students; his scores are the first value in scores.).
Do not alter the students and scores code.
*/
var students = ["Joseph", "Susan", "William", "Elizabeth"]
var scores = [ [80, 70, 70, 100],
[85, 80, 90, 90],
[75, 70, 80, 75],
[100, 90, 95, 85] ]
//console.log(scores[2][1]);
// __________________________________________
// Write your code below.
var gradebook = {
Joseph: {
testScores: scores[0]
},
Susan: {
testScores: scores[1]
},
William: {
testScores: scores[2]
},
Elizabeth: {
testScores: scores[3]
},
addScore: function(name,score) {
scores[students.indexOf(name)].push(score);
},
getAverage: function(name) {
return average(scores[students.indexOf(name)]);
}
};
function average(arrayIntegers){
var total = 0;
for(var i = 0; i < arrayIntegers.length; i++) {
total += arrayIntegers[i];
}
var avg = total / arrayIntegers.length;
return avg;
};
// __________________________________________
// Refactored Solution
// I used the object constructor notation rather than the literal notation.
// Tried to find an average method in Math but there was nothing. Found array method .reduce instead.
var gradebook = {};
// Learned this from another peer and I like its efficiency!
for (var student in students) {
gradebook[students[student]] = {
testScores: scores[student]
};
}
gradebook.addScore = function(name, score) {
gradebook[name]["testScores"].push(score);
}
gradebook.getAverage = function(name) {
return average(gradebook[name]["testScores"]);
}
function average(arrayIntegers) {
var total = arrayIntegers.reduce(function(a, b) {return a + b});
return total / arrayIntegers.length;
};
// __________________________________________
// Reflect
// What did you learn about adding functions to objects?
// Some need another function constructed outside of the object, as we did for average here.
// We were hung up on getAverage function for awhile, we couldn't make it work until we realized we needed to use return to return the value.
// In the addScore function, we didn't need to return anything because it just updated the gradebook object.
// How did you iterate over nested arrays in JavaScript?
// The iteration expression remained the same, the trick was locating the pieces to iterate over. Working backwards,
// for the getAverage function, we called the indexOf function on the student array for the name that is passed through the function.
// This index number was then passed through the average function as the indexed value we want to access in the scores nested array.
// In refactoring, I thought there had to be a way to iterate through the gradebook object and
// access the elements there, differently than we had done in the initial solution. I used
// brackets for each key as so: gradebook[name]["testScores"]. I thought you could use dot
// notation or brackets, but dot notation does not work. I need to look into why.
// Were there any new methods you were able to incorporate? If so, what were they and how did they work?
// reduce was used to sum the elements in the array using the syntax:
// array.reduce(function(previousValue, currentValue, currentIndex, array) { return previousValue + currentValue;});
// Here I used it as so arrayIntegers.reduce(function(a, b) {return a + b}); where 'a' refers
// to the previousValue and 'b' refers to the currentValue. The callback function is invoked
// for each element in the array, excluding holes.
// initialValue does not always need to be provided, but if it is, you can add it as 10 is in this example:
// [0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, currentIndex, array) {
// return previousValue + currentValue;}, 10);
// It doesn't seem that the array argument is necessary when listing the parameter where I used it above.
// __________________________________________
// Test Code: Do not alter code below this line.
function assert(test, message, test_number) {
if (!test) {
console.log(test_number + "false");
throw "ERROR: " + message;
}
console.log(test_number + "true");
return true;
}
assert(
(gradebook instanceof Object),
"The value of gradebook should be an Object.\n",
"1. "
)
assert(
(gradebook["Elizabeth"] instanceof Object),
"gradebook's Elizabeth property should be an object.",
"2. "
)
assert(
(gradebook.William.testScores === scores[2]),
"William's testScores should equal the third element in scores.",
"3. "
)
assert(
(gradebook.addScore instanceof Function),
"The value of gradebook's addScore property should be a Function.",
"4. "
)
gradebook.addScore("Susan", 80)
assert(
(gradebook.Susan.testScores.length === 5
&& gradebook.Susan.testScores[4] === 80),
"Susan's testScores should have a new score of 80 added to the end.",
"5. "
)
assert(
(gradebook.getAverage instanceof Function),
"The value of gradebook's getAverage property should be a Function.",
"6. "
)
assert(
(average instanceof Function),
"The value of average should be a Function.\n",
"7. "
)
assert(
average([1, 2, 3]) === 2,
"average should return the average of the elements in the array argument.\n",
"8. "
)
assert(
(gradebook.getAverage("Joseph") === 80),
"gradebook's getAverage should return 80 if passed 'Joseph'.",
"9. "
) |
const express = require("express");
const router = express.Router();
const Course = require("../models/Course");
const Folder = require("../models/Folder");
const Content = require("../models/Content")
const Notification = require("../models/Notification")
const moment = require("moment")
const { contentValidation } = require("../validation");
const { deleteContent, tagHelper } = require("../helpers")
const { authStaff, authStudent, authAdmin, auth } = require("../auth");
const fs = require('fs')
const multer = require('multer');
const User = require("../models/User");
// const { storage, cloudinary } = require("../cloudinary")
// const { cloudinary } = require("../cloudinary")
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, `D:/GUC/bachelor/client/public/uploads/`)
},
filename: function (req, file, cb) {
const dotIndex = file.originalname.lastIndexOf(".")
cb(null, file.originalname.substring(0, dotIndex) + '-' + Date.now() + file.originalname.substring(dotIndex))
}
})
const upload = multer({ storage })
// const upload = multer({ dest: "../client/public/uploads/" })
if (process.env.NODE_ENV !== "production") {
const dotenv = require("dotenv")
dotenv.config()
}
router.get("/:contentID", auth, async (req, res) => {
try {
const { contentID } = req.params
const data = await Content.findById(contentID).populate("author")
res.send(data)
} catch (error) {
console.log(error)
return res.status(400).json(error.details[0].message);
}
});
router.get('/:contentID/download', async (req, res) => {
try {
const { contentID } = req.params
const data = await Content.findById(contentID)
res.download(data.file.path)
// const download = cloudinary.
} catch (error) {
console.log(error)
return res.status(400).json(error.details[0].message);
}
});
//http://res.cloudinary.com/improved-cms/raw/upload/fl_attachment/v1624779647/mhap4v8yuo9iloksbiyv.pdf
//localhost:8080/contents/upload/60c5bb45cf8bd0281c189758
router.post("/upload/:folderID", authStaff, upload.single('file'), async (req, res) => {
try {
// console.log(req.file)
// const result = await cloudinary.uploader.upload(req.file.path, { resource_type: "raw"},
// function (error, result) { console.log(result, error); });
req.body.tag = tagHelper(req.body.tag)
const { error } = contentValidation({ ...req.body, file: req.file });
if (error)
return res.status(400).json(error.details[0].message);
//check course in courses DB
const { folderID } = req.params
const foundFolder = await Folder.findById(folderID)
if (!foundFolder)
return res.status(400).json(`Folder ${folderID} not found`);
const { courseID } = req.body
//save content in DB
const newContent = new Content({ author: req.user.id, folderID, ...req.body, file: req.file, })
const savedContent = await newContent.save()
// console.log("🚀 ~ file: content.js ~ line 82 ~ router.post ~ savedContent", savedContent)
//add content to course array
await Folder.findByIdAndUpdate(folderID, { $addToSet: { contents: [savedContent._id] } },
{ new: true, runValidators: true, useFindAndModify: true })
const courseData = await Course.findById(courseID)
//add notification
const userData = await User.findById(req.user.id)
const authorFullName = `${userData.firstName} ${userData.lastName}`
const courseNameCode = `${courseData.name} (${courseData.code})`
const notificationDetails = `to ${courseNameCode} course`
const text = `${authorFullName} uploaded a new content ${notificationDetails}`
const type = "content"
const refID = folderID
const newNotification = new Notification({ role: userData.role, text, type, refID })
const savedNotification = await newNotification.save()
//send the notification
const studentsArr = courseData.students
const staffArr = courseData.staff
for (const studentID of studentsArr) {
await User.findByIdAndUpdate(studentID, { $addToSet: { notifications: [savedNotification._id] } },
{ new: true, runValidators: true, useFindAndModify: true })
}
for (const staffID of staffArr) {
if (staffID != req.user.id)
await User.findByIdAndUpdate(staffID, { $addToSet: { notifications: [savedNotification._id] } },
{ new: true, runValidators: true, useFindAndModify: true })
}
res.send(savedContent)
}
catch (err) {
console.log("catch error")
console.log(err)
if (err.driver && err.name == "MongoError" && err.keyValue)
res.json(`${err.keyValue.code} already exists`)
fs.unlinkSync(req.file.path)
res.json(err);
}
});
router.patch("/:contentID", upload.single('file'), async (req, res) => {
try {
const { contentID } = req.params
const { newTitle, newTag } = req.body
const newFile = req.file
console.log("🚀 ~ file: content.js ~ line 135 ~ router.patch ~ newFile", newFile)
const foundContent = await Content.findById(contentID)
if (!foundContent)
return res.status(400).json("Content not found");
if (newTitle) {
await Content.findByIdAndUpdate(contentID, { title: newTitle },
{ new: true, runValidators: true, useFindAndModify: true })
}
if (newTag) {
const tagForm = tagHelper(newTag)
await Content.findByIdAndUpdate(contentID, { tag: tagForm },
{ new: true, runValidators: true, useFindAndModify: true })
}
if (newFile) {
await Content.findByIdAndUpdate(contentID, { file: newFile },
{ new: true, runValidators: true, useFindAndModify: true })
}
res.send("content edited");
} catch (err) {
console.log("catch error")
console.log(err)
res.json(err);
}
});
router.delete("/:folderID/:contentID", authStaff, async (req, res) => {
try {
const { contentID, folderID } = req.params
const foundContent = await Content.findById(contentID)
if (!foundContent)
return res.status(400).json("Content not found");
deleteContent(contentID, folderID)
res.send("content deleted");
} catch (err) {
console.log("catch error")
console.log(err)
res.json(err);
}
});
module.exports = router; |
function printCtrl($scope, User, Spend, $rootScope) {
$rootScope.root_title = 'In ấn';
// end code create by lesonapt =============================================
}
|
const fill = (length) => (cb) => new Array(length).fill(true).map((item, index) => cb(index));
const getKernelCoreStr = ({ width, depth, f, inputMap }) => `
${fill(f.length)((fIndex) => `let f${fIndex} = ${f[fIndex]};`).join('')}
${fill(width)((iIndex) => `let i${iIndex} = 0;`).join('')}
${fill(width)((oIndex) => `let o${oIndex} = 0;`).join('')}
${fill(width)((iIndex) => `i${iIndex} = ${inputMap[iIndex]};`).join('')}
${fill(depth)((lIndex) =>
`${fill(width)((oIndex) =>
`o${oIndex} = Math.tanh(${fill(width)((iIndex) =>
`i${iIndex} * f${lIndex * width * (width + 1) + oIndex * (width + 1) + iIndex}`).join(' + ')} + f${lIndex * width * (width + 1) + oIndex * (width + 1) + width});`
).join('\n')}
${fill(width)((index) => `i${index} = o${index};`).join('')}`
).join('')}
`;
const animation = (cb) => {
let running = false;
let time = 0;
const go = () => {
if (running) {
cb(time);
time += 1;
window.requestAnimationFrame(go);
}
};
return {
start: () => {
running = true;
window.requestAnimationFrame(go);
},
stop: () => {
running = false;
}
};
};
const data = {
canvSize: 600,
depth: 32,
width: 16,
tCount: 8,
tChance: 0.5,
fMax: 1000,
step: 0.000001,
timeFunc: (data, time) => data.tsDefinition.map(({ f, a, p }) => {
return Math.cos((f * data.fMax) * ((((((data.step * time) % 1) + p) % 1) * 2 - 1) * Math.PI)) * a;
})
};
data.tsDefinition = new Array(data.tCount).fill(true).map(() => ({ f: Math.random(), p: Math.random(), a: Math.random() }));
data.f = new Float32Array(data.depth * data.width * (data.width + 1)).map(() => Math.random() * 2 - 1);
data.inputMap = fill(data.width)(() => Math.random() < data.tChance ? `$[${Math.floor(Math.random() * data.tCount)}]` : ['x', 'y'][Math.floor(Math.random() * 2)]);
data.k = new Function('$', `
let x = (this.thread.x / this.output.x) * 2 - 1;
let y = (this.thread.y / this.output.y) * 2 - 1;
${getKernelCoreStr(data)}
this.color((o0 + 1) / 2, (o1 + 1) / 2, (o2 + 1) / 2, 1);
`);
console.log(data);
const render = new GPU().createKernel(data.k)
.setOutput([data.canvSize, data.canvSize])
.setGraphical(true);
const cb = (time) => {
const $ = data.timeFunc(data, time);
render($);
document.body.firstChild && document.body.firstChild.remove();
document.body.appendChild(render.canvas);
};
window.addEventListener('DOMContentLoaded', () => animation(cb).start());
|
const mongoose = require('mongoose')
const Place = require('../models/Place')
const places = [
{
name: 'El Péndulo',
image: 'https://images.ecosia.org/dp_p-zAmfaAnBDNxLpcvWgyF26M=/0x390/smart/https%3A%2F%2Fassets.atlasobscura.com%2Fmedia%2FW1siZiIsInVwbG9hZHMvcGxhY2VfaW1hZ2VzL2UzZGFhODliNGM0ZmY1NWE0Ml9wZW5kdWxvLWRlLXBvbGFuY28tdmVnZXRhY2lvbi5qcGciXSxbInAiLCJjb252ZXJ0IiwiLXF1YWxpdHkgODEgLWF1dG8tb3JpZW50Il0sWyJwIiwidGh1bWIiLCI2MDB4PiJdXQ',
category: 'Coffee Shop',
stars: 5,
location: {
coordinates: [ -99.195666, 19.430487 ]
}
},
{
name: 'Gandhi',
image: 'https://images.ecosia.org/EXlvS3ST-vyvNtCRwDxAWV2RHQU=/0x390/smart/https%3A%2F%2Fwww.frogx3.com%2Fwp-content%2Fuploads%2F2012%2F01%2Ffrases-libreria-gandhi-menos-face.gif',
category: 'Book store',
stars: 5,
location: {
coordinates: [-99.196276, 19.432103 ]
}
},
{
name: 'Almanegra',
image: 'https://images.ecosia.org/xueRax_iSI4H89Xi3K6kFVQH3CU=/0x390/smart/https%3A%2F%2Fmedia-cdn.tripadvisor.com%2Fmedia%2Fphoto-s%2F07%2Fa8%2F13%2Fa4%2Falma-negra-cafe.jpg',
category: 'Coffee Shop',
stars: 5,
location: {
coordinates: [-99.162906, 19.418999 ]
}
}
]
mongoose
.connect('mongodb://localhost/booksandcoffee')
.then(()=> {
Place.create(places)
.then(places => {
console.log(`You created ${places.length} places successfully`)
mongoose.connection.close()
})
.catch((err)=> {
console.log(err)
})
})
.catch((err)=> {
console.log(err)
})
|
#!/usr/bin/env node
require('../lib/commander'); |
import axios from 'axios';
import Vue from 'vue';
import Vuex from 'vuex'
import 'es6-promise/auto'
window.axios = axios;
window.Vue = Vue;
import Reservation from 'Pages/reservation'
import Notification from "Components/Notification";
import Vuetify from "vuetify";
Vue.use(Vuetify);
Vue.use(Vuex);
document.addEventListener("DOMContentLoaded", function () {
if (document.getElementById('app')) {
new Vue({
el: '#app',
vuetify: new Vuetify(),
render: function (h) {
return (
<div>
<Notification />
<Reservation />
</div>
)
}
})
}
})
|
'use strict';
authApp.controller('DashboardController', [ '$scope', '$cookies', '$location', '$state', DashboardController]);
function DashboardController($scope, $cookies, $location, $state) {
if(!$cookies.get("user")){
$state.go('login');
return;
}
var user = JSON.parse($cookies.get("user"));
$scope.master = angular.copy(user);
$scope.user = angular.copy(user);
$scope.bClick="show";
if ($state.is('dashboard.edit')) {
$scope.bClick="edit";
}
$scope.apply = function(user) {
$scope.master = angular.copy(user);
};
} |
this.VelhaMania = (function (Backbone, Marionette) {
var App = new Marionette.Application();
App.addRegions({
mainRegion: '.main-region',
navRegion: '.nav-region',
modalRegion: '.modal-region'
});
App.addInitializer(function () {
App.module('Utilities').start();
App.module('HomeApp').start();
App.module('UsersApp').start();
App.module('BoardApp').start();
});
App.reqres.setHandler('concern', function (concern) {
App.Concerns[concern] = void(0);
});
App.on('start', function () {
this.startHistory();
});
return App;
})(Backbone, Marionette); |
import { addons } from '@storybook/addons';
import bundTheme from './bundTheme';
addons.setConfig({
theme: bundTheme,
}); |
import { createSlice } from '@reduxjs/toolkit';
import { toast } from 'react-toastify';
import { getLocalStorage, setLocalStorage } from '../../utils/localstorage';
export const wishlistSlice = createSlice({
name: 'wishlist',
initialState: {
wishlists: [],
},
reducers: {
add_wishlist: (state, { payload }) => {
if (payload.changeType === 'remove') {
state.wishlists = state.wishlists.filter(item => item.id !== payload.item.id);
// message
toast.error(`${payload.item.title} remove to wishlist`, {
position: 'top-left'
})
}
else if (payload.changeType === 'added') {
state.wishlists.push(payload.item);
// message
toast.success(`${payload.item.title} added to wishlist`, {
position: 'top-left'
})
}
// set local storage
setLocalStorage('wishlist_products', state.wishlists)
},
remove_wishlist: (state, { payload }) => {
state.wishlists = state.wishlists.filter(item => Number(item.id) !== Number(payload.id));
// message
toast.error(`${payload.title} remove to wishlist`, {
position: 'top-left'
})
// set local storage
setLocalStorage('wishlist_products', state.wishlists)
},
get_wishlist_products: (state, { payload }) => {
state.wishlists = getLocalStorage('wishlist_products')
}
}
})
export const { add_wishlist, get_wishlist_products,remove_wishlist } = wishlistSlice.actions;
export default wishlistSlice.reducer; |
// var str = '1234'; // 数字的 1234
// 生写( 秦九韶算法 )
// 1234 => 1000 + 200 + 30 + 4 按权展开
// 算法描述
// s = 0;
// s += 4 * 10^0; // 4
// s += 3 * 10^1; // 34
// s += 2 * 10^2; // 234
// s += 1 * 10^3; // 1234
// Math.pow()
/*
var s = 0;
for ( var i = str.length - 1; i >= 0; i-- ) {
var base = str.length - i - 1; //
// console.log( base ); // 0, 1, 2, 3
// console.log( str.charCodeAt( i ) );
s += ( str.charCodeAt( i ) - 48 ) * Math.pow( 10, base );
}
console.log( s );
*/
// 真正的 秦九韶
var str = '2468';
// 算法描述
// s = 0;
// s = s * 10 + 2; // 2
// s = s * 10 + 4 // 24
// s = s * 10 + 6 // 246
// s = s * 10 + 8 // 2468
var s = 0;
for ( var i = 0; i < str.length; i++ ) {
var num = str.charCodeAt( i ) - 48;
s = s * 10 + num;
}
|
global.ROUTER.web.Request.request_form = function( req, res, d, pathname ){
global.api.HTML.render_html( req, res, d , pathname )
}
|
import React, { Component } from "react";
import { Bar, Line } from "react-chartjs-2";
import {
Button,
Card,
CardBody,
CardFooter,
CardTitle,
Col,
Progress,
Row,
} from "reactstrap";
// import { CustomTooltips } from '@coreui/coreui-plugin-chartjs-custom-tooltips';
import { getStyle, hexToRgba } from "@coreui/coreui/dist/js/coreui-utilities";
import { token, API_SERVER } from "../../helper/variable.js";
import Cookie from "js-cookie";
import axios from "axios";
import jwt_decode from "jwt-decode";
// const Widget02 = lazy(() => import('../../views/Widgets/Widget02'));
const brandPrimary = getStyle("--primary");
const brandSuccess = getStyle("--success");
const brandInfo = getStyle("--info");
const brandDanger = getStyle("--danger");
//Random Numbers
function random(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
var elements = 27;
var data1 = [];
var data2 = [];
var data3 = [];
for (var i = 0; i <= elements; i++) {
data1.push(random(50, 200));
data2.push(random(80, 100));
data3.push(65);
}
const mainChart = {
labels: [
"Mo",
"Tu",
"We",
"Th",
"Fr",
"Sa",
"Su",
"Mo",
"Tu",
"We",
"Th",
"Fr",
"Sa",
"Su",
"Mo",
"Tu",
"We",
"Th",
"Fr",
"Sa",
"Su",
"Mo",
"Tu",
"We",
"Th",
"Fr",
"Sa",
"Su",
],
datasets: [
{
label: "My First dataset",
backgroundColor: hexToRgba(brandInfo, 10),
borderColor: brandInfo,
pointHoverBackgroundColor: "#fff",
borderWidth: 2,
data: data1,
},
{
label: "My Second dataset",
backgroundColor: "transparent",
borderColor: brandSuccess,
pointHoverBackgroundColor: "#fff",
borderWidth: 2,
data: data2,
},
{
label: "My Third dataset",
backgroundColor: "transparent",
borderColor: brandDanger,
pointHoverBackgroundColor: "#fff",
borderWidth: 1,
borderDash: [8, 5],
data: data3,
},
],
};
const mainChartOpts = {
// tooltips: {
// enabled: false,
// custom: CustomTooltips,
// intersect: true,
// mode: 'index',
// position: 'nearest',
// callbacks: {
// labelColor: function(tooltipItem, chart) {
// return { backgroundColor: chart.data.datasets[tooltipItem.datasetIndex].borderColor }
// }
// }
// },
maintainAspectRatio: false,
legend: {
display: false,
},
scales: {
xAxes: [
{
gridLines: {
drawOnChartArea: false,
},
},
],
yAxes: [
{
ticks: {
beginAtZero: true,
maxTicksLimit: 5,
stepSize: Math.ceil(250 / 5),
max: 250,
},
},
],
},
elements: {
point: {
radius: 0,
hitRadius: 10,
hoverRadius: 4,
hoverBorderWidth: 3,
},
},
};
// Card Chart 1
const cardChartData1 = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
backgroundColor: brandPrimary,
borderColor: "rgba(255,255,255,.55)",
data: [65, 59, 84, 84, 51, 55, 40],
},
],
};
const cardChartOpts1 = {
// tooltips: {
// enabled: false,
// custom: CustomTooltips
// },
maintainAspectRatio: false,
legend: {
display: false,
},
scales: {
xAxes: [
{
gridLines: {
color: "transparent",
zeroLineColor: "transparent",
},
ticks: {
fontSize: 2,
fontColor: "transparent",
},
},
],
yAxes: [
{
display: false,
ticks: {
display: false,
min: Math.min.apply(Math, cardChartData1.datasets[0].data) - 5,
max: Math.max.apply(Math, cardChartData1.datasets[0].data) + 5,
},
},
],
},
elements: {
line: {
borderWidth: 1,
},
point: {
radius: 4,
hitRadius: 10,
hoverRadius: 4,
},
},
};
// Card Chart 2
const cardChartData2 = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
backgroundColor: brandInfo,
borderColor: "rgba(255,255,255,.55)",
data: [1, 18, 9, 17, 34, 22, 11],
},
],
};
const cardChartOpts2 = {
// tooltips: {
// enabled: false,
// custom: CustomTooltips
// },
maintainAspectRatio: false,
legend: {
display: false,
},
scales: {
xAxes: [
{
gridLines: {
color: "transparent",
zeroLineColor: "transparent",
},
ticks: {
fontSize: 2,
fontColor: "transparent",
},
},
],
yAxes: [
{
display: false,
ticks: {
display: false,
min: Math.min.apply(Math, cardChartData2.datasets[0].data) - 5,
max: Math.max.apply(Math, cardChartData2.datasets[0].data) + 5,
},
},
],
},
elements: {
line: {
tension: 0.00001,
borderWidth: 1,
},
point: {
radius: 4,
hitRadius: 10,
hoverRadius: 4,
},
},
};
// Card Chart 3
const cardChartData3 = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
backgroundColor: "rgba(255,255,255,.2)",
borderColor: "rgba(255,255,255,.55)",
data: [78, 81, 80, 45, 34, 12, 40],
},
],
};
const cardChartOpts3 = {
// tooltips: {
// enabled: false,
// custom: CustomTooltips
// },
maintainAspectRatio: false,
legend: {
display: false,
},
scales: {
xAxes: [
{
display: false,
},
],
yAxes: [
{
display: false,
},
],
},
elements: {
line: {
borderWidth: 2,
},
point: {
radius: 0,
hitRadius: 10,
hoverRadius: 4,
},
},
};
// Card Chart 4
const cardChartData4 = {
labels: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""],
datasets: [
{
label: "My First dataset",
backgroundColor: "rgba(255,255,255,.3)",
borderColor: "transparent",
data: [78, 81, 80, 45, 34, 12, 40, 75, 34, 89, 32, 68, 54, 72, 18, 98],
},
],
};
const cardChartOpts4 = {
// tooltips: {
// enabled: false,
// custom: CustomTooltips
// },
maintainAspectRatio: false,
legend: {
display: false,
},
scales: {
xAxes: [
{
display: false,
barPercentage: 0.6,
},
],
yAxes: [
{
display: false,
},
],
},
};
class Dashboard extends Component {
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.onRadioBtnClick = this.onRadioBtnClick.bind(this);
this.state = {
dropdownOpen: false,
radioSelected: 2,
data: [],
};
}
componentDidMount() {
let decodedToken = jwt_decode(token);
let url = "detail/dashboard";
axios
.get(`${API_SERVER}/${url}`, {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((result) => {
this.setState({ data: result.data.data });
})
.catch((error) => console.log(error));
}
toggle() {
this.setState({
dropdownOpen: !this.state.dropdownOpen,
});
}
onRadioBtnClick(radioSelected) {
this.setState({
radioSelected: radioSelected,
});
}
loading = () => (
<div className="animated fadeIn pt-1 text-center">Loading...</div>
);
render() {
let decodedToken = jwt_decode(token);
return (
<div className="animated fadeIn">
{this.settoken}
<Row>
<Col xs="12" sm="6" lg="3">
<Card className="text-white bg-info">
<CardBody className="pb-0">
<div className="text-value">{this.state.data.produk}</div>
<div>Jumlah Data Produk</div>
</CardBody>
<div className="chart-wrapper mx-3" style={{ height: "70px" }}>
<Line
data={cardChartData2}
options={cardChartOpts2}
height={70}
/>
</div>
</Card>
</Col>
<Col xs="12" sm="6" lg="3">
<Card className="text-white bg-primary">
<CardBody className="pb-0">
<div className="text-value">{this.state.data.penjualan}</div>
<div>Jumlah Data Penjualann</div>
</CardBody>
<div className="chart-wrapper mx-3" style={{ height: "70px" }}>
<Line
data={cardChartData1}
options={cardChartOpts1}
height={70}
/>
</div>
</Card>
</Col>
<Col xs="12" sm="6" lg="3">
<Card className="text-white bg-warning">
<CardBody className="pb-0">
<div className="text-value">{this.state.data.role}</div>
<div>Jumlah Role</div>
</CardBody>
<div className="chart-wrapper" style={{ height: "70px" }}>
<Line
data={cardChartData3}
options={cardChartOpts3}
height={70}
/>
</div>
</Card>
</Col>
<Col xs="12" sm="6" lg="3">
<Card className="text-white bg-danger">
<CardBody className="pb-0">
<div className="text-value">{this.state.data.akun}</div>
<div>Jumlah Akun</div>
</CardBody>
<div className="chart-wrapper mx-3" style={{ height: "70px" }}>
<Bar
data={cardChartData4}
options={cardChartOpts4}
height={70}
/>
</div>
</Card>
</Col>
</Row>
</div>
);
}
}
export default Dashboard;
|
import React from 'react/addons';
import ReactContext from 'react/lib/ReactContext';
const TestUtils = React.addons.TestUtils;
/**
* Wraps a React shallow renderer instance that can set a context.
*/
export default class Renderer {
/**
* Creates a new `Renderer`
*/
constructor() {
this.renderer = TestUtils.createRenderer();
}
/**
* Renders the `Component` into the shallow renderer instance.
*
* @param {ReactComponent} Component the component to render
* @param {Object} [context={}] the context to render the component into
* @param {Object} [props={}] the props to pass into the component
* @return {ReactComponent} the rendered tree
*/
render(Component, context = {}, props = {}) {
ReactContext.current = context;
this.renderer.render(<Component {...props} />, context);
ReactContext.current = {};
return this.renderer.getRenderOutput();
}
}
|
var express = require('express');
var router = express.Router();
let passport = require('passport');
let passportJWT = require('passport-jwt');
let extractJWT = passportJWT.ExtractJwt;
let strategyJWT = passportJWT.Strategy;
passport.use(
new strategyJWT(
{
jwtFromRequest: extractJWT.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET
},
(payload, next)=>{
var user = payload;
return next(null, user);
}
)
)
const jwtAuthMiddleware = passport.authenticate('jwt', {session:false});
const securityRoutes = require('./api/seguridad');
const productosRoutes = require('./api/productosdb');
router.get('/version',(req, res)=>{
let versionObj = {
app:"tienda-virtual",
version: "0.0.1",
state: "alpha"
}
res.status(200).json(versionObj);
});
//-------//
router.use('/security', securityRoutes);
router.use('/productos', jwtAuthMiddleware, productosRoutes);
module.exports = router; |
import React from 'react';
import { Link } from 'react-router-dom';
import Track from '../track/track';
import PlaylistIndex from './playlist_index';
import './playlist.scss';
class Playlist extends React.Component {
constructor(props) {
super(props)
// this.handleClick = this.handleClick.bind(this);
}
// handleClick() {
// const playlistId = this.props.playlist.id;
// this.props.history.push(`/playlists/${playlistId}`);
// }
render() {
const { playlist } = this.props;
if (!playlist) return null;
// var source = `https://open.spotify.com/embed/playlist/${playlist.spotifyId}`;
if (playlist.title === 'Happy')
var imgSrc = "https://mosaic.scdn.co/640/ab67616d0000b27304bfd5a5fd5aa6ca648f66aaab67616d0000b2733138f891f3075c9c5d944037ab67616d0000b27382c80d6ec5b001d9ae49564dab67616d0000b2738e26bf4293c9da7a6439607b";
else if (playlist.title === 'Chill')
var imgSrc = "https://mosaic.scdn.co/640/24ed37770972eb75f697dcc6af3e3820ee2413e8ab67616d0000b27335f1ecb5dd00dfee10900806ab67616d0000b2734ff02465293ecbc4fcbe0bbaab67616d0000b2739aafa820f8f3e52cbebd18c0";
else if (playlist.title === 'Sad')
var imgSrc = "https://mosaic.scdn.co/640/ab67616d0000b27334d4dd05ab32165c37775f09ab67616d0000b2737aede4855f6d0d738012e2e5ab67616d0000b273c5649add07ed3720be9d5526ab67616d0000b273f5d8fc1c5ffe3044d1f0a72e";
else if (playlist.title === 'Angry')
var imgSrc = "https://mosaic.scdn.co/640/ab67616d0000b27327c8e79e48a7b9b7c9ed6ba0ab67616d0000b2739203fd1f5c23f0ad92ce63faab67616d0000b273b12877d8bdfaa0f19b4624faab67616d0000b273dcbd25c605dddb32022cecba";
else if (playlist.title === 'In Love')
var imgSrc = "https://mosaic.scdn.co/640/ab67616d0000b273391ba47a00139cfab4c4d716ab67616d0000b27367ba7772d52aa06acc78e62dab67616d0000b273bb3df70b7531c9a5fb5d9974ab67616d0000b273f641512591d1a58c3b1543f8";
return(
<li className="playlist-item" >
<Link to={`/playlists/${playlist._id}`} style={{ textDecoration: 'none' }}>
{/* check HOW TO REFERENCE mongo ids */}
<h2>{playlist.title}</h2>
<ul className="playlist-body">
{/* {playlist.songs.map(song =>
<li>
<Track key={song.id} track={song}/>
</li>
)} */}
<img src={imgSrc} className="playlist-image" />
</ul>
</Link>
</li>
)
}
}
export default Playlist; |
var pageSize = 25;
//申請處理狀態
var reqStatusStore = Ext.create('Ext.data.Store', {
fields: ['text', 'value'],
data: [
{ "text": '全部', "value": "0" },
{ "text": '申請中', "value": "1" },
{ "text": '已完成', "value": "2" },
{ "text": '不更動', "value": "3" }
]
});
//申請類型
var reqTypeStore = Ext.create('Ext.data.Store', {
fields: ['text', 'value'],
data: [
{ "text": '全部', "value": "0" },
{ "text": '申請上架', "value": "1" },
{ "text": '申請下架', "value": "2" }
]
});
//品牌store
var brandStore = Ext.create('Ext.data.Store', {
model: 'gigade.Brand',
autoLoad: true,
proxy: {
type: 'ajax',
url: "/Brand/QueryBrand",
noCache: false,
getMethod: function () { return 'get'; },
actionMethods: 'post',
reader: {
type: 'json',
root: 'item'
}
}
});
var apply_Accdi = Ext.create('Ext.form.FieldContainer', {
layout: 'hbox',
anchor: '100%',
items: [
{
xtype: 'combobox',
fieldLabel: BRAND,
store: brandStore,
id: 'brand_id',
colName: 'brand_id',
name: 'brand_id',
displayField: 'brand_name',
typeAhead: true,
queryMode: 'local',
valueField: 'brand_id'
}, {
xtype: 'textfield',
fieldLabel: '商品編號',
id: 'productid',
colName: 'productid',
margin: '0 20px',
//hidden: true,
submitValue: false,
name: 'productid'
},
{
xtype: 'combobox',
id: 'reqstatus',
margin: '0 20px',
fieldLabel: '申請處理狀態',
colName: 'reqstatus',
queryMode: 'local',
editable: false,
store: reqStatusStore,
displayField: 'text',
valueField: 'value',
value: 1
}
]
});
var reqTime = {
xtype: 'fieldcontainer',
layout: 'hbox',
anchor: '100%',
items: [
{
xtype: 'combobox',
id: 'reqtype',
margin: '0 5px 0 0',
fieldLabel: '申請類型',
colName: 'reqtype',
queryMode: 'local',
editable: false,
store: reqTypeStore,
displayField: 'text',
valueField: 'value'
},
{
xtype: 'datetimefield',
format: 'Y/m/d H:i:s',
time: { hour: 00, min: 00, sec: 00 },
id: 'time_start',
name: 'time_start',
fieldLabel: '申請時間',
margin: '0 5px 0 15px',
width: 245,
editable: false,
listeners: {//change by shiwei0620j 20151217,將時間控件改為可以選擇時分秒,開始時間時分秒默認為00:00:00,結束時間時分秒默認為23:59:59,當選擇的開始時間大於結束時間,結束時間在開始時間月份加1,當選擇的結束時間大於開始時間,開始時間在結束時間月份加1;
select: function (a, b, c) {
var start = Ext.getCmp("time_start");
var end = Ext.getCmp("time_end");
var start_date = start.getValue();
if (end.getValue() == ""||end.getValue() == null) {
Ext.getCmp('time_end').setValue(new Date(start_date.getFullYear(), start_date.getMonth() + 1, start_date.getDate(), 23, 59, 59));
}
else if (end.getValue() < start.getValue()) {
Ext.getCmp('time_end').setValue(new Date(start_date.getFullYear(), start_date.getMonth() + 1, start_date.getDate(), 23, 59, 59));
}
}
}
//vtype: 'daterange',
//endDateField: 'time_end'
}, {
xtype: 'displayfield',
value: '~'
}, {
xtype: 'datetimefield',
format: 'Y/m/d H:i:s',
time: { hour: 23, min: 59, sec: 59 },
id: 'time_end',
name: 'time_end',
width: 140,
margin: '0 5px',
editable: false,
listeners: {
select: function (a, b, c) {
var start = Ext.getCmp("time_start");
var end = Ext.getCmp("time_end");
var end_date = end.getValue();
if (start.getValue() == ""||start.getValue() ==null) {
Ext.getCmp('time_start').setValue(new Date(end_date.getFullYear(), end_date.getMonth() - 1, end_date.getDate()));
}
if (end.getValue() < start.getValue()) {
Ext.getCmp('time_start').setValue(new Date(end_date.getFullYear(), end_date.getMonth() - 1, end_date.getDate()));
}
}
},
//vtype: 'daterange',
//startDateField: 'time_start'
}
]
};
//供應商上下架申請model
Ext.define('GIGADE.ProdVdReqModel', {
extend: 'Ext.data.Model',
fields: [
{ name: 'rid', type: 'int' },
{ name: 'vendor_id', type: 'int' },
{ name: 'vendor_name', type: 'string' },
{ name: 'brand_id', type: 'int' },
{ name: 'brand_name', type: 'string' },
{ name: 'product_id', type: 'int' },
{ name: 'product_status', type: 'int' },
{ name: 'statusName', type: 'string' },
{ name: 'req_status', type: 'int' },
{ name: 'req_datatime', type: 'string' },
{ name: 'explain', type: 'string' },
{ name: 'req_type', type: 'int' },
{ name: 'user_id', type: 'int' },
{ name: 'reply_datetime', type: 'string' },
{ name: 'reply_note', type: 'string' }
]
});
var prodVdReqListStore = Ext.create("Ext.data.Store", {
model: 'GIGADE.ProdVdReqModel',
autoLoad: false,
proxy: {
type: 'ajax',
url: '/ProductVendorList/ProdVdReqListQuery',
actionMethods: 'post',
reader: {
type: 'json',
root: 'data',
totalProperty: 'totalCount'
}
}
});
prodVdReqListStore.on("beforeload", function () {
Ext.apply(prodVdReqListStore.proxy.extraParams,
{
brand_id: Ext.htmlEncode(Ext.getCmp("brand_id").getValue()),
product_id: Ext.htmlEncode(Ext.getCmp('productid').getValue()),
req_status: Ext.getCmp('reqstatus').getValue(),
time_start: Ext.getCmp("time_start").getValue(),
time_end: Ext.getCmp("time_end").getValue(),
req_type: Ext.getCmp("reqtype").getValue()
});
});
Ext.onReady(function () {
var query = function () {
prodVdReqListStore.loadPage(1);
}
document.body.onkeydown = function () {
if (event.keyCode == 13) {
$("#btnSearch").click();
}
};
function searchShow() {
Ext.getCmp('prodVdReqGrid').show();
query();
}
var frm = Ext.create('Ext.form.Panel', {
layout: 'column',
border: false,
width: 1185,
margin: '0 0 10 0',
defaults: { anchor: '95%', msgTarget: "side", padding: '5 5' },
items: [{
xtype: 'panel',
columnWidth: 1,
border: 0,
layout: 'anchor',
items: [apply_Accdi, reqTime]
}],
buttonAlign: 'center',
buttons: [{
text: SEARCH,
id: 'btnSearch',
colName: 'btnSearch',
iconCls: 'ui-icon ui-icon-search-2',
handler: function () {
Ext.getCmp('prodVdReqGrid').show();
query();
}
}, {
text: RESET,
id: 'btn_reset',
iconCls: 'ui-icon ui-icon-reset',
listeners: {
click: function () {
frm.getForm().reset();
Ext.getCmp("reqstatus").setValue(1);
Ext.getCmp("reqtype").reset();
}
}
}]
});
//列选择模式
var sm = Ext.create('Ext.selection.CheckboxModel', {
listeners: {
selectionchange: function (sm, selections) {
var rows = Ext.getCmp('prodVdReqGrid').getSelectionModel().getSelection();
if (selections.length > 0) {
Ext.Array.each(selections, function (rows) {
if (rows.data.req_status == 1) {
Ext.getCmp("prodVdReqGrid").down('#btnPass').setDisabled(false);
Ext.getCmp("prodVdReqGrid").down('#btnBack').setDisabled(false);
}
})
} else {
Ext.getCmp("prodVdReqGrid").down('#btnPass').setDisabled(true);
Ext.getCmp("prodVdReqGrid").down('#btnBack').setDisabled(true);
}
}
}
});
var grid = Ext.create("Ext.grid.Panel", {
id: 'prodVdReqGrid',
selModel: sm,
height: document.documentElement.clientWidth <= 1185 ? document.documentElement.clientHeight - 103 - 20 : document.documentElement.clientHeight - 103,
columnLines: true,
store: prodVdReqListStore,
columns: [
{ header: 'rid', colName: 'rid', hidden: true, dataIndex: 'rid', width: 120, align: 'left' },
{ header: '申請供應商ID', colName: 'vendor_id', hidden: true, dataIndex: 'vendor_id', width: 120, align: 'left' },
{ header: '供應商', colName: 'vendor_name', hidden: true, dataIndex: 'vendor_name', width: 120, align: 'left' },
{ header: '品牌', colName: 'brand_id', hidden: true, dataIndex: 'brand_id', width: 120, align: 'left' },
{ header: '品牌名稱', colName: 'brand_name', hidden: true, dataIndex: 'brand_name', width: 120, align: 'left' },
{ header: '申請之商品編號', colName: 'product_id', hidden: true, xtype: 'templatecolumn',
tpl: Ext.create('Ext.XTemplate',
'<tpl if="this.canCopy(product_id)">',
'<a href="javascript:ProductLink({product_id})">{product_id}</a>',
'</tpl>',
{
canCopy: function (product_id) {
return product_id >= 10000;
}
}), width: 120, align: 'center', sortable: false, menuDisabled: true
},
// { header: '申請之商品編號', colName: 'product_id', hidden: false, xtype: 'templatecolumn', tpl: '<a href=# onclick="javascript:showDetail({product_id})" >{product_id}</a>', width: 120, align: 'center', sortable: false, menuDisabled: true },
// {
// header: PREVIEW_PRODUCT, colName: 'preview_product', hidden: false, xtype: 'templatecolumn',
// tpl: '<a href=javascript:ProductPreview(0,{product_id})>' + PREVIEW_PRODUCT + '</a>', //0為商品預覽 调用自己写的方法 ProductPreview()
// width: 60, align: 'center', sortable: false, menuDisabled: true
// },
{header: '商品目前狀態', colName: 'product_status', hidden: true, dataIndex: 'product_status', width: 120, align: 'left' },
{ header: '商品目前狀態', colName: 'statusName', hidden: true, dataIndex: 'statusName', width: 120, align: 'left' },
{ header: '申請處理狀態', colName: 'req_status', hidden: true, dataIndex: 'req_status', width: 120, align: 'left', renderer: ReqStatus
},
{ header: '申請時間', colName: 'req_datatime', hidden: true, dataIndex: 'req_datatime', width: 120, align: 'left' },
{ header: '申請說明', colName: 'explain', hidden: true, dataIndex: 'explain', width: 120, align: 'left' },
{ header: '申請類型', colName: 'req_type', hidden: true, dataIndex: 'req_type', width: 120, align: 'left', renderer: ReqType },
{ header: '處理之管理人員ID', colName: 'user_id', hidden: true, dataIndex: 'user_id', width: 120, align: 'left',
renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) {
if (record.data.user_id != 0) {
return value;
} else {
return null;
}
}
},
{ header: '處理完成時間', colName: 'reply_datetime', hidden: true, dataIndex: 'reply_datetime', width: 120, align: 'left',
renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) {
if (record.data.reply_datetime == '0001-01-01 00:00:00') {
return null;
} else {
return value;
}
}
},
{ header: '處理說明', colName: 'reply_note', hidden: true, dataIndex: 'reply_note', width: 120, align: 'left' }
],
listeners: {
viewready: function (grid) {
ToolAuthorityQuery(function () {
setShow(grid, 'colName');
});
}
},
tbar: [
{
text: VERIFY_PASS,
id: 'btnPass',
colName: 'btnPass',
hidden: false,
disabled: true,
iconCls: 'icon-accept',
handler: btnPassOnClick
}, {
text: VERIFY_BACK,
colName: 'btnBack',
disabled: true,
hidden: false,
id: 'btnBack',
icon: '../../../Content/img/icons/drop-no.gif',
handler: btnBackOnClick
}
, '->', { text: '' }
],
bbar: Ext.create('Ext.PagingToolbar', {
store: prodVdReqListStore,
pageSize: pageSize,
displayInfo: true,
displayMsg: NOW_DISPLAY_RECORD + ': {0} - {1}' + TOTAL + ': {2}',
emptyMsg: NOTHING_DISPLAY
}
)
});
Ext.EventManager.onWindowResize(function () { grid.getView().refresh(); });
Ext.create('Ext.Viewport', {
layout: 'anchor',
items: [frm, grid],
renderTo: Ext.getBody(),
autoScroll: true,
listeners: {
resize: function () {
if (document.documentElement.clientWidth <= 1185) {
Ext.getCmp('prodVdReqGrid').setHeight(document.documentElement.clientHeight - 103 - 20);
Ext.getCmp('prodVdReqGrid').setWidth(document.documentElement.clientWidth);
}
else {
Ext.getCmp('prodVdReqGrid').setHeight(document.documentElement.clientHeight - 103);
Ext.getCmp('prodVdReqGrid').setWidth(document.documentElement.clientWidth);
}
this.doLayout();
},
afterrender: function (view) {
ToolAuthorityQuery(function () {
//alert("权限");
setShow(frm, 'colName');
window.setTimeout(searchShow, 1);
});
}
}
});
prodVdReqListStore.loadPage(1);
});
function ReqStatus(val) {
switch (val) {
case 1:
return '申請中';
break;
case 2:
return '已完成';
break;
case 3:
return '不更動';
break;
}
}
function ReqType(val) {
switch (val) {
case 1:
return '申請上架';
break;
case 2:
return '申請下架';
break;
}
}
function ProductLink(product_id) {
var url;
url = '/ProductList?product_id=' + product_id;
var panel = window.parent.parent.Ext.getCmp('ContentPanel');
var vendorProduct = panel.down('#308');
if (vendorProduct) {
vendorProduct.close();
}
vendorProduct = panel.add({
id: '308',
title: '商品列表',
html: window.top.rtnFrame(url),
closable: true
});
panel.setActiveTab(vendorProduct);
panel.doLayout();
//window.location.href = 'http://' + window.location.host + url;
}
var back = function (row, reason, functionid) {
var result = '';
for (var i = 0, j = row.length; i < j; i++) {
if (i > 0) {
result += ';';
}
result += row[i].data.rid + "," + row[i].data.product_id;
}
Ext.Ajax.request({
url: '/ProductVendorList/ProdVdReqBack',
params: {
rIdAndProdId: result,
backReason: reason
},
success: function (response) {
var result = Ext.decode(response.responseText);
if (result.success) {
Ext.Msg.alert(INFORMATION, SUCCESS, function () {
prodVdReqListStore.loadPage(1);
});
}
else {
Ext.Msg.alert(INFORMATION, FAILURE);
}
}
});
}
//核可
var btnPassOnClick = function () {
var rows = Ext.getCmp("prodVdReqGrid").getSelectionModel().getSelection();
if (rows.length == 0) {
Ext.Msg.alert(INFORMATION, NO_SELECTION);
return false;
}
var result = '';
for (var i = 0, j = rows.length; i < j; i++) {
if (i > 0) {
result += ';';
}
result += rows[i].data.rid + "," + rows[i].data.product_id;
}
Ext.Ajax.request({
url: '/ProductVendorList/ProdVdReqPass',
params: {
rIdAndProdId: result
},
success: function (response) {
var result = Ext.decode(response.responseText);
if (result.success) {
Ext.Msg.alert(INFORMATION, SUCCESS);
prodVdReqListStore.loadPage(1);
}
else {
Ext.Msg.alert(INFORMATION, result.msg);
}
}
});
}
//駁回
var btnBackOnClick = function () {
var row = Ext.getCmp("prodVdReqGrid").getSelectionModel().getSelection();
if (row.length == 0) {
Ext.Msg.alert(INFORMATION, NO_SELECTION);
return false;
}
Ext.MessageBox.show({
title: BACK_REASON,
id: 'txtReason',
msg: INPUT_BACK_REASON,
width: 300,
buttons: Ext.MessageBox.OKCANCEL,
multiline: true,
fn: function (btn, text) {
if (btn == "cancel") {
return false;
}
back(row, text, 'btnBack');
},
animateTarget: 'btnBack'
});
}
////預覽信息(商品)
////没有什么逻辑的地方
////基本都为Ext的创建方法
//function ProductPreview(type, product_id) {
// Ext.Ajax.request({
// url: '/ProductVendorList/ProductPreview',
// params: { Product_Id: product_id, Type: type },
// success: function (form, action) {
// var result = form.responseText;
// var htmlval = "<a href=" + result + " target='new'>" + result + "</a>";
// Ext.create('Ext.window.Window', {
// title: PREVIEW_PRODUCT,
// modal: true,
// height: 110,
// width: 600,
// constrain: true,
// layout: 'fit',
// items: [{
// xtype: 'panel',
// border: false,
// layout: 'hbox',
// autoScroll: true,
// bodyStyle: {
// padding: '20px 10px'
// },
// items: [{
// xtype: 'displayfield',
// labelWidth: 55,
// labelAlign: 'top',
// fieldLabel: PREVIEW_PRODUCT,
// value: htmlval
// }]
// }]
// }).show();
// }
// })
//}
|
import { Button } from 'antd';
import React from 'react';
import UploadEpisode from '../../common/UploadEpisode';
function UploadStoryPopup(props) {
return props.trigger ? (
<div className="popup">
<div className="popup-inner">
<Button
className="close-button"
onClick={() => props.setTrigger(false)}
danger
>
Close
</Button>
<UploadEpisode />
</div>
</div>
) : (
''
);
}
export default UploadStoryPopup;
|
//封装了笔记本的操作
$(function () {
//1.加载用户笔记本
loadUserBooks();
//6.弹出"创建笔记本"对话框dialog模态框
$("#add_notebook").click(alertAddBookWindow);
//7.给新建笔记本的创建按钮绑定单击事件
$("#can").on("click", "#sure_addbook", addBook);
//10.给笔记本列表添加双击事件
$("#book_ul").on("dblclick", "li", alertRenameBookWindow);
//11.给新建笔记按钮添加单击事件
$("#can").on("click", "#sure_renameBook", renameBook);
});
//加载用户笔记本列表
function loadUserBooks() {
//1.获取请求参数
var userId = getCookie("uid");
//2.参数格式校验
if (userId == null) {
window.location.href = "log_in.html";
} else {
//3.发送Ajax
$.ajax({
url: base_path + "/book/loadbooks.do",
type: "post",
data: {"userId": userId},
dataType: "json",
success: function (result) {
//回调处理
//获取返回的笔记本集合
var books = result.data;
//循环生成列表元素
for (var i = 0; i < books.length; i++) {
//获取笔记本id
var bookId = books[i].cn_notebook_id;
//获取笔记名称
var bookName = books[i].cn_notebook_name;
//创建笔记本列表li
createBookLi(bookId, bookName);
}
},
error: function () {
alert("查询笔记本异常")
}
});
}
}
//创建笔记本li元素
function createBookLi(bookId, bookName) {
/*<li class="online">
<a class='checked'>
<i class="fa fa-book" title="online" rel="tooltip-bottom">
</i> 默认笔记本</a></li>*/
//构建列表li元素
var sli =
'<li class="online">' +
' <a>' +
' <i class="fa fa-book" title="online" rel="tooltip-bottom"></i>' +
bookName +
' </a>' +
'</li>';
//将JS对象转换成JQuery对象
var $li = $(sli);
//将bookId绑定到li元素上
$li.data("bookId", bookId);
//将li元素添加到ul列表中
$("#book_ul").append($li);
}
//创建笔记本
function addBook() {
var userId = getCookie("uid");
if (userId == null) {
window.location.href = "log_in.html";
return;
}
var bookName = $("#input_notebook").val().trim();
if (bookName == "") {
$("#notebook_span").html("笔记本名字不能为空");
return;
}
$.ajax({
url: base_path + "/book/add.do",
type: "post",
data: {"bookName": bookName, "userId": userId},
dataType: "json",
success: function (result) {
if (result.status == 0) {
//关闭新建笔记本对话框
closeAlertWindow();
var bookId = result.data;
createBookLi(bookId, bookName);
alert(result.msg);
} else {
alert(result.msg)
}
},
error: function () {
alert("创建笔记本异常")
}
});
}
//笔记本重命名
function renameBook() {
//获取用户id
var userId = getCookie("uid");
//判断是否登录过时
if (userId == null) {
window.location.href = "log_in.html";
return;
}
//获取笔记本id
var $li = $("#book_ul a.checked").parent();
var bookId = $li.data("bookId");
//判断是否选择了笔记本
if (bookId == null) {
alert("请选择笔记本");
return;
}
//获取输入的笔记本名称
var bookName = $("#input_notebook_rename").val().trim();
//判断输入的名称如果为空
if (bookName == "") {
//提示输入为空
$("#rename_span").html("笔记本名称为空");
return;
}
//发送Ajax
$.ajax({
url: base_path + "/book/update.do",
type: "post",
data: {"bookId": bookId, "bookName": bookName},
dataType: "json",
success: function (result) {
if (result.status == 0) {
var li = '<i class="fa fa-book" title="online" rel="tooltip-bottom"></i>' + bookName;
$li.find("a").html(li);
alert(result.msg);
} else {
alert(result.msg);
}
},
error: function () {
alert("笔记本重命名异常")
}
});
} |
import firebase from 'firebase'
// Initialize Firebase
let config = {
// ADD CONFIG FILE FROM FIREBASE
};
firebase.initializeApp(config);
export function googleLogin(){
let provider = new firebase.auth.GoogleAuthProvider()
return firebase.auth().signInWithPopup(provider)
.then(snap=>snap.user)
.catch(e=>console.log(e))
}
// export function googleLogout(){
// return firebase.auth().signOut()
// }
export default firebase
|
// 定义一些基本的文件配置
module.exports = {
common: ["jquery"] // 配置不会变的第三方库
}; |
/**
* Initialize jquery.dtag_tooltip
*/
//Add qTip dependency, don't compile into plugin itself
//define(['jquery', 'libs/jquery/jquery.qtip.min', 'libs/jquery.dtag_tooltip'], function ($) {
define('components/tooltip', ['jquery', 'libs/jquery/jquery.qtip.min', 'libs/jquery/jquery.dtag_tooltip'], function ($) {
$(function () {
$.dtag_tooltip({
container_classes: 'DTExperience',
tooltip_classes: 'dtag-tooltip-style'
});
});
}); |
$(function() {
var on = true;
for(var i = 0 ; i < 8 ; i++) {
$(".nav-nav li").eq(i).mouseenter(function () {
$(this).find("em").stop().animate({
top : "24px"
},200);
$(this).find("span").stop().animate({
bottom : "24px"
},200);
var index = $(this).index() - 1;
if(index >= 4) {
$(this).find(".hide-nav").css("left", -index * 137 - 241).stop().slideDown(200);
} else {
$(this).find(".hide-nav").css("left", -index * 137).stop().slideDown(200);
}
if( on ) {
$(".logo").addClass("width116");
on = false;
}
}).mouseleave(function() {
$(this).find("em").stop().animate({
top : "0"
},200);
$(this).find("span").stop().animate({
bottom : "0"
},200);
$(this).find(".hide-nav").stop().slideUp(200);
})
}
$(".logo").mouseenter(function () {
if(!on) {
$(this).removeClass("width116");
on = true;
}
})
$(window).on("scroll",function () {
var scrollY = window.pageYOffset;
if(scrollY > 110) {
$(".top-nav").addClass("fixed");
// $(".logo").children("img").attr("src", "images/logo2.png");
if( on ) {
$(".logo").addClass("width116");
}
}
if(scrollY < 110) {
$(".top-nav").removeClass("fixed");
// $(".logo").children("img").attr("src", "images/logo-sanjiao.png").removeClass("width116");
if( on ) {
$(".logo").removeClass("width116");
}
}
});
//获取验证码
$("button").click(function(){
$(this).prop('disabled',true);
$(this).text("30秒后再次发送");
var that = $(this);
var index = 30;
var timeId = setInterval(function(){
index--;
$(that).text(index+"秒后再次发送");
if (index==0) {
clearInterval(timeId)
$(that).text("获取验证码")
}
},1000)
});
//手机号码不正确 无法登陆
var Val={
isMobile:function(s){return this.test(s,/(^0{0,1}1[3|4|5|6|7|8|9][0-9]{9}$)/)},
isEmail:function(a){var b ="^[-!#$%&'*+\\./0-9=?A-Z^_`a-z{|}~]+@[-!#$%&'*+\\/0-9=?A-Z^_`a-z{|}~]+.[-!#$%&'*+\\./0-9=?A-Z^_`a-z{|}~]+$";
return this.test(a, b);},
isNumber:function(s,d){return !isNaN(s.nodeType==1?s.value:s)&&(!d||!this.test(s,"^-?[0-9]*\\.[0-9]*$"))},
isEmpty:function(s){return !jQuery.isEmptyObject(s)},test:function(s,p){s=s.nodeType==1?s.value:s;return new RegExp(p).test(s)}};
//上面给你一个常用的验证代码,比较使用
$(".in_for .user").blur(function(){
var v=$(this).val();
var n=$(this).next();
if(!Val.isMobile(v)){
n.html("<font color='red'>请输入正确的手机号码</font>");
$
}else{
// n.css("display","block")
n.text("正确");
n.css("color","green")
}
});
}) |
const clog = require('columnify');
const exec = require('child_process').exec;
const t = require('./tool');
const dapi = require('./douyu-api');
const KeyPress = require('./keypress');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const VIDEO_URL_BASE = 'http://www.douyu.com/';
const PLAY_CMD = 'mpv -vo=opengl';
const kp = new KeyPress();
let offset = 0;
const LIMIT = 30;
let choices = [];
class Viewer {
static room() {
dapi.list(null, offset, LIMIT, (list) => {
offset += LIMIT;
list.forEach((room, i) => {
const roomStr = { 序号: i, 房间名: room.room_name, 主播名: room.nickname, id: room.room_id };
choices.push(roomStr);
});
console.log('\n\n');
console.log(clog(choices));
rl.question('输入房间号回车观看直播, n键下一页, p键上一页, q键推出\n房间号: ', Viewer.exec);
});
}
static nextPage() {
choices = [];
rl.clearLine();
Viewer.room();
}
static prevPage() {
choices = [];
rl.clearLine();
offset -= LIMIT;
Viewer.room();
}
static bindKey() {
kp.bind('n', 0, 0, Viewer.nextPage);
kp.bind('p', 0, 0, Viewer.prevPage);
kp.bind('q', 0, 0, () => process.stdin.destroy());
}
static exec(answer) {
if (choices[answer]) {
const roomId = choices[answer].id;
exec(`mpv -vo=opengl ${VIDEO_URL_BASE}${roomId}`);
rl.close();
}
}
}
module.exports = Viewer;
Viewer.bindKey();
Viewer.room();
|
function initCarousel() {
let carousel = document.querySelector('.carousel__inner');
let slideWidth = carousel.offsetWidth;
let arrowRight = document.querySelector('.carousel__arrow_right');
let arrowLeft = document.querySelector('.carousel__arrow_left');
let count = 0;
arrowLeft.style.display = 'none';
function moveRight() {
count += slideWidth;
if (count > slideWidth && count < `${slideWidth * 3}`) {
arrowLeft.style.display = '';
arrowRight.style.display = '';
} else if (count >= `${slideWidth * 3}`) {
arrowRight.style.display = 'none';
} else {
arrowLeft.style.display = 'none';
}
carousel.style.transform = `translateX(-${count}px)`;
}
function moveLeft() {
count -= slideWidth;
if (count > slideWidth && count < `${slideWidth * 3}`) {
arrowLeft.style.display = '';
arrowRight.style.display = '';
} else if (count >= `${slideWidth * 3}`) {
arrowRight.style.display = 'none';
} else {
arrowLeft.style.display = 'none';
}
carousel.style.transform = `translateX(-${count}px)`;
}
arrowRight.addEventListener('click', moveRight);
arrowLeft.addEventListener('click', moveLeft);
}
|
(function () {
'use strict';
/* @ngdoc object
* @name teenVideos
* @description
*
*/
angular
.module('teenVideos', [
'ui.router'
]);
}());
|
function download(videoId) {
action("/link/download", videoId);
}
function remove(videoId) {
action("/link/remove", videoId)
.then(res => {
if (!res) return;
window.location.reload();
});
}
function saveFormat() {
const formatSelect = document.getElementById('formatSelect');
const value = formatSelect.value;
const opt = {
timeOut: 1000
};
fetch('/format/select', {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
format: value
})
})
.then(res => res.json())
.then(res => {
let msg = res.msg.replace(/\n/g, '<br/>');
if (res.code === 200)
toastr.success(msg, "Success", opt);
else
toastr.error(msg, "Error", opt);
});
}
function action(url, videoId) {
return new Promise(resolve => {
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
videoId: videoId
})
})
.then(res => res.json())
.then(res => resolve(res.code === 200));
});
} |
const { error } = require('./log');
const argv = process.argv.slice(2) || [];
let pages = [];
try {
const str = argv.filter(p => p.indexOf('entries') > -1)[0];
pages = str ? str.split('=')[1].split(',') : [];
} catch (e) {
error(e);
pages = [];
}
module.exports = {
pages,
dirName: `${pages[0]}-static`
};
|
'use strict';
angular.module('ngHugeApp._common', [
'ngHugeApp._common.directives'
]);
|
import angular from 'angular';
import {Observable} from 'rxjs/Observable.js';
import 'rxjs/add/operator/map.js';
import 'rxjs/add/operator/distinctUntilChanged.js';
import 'rxjs/add/operator/share.js';
import 'rxjs/add/operator/filter.js'
import 'rxjs/add/operator/switch.js'
const module = angular.module('rxReduxState', []);
export default module;
export const {directive, constant, config} = module;
constant('$parseRxExpression', (exp) => {
const [obsPart, ...ngExpression] = exp.split(': ');
const [, obsName, asName] = obsPart.trim().match(/^([\s\S]+) as (\w+)$/);
return [
obsName.trim(),
asName ? asName.trim() : 'value',
ngExpression.join(': ').trim()
]
})
constant('$createRxExpression', ([obsName, asName, ngExpression]) => {
return `${obsName} as ${asName}: ${ngExpression}`;
})
config(['$provide', ($provide) => {
$provide.decorator('$rootScope', ['$delegate', '$parse', '$parseRxExpression',
($delegate, $parse, $parseRxExpression) => {
Object.assign($delegate.constructor.prototype, {
$$rxWatch,
$rxWatch(ngExpression, objectEquality) {
return this.$$rxWatch(ngExpression, objectEquality).share();
},
$$rxWatchObservable,
$rxWatchObservable(ngExpression) {
return this.$$rxWatchObservable(ngExpression).share();
},
$$rxWatchRxExpression,
$rxWatchRxExpression(rxExpression) {
return this.$$rxWatchRxExpression(rxExpression).share();
}
});
return $delegate;
function $$safeApply(fn, ...args) {
if (this.$$phase || this.$root.$$phase) {
fn(...args);
} else {
this.$apply(() => { fn(...args) });
}
}
function $$rxWatch(ngExpression, objectEquality) {
return Observable.create((observer) => {
return this.$watch(ngExpression, observer.next.bind(observer));
})
}
function $$rxWatchObservable (ngExpression) {
return Observable.create((observer) => {
const subscription = this
.$$rxWatch(ngExpression)
.filter((value) => value && typeof value.subscribe === 'function')
.switch()
.distinctUntilChanged()
.subscribe(
(val) => { $$safeApply.call(this, observer.next.bind(observer), val) },
(err) => { $$safeApply.call(this, observer.error.bind(observer), err) },
() => { $$safeApply.call(this, observer.complete.bind(observer)) }
)
this.$on('$destroy', subscription.unsubscribe.bind(subscription));
return subscription;
})
}
function $$rxWatchRxExpression(rxExpression) {
const [obsName, asName, ngExpression] = $parseRxExpression(rxExpression);
const parsedNgExp = $parse(ngExpression);
return this
.$$rxWatchObservable(obsName)
.map((value) => parsedNgExp(this, {[asName]: value}))
.distinctUntilChanged()
}
}])
}])
|
import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
function App() {
return <h4>Portfolio Project...</h4>;
}
export default App;
|
// warn when navigating away from a page where the user has entered data into
// certain form fields.
const FIELDS = [
'textarea',
'input:not([type])',
'input[type="text"]',
'input[type="url"]',
'input[type="file"]',
].map(f => '.form ' + f).join(', ');
const widgetsChanged = new Set();
function onBeforeUnload(event) {
if (widgetsChanged.size > 0) {
event.preventDefault();
event.returnValue = "Leave the page? You'll lose your changes.";
return event.returnValue;
}
}
function onChange(event) {
const fieldEl = event.target.closest(FIELDS);
if (!fieldEl) {
return;
}
// todo: need a better way to check nothing was changed
if (fieldEl.value !== '') {
widgetsChanged.add(fieldEl);
} else if (widgetsChanged.has(fieldEl)) {
widgetsChanged.delete(fieldEl);
}
}
function onSubmit(event) {
if (event.target.closest('.form')) {
removeEventListener('beforeunload', onBeforeUnload);
}
}
addEventListener('beforeunload', onBeforeUnload);
addEventListener('change', onChange);
addEventListener('input', onChange);
addEventListener('submit', onSubmit);
|
$(function(){
//Top 100
$.getJSON("top100.php", function(sonuc){
$.each(sonuc, function(i, sonuc){
var veri = "<li><a href='bookpage.php?bId="+sonuc.bookId+"'>"+ sonuc.bookName +"<span class='top-point'><i class='fa fa-star' aria-hidden='true'></i> "+ sonuc.bookPoint + "</span></a></li>";
$("#top100").append(veri);
});
});
//Popüler Kitaplar
$.getJSON("popularbooks.php", function(sonuc){
$.each(sonuc, function(i, sonuc){
var veri = "<li><a href='bookpage.php?bId="+sonuc.bookId+"'>"+ sonuc.bookName +"<span class='top-point'><i class='fa fa-star' aria-hidden='true'></i> "+ sonuc.bookPoint + "</span></a></li>";
$("#popularbooks").append(veri);
});
});
//Son Eklenenler
$.getJSON("lastadded.php", function(sonuc){
$.each(sonuc, function(i, sonuc){
var veri = "<div class='item' id='slider'><div class='row'><div class='col-md-12' style = 'width:100%'><a class='thumbnail' href='bookpage.php?bId="+sonuc.bookId+"'><img alt='' src='" + sonuc.frontcoverphoto + "'><div class='end-book-name'>" + sonuc.bookName + "</div><div class='end-book-author'>" + sonuc.authorName +" "+sonuc.authorSurname +"</div></a></div></div></div>";
$(".carousel-inner").append(veri);
$("#slider:first").addClass("active");
});
});
});
|
// Функция Ajax
var st_process = new Object();
function process(url, ident, before_id, form_id) {
if(st_process[ident] == false) return;
if(form_id == '') form_id = 'undefined';
jQuery.ajax({
url: url,
type: "POST",
dataType: "json",
data: jQuery("#"+form_id).serialize(),
beforeSend: function () {
st_process[ident] = false;
if(before_id) {
$(before_id).addClass('js-process');
}
},
success: function(response) {
$.each(response, function(i, val) {
$('#'+i).html(val);
});
},
error: function(response) {
messager('error', 'Unknown error');
},
complete: function () {
st_process[ident] = true;
if(before_id) {
$(before_id).removeClass('js-process');
}
}
});
}
// launch fancybox
if($('.fancybox').length != 0) {
$(".fancybox").fancybox();
}
// log_view
$('#log__list').on('click', '.log__login', function() {
$('input[name=query]').val($(this).text());
});
$('select[name=per_page]').on('change', function() {
location.href='/admin/log/'+$('select[name=per_page]').val()+'/'+$('input[name=query]').val();
});
// warning_view
$('#warn__list').on('click', '.warn__login', function() {
$('input[name=query]').val($(this).text());
});
$('#warn__list').on('click', '.warn__ip', function() {
$('input[name=query]').val($(this).text());
});
//$('#users__list').on('click', '.users__group', function(){
// process('/admin/users/change_status/'+$(this).attr('data-group')+'/'+$(this).attr('data-id'), 'block');
//});
|
import {baseUrl} from '../util/publicParams'
let platform = "wx";
export default {
timestamp: baseUrl + "sys/" + platform + "/systemTime/1.0",
getopenid: baseUrl + "external/payment/getOpenId",
xkUserGzhLogin: baseUrl + `user/${platform}/xkUserGzhLogin/1.0`,//登录(刘国权)
sendAuthMessage: baseUrl + `sys/${platform}/sendAuthMessage/1.0`,//发送验证短信(闫菘)
xkUserGzhBindPhone: baseUrl + `user/${platform}/xkUserGzhBindPhone/1.0`,//绑定手机号(刘国权)
xkUserGzhBindPhoneByPwd: baseUrl + `user/${platform}/xkUserGzhBindPhoneByPwd/1.0`,//通过密码绑定手机号(刘国权)
xkUserGzhRegister: baseUrl + `user/${platform}/xkUserGzhRegister/1.0`,//注册(刘国权)
xkUserGzhConfig: baseUrl + `user/${platform}/xkUserGzhConfig/1.0`,//获取公众号配置(刘国权)
gameQpage: baseUrl + `goods/${platform}/gameQpage/1.0`,//游戏查询(王琪)
gameDetail: baseUrl + `goods/${platform}/gameDetail/1.0`,//游戏详情(王琪)
gameCategoryList: baseUrl + `goods/${platform}/gameCategoryList/1.0`,//游戏分类列表(王琪)
gameRecommendQpage: baseUrl + `goods/${platform}/gameRecommendQpage/1.0`,//推荐游戏列表(王琪)
gameUpdateRecommend: baseUrl + `goods/${platform}/gameUpdateRecommend/1.0`,//修改游戏推荐人(王琪)
gameQueryJumpUrl: baseUrl + `goods/${platform}/gameQueryJumpUrl/1.0`,//查询游戏跳转url接口(王琪)
gameDetailShare: baseUrl + `goods/${platform}/gameDetailShare/1.0`,//站内游戏详情分享(王琪)
newestQpage: baseUrl + `goods/${platform}/newestQpage/1.0`,//最新游戏(王琪)
gameHotGameQpage: baseUrl + `goods/${platform}/gameHotGameQpage/1.0`,//热门游戏接口(王琪)
uniPayment: baseUrl + `trade/${platform}/uniPayment/1.0`,//统一的收银台发起支付(邓小江)
tradeGameUniorder: baseUrl + `trade/${platform}/tradeGameUniorder/1.0`,//游戏充值下单(邓小江)
xkUserGzhOpenidLogin: baseUrl + `user/${platform}/xkUserGzhOpenidLogin/1.0`,//openId登录(邓小江)
bannerList: baseUrl + `sys/${platform}/bannerList/1.0`,//bannerList 列表(雷国敏)
platformPtotocolConfigDetail: baseUrl + `sys/${platform}/platformPtotocolConfigDetail/1.0`,//平台协议设置详情(王琪)
xkFavoriteCreate: baseUrl + `user/${platform}/xkFavoriteCreate/1.0`,//收藏(王琪)
xkFavoriteQPage: baseUrl + `user/${platform}/xkFavoriteQPage/1.0`,//查询收藏 (王琪)
shopWindowCreate: baseUrl + `user/${platform}/shopWindowCreate/1.0`,//新增(刘国权)
xkUserUpdateReferralCode: baseUrl + `user/${platform}/xkUserUpdateReferralCode/1.0`,//填写邀请码(闫菘)
userAccDetail: baseUrl + `trade/${platform}/userAccDetail/1.0`,//用户账户明细(王鹏)
xkFavoriteDoFavorite: baseUrl + `user/${platform}/xkFavoriteDoFavorite/1.0`, // 确认是否收藏(王琪)
xkFavoriteCreate: baseUrl + `user/${platform}/xkFavoriteCreate/1.0`, // 收藏(王琪)
xkFavoriteUnFavorite: baseUrl + `user/${platform}/xkFavoriteUnFavorite/1.0`, // 单个取消收藏(王琪)
xkFavoriteQPage: baseUrl + `user/${platform}/xkFavoriteQPage/1.0`, // 收藏列表(王琪)
xkFavoriteDelete: baseUrl + `user/${platform}/xkFavoriteDelete/1.0`, // 批量删除收藏(王琪)
}
|
angular
.module('altairApp')
.controller("tzs",['$scope','$rootScope','utils','mainService','sweet','user_data','$timeout',
function ($scope,$rootScope,utils,mainService,sweet,user_data,$timeout) {
var progressbar = $("#file_upload-progressbar"),
bar = progressbar.find('.uk-progress-bar'),
settings = {
action: '/user/upload/data', // upload url
allow : '*.(jpg|jpeg|gif|png|xlsx)', // allow only images
loadstart: function() {
bar.css("width", "0%").text("0%");
progressbar.removeClass("uk-hidden");
},
progress: function(percent) {
percent = Math.ceil(percent);
bar.css("width", percent+"%").text(percent+"%");
},
allcomplete: function(response) {
bar.css("width", "100%").text("100%");
setTimeout(function(){
progressbar.addClass("uk-hidden");
}, 250);
alert("Upload Completed")
}
};
var select = UIkit.uploadSelect($("#file_upload-select"), settings),
drop = UIkit.uploadDrop($("#file_upload-drop"), settings);
$scope.licensetz = {
dataSource: {
pageSize: 10,
serverPaging: true,
serverSorting: true,
serverFiltering: true,
transport: {
read: {
url: "/user/angular/SubLicenses",
contentType:"application/json; charset=UTF-8",
type:"POST"
},
update: {
url: "/user/service/editing/update/"+$scope.domain+"",
contentType:"application/json; charset=UTF-8",
type:"POST"
},
destroy: {
url: "/user/service/editing/delete/"+$scope.domain+"",
contentType:"application/json; charset=UTF-8",
type:"POST"
},
create: {
url: "/user/service/editing/create/"+$scope.domain+"",
contentType:"application/json; charset=UTF-8",
type:"POST",
complete: function(e) {
$(".k-grid").data("kendoGrid").dataSource.read();
}
},
parameterMap: function(options) {
return JSON.stringify(options);
}
},
schema: {
data:"data",
total:"total",
model: {
id: "id"
}
}
},
filterable: {
mode: "row"
},
excel: {
fileName: "Export.xlsx",
proxyURL: "https://demos.telerik.com/kendo-ui/service/export",
filterable: true,
allPages: true
},
sortable: {
mode: "multiple",
allowUnsort: true
},
toolbar: ["excel","pdf"],
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
columns: [
{title: "#",template: "<span class='row-number'></span>", width:"60px"},
{ field:"id", title: "id" },
{ field:"licenseNum", title: "licenseNum" },
{ field:"licenseXB", title: "licenseXB"},
{ field:"areaNameMon", title: "areaNameMon" },
{ field:"lpName", title: "lpName"},
{ field:"areaSize", title: "areaSize" },
{ field:"locationAimag", title: "locationAimag" },
{ field:"locationSoum", title: "locationSoum" },
{ field:"licTypeId", title: "licTypeId" },
{ field:"licStatusId", title: "licStatusId" },
{ field:"lpReg", title: "lpReg" },
{ field:"lpName", title: "lpName" },
{ field:"grantDate", title: "grantDate" },
{ field:"expDate", title: "expDate" },
{ field:"mintype", title: "mintype" },
{ field:"divisionId", title: "divisionId" },
{ field:"lplan", title: "lplan" },
{field:"lreport", title: "lreport" },
],
dataBound: function () {
var rows = this.items();
$(rows).each(function () {
var index = $(this).index() + 1
+ ($(".k-grid").data("kendoGrid").dataSource.pageSize() * ($(".k-grid").data("kendoGrid").dataSource.page() - 1));;
var rowLabel = $(this).find(".row-number");
$(rowLabel).html(index);
});
},
editable: "popup"
};
}
]);
|
'use strict';
var app = angular.module('talkpointsApp', [
'talkpointsApp.controllers',
'talkpointsApp.services',
'talkpointsApp.directives',
'ngSanitize'
]);
app.config(['$sceDelegateProvider', function ($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
'self',
'http://player.nimbb.com/**',
'https://player.nimbb.com/**',
'http://api.nimbb.com/**',
'https://api.nimbb.com/**'
]);
}]);
/*
app.config(['$sceProvider', function ($sceProvider) {
$sceProvider.enabled(false);
}]);
*/
app.constant('NIMBB_PUBLIC_KEY', 'c7d8097faa');
app.constant('NIMBB_SWF_URL', 'https://player.nimbb.com/nimbb.swf');
app.constant('CONFIG', window.CONFIG);
delete window.CONFIG;
|
// Imports
import React from 'react'
// App Imports
import JobsListingContainer from '../components/jobs/JobsListingContainer';
import JobDetailsContainer from '../components/Jobs/JobDetailsContainer'
// Routes
const routes = [
{
path: '/',
component: JobsListingContainer,
exact: true
},
{
path: '/jobDetails/:id',
component: JobDetailsContainer
}
]
export default routes |
const express = require('express');
const websiteRoutes = require('./routes/website');
const scoutingRoutes = require('./routes/scouting');
const content = require('./content/content.js').content();
// set variables for environment
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
// Set server port
var port = process.env.PORT || 3001;
app.use('/scripts', express.static(__dirname + '/node_modules/material-components-web/dist/'));
app.listen(port, function() {
console.log('Our app is running on http://localhost:' + port);
});
console.log('server is running');
app.set('views', [path.join(__dirname, 'views/website'), path.join(__dirname, 'views/scouting')]);
app.set('view engine', 'pug'); // use either jade or ejs
// instruct express to server up static assets
app.use(express.static('public'));
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use('/', websiteRoutes);
app.use('/scouting', scoutingRoutes);
app.use(function(req, res, next){
res.status(404);
// respond with html page
if (req.accepts('html')) {
res.render('404', content.home);
return;
}
if (req.accepts('json')) {
res.send({ error: 'Not found' });
return;
}
res.type('txt').send('Not found');
});
|
const webpack = require("webpack");
const path = require("path");
const WebpackDevServer = require('webpack-dev-server');
const webpackConfig = require("./webpack.config.dev.js");
const compiler = webpack(webpackConfig);
const server = new WebpackDevServer(compiler, {
stats: {
colors: true
},
historyApiFallback: true,
contentBase: path.join(__dirname, ".."),
hot: true,
overlay: true,
open: true,
disableHostCheck: true,
proxy: {
// '/api/**':{
// target: 'http://10.0.0.171:8778',
// changeOrigin: true
// },
},
});
server.listen(9000, "0.0.0.0", function(err) {
console.log(err || "Starting server on http://localhost:9000");
});
|
var mongoose = require("mongoose"),
Appdata = require("./models/appdata"),
fs = require("fs"),
fastcsv = require("fast-csv");
var stream = fs.createReadStream("E:/Workspace/My Projects/NewsBulletin/V2/input.csv");
function seedDB() {
//Remove all the data in case there is some existing data in the current database
Appdata.deleteMany({}, function (err) {
if (err) {
console.log(err);
}
console.log("Cleared all the data from the database.");
//Read in the data from the csv input file row by row
fastcsv.fromStream(stream, { headers: true })
.on("data", function (data) {
//To remove the backslash characters from the publisher field in the input data
data.publisher = data.publisher.replace(/\\/g, "");
addToCollection(data);
})
.on("end", function () {
console.log("Successfully added data to the database.");
});
function addToCollection(data) {
//Create a model and save to the database
var appData = new Appdata(data);
appData.save(function (err) {
if (err) {
console.log(err);
}
});
}
});
};
module.exports = seedDB; |
Ext.define('Accounts.view.main.MainDB', {
extend: 'Ext.tab.Panel',
xtype: 'mainDB',
requires: [
'Ext.plugin.Viewport',
'Ext.window.MessageBox',
'Accounts.view.main.MainController',
'Accounts.view.main.MainModel'
],
viewModel: 'main',
tabBarPosition: 'bottom',
items: [{
xtype : 'accountList',
title : 'AccountsDB'
}]
});
|
require("dotenv").config();
var pg = require("pg");
const { Pool, Client } = require("pg");
var conString = process.env.DB_URL;
var client = new pg.Client(conString);
client.connect(function(err) {
if (err) {
return console.error("could not connect to postgres", err);
}
client.query('SELECT NOW() AS "theTime"', function(err, result) {
if (err) {
return console.error("error running query", err);
}
console.log("Database Connected");
});
});
module.exports = client;
|
import React from 'react';
import './style.scss';
const grids = [
{
title: 'Baptism after Salvation',
mid: '01',
designed: true,
desc:
'After you have accepted Christ as your personal Saviour, you may follow God’s simple command of being baptized. Baptism is not necessary for salvation; it is simply a public testimony of your faith. As you follow Christ in baptism you will be added as a member of Gbagada Estate Baptist Church.',
},
{
title: '',
mid: 'OR',
designed: false,
desc: '',
},
{
title: 'Statement of Faith or Transfer of Letter',
mid: '02',
designed: true,
desc:
'If you have already accepted Christ and have been baptized in a church whose doctrine is in agreement with Gbagada Estate Baptist Church, you may present your testimony of salvation and be voted into membership by your statement of faith or transfer of membership from another church.',
},
{
title: '',
mid: 'OR',
designed: false,
desc: '',
},
{
title: 'Statement of Faith by Baptism',
mid: '03',
designed: true,
desc:
'If you have accepted Christ and have not been baptized in a church of like faith, you will be asked to publicly identify with Christ and the Faith Baptist Church by being baptized into our membership. This is also true if your mode of baptism was other than immersion, or if the doctrine was different in your previous church. Gbagada Estate Baptist Church is committed to maintaining a doctrinal unity in this day of confusion and doctrinal compromise. If you believe that God has led you to this church, and if you understand that baptism is simply a testimony of your faith, we invite you to identify with Christ and the Gbagada Estate Baptist Church by being baptized as the Lord leads you.',
},
];
const Join = () => {
return (
<section className="join">
<h2 className="hd txt-center">Three ways to joining GEBC Family</h2>
<div className="grid-sec container">
{grids.map((grid, i) => (
<div className="grid reg_text" key={`grid_sec_${i}`}>
<h2 className="right-man">{grid.title}</h2>
<p className={`${grid.designed ? 'designed' : 'reg'} flex-row`}>
{grid.mid}
</p>
<p className="desc">{grid.desc}</p>
</div>
))}
</div>
</section>
);
};
export default Join;
|
/* eslint-disable jsx-a11y/click-events-have-key-events */
/* eslint-disable jsx-a11y/no-noninteractive-element-interactions */
import React, { Fragment, useState } from 'react';
import axios from 'axios';
import { withRouter } from 'react-router-dom';
import { ApiDeletePost } from '../../api/deletePost';
import {
StyledBottomSubSection,
StyledPostCard,
StyledPostCardContent,
StyledPostCardButtons
} from '../../containers/ProfilePrivate/styles';
const ProfilePostList = ({ postList, publicProfile, history }) => {
const [deletedList, setdeletedList] = useState([]);
const EditPost = () => {
alert('Sorry!. Still working on it...');
};
const DeletePostFunc = uuid => {
ApiDeletePost(
axios,
'delete',
`/api/deletePost/${uuid}`,
null,
null,
deletedList,
setdeletedList
);
};
return (
<StyledBottomSubSection>
{postList.map(val => {
const { uuid, photo400, title, price, status } = val;
const deleted = deletedList.includes(uuid) ? 'yes' : 'no';
return (
<StyledPostCard key={title}>
<img
src={photo400}
alt={title}
width="300px"
onClick={() => history.push(`/feed/${uuid}`)}
/>
<StyledPostCardContent>
<h5>{status}</h5>
<p>{title}</p>
<p>{`$${price}`}</p>
{!publicProfile && (
<Fragment>
<StyledPostCardButtons
type="button"
onClick={EditPost}
>
Edit
</StyledPostCardButtons>
<StyledPostCardButtons
type="button"
onClick={() => DeletePostFunc(uuid)}
deleted={deleted}
>
{deleted === 'yes' ? (
<span>Deleted</span>
) : (
<span>Delete</span>
)}
</StyledPostCardButtons>
</Fragment>
)}
</StyledPostCardContent>
</StyledPostCard>
);
})}
</StyledBottomSubSection>
);
};
export default withRouter(ProfilePostList);
|
(function(root){
var _info = '';
var CHANGE_EVENT = 'info_change';
root.InfoStore = $.extend({}, EventEmitter.prototype, {
currentInfo: function(){
return _info;
},
changeInfo: function(property){
_info = property;
InfoStore.emit(CHANGE_EVENT);
},
clearInfo: function(){
_info='';
InfoStore.emit(CHANGE_EVENT);
},
addChangeListener: function(callback){
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function(callback){
this.removeListener(CHANGE_EVENT, callback);
},
dispatchID: AppDispatcher.register(function(payload){
switch(payload.actionType){
case ActionTypes.CHANGE_INFO:
InfoStore.changeInfo(payload.property);
break;
}
})
})
})(this);
|
/*
SpritesPacking.js
Generate a compact packing of imges from a folder of png images
with Nodejs (use node-canvas), and Generate the data file who
contains ids, sizes, offsets, positions of the images.
***************
Copyright (c) 2013, Christophe Matthieu
https://github.com/Gorash
Released under the MIT license
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
(function (module){ "use strict";
var Canvas = module.Canvas || Canvas || (typeof require !== 'undefined' ? require('canvas') : null);
var fs = module.fs || fs || (typeof require !== 'undefined' ? require('fs') : null);
var Image = module.Image || Image || Canvas.Image;
var SpritesPacking = function SpritesPacking (pathFolder) {
this.init(pathFolder);
};
SpritesPacking.prototype.init = function (pathFolder) {
var self = this;
if (!pathFolder) return;
pathFolder = pathFolder.replace(/\/$/, '');
this.get_tiles(pathFolder, function (tiles) {
self.set_tiles_offset(tiles);
self.packing(tiles);
self.generate_image(tiles, pathFolder);
self.generate_data(tiles, pathFolder);
});
};
SpritesPacking.prototype.generate_image = function (tiles, pathFolder) {
var width = 0;
var height = 0;
for (var i in tiles) {
var tile = tiles[i];
if (tile.pos_x+tile.size_x > width) width = tile.pos_x+tile.size_x;
if (tile.pos_y+tile.size_y > height) height = tile.pos_y+tile.size_y;
}
var canvas = new Canvas(width, height);
var ctx = canvas.getContext("2d");
for (var i in tiles) {
var tile = tiles[i];
ctx.drawImage(tile.image, tile.pos_x-tile.offset_x, tile.pos_y-tile.offset_y);
}
canvas.toBuffer(function(err, buf){
if (err) throw err;
fs.writeFile(pathFolder + "/SpritesPacking.png", buf);
});
};
SpritesPacking.prototype.generate_data = function (tiles, pathFolder) {
var data = "#id:width,height,offset_x,offset_y,pos_x,pos_y,size_x,size_y";
for (var i=0; i<tiles.length; i++) {
var tile = tiles[i];
data += "\n"+tile.id+":" +
tile.image.width+","+tile.image.height +","+
tile.offset_x+","+tile.offset_y+"," +
tile.pos_x+","+tile.pos_y+"," +
tile.size_x+","+tile.size_y;
}
fs.writeFile(pathFolder + "/SpritesPacking.data", data);
};
SpritesPacking.prototype.get_tiles = function (pathFolder, callback) {
var files = [];
var data = fs.readdirSync(pathFolder);
for (var k in data) {
var file = pathFolder + '/' + data[k];
if (!fs.lstatSync(file).isDirectory() && file.match(/\.png$/) && data[k] != "SpritesPacking.png") {
files.push(file);
}
}
var tiles = [];
for (var i in files) {
var img = new Image();
img.onload = function (){
tiles.push({
'id': img.src.slice(pathFolder.length+1, img.src.length-4),
'image': img,
});
if (tiles.length == files.length) {
callback.call(this, tiles);
}
};
img.onerror = function (error){
error.src = img.src;
throw error;
};
img.src = files[i];
}
};
SpritesPacking.prototype.margin = 0;
SpritesPacking.prototype.set_tiles_offset = function (tiles) {
for (var i in tiles) {
var tile = tiles[i];
var width = tile.image.width;
var height = tile.image.height;
var canvas = new Canvas(width, height);
var ctx = canvas.getContext("2d");
ctx.drawImage(tile.image, 0, 0);
var pixels = ctx.getImageData(0,0,width,height).data;
var max_x = 1;
var min_x = width;
var max_y = 1;
var min_y = height;
var index = pixels.length;
while(index) {
index -= 4;
var x = (index>>2)%width;
var y = (index>>2)/width | 0;
if (pixels[index + 3]) {
if (max_x < x+1) max_x = x+1;
if (max_y < y+1) max_y = y+1;
if (min_x > x) min_x = x;
if (min_y > y) min_y = y;
}
}
tile.size_x = max_x-min_x+this.margin;
tile.size_y = max_y-min_y+this.margin;
tile.offset_x = min_x;
tile.offset_y = min_y;
tile.outer_x = width-max_x;
tile.outer_y = height-max_y;
}
return tiles;
};
SpritesPacking.prototype.packing = function (tiles) {
var max_x = this.get_max_size(tiles);
tiles.sort(this._sort_method);
var table = this._packing(tiles, max_x);
return table;
};
SpritesPacking.prototype.get_max_size = function (tiles) {
var size_sqrt = 0;
var min = 0;
for (var index in tiles) {
var tile = tiles[index];
if (tile.size_x > min) min = tile.size_x;
size_sqrt += tile.size_x * tile.size_y;
}
var max = Math.ceil(Math.sqrt(size_sqrt) * 1.2);
if (min > max) max = min;
return max;
};
SpritesPacking.prototype._sort_method = function (a,b) {
// Sort by size
return b.size_x != a.size_x ? b.size_x - a.size_x :
(b.size_y != a.size_y ? b.size_y - a.size_y : b.id - a.id);
};
SpritesPacking.prototype._check_place = function (table, posx, posy, sizex, sizey) {
var dpos = -1;
for (var y=0; y<sizey; y++) {
for (var x=0; x<sizex; x++) {
if (!table[posy+y]) table[posy+y] = [];
if (table[posy+y][posx+x] != null) {
if (dpos < x) {
dpos = x;
if (dpos == sizex) {
return dpos+1;
}
}
}
}
}
return dpos+1;
};
SpritesPacking.prototype._packing = function (tiles, max_x) {
// Compute tiles positions on the grid
var table = [];
var minpos = 0;
var tile, x, y, pos, dpos, x2, y2, i, len, px;
max_x |= 0;
for (i=0, len=tiles.length; i<len; i++) {
tile = tiles[i];
tile.id = tile.id || i;
x = tile.size_x;
y = tile.size_y;
pos = minpos;
if (x>max_x) throw new Error(x+">"+max_x+" : Tile ("+tile.id+") is greather than max size x");
while ((px = pos%max_x)>max_x-x || (dpos = this._check_place(table, px, pos/max_x | 0, x, y))) {
if (px+dpos>max_x) dpos = max_x - px;
pos+=dpos;
}
if (x==1 && y==1) { // simple heuristic for CPU optimization
minpos = pos/max_x | 0;
}
for (y2=0; y2<y; y2++) {
for (x2=0; x2<x; x2++) {
if (!table[(pos/max_x | 0)+y2]) table[(pos/max_x | 0)+y2] = [];
table[(pos/max_x | 0)+y2][(pos%max_x)+x2] = tile.id;
}
}
if (!table[pos/max_x | 0]) table[pos/max_x | 0] = [];
table[pos/max_x | 0][pos%max_x] = tile.id;
tile.pos_y = pos/max_x | 0;
tile.pos_x = pos%max_x;
}
return table;
};
if (process && process.argv) {
if (process.argv[1].indexOf("SpritesPacking.js") > -1 && process.argv[2]) {
var obj = new SpritesPacking( process.argv[2] );
}
if (process.argv[2] === "-h" || process.argv[2] === "--help") {
console.log("To create a sprites packing from a folder of png images use: node SpritesPacking.js ~/your path folder of tiles/");
}
}
module.SpritesPacking = SpritesPacking;
if(typeof module.exports !== 'undefined') module.exports = SpritesPacking;
})(typeof module === 'undefined' ? this : module);
|
import React, { useState, useReducer, useEffect } from 'react'
export default ({svgClass, points}) => {
return (
<div className={svgClass}>
<svg style={{position:'absolute',left:0, top: 0, height: '100vh', width: '100vw', zIndex: -1}}>
{/* {hasCoords && <circle cx={coords.x} cy={coords.y} r={coords.r} stroke="red" strokeWidth="2" fill="none" />} */}
<polygon points={points} stroke="#f45f42" strokeWidth="2" fill="#f45f42" />
</svg>
</div>
)
} |
/* See license.txt for terms of usage */
define([
"firebug/firefox/browserOverlayLib",
],
function(BrowserOverlayLib) {
// ********************************************************************************************* //
// Constants
var {$menupopupOverlay, $, $menupopup, $menu, $menuseparator, $menuitem} = BrowserOverlayLib;
// ********************************************************************************************* //
// GlobalCommands Implementation
var BrowserMenu =
{
overlay: function(doc)
{
this.overlayStartButtonMenu(doc);
this.overlayFirebugMenu(doc);
this.overlayFirefoxMenu(doc);
},
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Firebug Start Button Popup Menu
overlayStartButtonMenu: function(doc)
{
$menupopupOverlay(doc, $(doc, "mainPopupSet"), [
$menupopup(doc,
{
id: "fbStatusContextMenu",
onpopupshowing: "Firebug.browserOverlay.onOptionsShowing(this)"
},
[
$menu(doc,
{
label: "firebug.uiLocation",
tooltiptext: "firebug.menu.tip.UI_Location"
},
[
$menupopup(doc, {
onpopupshowing: "Firebug.browserOverlay.onPositionPopupShowing(this)"
})
]),
$menuseparator(doc),
$menuitem(doc, {
id: "menu_firebug_ClearConsole",
label: "firebug.ClearConsole",
tooltiptext: "firebug.ClearTooltip",
command: "cmd_firebug_clearConsole",
key: "key_firebug_clearConsole"
}),
$menuitem(doc, {
id: "menu_firebug_showErrorCount",
type: "checkbox",
label: "firebug.Show_Error_Count",
tooltiptext: "firebug.menu.tip.Show_Error_Count",
oncommand: "Firebug.browserOverlay.onToggleOption(this)",
option: "showErrorCount"
}),
$menuseparator(doc),
$menuitem(doc, {
id: "menu_firebug_enablePanels",
label: "firebug.menu.Enable_All_Panels",
tooltiptext: "firebug.menu.tip.Enable_All_Panels",
command: "cmd_firebug_enablePanels"
}),
$menuitem(doc, {
id: "menu_firebug_disablePanels",
label: "firebug.menu.Disable_All_Panels",
tooltiptext: "firebug.menu.tip.Disable_All_Panels",
command: "cmd_firebug_disablePanels"
}),
$menuseparator(doc),
$menuitem(doc, {
id: "menu_firebug_AllOn",
type: "checkbox",
label: "On_for_all_web_pages",
tooltiptext: "firebug.menu.tip.On_for_all_Web_Sites",
command: "cmd_firebug_allOn",
option: "allPagesActivation"
}),
$menuitem(doc, {
id: "menu_firebug_clearActivationList",
label: "firebug.menu.Clear_Activation_List",
tooltiptext: "firebug.menu.tip.Clear_Activation_List",
command: "cmd_firebug_clearActivationList"
})
])
]);
},
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Firebug Global Menu
/**
* There are more instances of Firebug Menu (e.g. one in Firefox -> Tools -> Web Developer
* and one in Firefox 4 (top-left orange button menu) -> Web Developer
*
* If extensions want to override the menu they need to iterate all existing instance
* using document.querySelectorAll(".fbFirebugMenuPopup") and append new menu items to all
* of them. Iteration must be done in the global space (browser.xul)
*
* The same menu is also used for Firebug Icon Menu (Firebug's toolbar). This menu is cloned
* and initialized as soon as Firebug UI is actually loaded. Since it's cloned from the original
* (global scope) extensions don't have to extend it (possible new menu items are already there).
*/
overlayFirebugMenu: function(doc)
{
this.firebugMenuContent =
[
// Open/close Firebug
$menuitem(doc,
{
id: "menu_firebug_toggleFirebug",
label: "firebug.ShowFirebug",
tooltiptext: "firebug.menu.tip.Open_Firebug",
command: "cmd_firebug_toggleFirebug",
key: "key_firebug_toggleFirebug"
}),
$menuitem(doc,
{
id: "menu_firebug_closeFirebug",
label: "firebug.Deactivate_Firebug",
tooltiptext: "firebug.tip.Deactivate_Firebug",
command: "cmd_firebug_closeFirebug",
key: "key_firebug_closeFirebug"
}),
// Firebug UI position
$menu(doc,
{
label: "firebug.uiLocation",
tooltiptext: "firebug.menu.tip.UI_Location"
},
[
$menupopup(doc, {
onpopupshowing: "Firebug.browserOverlay.onPositionPopupShowing(this)"
})
]),
$menuseparator(doc),
// External Editors
$menu(doc,
{
id: "FirebugMenu_OpenWith",
label: "firebug.OpenWith",
tooltiptext: "firebug.menu.tip.Open_With",
insertafter: "menu_firebug_openActionsSeparator",
openFromContext: "true",
command: "cmd_firebug_openInEditor"
},
[
$menupopup(doc, {id: "fbFirebugMenu_OpenWith",
onpopupshowing: "return Firebug.browserOverlay.onEditorsShowing(this);"})
]),
// Text Size
$menu(doc,
{
id: "FirebugMenu_TextSize",
label: "firebug.TextSize",
tooltiptext: "firebug.menu.tip.Text_Size"
},
[
$menupopup(doc, {},
[
$menuitem(doc,
{
id: "menu_firebug_increaseTextSize",
label: "firebug.IncreaseTextSize",
tooltiptext: "firebug.menu.tip.Increase_Text_Size",
command: "cmd_firebug_increaseTextSize",
key: "key_firebug_increaseTextSize"
}),
$menuitem(doc,
{
id: "menu_firebug_decreaseTextSize",
label: "firebug.DecreaseTextSize",
tooltiptext: "firebug.menu.tip.Decrease_Text_Size",
command: "cmd_firebug_decreaseTextSize",
key: "key_firebug_decreaseTextSize"
}),
$menuitem(doc,
{
id: "menu_firebug_normalTextSize",
label: "firebug.NormalTextSize",
tooltiptext: "firebug.menu.tip.Normal_Text_Size",
command: "cmd_firebug_normalTextSize",
key: "key_firebug_normalTextSize"
}),
])
]),
// Options
$menu(doc,
{
id: "FirebugMenu_Options",
label: "firebug.Options",
tooltiptext: "firebug.menu.tip.Options"
},
[
$menupopup(doc,
{
id: "FirebugMenu_OptionsPopup",
onpopupshowing: "return Firebug.browserOverlay.onOptionsShowing(this);"
},
[
$menuitem(doc,
{
id: "menu_firebug_toggleShowErrorCount",
type: "checkbox",
label: "firebug.Show_Error_Count",
tooltiptext: "firebug.menu.tip.Show_Error_Count",
oncommand: "Firebug.browserOverlay.onToggleOption(this)",
option: "showErrorCount"
}),
$menuitem(doc,
{
id: "menu_firebug_showTooltips",
type: "checkbox",
label: "firebug.menu.Show_Info_Tips",
tooltiptext: "firebug.menu.tip.Show_Info_Tips",
oncommand: "Firebug.browserOverlay.onToggleOption(this)",
option: "showInfoTips"
}),
$menuitem(doc,
{
id: "menu_firebug_shadeBoxModel",
type: "checkbox",
label: "ShadeBoxModel",
tooltiptext: "inspect.option.tip.Shade_Box_Model",
oncommand: "Firebug.browserOverlay.onToggleOption(this)",
option: "shadeBoxModel"
}),
$menuitem(doc,
{
id: "menu_firebug_showQuickInfoBox",
type: "checkbox",
label: "ShowQuickInfoBox",
tooltiptext: "inspect.option.tip.Show_Quick_Info_Box",
oncommand: "Firebug.browserOverlay.onToggleOption(this)",
option: "showQuickInfoBox"
}),
$menuitem(doc,
{
id: "menu_firebug_enableA11y",
type: "checkbox",
label: "firebug.menu.Enable_Accessibility_Enhancements",
tooltiptext: "firebug.menu.tip.Enable_Accessibility_Enhancements",
oncommand: "Firebug.browserOverlay.onToggleOption(this)",
option: "a11y.enable"
}),
$menuitem(doc,
{
id: "menu_firebug_activateSameOrigin",
type: "checkbox",
label: "firebug.menu.Activate_Same_Origin_URLs2",
tooltiptext: "firebug.menu.tip.Activate_Same_Origin_URLs",
oncommand: "Firebug.browserOverlay.onToggleOption(this)",
option: "activateSameOrigin"
}),
$menuitem(doc,
{
id: "menu_firebug_toggleOrient",
type: "checkbox",
label: "firebug.menu.Vertical_Panels",
tooltiptext: "firebug.menu.tip.Vertical_Panels",
command: "cmd_firebug_toggleOrient",
option: "viewPanelOrient"
}),
$menuseparator(doc, {id: "menu_firebug_optionsSeparator"}),
$menuitem(doc,
{
id: "menu_firebug_resetAllOptions",
label: "firebug.menu.Reset_All_Firebug_Options",
tooltiptext: "firebug.menu.tip.Reset_All_Firebug_Options",
command: "cmd_firebug_resetAllOptions"
}),
])
]),
$menuseparator(doc, {id: "FirebugBetweenOptionsAndSites", collapsed: "true"}),
// Sites
$menu(doc,
{
id: "FirebugMenu_Sites",
label: "firebug.menu.Firebug_Online",
tooltiptext: "firebug.menu.tip.Firebug_Online"
},
[
$menupopup(doc, {},
[
$menuitem(doc,
{
id: "menu_firebug_firebugUrlWebsite",
label: "firebug.Website",
tooltiptext: "firebug.menu.tip.Website",
oncommand: "Firebug.chrome.visitWebsite('main')"
}),
$menuitem(doc,
{
id: "menu_firebug_firebugUrlExtensions",
label: "firebug.menu.Extensions",
tooltiptext: "firebug.menu.tip.Extensions",
oncommand: "Firebug.chrome.visitWebsite('extensions')"
}),
$menuitem(doc,
{
id: "menu_firebug_firebugHelp",
label: "firebug.help",
tooltiptext: "firebug.menu.tip.help",
command: "cmd_firebug_openHelp",
key: "key_firebug_help"
}),
$menuitem(doc,
{
id: "menu_firebug_firebugDoc",
label: "firebug.Documentation",
tooltiptext: "firebug.menu.tip.Documentation",
oncommand: "Firebug.chrome.visitWebsite('docs')"
}),
$menuitem(doc,
{
id: "menu_firebug_firebugKeyboard",
label: "firebug.KeyShortcuts",
tooltiptext: "firebug.menu.tip.Key_Shortcuts",
oncommand: "Firebug.chrome.visitWebsite('keyboard')"
}),
$menuitem(doc,
{
id: "menu_firebug_firebugForums",
label: "firebug.Forums",
tooltiptext: "firebug.menu.tip.Forums",
oncommand: "Firebug.chrome.visitWebsite('discuss')"
}),
$menuitem(doc,
{
id: "menu_firebug_firebugIssues",
label: "firebug.Issues",
tooltiptext: "firebug.menu.tip.Issues",
oncommand: "Firebug.chrome.visitWebsite('issues')"
}),
$menuitem(doc,
{
id: "menu_firebug_firebugDonate",
label: "firebug.Donate",
tooltiptext: "firebug.menu.tip.Donate",
oncommand: "Firebug.chrome.visitWebsite('donate')"
}),
])
]),
// Panel selector (see 'firebug/chrome/panelSelector' module for implementation).
$menu(doc,
{
id: "FirebugMenu_PanelSelector",
label: "firebug.panel_selector2",
tooltiptext: "firebug.panel_selector2.tip",
"class": "fbInternational"
},
[
$menupopup(doc,
{
id: "FirebugMenu_PanelSelectorPopup",
onpopupshowing: "return Firebug.browserOverlay.onPanelSelectorShowing(this);",
onpopuphiding: "return Firebug.browserOverlay.onPanelSelectorHiding(this)"
})
]),
$menuseparator(doc, {id: "menu_firebug_miscActionsSeparator", collapsed: "true"}),
$menuseparator(doc, {id: "menu_firebug_toolsSeparator", collapsed: "true"}),
$menuitem(doc,
{
id: "menu_firebug_customizeShortcuts",
label: "firebug.menu.Customize_shortcuts",
tooltiptext: "firebug.menu.tip.Customize_Shortcuts",
command: "cmd_firebug_customizeFBKeys",
key: "key_firebug_customizeFBKeys"
}),
$menuseparator(doc, {id: "menu_firebug_aboutSeparator"}),
$menuitem(doc, {
id: "menu_firebug_about",
label: "firebug.About",
tooltiptext: "firebug.menu.tip.About",
oncommand: "Firebug.browserOverlay.openAboutDialog()",
"class": "firebugAbout"
}),
];
},
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Global Menu Overlays
overlayFirefoxMenu: function(doc)
{
// Firefox page context menu
$menupopupOverlay(doc, $(doc, "contentAreaContextMenu"), [
$menuseparator(doc),
$menuitem(doc, {
id: "menu_firebug_firebugInspect",
label: "firebug.InspectElementWithFirebug",
command: "cmd_firebug_inspect",
"class": "menuitem-iconic"
})
]);
// Firefox view menu
$menupopupOverlay(doc, $(doc, "menu_viewPopup"),
[
$menuitem(doc, {
id: "menu_firebug_viewToggleFirebug",
insertbefore: "toggle_taskbar",
label: "firebug.Firebug",
type: "checkbox",
key: "key_firebug_toggleFirebug",
command: "cmd_firebug_toggleFirebug"
})
],
{
onpopupshowing: "return Firebug.browserOverlay.onViewMenuShowing();"
}
);
// SeaMonkey view menu
$menupopupOverlay(doc, $(doc, "menu_View_Popup"),
[
$menuitem(doc, {
id: "menu_firebug_viewToggleFirebug",
insertafter: "menuitem_fullScreen",
label: "firebug.Firebug",
type: "checkbox",
key: "key_firebug_toggleFirebug",
command: "cmd_firebug_toggleFirebug",
"class": "menuitem-iconic"
})
],
{
onpopupshowing: "return Firebug.browserOverlay.onViewMenuShowing();"
}
);
// Firefox Tools -> Web Developer Menu
$menupopupOverlay(doc, $(doc, "menuWebDeveloperPopup"), [
$menu(doc, {
id: "menu_webDeveloper_firebug",
position: 1,
label: "firebug.Firebug",
"class": "menu-iconic"
}, [
$menupopup(doc, {
id: "menu_firebug_firebugMenuPopup",
"class": "fbFirebugMenuPopup",
onpopupshowing: "return Firebug.browserOverlay.onMenuShowing(this, event);",
onpopuphiding: "return Firebug.browserOverlay.onMenuHiding(this, event);"
})
]),
$menuseparator(doc, {
insertafter: "menu_webDeveloper_firebug"
})
]);
// Firefox Button -> Web Developer Menu
$menupopupOverlay(doc, $(doc, "appmenu_webDeveloper_popup"), [
$menu(doc, {
id: "appmenu_firebug",
position: 1,
label: "firebug.Firebug",
iconic: "true",
"class": "menu-iconic"
}, [
$menupopup(doc, {
id: "appmenu_firebugMenuPopup",
"class": "fbFirebugMenuPopup",
onpopupshowing: "return Firebug.browserOverlay.onMenuShowing(this, event);",
onpopuphiding: "return Firebug.browserOverlay.onMenuHiding(this, event);"
})
]),
$menuseparator(doc, {
insertafter: "appmenu_firebug"
})
]);
// Sea Monkey Tools Menu
$menupopupOverlay(doc, $(doc, "toolsPopup"), [
$menu(doc, {
id: "menu_firebug",
insertbefore: "appmenu_webConsole",
command: "cmd_firebug_toggleFirebug",
key: "key_firebug_toggleFirebug",
label: "firebug.Firebug",
"class": "menuitem-iconic"
}, [
$menupopup(doc, {
id: "toolsmenu_firebugMenuPopup",
"class": "fbFirebugMenuPopup",
onpopupshowing: "return Firebug.browserOverlay.onMenuShowing(this, event);",
onpopuphiding: "return Firebug.browserOverlay.onMenuHiding(this, event);"
})
])
]);
}
};
// ********************************************************************************************* //
// Registration
return BrowserMenu;
// ********************************************************************************************* //
});
|
$(document).on('ready',function() {
if ($('#authenticate').length > 0) {
// authentication specific stuff
}
});
|
import React, { Component } from 'react';
import './App.css';
import RadioSet from './components/RadioSet';
import songData from './data/tracks.json';
songData.forEach((song, i) => {
song.id = i;
song.favorite = false;
});
class App extends Component {
constructor() {
super();
this.state = {
songs: songData,
morningTrackCount: songData.length / 2,
playlists: {
morningTracks: songData.slice(0, songData.length / 2),
eveningTracks: songData.slice(songData.length / 2, songData.length)
}
};
};
changeFavorite = (songId) => {
const newSongs = this.state.songs;
const index = newSongs.findIndex(k => k.id === songId);
newSongs[index].favorite = !newSongs[index].favorite;
this.setState({
songs: newSongs
});
};
moveToTop = (songId) => {
const newSongs = this.state.songs.slice(0);
const index = newSongs.findIndex(k => k.id === songId);
const temp = newSongs.splice(index, 1);
index <= this.state.morningTrackCount ? newSongs.unshift(temp[0]) : newSongs.splice(this.state.morningTrackCount, 0, temp[0]);
this.setState({
songs: newSongs
});
};
changePlayList = (songId) => {
const newSongs = this.state.songs.slice(0);
const index = newSongs.findIndex(k => k.id === songId);
const temp = newSongs.splice(index, 1);
if (index <= this.state.morningTrackCount) {
this.setState({
morningTrackCount: this.state.morningTrackCount - 1
});
newSongs.splice(this.state.morningTrackCount - 1, 0, temp[0]);
} else {
this.setState({
morningTrackCount: this.state.morningTrackCount + 1
});
newSongs.unshift(temp[0]);
}
this.setState({
songs: newSongs
});
};
render() {
return (
<div className="App">
<header>
<h1 className="page-header--title">Radio Lovelace</h1>
</header>
<main className="main">
<RadioSet
tracks={this.state.songs}
changeFavoriteCallback={this.changeFavorite}
moveToTopCallback={this.moveToTop}
changePlayListCallback={this.changePlayList}
playlists={this.state.playlists}
morningTrackCount={this.state.morningTrackCount} />
</main>
</div>
);
}
}
export default App;
|
import React , {Component} from 'react';
class ClockTimer extends Component{
constructor(props){
super(props);
this.state = {
dateTime: new Date().toLocaleString(),
}
}
componentDidMount(){
this.startTimer();
}
compoenentWillUnmount(){
this.stopTimer();
}
startTimer(){
this.timmer= setInterval(()=>this.resetTimer(),1000);
}
resetTimer(){
this.setState ({
dateTime: new Date().toLocaleString() ,
status:true
})
}
stopTimer(e){
clearInterval(this.timmer);
this.setState({
status:false
})
}
render() {
return (
<p >Date Time : {this.state.dateTime}</p>
)
}
}
export default ClockTimer; |
import utils from 'utility'
import rand from 'csprng'
import qiniu from 'qiniu'
import { qiniuCfg } from '../config'
qiniu.conf.ACCESS_KEY = qiniuCfg.accessKey
qiniu.conf.SECRET_KEY = qiniuCfg.secretKey
const formatedUserInfo = ({
user,
followings = [],
followers = [],
following = false,
}) => {
const {
account,
name,
avatar,
motto,
} = user
return {
account,
name,
avatar,
motto,
following,
followings,
followers,
}
}
const avatarUploadInfo = account => {
const dateString = ((new Date()).getTime()).toString()
const accountPart = utils.sha1(account, 'base64')
const datePart = utils.sha1(dateString, 'base64')
const randomPart = rand(80, 36)
const key = `${randomPart}${accountPart}${datePart}`
const putPolicy = new qiniu.rs.PutPolicy(`${qiniuCfg.bucket}:${key}`)
return {
token: putPolicy.token(),
key,
}
}
const imageUploadInfo = (account, amount) => {
const result = []
const dateString = ((new Date()).getTime()).toString()
const accountPart = utils.sha1(account, 'base64')
const datePart = utils.sha1(dateString, 'base64')
for (let i = 0; i < amount; i++) {
const randomPart = rand(80, 36)
const key = `${randomPart}${accountPart}${datePart}${i}`
const putPolicy = new qiniu.rs.PutPolicy(`${qiniuCfg.bucket}:${key}`)
result.push({
token: putPolicy.token(),
key,
})
}
return result
}
export {
formatedUserInfo,
avatarUploadInfo,
imageUploadInfo,
} |
import React from 'react';
import { Grid, Divider, Icon } from 'semantic-ui-react';
import Layout from '../components/Layout/';
import StaticForm from '../components/StaticForm/';
import Helmet from 'react-helmet';
const keywords = "email, contact form, ADP Contact, ADP connction, help, documentation.";
class ContactPage extends React.Component {
render() {
return (
<>
<Helmet
title={"ADP: Contact Us"}
meta={[
{
name: 'description',
content: 'ADP Contact us page. Communicate by phone or through email'
},
{
name: 'keywords',
content: keywords
},
]}
/>
<Layout>
<Grid stackable>
<Grid.Row columns={2} style={{width: '100%'}}>
<Grid.Column textAlign={"center"}>
<h3>Advanced Digital NYC, Inc.</h3>
<p>242 West 36th Street, 8th Floor</p>
<p>New York, NY 10018</p>
<p>Phone: 646-968-8871</p>
</Grid.Column>
<Grid.Column textAlign={"center"}>
<h3>Office Hours</h3>
<p><Icon name="checked calendar"/>Monday – Friday 8am to 5pm</p>
<p><Icon name="calendar plus"/>After 5pm By Appointment Only</p>
<p><Icon name="delete calendar"/>Closed On Weekends</p>
</Grid.Column>
</Grid.Row>
</Grid>
<Divider />
<StaticForm />
</Layout>
</>
);
}
}
export default ContactPage;
|
process.env.NODE_CONFIG_DIR = `${__dirname}/config`
const webpack = require('webpack')
const styleLoaders = require('@soapbubble/style').loaders
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const { DuplicatesPlugin } = require('inspectpack/plugin')
const config = require('config')
const dirJs = path.resolve(__dirname, 'client/js')
const dirParent = path.resolve(__dirname, '../')
const dirSharedComponents = [
path.join(dirParent, 'components', 'src'),
path.join(dirParent, 'style'),
]
// cheap-module-eval-source-map
module.exports = env => {
const outputPath = (() => {
if (env.cordova) {
return path.resolve(__dirname, '../cordova/www')
} else if (env.electron) {
return path.resolve(__dirname, '../electron/dist')
} else if (env.firebase) {
return path.resolve(__dirname, '../../public/morpheus')
}
return path.resolve(__dirname, 'public')
})()
let publicPath = ''
const htmlTemplate = (() => {
if (env.cordova) {
return 'cordova.ejs'
}
if (env.electron) {
return 'electron.ejs'
}
return 'index.ejs'
})()
let htmlFilename = 'index.html'
const isProduction = env.production || env.staging
const jsName = isProduction ? '[name].[hash].js' : '[name].js'
const appConfig = {}
if (env.firebase) {
Object.assign(appConfig, {
assetHost: 'https://s3-us-west-2.amazonaws.com/soapbubble-morpheus-dev',
apiHost: '/api',
authHost: 'https://soapbubble.web.app/auth',
botHost: 'https://soapbubble.web.app/bot',
})
} else if ((env.production || env.cordova || env.electron) && !env.debug) {
Object.assign(appConfig, {
assetHost: 'https://s3-us-west-2.amazonaws.com/soapbubble-morpheus-dev',
apiHost: 'https://soapbubble.online/morpheus',
authHost: 'https://soapbubble.online/auth',
botHost: 'https://soapbubble.online/bot',
})
if (env.production && !(env.cordova || env.electron)) {
publicPath = '/morpheus/'
htmlFilename = 'index-production.html'
}
} else if (env.staging) {
Object.assign(appConfig, {
assetHost: 'https://s3-us-west-2.amazonaws.com/soapbubble-morpheus-dev',
apiHost: 'https://staging.soapbubble.online/morpheus',
authHost: 'https://staging.soapbubble.online/auth',
})
if (!(env.cordova || env.electron)) {
publicPath = '/morpheus/'
htmlFilename = 'index-staging.html'
}
new DuplicatesPlugin({
// Emit compilation warning or error? (Default: `false`)
emitErrors: false,
// Display full duplicates information? (Default: `false`)
verbose: false,
})
}
if (env.localSSL || process.env.SOAPBUBBLE_LOCAL_SSL) {
Object.assign(appConfig, {
assetHost: 'https://s3-us-west-2.amazonaws.com/soapbubble-morpheus-dev',
apiHost: 'https://dev.soapbubble.online/morpheus',
authHost: 'https://dev.soapbubble.online/auth',
})
if (!(env.cordova || env.electron)) {
publicPath = '/morpheus/'
}
} else if (env.development) {
Object.assign(appConfig, {
assetHost: 'http://localhost:8050',
apiHost: '/api',
authHost: 'http://localhost:4000',
})
}
const target = env.electron ? 'electron-renderer' : 'web'
const mainFields = ['esnext', 'browser', 'module', 'main']
let nodeEnv = 'development'
if (isProduction) {
nodeEnv = 'production'
}
const webpackDefineConfig = {
'process.env.NODE_ENV': JSON.stringify(nodeEnv),
'process.env.AUTOSTART': JSON.stringify(env.electron || env.cordova),
config: JSON.stringify(appConfig),
}
const devToolOptions = {}
if (env.development && !env.cordova) {
devToolOptions.filename = '[file].map'
if (env.localSSL || process.env.SOAPBUBBLE_LOCAL_SSL) {
// devToolOptions.publicPath = 'https://dev.soapbubble.online/morpheus/';
}
}
const externals = {
greenworks: 'require("greenworks")',
}
if (!env.electron) {
externals.electron = '_'
}
let webpackConfig = {
mode: nodeEnv,
target,
devtool: false,
entry: {
app: './client/js/app.jsx',
browser: './client/js/browser.js',
vendor: [
'babel-polyfill',
'axios',
'bluebird',
'browser-bunyan',
'classnames',
'immutable',
'keycode',
'generic-pool',
'local-storage',
'lodash',
'promise-queue',
'query-string',
'raf',
'react',
'redux',
'react-dom',
'react-redux',
'redux-logger',
'redux-observable',
'redux-promise',
'redux-thunk',
'reselect',
'@tweenjs/tween.js',
'three',
'ua-parser-js',
],
},
externals,
output: {
path: outputPath,
filename: jsName,
publicPath,
},
resolve: {
extensions: ['.js', '.jsx', '.json', '.ts', '.tsx'],
mainFields,
alias: {
service: path.resolve(__dirname, 'client/js/service'),
morpheus: path.resolve(__dirname, 'client/js/morpheus'),
utils: path.resolve(__dirname, 'client/js/utils'),
soapbubble: path.resolve(__dirname, 'client/js/soapbubble'),
},
},
module: {
rules: styleLoaders(env).concat([
{
test: /\.jsx?$/,
include: [/node_modules\/@soapbubble/, /node_modules\/generic-pool/],
exclude: [
/@soapbubble\/.*\/node_modules/,
/generic-pool\/node_modules/,
],
use: [
{
loader: 'babel-loader',
options: {
rootMode: 'upward-optional',
},
},
],
},
{
test: /\.jsx?$/,
include: [/generic-pool/],
exclude: [/generic-pool\/node_modules/],
use: ['babel-loader'],
},
{
test: /\.tsx?$/,
exclude: [/node_modules/],
use: [
{
loader: 'ts-loader',
},
],
},
{
test: /\.jsx?$/,
exclude: [/node_modules/],
use: [
{
loader: 'babel-loader',
options: {
rootMode: 'upward-optional',
},
},
],
},
{
test: /\.png$/,
use: {
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'image/png',
},
},
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'image/svg+xml',
},
},
},
{
test: /\.css$/,
include: [/@soapbubble/].concat(dirSharedComponents),
exclude: [
/@soapbubble\/style\/dist\/soapbubble.css/,
/packages\/style\/dist\/soapbubble.css/,
],
use: [
{
loader: MiniCssExtractPlugin.loader,
},
{
loader: 'css-loader',
options: {
modules: true,
importLoaders: 1,
localIdentName: '[path]___[name]__[local]___[hash:base64:5]',
},
},
{ loader: 'postcss-loader' },
],
},
]),
},
plugins: [
new CleanWebpackPlugin(),
new DuplicatesPlugin({
// Emit compilation warning or error? (Default: `false`)
emitErrors: true,
// Display full duplicates information? (Default: `false`)
verbose: true,
}),
...(isProduction
? [
new MiniCssExtractPlugin({
filename: '[id].[contenthash].css',
}),
]
: []),
new HtmlWebpackPlugin({
title: 'Morpheus',
filename: htmlFilename,
template: `client/html/${htmlTemplate}`,
googleAnalyticsClientId: config.googleAnalyticsClientId,
chunks: ['vendor', 'app'],
}),
new webpack.DefinePlugin(webpackDefineConfig),
].concat(
env.development ? new webpack.SourceMapDevToolPlugin(devToolOptions) : []
),
}
return webpackConfig
}
|
import { injectReducer } from '../../../../store/reducers';
export default (store) => ({
path: 'posts',
getComponent (nextState, cb) {
require.ensure([], (require) => {
const PostRoute = require('./containers/BlogPageContainer').default;
const reducer = require('./reducers/index').default;
injectReducer(store, { key: 'posts', reducer });
cb(null, PostRoute)
}, 'PostsRoute')
}
})
|
const botconfig = require("./botconfig.json");
const Discord = require("discord.js");
const fs = require("fs");
const bot = new Discord.Client({disableEveryone: true});
bot.commands = new Discord.Collection();
// Bot startup
console.log(`${botconfig["bot_messages"].Setup_log}`)
fs.readdir("./commands/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log(`${botconfig["bot_Commands_logs"].General_commands_log_error}`);
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/${f}`);
if(botconfig["bot_setup"].debug_mode) {
console.log(`${f} ${botconfig["bot_Commands_logs"].General_commands_log_loaded}`);
}
bot.commands.set(props.help.name, props);
bot.commands.set(props.help.name2, props);
bot.commands.set(props.help.name3, props);
});
});
if(botconfig["module_toggles"].ticket_system) {
fs.readdir("./commands/ticket_system/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log('\x1b[31m%s\x1b[0m',`${botconfig["bot_Commands_logs"].Ticket_error}`);
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/ticket_system/${f}`);
if(botconfig["bot_setup"].debug_mode) {
console.log(`${f} loaded!`);
}
bot.commands.set(props.help.name, props);
});
console.log('\x1b[36m%s\x1b[0m',`${botconfig["bot_Commands_logs"].Ticket_Loaded}`)
});
}
if(botconfig["module_toggles"].utility_commands) {
fs.readdir("./commands/utility_module/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log('\x1b[31m%s\x1b[0m',`${botconfig["bot_Commands_logs"].utility_error}`);
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/utility_module/${f}`);
if(botconfig["bot_setup"].debug_mode) {
console.log(`${f} loaded!`);
}
bot.commands.set(props.help.name, props);
});
console.log('\x1b[36m%s\x1b[0m',`${botconfig["bot_Commands_logs"].utility_Loaded}`)
});
}
if(botconfig["module_toggles"].moderation_commands) {
fs.readdir("./commands/moderation_module/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log('\x1b[31m%s\x1b[0m',`${botconfig["bot_Commands_logs"].Moderation_error}`);
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/moderation_module/${f}`);
if(botconfig["bot_setup"].debug_mode) {
console.log(`${f} loaded!`);
}
bot.commands.set(props.help.name, props);
bot.commands.set(props.help.name2, props);
});
console.log('\x1b[36m%s\x1b[0m',`${botconfig["bot_Commands_logs"].Moderation_Loaded}`)
});
}
if(botconfig["module_toggles"].fun_commands) {
fs.readdir("./commands/fun_module/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log('\x1b[31m%s\x1b[0m',`${botconfig["bot_Commands_logs"].fun_error}`);
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/fun_module/${f}`);
if(botconfig["bot_setup"].debug_mode) {
console.log(`${f} loaded!`);
}
bot.commands.set(props.help.name, props);
bot.commands.set(props.help.name2, props);
});
console.log('\x1b[36m%s\x1b[0m',`${botconfig["bot_Commands_logs"].fun_Loaded}`)
});
}
if(botconfig["module_toggles"].General_module) {
fs.readdir("./commands/General_module/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log('\x1b[31m%s\x1b[0m',`${botconfig["bot_Commands_logs"].General_error}`);
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/General_module/${f}`);
if(botconfig["bot_setup"].debug_mode) {
console.log(`${f} loaded!`);
}
bot.commands.set(props.help.name, props);
bot.commands.set(props.help.name2, props);
});
console.log('\x1b[36m%s\x1b[0m',`${botconfig["bot_Commands_logs"].General_loaded}`)
});
}
if(botconfig["module_toggles"].Tools_module) {
fs.readdir("./commands/Tools_module/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log('\x1b[31m%s\x1b[0m',`${botconfig["bot_Commands_logs"].Tools_error}`);
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/Tools_module/${f}`);
if(botconfig["bot_setup"].debug_mode) {
console.log(`${f} loaded!`);
}
bot.commands.set(props.help.name, props);
bot.commands.set(props.help.name2, props);
});
console.log('\x1b[36m%s\x1b[0m',`${botconfig["bot_Commands_logs"].Tools_loaded}`)
});
}
if(botconfig["module_toggles"].Owner_module) {
fs.readdir("./commands/Owner_module/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log('\x1b[31m%s\x1b[0m',`${botconfig["bot_Commands_logs"].Owner_error}`);
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/Owner_module/${f}`);
if(botconfig["bot_setup"].debug_mode) {
console.log(`${f} loaded!`);
}
bot.commands.set(props.help.name, props);
bot.commands.set(props.help.name2, props);
});
console.log('\x1b[36m%s\x1b[0m',`${botconfig["bot_Commands_logs"].Owner_loaded}`)
});
}
if(botconfig["module_toggles"].Misc_module) {
fs.readdir("./commands/Misc_module/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log('\x1b[31m%s\x1b[0m',`${botconfig["bot_Commands_logs"].Misc_error}`);
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/Misc_module/${f}`);
if(botconfig["bot_setup"].debug_mode) {
console.log(`${f} loaded!`);
}
bot.commands.set(props.help.name, props);
bot.commands.set(props.help.name2, props);
});
console.log('\x1b[36m%s\x1b[0m',`${botconfig["bot_Commands_logs"].Misc_loaded}`)
});
}
if(botconfig["module_toggles"].jokes_module) {
fs.readdir("./commands/jokes_module/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log('\x1b[31m%s\x1b[0m',`${botconfig["bot_Commands_logs"].jokes_error}`);
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/jokes_module/${f}`);
if(botconfig["bot_setup"].debug_mode) {
console.log(`${f} loaded!`);
}
bot.commands.set(props.help.name, props);
bot.commands.set(props.help.name2, props);
});
console.log('\x1b[36m%s\x1b[0m',`${botconfig["bot_Commands_logs"].jokes_loaded}`)
});
}
if(botconfig["module_toggles"].info_module) {
fs.readdir("./commands/info_module/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log('\x1b[31m%s\x1b[0m',`${botconfig["bot_Commands_logs"].info_error}`);
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/info_module/${f}`);
if(botconfig["bot_setup"].debug_mode) {
console.log(`${f} loaded!`);
}
bot.commands.set(props.help.name, props);
bot.commands.set(props.help.name2, props);
});
console.log('\x1b[36m%s\x1b[0m',`${botconfig["bot_Commands_logs"].info_Loaded}`)
});
}
if(botconfig["module_toggles"].emojis_module) {
fs.readdir("./commands/emojis_module/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log('\x1b[31m%s\x1b[0m',`${botconfig["bot_Commands_logs"].emojis_error}`);
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/emojis_module/${f}`);
if(botconfig["bot_setup"].debug_mode) {
console.log(`${f} loaded!`);
}
bot.commands.set(props.help.name, props);
bot.commands.set(props.help.name2, props);
});
console.log('\x1b[36m%s\x1b[0m',`${botconfig["bot_Commands_logs"].emojis_loaded}`)
});
}
if(botconfig["module_toggles"].Randomstuff_module) {
fs.readdir("./commands/Randomstuff_module/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log('\x1b[31m%s\x1b[0m',`${botconfig["bot_Commands_logs"].Randomstuff_error}`);
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/Randomstuff_module/${f}`);
if(botconfig["bot_setup"].debug_mode) {
console.log(`${f} loaded!`);
}
bot.commands.set(props.help.name, props);
bot.commands.set(props.help.name2, props);
});
console.log('\x1b[36m%s\x1b[0m',`${botconfig["bot_Commands_logs"].Randomstuff_loaded}`)
});
}
if(botconfig["module_toggles"].Servers_module) {
fs.readdir("./commands/Servers_module/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log('\x1b[31m%s\x1b[0m',`${botconfig["bot_Commands_logs"].Servers_error}`);
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/Servers_module/${f}`);
if(botconfig["bot_setup"].debug_mode) {
console.log(`${f} loaded!`);
}
bot.commands.set(props.help.name, props);
bot.commands.set(props.help.name2, props);
});
console.log('\x1b[36m%s\x1b[0m',`${botconfig["bot_Commands_logs"].Servers_loaded}`)
});
}
if(botconfig["module_toggles"].level_module) {
fs.readdir("./commands/level_module/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log('\x1b[31m%s\x1b[0m',`${botconfig["bot_Commands_logs"].Level_error}`);
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/level_module/${f}`);
if(botconfig["bot_setup"].debug_mode) {
console.log(`${f} loaded!`);
}
bot.commands.set(props.help.name, props);
bot.commands.set(props.help.name2, props);
});
console.log('\x1b[36m%s\x1b[0m',`${botconfig["bot_Commands_logs"].Level_loaded}`)
});
}
if(botconfig["module_toggles"].giveaway_module) {
fs.readdir("./commands/giveaway_module/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log('\x1b[31m%s\x1b[0m',`${botconfig["bot_Commands_logs"].Giveaway_error}`);
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/giveaway_module/${f}`);
if(botconfig["bot_setup"].debug_mode) {
console.log(`${f} loaded!`);
}
bot.commands.set(props.help.name, props);
bot.commands.set(props.help.name2, props);
});
console.log('\x1b[36m%s\x1b[0m',`${botconfig["bot_Commands_logs"].Giveaway_loaded}`)
});
}
if(botconfig["module_toggles"].verify_module) {
fs.readdir("./commands/verify_module/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log('\x1b[31m%s\x1b[0m',`${botconfig["bot_Commands_logs"].Verify_error}`);
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/verify_module/${f}`);
if(botconfig["bot_setup"].debug_mode) {
console.log(`${f} loaded!`);
}
bot.commands.set(props.help.name, props);
bot.commands.set(props.help.name2, props);
});
console.log('\x1b[36m%s\x1b[0m',`${botconfig["bot_Commands_logs"].Verify_loaded}`)
});
}
if(botconfig["module_toggles"].memes_module) {
fs.readdir("./commands/memes_module/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log('\x1b[31m%s\x1b[0m',`${botconfig["bot_Commands_logs"].Memes_error}`);
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/memes_module/${f}`);
if(botconfig["bot_setup"].debug_mode) {
console.log(`${f} loaded!`);
}
bot.commands.set(props.help.name, props);
bot.commands.set(props.help.name2, props);
});
console.log('\x1b[36m%s\x1b[0m',`${botconfig["bot_Commands_logs"].Memes_loaded}`)
});
}
if(botconfig["module_toggles"].nsfw_module) {
fs.readdir("./commands/nsfw_module/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log('\x1b[31m%s\x1b[0m',`${botconfig["bot_Commands_logs"].NSFW_error}`);
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/nsfw_module/${f}`);
if(botconfig["bot_setup"].debug_mode) {
console.log(`${f} loaded!`);
}
bot.commands.set(props.help.name, props);
bot.commands.set(props.help.name2, props);
});
console.log('\x1b[36m%s\x1b[0m',`${botconfig["bot_Commands_logs"].NSFW_loaded}`)
});
}
if(botconfig["module_toggles"].economy_module) {
fs.readdir("./commands/economy_module/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log('\x1b[31m%s\x1b[0m',`${botconfig["bot_Commands_logs"].Economy_error}`);
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/economy_module/${f}`);
if(botconfig["bot_setup"].debug_mode) {
console.log(`${f} loaded!`);
}
bot.commands.set(props.help.name, props);
bot.commands.set(props.help.name2, props);
});
console.log('\x1b[36m%s\x1b[0m',`${botconfig["bot_Commands_logs"].Economy_loaded}`)
});
}
if(botconfig["module_toggles"].invite_module) {
fs.readdir("./commands/invite_module/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log('\x1b[31m%s\x1b[0m',`${botconfig["bot_Commands_logs"].invite_error}`);
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/invite_module/${f}`);
if(botconfig["bot_setup"].debug_mode) {
console.log(`${f} loaded!`);
}
bot.commands.set(props.help.name, props);
bot.commands.set(props.help.name2, props);
});
console.log('\x1b[36m%s\x1b[0m',`${botconfig["bot_Commands_logs"].invite_loaded}`)
});
}
if(botconfig["module_toggles"].GameStats_module) {
fs.readdir("./commands/GameStats_module/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log('\x1b[31m%s\x1b[0m',`${botconfig["bot_Commands_logs"].GameStats_error}`);
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/GameStats_module/${f}`);
if(botconfig["bot_setup"].debug_mode) {
console.log(`${f} loaded!`);
}
bot.commands.set(props.help.name, props);
bot.commands.set(props.help.name2, props);
});
console.log('\x1b[36m%s\x1b[0m',`${botconfig["bot_Commands_logs"].GameStats_loaded}`)
});
}
if(botconfig["module_toggles"].Music_module) {
fs.readdir("./commands/Music_module/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log('\x1b[31m%s\x1b[0m',`${botconfig["bot_Commands_logs"].music_error}`);
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/Music_module/${f}`);
if(botconfig["bot_setup"].debug_mode) {
console.log(`${f} loaded!`);
}
bot.commands.set(props.help.name, props);
bot.commands.set(props.help.name2, props);
});
console.log('\x1b[36m%s\x1b[0m',`${botconfig["bot_Commands_logs"].music_loaded}`)
});
}
if(botconfig["module_toggles"].Help_module) {
fs.readdir("./commands/Help_module/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log('\x1b[31m%s\x1b[0m',`${botconfig["bot_Commands_logs"].help_error}`);
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/Help_module/${f}`);
if(botconfig["bot_setup"].debug_mode) {
console.log(`${f} loaded!`);
}
bot.commands.set(props.help.name, props);
bot.commands.set(props.help.name2, props);
});
console.log('\x1b[36m%s\x1b[0m',`${botconfig["bot_Commands_logs"].help_loaded}`)
});
}
bot.on('error', console.error);
bot.on("ready", async () => {
console.log('\x1b[32m%s\x1b[0m',`${botconfig["bot_messages"].Online_log} ${bot.guilds.size} servers.`);
bot.user.setPresence(botconfig["bot_setup"].bot_game, {type: botconfig["bot_setup"].bot_game_type});
bot.user.setStatus(botconfig["bot_setup"].bot_status)
})
bot.on("guildCreate", server => {
if(botconfig["module_toggles"].Bot_Server_Add_message) {
let embed = new Discord.MessageEmbed()
.setTitle(`${botconfig["bot_messages"].Thanks_message}`)
.addField('Bot Name',`${botconfig["bot_messages"].Bot_name}`)
.addField('Darks',`${botconfig["bot_messages"].Important}`)
.addField('Darks Prefix',`${botconfig["bot_setup"].prefix}`)
.addField('invite',`${botconfig["bot_links"].invite}`)
.addField('Forum',`${botconfig["bot_links"].Forum}`)
.addField('Donate',`${botconfig["bot_links"].Donate}`)
.addField('Support Server', `${botconfig["bot_links"].Support_Server}`)
.addField('Store', `${botconfig["bot_links"].Store}`)
.setColor(botconfig["bot_setup"].main_embed_color)
.setFooter(botconfig["bot_setup"].copyright);
server.owner.send(embed);
}
});
bot.on("message", async message => {
if(message.author.bot) return;
if(message.channel.type === "dm") return;
let prefix = botconfig["bot_setup"].prefix;
let messageArray = message.content.split(" ");
let cmd = messageArray[0].toLowerCase();
let args = messageArray.slice(1);
if (!message.content.startsWith(prefix)) return;
let commandfile = bot.commands.get(cmd.slice(prefix.length));
if(commandfile) commandfile.run(bot, message, args);
// Bot Command Logs
if(botconfig["module_toggles"].mod_logs) {
const cmdChannel = message.guild.channels.cache.find(channel => channel.id === botconfig["channel_setup"].command_logs_channel);
if(!cmdChannel) return console.log("Channel not found (Config: 'commands_logs_channel')");
const logEmbed = new Discord.MessageEmbed()
.setAuthor("Command Logs")
.setColor(botconfig["bot_setup"].main_embed_color)
.setDescription(`**${message.author} (${message.author.tag})** used command: \n\`\`\`css\n${cmd} ${args}\`\`\``.split(',').join(' '))
.setTimestamp()
cmdChannel.send(logEmbed)
}
});
// Welcome message
bot.on('guildMemberAdd', member => {
if(botconfig["module_toggles"].role) {
var role = member.guild.roles.find(role => role.id === botconfig["join_roles"].role);
if (!role) return console.log("role not found (Config: 'role')");
member.addRole(role);
}
if(botconfig["module_toggles"].welcome) {
// Send the message to a designated channel on a server:
const channel = member.guild.channels.find(channel => channel.id === botconfig["channel_setup"].welcome_channel);
// Do nothing if the channel wasn't found on this server
if (!channel) return;
// Send the message, mentioning the member
let embed1 = new Discord.MessageEmbed()
.setTitle(`${botconfig["bot_messages"].Welcome_message} ${member.user.tag}`, member.user.displayAvatarURL)
//.setAuthor(`Welcome to the Discord server,`, member.user.displayAvatarURL,)
.setThumbnail(member.user.displayAvatarURL)
.addField('Date Joined', member.user.createdAt, true)
.addField('Total Members', member.guild.memberCount, true)
channel.send(embed1);
}
});
// Leave Message
bot.on('guildMemberRemove', member => {
if(botconfig["module_toggles"].leave) {
// Send the message to a designated channel on a server:
const channel = member.guild.channels.find(channel => channel.id === botconfig["channel_setup"].leave_channel);
// Do nothing if the channel wasn't found on this server
if (!channel) return;
// Send the message, mentioning the member
let embed2 = new Discord.MessageEmbed()
//.setTitle("leave")
.setAuthor(`${member.user.tag} Has left the server.`, member.user.displayAvatarURL,)
.setThumbnail(member.user.displayAvatarURL)
.addField('Date Joined', member.user.createdAt, true)
.addField('Total Members', member.guild.memberCount, true)
channel.send(embed2);
}
});
// Message Delete Logger
bot.on("messageDelete", message => {
if(botconfig["module_toggles"].logs) {
if (message.channel.type === 'dm') return;
if (message.content.startsWith("!")) return undefined;
if (message.content.startsWith(".")) return undefined;
if (message.content.startsWith("?")) return undefined;
if (message.content.startsWith("-")) return undefined;
if (message.content.startsWith("--")) return undefined;
if (message.author.bot) return undefined;
if (message.content.length > 1020) return undefined;
let logEmbed = new Discord.MessageEmbed()
.setAuthor("Action Logs", bot.user.avatar_url)
.setColor(botconfig["bot_setup"].main_embed_color)
.setTimestamp()
.setFooter(`${botconfig["bot_setup"].copyright}`)
.setDescription("**Action:** Message Delete")
.addField("Message Author:", `${message.author.toString()} - Hash: ${message.author.tag} - ID: ${message.author.id}`)
.addField("Channel:", message.channel)
.addField("Message Content:", `${message.content}.`)
let logChannel = message.guild.channels.cache.find(channel => channel.id === botconfig["channel_setup"].general_logs_channel);
if (!logChannel) return console.log("leave channel not found (Config: 'general_logs_channel')");
logChannel.send(logEmbed);
}
});
// Message Edit Logger
bot.on("messageUpdate", (oldMessage, newMessage) => {
if(botconfig["module_toggles"].logs) {
if (oldMessage.author.bot) return undefined;
if (oldMessage.content.length > 1020) return undefined;
if (newMessage.content.length > 1020) return undefined;
if (!oldMessage.guild) return undefined;
let logEmbed = new Discord.MessageEmbed()
.setAuthor("Action Logs", bot.user.avatar_url)
.setColor(botconfig["bot_setup"].main_embed_color)
.setTimestamp()
.setFooter(`${botconfig["bot_setup"].copyright} `)
.setDescription("**Action:** Message Edited")
.addField("Old Content", `${oldMessage.content}.`)
.addField("New Content", `${newMessage.content}.`)
.addField("Message Author:", `${newMessage.author.toString()} - Hash: ${newMessage.author.tag} - ID: ${newMessage.author.id}`)
.addField("Channel", oldMessage.channel)
let logChannel = newMessage.guild.channels.cache.find(channel => channel.id === botconfig["channel_setup"].general_logs_channel);
if (!logChannel) return console.log("leave channel not found (Config: 'general_logs_channel')");
logChannel.send(logEmbed);
}
});
// Member Update Logger
bot.on("guildMemberUpdate", async (oldMember, newMember) => {
setTimeout(async () => {
var Change = {
rolesGiven: {
update: false,
updateArray: ""
},
rolesRemoved: {
update: false,
updateArray: ""
},
nickname: {
update: false,
updateArray: []
}
};
const entry = await newMember.guild.fetchAuditLogs({ type: 'MEMBER_UPDATE' }).then(audit => audit.entries.first())
oldMember.roles.forEach(function(rInfo) {
if (newMember.roles.find(roles => roles.id == rInfo.id) == null)
{
Change.rolesRemoved.updateArray = rInfo.id;
Change.rolesRemoved.update = true;
}
});
newMember.roles.forEach(function(rInfo) {
if (oldMember.roles.find(roles => roles.id == rInfo.id) == null)
{
Change.rolesGiven.updateArray = rInfo.id;
Change.rolesGiven.update = true;
}
});
// Check If Member Has Been Given A New Nickname
if (oldMember.nickname !== newMember.nickname) {
Change.nickname.updateArray.push({newNickname: newMember.nickname != null ? newMember.nickname : newMember.guild.members.get(newMember.id).user.username, oldNickname: oldMember.nickname != null ? oldMember.nickname : oldMember.guild.members.get(oldMember.id).user.username});
Change.nickname.update = true;
}
if (Change.nickname.update) {
let cName = Change.nickname.updateArray[0];
let oldName = cName.oldNickname;
let newName = cName.newNickname;
let member = newMember.guild.members.get(entry.target.id);
let logEmbed = new Discord.MessageEmbed()
.setAuthor("Action Logs", bot.user.avatarURL)
.setColor(botconfig["bot_setup"].main_embed_color)
.setTimestamp()
.setFooter(`${botconfig["bot_setup"].copyright} `)
logEmbed.setDescription("**Action:** Nickname Changed")
if (entry.executor.id == newMember.id) {
logEmbed.addField(`Changed By`, `${entry.executor} ( By Himself/Herself )`, true);
} else {
logEmbed.addField(`Changed By`, `${entry.executor}`, true);
}
logEmbed.addField("Target User", `${member} - ${member.user.tag}`, true)
logEmbed.addField("Old Nickname", oldName)
logEmbed.addField("New Nickname", newName)
let logChannel = message.guild.channels.cache.find(channel => channel.id === botconfig["channel_setup"].general_logs_channel);
if(!logChannel) return console.log("Channel not found (Config: 'general_logs_channel')");
logChannel.send(logEmbed);
}
if (Change.rolesGiven.update) {
let addedRole = Change.rolesGiven.updateArray;
let logEmbed = new Discord.MessageEmbed()
.setAuthor("Action Logs", bot.user.avatarURL)
.setColor(botconfig["bot_setup"].main_embed_color)
.setTimestamp()
.setFooter(`${botconfig["bot_setup"].copyright} `)
logEmbed.setDescription("**Action:** Roles Added")
logEmbed.addField("Target User", `${newMember} - ${newMember.user.tag}`, true)
logEmbed.addField("Role Added", `<@&${addedRole}>`)
let logChannel = oldMember.guild.channels.find(channel => channel.id === botconfig["channel_setup"].general_logs_channel);
if(!logChannel) return console.log("Channel not found (Config: 'general_logs_channel')");
logChannel.send(logEmbed);
}
if (Change.rolesRemoved.update) {
let removedRole = Change.rolesRemoved.updateArray
let logEmbed = new Discord.MessageEmbed()
.setAuthor("Action Logs", bot.user.avatarURL)
.setColor(botconfig["bot_setup"].main_embed_color)
.setTimestamp()
.setFooter(`${botconfig["bot_setup"].copyright} `)
logEmbed.setDescription("**Action:** Roles Removed")
logEmbed.addField("Target User", `${newMember} - ${newMember.user.tag}`, true)
logEmbed.addField("Role Removed", `<@&${removedRole}>`)
let logChannel = oldMember.guild.channels.find(channel => channel.id === botconfig["channel_setup"].general_logs_channel);
if(!logChannel) return console.log("Channel not found (Config: 'general_logs_channel')");
logChannel.send(logEmbed);
}
}, 200);
});
// Filters
if(botconfig["module_toggles"].filter_lang_links) {
bot.on("message", message => {
if(message.channel.type === 'dm') return;
if (message.author.bot) return;
if (!message.guild) return;
if(message.member.hasPermission("ADMINISTRATOR")) return; // This may crash or give errors. Not 100% sure why...
let allowedRole = message.guild.roles.find(role => role.name === botconfig["filter_module"].language_bypass_role);
switch (true) {
case message.member.roles.has(allowedRole.id):
return;
case new RegExp(botconfig["filter_module"].filter_words.join("|")).test(message.content.toLowerCase()):
return message.channel.send(`${botconfig["bot_messages"].use_language_message}`).then(msg => msg.delete(10000));
};
});
bot.on("message", message => {
if(message.channel.type === 'dm') return;
if (message.author.bot) return;
if (!message.guild) return;
if(message.member.hasPermission("ADMINISTRATOR")) return; // This may crash or give errors. Not 100% sure why...
let allowedRole = message.guild.roles.find(role => role.name === botconfig["filter_module"].link_bypass_role);
switch (true) {
case message.member.roles.has(allowedRole.id): // Debug Error Code: ERRID08
return;
case new RegExp(botconfig["filter_module"].filter_links.join("|")).test(message.content.toLowerCase()):
return message.channel.send(`${botconfig["bot_messages"].post_language_message}`).then(msg => msg.delete(10000));
};
});
}
bot.login(botconfig["bot_setup"].token); |
import { TestScheduler } from "@jest/core"
import { login , logout } from "../../actions/auth"
test("Should generate login action object " , () => {
const action = login( "1578" )
expect(action).toEqual({
type : "Login" ,
uid : "1578"
})
})
test("Should generate logout action object" , () => {
const action = logout()
expect(action).toEqual({
type : "Logout"
})
}) |
var searchData=
[
['estadistica',['Estadistica',['../classdomini_1_1estadistica_1_1Estadistica.html',1,'domini::estadistica']]]
];
|
(function() {
'use strict';
angular
.module('app')
.config(config);
config.injector = ['$stateProvider', '$urlRouterProvider'];
function config($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('todos', {
url: '/todos',
templateUrl: 'templates/todos/index.html',
controller: 'TodosController',
controllerAs: 'todos'
});
$stateProvider
.state('todosNew', {
url: '/todos/new',
templateUrl: 'templates/todos/new.html',
controller: 'TodosController',
controllerAs: 'todos'
});
}
})();
|
// Anonymous Function. // window.onload and btn.onclick both are anonymous function.
window.onload = function(){
//do all binding here
var btn = document.getElementById("btnAdd");
btn.onclick = function(){
console.log("Handling Add New Todo Button");
};
};
|
import Race from './Race';
import Dwarf from './Dwarf';
export default class Duergar extends Dwarf {
constructor() {
super('duergar');
this.statMods.strength = 1;
}
} |
import React from "react";
import { action } from "@storybook/addon-actions";
import { InputStory } from "../Input.stories.styles";
import Input from "../../src";
const UncontrolledExample = () => {
return (
<InputStory>
<Input
defaultValue="hello world"
hasClearButton
onChange={event => {
action("value changed")(event.target.value);
}}
/>
</InputStory>
);
};
export default UncontrolledExample;
|
import React, { Component } from "react";
import { imagePath } from '../../utils/assetUtils';
import styles from './compareProduct.scss';
import PropTypes from 'prop-types';
import { Row, Col } from 'reactstrap';
import StarRating from '../../components/StarRating/starRating';
import { connect } from 'react-redux';
import * as actions from '../../modules/detailPage/actions';
import * as wishlistActions from '../../modules/wishlist/actions';
import { getDataFromResponse, formatMoney, getChargeType } from "../../utils/utilities";
const mapStateToProps = state => ({
wishlistId: state.wishlist.current.wishlist_id,
});
const mapDispatchToProps = dispatch => ({
dispatch
});
class CompareProduct extends Component {
state = {
gallery : []
}
componentWillMount() {
this.props.dispatch(actions.fetchVendorGallery(String(this.props.data.vendor_id))).then((respose) => {
if(getDataFromResponse(respose) == null){
this.setState({gallery: respose.data.data.gallery})
}
})
}
renderGallery = (gallery) => {
const images = gallery.map((image, index) => {
return(
<Col md="6" className="p-1" key={index}>
<img src={image.image} className={styles.galleryImage} alt="gallery" />
</Col>
);
});
return <Row className="m-0">{images}</Row>;
}
removeFromWishList(vendor) {
let params = {
vendor_id: this.props.data.vendor_id,
wishlist_id: this.props.wishlistId,
category_id: this.props.categoryId,
};
this.props.dispatch(wishlistActions.removeFromWishlist(params));
this.props.removeAction(vendor);
}
render() {
var vendor = this.props.data;
return (
<Col xs="6" sm="4" className={styles.compareComponent}>
<div className={styles.closeBtnSmall}>
<img src={imagePath('close-blank.svg')} alt="close button" aria-hidden onClick={() => this.props.removeAction(vendor)}/>
</div>
<img src={this.props.data.pic_url || imagePath('card_1_1.jpg')} className={styles.vendorImage} alt="Outline"
onError={(e) => { e.target.onerror = null; e.target.src = `${imagePath('card_1_1.jpg')}` }} />
<div className={styles.vendorInfo}>
<h5>{vendor.name}</h5>
<p>{vendor.city}</p>
</div>
<div className={styles.price}>
{formatMoney(vendor.price.format_price)} <span>{getChargeType(vendor.format_price,vendor.charge_type)}</span>
</div>
<div className={styles.rating}>
<StarRating rating={String(vendor.rating)} size={'small'} />
</div>
{this.state.gallery && this.state.gallery.length > 0 &&
<div className={styles.galleryWrap}>
{this.renderGallery(this.state.gallery)}
</div>
}
<div className={styles.removeBtn} onClick={() => this.removeFromWishList(vendor)} aria-hidden>
Remove from wishlist
</div>
</Col>
);
}
}
CompareProduct.propTypes = {
data: PropTypes.object,
removeAction: PropTypes.func,
dispatch: PropTypes.func,
wishlistId: PropTypes.number,
categoryId: PropTypes.number
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(CompareProduct);
|
import reviewReducer from "../../reducers/reviewReducer";
import * as types from "../../actions/types";
describe("INITIAL_STATE", () => {
it("returns initial state", () => {
const action = { type: "dummy_action" };
const initialState = { reviews: [], loading: false };
expect(reviewReducer(undefined, action)).toEqual(initialState);
});
});
describe("REVIEW_LOADING", () => {
it("returns the correct state", () => {
const initialState = { reviews: [] };
const action = { type: types.REVIEW_LOADING };
const expectedState = { reviews: [], loading: true };
expect(reviewReducer(initialState, action)).toEqual(expectedState);
});
});
describe("GET_REVIEWS", () => {
it("returns the correct state", () => {
const initialState = { reviews: [] };
const action = { type: types.GET_REVIEWS, payload: "review" };
const expectedState = { reviews: "review", loading: false };
expect(reviewReducer(initialState, action)).toEqual(expectedState);
});
});
describe("ADD_REVIEW", () => {
const initialState = { reviews: ["first review", "second review"] };
const action = { type: types.ADD_REVIEW, payload: "new review" };
const expectedState = {
reviews: ["new review", "first review", "second review"]
};
expect(reviewReducer(initialState, action)).toEqual(expectedState);
});
|
module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
var taskList = [];
var karmaOptions = require('./build/karma_options')();
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
mangle: true
},
build: {
src: "./assets/js/*.js",
dest: "./assets/js/min/script.js"
}
},
handlebars: {
compile: {
options: {
amd: true,
namespace: 'template',
processName: function (filePath) {
var file = filePath.split('/');
return file[file.length - 1].split('.')[0];
}
},
// output file: input files
files: {
'./assets/js/compiled_templates.js': './assets/**/*.hbs'
}
}
},
karma: {
validate: {
options : karmaOptions
}
},
coverage: {
options: {
thresholds: {
'statements': 60,
'branches': 60,
'funcitons': 60,
'lines': 60
},
dir : './karma_code_coverage/coverage_json',
root: ''
}
}
});
taskList = ['uglify', 'handlebars', 'karma:validate'];
grunt.registerTask('build', taskList);
}; |
import React, {Component} from 'react'
import ReactDOM from 'react-dom'
import _ from 'lodash'
import Alert from '../../../../shared/Alert'
import SaveButton from '../../../../shared/SaveButton'
import { Link } from 'react-router'
import Select from 'react-select'
import 'react-select/dist/react-select.css'
import Notification from 'react-notification-system'
class BatchForm extends Component{
constructor(props){
super(props)
if (props.params.id!='add'){
this.props.edit(this.props.params.id)
}else{
props.add()
}
}
showNotif(msg){
this.refs.notify.addNotification({
message: msg,
level: 'success',
position: 'tc',
autoDismiss: 3
})
}
handleSubmit(e){
e.preventDefault()
if (_.isEmpty(this.props.data.branchname)){
this.props.saveFailed("Please enter branch name!")
return
}else if (_.isEmpty(this.props.data.address)){
this.props.saveFailed("Please enter address")
return
}else if (_.isEmpty(this.props.data.city)){
this.props.saveFailed("Please enter city")
return
}else if (_.isEmpty(this.props.data.phoneno)){
this.props.saveFailed("Please enter contact number")
return
}
this.props.save(this.props.data, this.props.editMode)
}
onValueChanged(e){
this.props.valueChanged(this.props.data, e.target.name, e.target.value)
}
handleBack(e){
this.context.router.push('/settings/unit/branch/list')
}
onSelectChanged(val){
this.props.headChange(val)
}
componentWillReceiveProps(nextProps){
if (nextProps.saveAddSuccess){
this.showNotif('New branch successfully created.')
setTimeout(()=>{
this.context.router.push('/settings/unit/branch/list')
},1000)
}else if (nextProps.updateSuccess){
this.showNotif('Branch successfully modified.')
setTimeout(()=>{
this.context.router.push('/settings/unit/branch/list')
},1000)
}
}
render(){
const textareaStyle = {
width: '100%'
}
const { hasError, isSaving, message, data, isFetching, editMode, title, employees} = this.props
let content = <div className="col-sm-12">
<Alert hasError={hasError} message={message}/>
<form className="form-horizontal" onSubmit={this.handleSubmit.bind(this)}>
<div className="form-group">
<label className="col-sm-3 control-label">Branch Name<sup className="required_asterisk">*</sup> </label>
<div className="col-sm-5">
<input ref="branchname" name="branchname" type="text" className="form-control" onChange={this.onValueChanged.bind(this)} value={data.branchname}/>
</div>
</div>
<div className="form-group">
<label className="col-sm-3 control-label">Address<sup className="required_asterisk">*</sup> </label>
<div className="col-sm-7">
<textarea ref="address" name="address" style={textareaStyle} className="form-control" rows="2" onChange={this.onValueChanged.bind(this)} defaultValue={data.address}></textarea>
</div>
</div>
<div className="form-group">
<label className="col-sm-3 control-label">City<sup className="required_asterisk">*</sup> </label>
<div className="col-sm-5">
<input ref="city" name="city" type="text" className="form-control" onChange={this.onValueChanged.bind(this)} value={data.city}/>
</div>
</div>
<div className="form-group">
<label className="col-sm-3 control-label">Province</label>
<div className="col-sm-5">
<input ref="province" name="province" type="text" className="form-control" onChange={this.onValueChanged.bind(this)} value={data.province}/>
</div>
</div>
<div className="form-group">
<label className="col-sm-3 control-label">Zip Code</label>
<div className="col-sm-2">
<input ref="zip" name="zip" type="text" className="form-control" onChange={this.onValueChanged.bind(this)} value={data.zipcode}/>
</div>
</div>
<div className="form-group">
<label className="col-sm-3 control-label">Contact Number<sup className="required_asterisk">*</sup> </label>
<div className="col-sm-3">
<input ref="phoneno" name="phoneno" type="text" className="form-control" onChange={this.onValueChanged.bind(this)} value={data.phoneno}/>
</div>
</div>
<div className="form-group">
<label className="col-sm-3 control-label">Head</label>
<div className="col-sm-5">
<Select name="head" value={data.head} options={employees} onChange={this.onSelectChanged.bind(this)} clearable={true} searchable={true} />
</div>
</div>
<div className="form-group">
<div className="col-sm-3"></div>
<div className="col-sm-3">
<SaveButton isSaving={isSaving} sStyle="btn btn-success btn-lg" caption=" Save " />
</div>
</div>
</form>
</div>
if (isFetching){
content = <div className="panel-body">
<i className="fa fa-refresh fa-spin fa-3x fa-fw"></i><span> loading...</span>
</div>
}
return(
<div className="panel panel-default">
<div className="panel-heading">
<h3 className="panel-title pull-left">{title}</h3>
<button onClick={this.handleBack.bind(this)} className="btn btn-default pull-right">Cancel</button>
<div className="clearfix"></div>
</div>
<div className="panel-body">
<br/>
{content}
<br/>
</div>
<Notification ref="notify"/>
</div>
)
}
}
BatchForm.contextTypes={
router: React.PropTypes.object
}
export default BatchForm
|
import React, {useContext} from 'react';
import {observer} from "mobx-react";
import {ApiStoreContext} from "../../stores/api_store";
import Link from "next/link";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faBook, faListUl, faPlus, faSearch, faSignOutAlt, faUser} from "@fortawesome/free-solid-svg-icons";
const NavLinks = observer((props) => {
const context = useContext(ApiStoreContext);
return <ul>
<li>
<Link href={context.touring ? '#' : "/"}>
<a>
<FontAwesomeIcon icon={faSearch}/> Browse Recipes
</a>
</Link>
</li>
<li>
<Link href={"/users/[user_id]/groceries"}
as={context.touring ? "#" : `/users/${context.user.id}/groceries`}>
<a>
<FontAwesomeIcon icon={faListUl}/> Grocery List
</a>
</Link>
</li>
<li>
<Link href={context.touring ? "#" : '/add'}>
<a>
<FontAwesomeIcon icon={faPlus}/> Add Recipe
</a>
</Link>
</li>
<li>
<Link href={"/users/[user_id]/recipes"} as={context.touring ? "#" : `/users/${context.user.id}/recipes`}>
<a>
<FontAwesomeIcon icon={faBook}/> My Recipes
</a>
</Link>
</li>
<li>
<Link href={"/users/[user_id]/settings"} as={context.touring ? "#" : `/users/${context.user.id}/settings`}>
<a>
<FontAwesomeIcon icon={faUser}/> Settings
</a>
</Link>
</li>
<li>
<button onClick={() => !context.touring && context.userLogout()}><FontAwesomeIcon icon={faSignOutAlt}/> Log
Out
</button>
</li>
</ul>
})
export default NavLinks;
|
/*
Noble-Sockets example
This example uses Sandeep Mistry's noble library for node.js to
create a central server that reads and connects to BLE peripherals
and sends this info to a browser with socket.io
created 15 Jan 2015
by Maria Paula Saba
*/
//importing node modules (libraries)
var noble = require('noble'),
express = require('express'),
http = require('http'),
async = require('async'),
open = require("open");
// create a server calling the function onRequest
var app = express();
var server = http.createServer(app);
// start the server
server.listen(8080);
console.log('Server is listening to http://localhost on port 8080');
open("http://localhost:8080");
//read index.html page
app.use('/public/js', express.static(__dirname + '/public/js'));
app.use('/public/css', express.static(__dirname + '/public/css'));
app.get('/', function (request, response) {
response.sendFile(__dirname + '/public/index.html');
});
//array to save all peripherals found
var peripherals = [];
//variable to save UUID for the connected peripheral
var connected = "";
//to save interval on reading RSSI
var RSSIinterval;
//Bluetooth ON or OFF
noble.on('stateChange', function(state) {
if (state === 'poweredOn') {
console.log("start scanning");
noble.startScanning();
} else {
noble.stopScanning();
console.log("stop scanning, is Bluetooth on?");
}
});
//when discover new peripheral
noble.on('discover', function(peripheral) {
var peripheralData = {
"name": peripheral.advertisement.localName,
"uuid": peripheral.uuid
}
//check if this peripheral has been found previously
var newPeripheral = true;
peripherals.forEach(function(element){
if(element.uuid === peripheral.uuid){
newPeripheral = false;
}
});
//if it is a new one
if(newPeripheral){
//save to array in server
peripherals.push(peripheral);
//send peripheral discovered to client
io.sockets.emit('peripheral', peripheralData);
}
});
//this function is called in the sockets part
function connectPeripheral(peripheral) {
noble.stopScanning();
//connect to peripheral
peripheral.connect(function(error){
console.log('connected to peripheral');
connected = peripheral.uuid;
//log some data from it
logData(peripheral);
//read RSSI every 60 seconds
RSSIinterval = setInterval(getRSSI, 60);
//callback function to once disconnect happens
peripheral.once('disconnect', function() {
console.log('peripheral disconneted');
connected = "";
clearInterval();
io.sockets.emit('disconnectedPeripheral', peripheral.uuid);
noble.startScanning();
});
});
}
function logData(peripheral){
var advertisement = peripheral.advertisement;
var localName = advertisement.localName;
var txPowerLevel = advertisement.txPowerLevel;
var manufacturerData = advertisement.manufacturerData;
console.log("Peripheral "+localName + " with UUID " + peripheral.uuid + " connected");
console.log("TX Power Level "+ txPowerLevel + ", Manufacturer "+ manufacturerData);
var data = "Peripheral with name "+localName + " and UUID " + peripheral.uuid + " has signal strenght (RSSI) of <span id='rssi'>"+ peripheral.rssi+".<span>" ;
//<br/> TX Power Level "+ txPowerLevel + ", Manufacturer "+ manufacturerData;
io.sockets.emit('dataLogged',data);
}
function getRSSI(peripheral){
for (var i = 0; i < peripherals.length; i++){
if(connected == peripherals[i].uuid){
var uuid = peripherals[i].uuid
peripherals[i].updateRssi(function(error, rssi){
//rssi are always negative values
if(rssi < 0) io.sockets.emit('rssi', {'rssi': rssi, 'uuid':uuid});
});
}
}
}
// WebSocket Portion
var io = require('socket.io').listen(server);
// This is run for each individual user that connects
io.sockets.on('connection',
// We are given a websocket object in our function. This object has an id
function (socket) {
//check if clients are connected
console.log("We have a new client: " + socket.id);
socket.on('scan', function() {
// Request to rescan
peripherals = [];
console.log("start scanning client");
noble.startScanning();
});
socket.on('explorePeripheral', function(data) {
//find the right peripheral to connect
peripherals.forEach(function(element){
if(element.uuid === connected){
element.disconnect();
}
else if(element.uuid === data){
connectPeripheral(element);
}
});
});
socket.on('disconnectPeripheral', function(data) {
//find the right peripheral to disconnect
peripherals.forEach(function(element){
if(element.uuid === data){
element.disconnect();
console.log('peripheral disconnet requested by client');
}
});
});
socket.on('disconnect', function() {
//check if clients have disconnected
console.log("Client has disconnected");
clearInterval(RSSIinterval);
noble.startScanning();
});
}
); |
require("../common/vendor.js"), (global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/building/_components/_content" ], {
"0d66": function(n, e, o) {
Object.defineProperty(e, "__esModule", {
value: !0
}), e.default = void 0;
var t = {
mixins: [ function(n) {
return n && n.__esModule ? n : {
default: n
};
}(o("b159")).default ],
components: {
BuildingQr: function() {
o.e("pages/building/_components/_qr").then(function() {
return resolve(o("a642"));
}.bind(null, o)).catch(o.oe);
},
CollapseBtn: function() {
o.e("pages/building/_components/_collapse_btn").then(function() {
return resolve(o("d190"));
}.bind(null, o)).catch(o.oe);
}
},
data: function() {
return {
howmany: 3
};
},
computed: {
show_qr: function() {
var n = this, e = [ "surplus_houses_price", "surplus_houses_presell_no", "metros" ].filter(function(e) {
return n.is_selling && n.house[e];
}).length;
return this.house.house_info && (e += this.house.house_info.length > 2), e;
},
metros: function() {
return this.house.metros && this.house.metros.length ? this.house.metros.map(function(n) {
return {
name: n,
ongoing: n.indexOf("在建") > -1
};
}) : [];
},
show_audio: function() {
var n = this.house.audios;
return Boolean(n && n.length);
},
audio_url: function() {
return "/pages/building/audio/main?building_id=".concat(this.house.id);
},
showInfoCollapse: function() {
return this.house.house_info && this.house.house_info.length > 5;
},
presell_nos: function() {
var n = this.house.surplus_houses_presell_no;
return n ? n.split(",") : [];
},
presell_nos_slice: function() {
return this.presell_nos.slice(0, this.howmany);
},
showCollapse: function() {
return this.presell_nos.length > 3;
},
showEllipsis: function() {
return this.showCollapse && 3 === this.howmany ? "..." : "";
}
},
methods: {
goLocation: function() {
var n = this.house, e = n.latitude, o = n.longitude, t = n.name, s = n.address;
e && o && wx.openLocation({
latitude: Number(e),
longitude: Number(o),
name: t,
address: s
});
},
onShowAll: function(n) {
this.howmany = n ? this.presell_nos.length : 3;
},
onShowAllInfo: function(n) {
this.$emit("onCollapse", n);
}
},
props: {
house: {
type: Object,
default: {}
},
is_opened: {
type: Boolean,
default: !1
},
is_business: {
type: Boolean,
default: !1
},
is_selling: {
type: Boolean,
default: !1
},
show_surplus_houses: {
type: Boolean,
default: !1
},
baseinfos: {
type: Array,
default: []
},
macode_url: {
type: String
}
}
};
e.default = t;
},
"1cd3": function(n, e, o) {
o.r(e);
var t = o("f872"), s = o("85b4");
for (var u in s) [ "default" ].indexOf(u) < 0 && function(n) {
o.d(e, n, function() {
return s[n];
});
}(u);
o("8405");
var i = o("f0c5"), l = Object(i.a)(s.default, t.b, t.c, !1, null, "429ebc72", null, !1, t.a, void 0);
e.default = l.exports;
},
2708: function(n, e, o) {},
8405: function(n, e, o) {
var t = o("2708");
o.n(t).a;
},
"85b4": function(n, e, o) {
o.r(e);
var t = o("0d66"), s = o.n(t);
for (var u in t) [ "default" ].indexOf(u) < 0 && function(n) {
o.d(e, n, function() {
return t[n];
});
}(u);
e.default = s.a;
},
f872: function(n, e, o) {
o.d(e, "b", function() {
return t;
}), o.d(e, "c", function() {
return s;
}), o.d(e, "a", function() {});
var t = function() {
var n = this;
n.$createElement;
n._self._c;
}, s = [];
}
} ]), (global.webpackJsonp = global.webpackJsonp || []).push([ "pages/building/_components/_content-create-component", {
"pages/building/_components/_content-create-component": function(n, e, o) {
o("543d").createComponent(o("1cd3"));
}
}, [ [ "pages/building/_components/_content-create-component" ] ] ]); |
var emails = [
"sergio.gouvei@academiadecodigo.org",
"jorge.antunes@academiadecodigo.org",
"pedro.antoninho@academiadecodigo.org",
"123sdgj1g@com",
"balbalbal..asdsad@academiadecodigo.org",
"@ntunes@gmail.com",
"sadasdasd.com"
];
var validEmails = [];
var emailValidator = new RegExp("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$", "i");
for(var i = 0; i< emails.length; i++){
if(emails[i].match(emailValidator)){
validEmails.push(emails[i]);
}
}
console.log(validEmails);
|
import React, { PureComponent } from 'react';
import { Progress, Col, Row } from 'antd';
export default class MonthlyReport extends PureComponent {
static defaultProps = {
chats: 0,
offlineMessages: 0,
messages: 0,
rates: 0,
favorablePercent: 0,
criticalPercent: 0
};
render() {
let { chats, offlineMessages, messages, rates, favorablePercent, criticalPercent } = this.props;
let offlinePercent = chats ? Math.round(offlineMessages * 100 / messages) : 0;
const percentFormat = (percent) => percent + '%';
return (
<div>
<Row gutter={24}>
<Col lg={12} md={24}>
<div>
<div>
<div style={{padding: '10px 0', fontSize: '16px'}}>
<b>Monthly chats:<span style={{margin: '0 10px'}}>{ chats }</span></b>
</div>
</div>
<div>
<div style={{padding: '10px 0', fontSize: '16px'}}>
<b>Monthly messages:<span style={{margin: '0 10px'}}>{ messages }</span></b>
</div>
</div>
<div>
<div style={{padding: '10px 0', fontSize: '16px'}}><b>offline messages:</b></div>
<div style={{padding: '10px 0', fontSize: '16px'}}>
<Progress percent={ offlinePercent }
format={ (percent) => offlineMessages }/>
</div>
</div>
</div>
</Col>
<Col lg={12} md={24}>
<Col lg={12} md={24}>
<div style={{ textAlign: 'center' }}>
<Progress type="circle" percent={ favorablePercent }
format={ percentFormat }/>
<div style={{padding: '10px 0'}}>favorable rates</div>
</div>
</Col>
<Col lg={12} md={24}>
<div style={{ textAlign: 'center' }}>
<Progress type="circle" percent={ criticalPercent }
format={ percentFormat }/>
<div style={{padding: '10px 0', color: '#f69899'}}>critical rates</div>
</div>
</Col>
<div style={{ padding: '10px 0', textAlign: 'center', fontSize: '16px' }}>
<b>Monthly rates: { rates }</b>
</div>
</Col>
</Row>
</div>
);
}
} |
const EmployeeController = require('./employee.controller');
const Joi = require('joi');
module.exports = [
{
path: '/employees',
method: 'GET',
config: {
handler: EmployeeController.find,
tags: ['api','Employees'],
description: 'Find all Employees',
notes: 'Returns all Employees',
validate:{
headers:Joi.object({
'authorization' : Joi.string().required()
}).unknown()
}
}
},
{
path: '/employees',
method: 'POST',
config: {
handler: EmployeeController.create,
validate: {
payload: Joi.object().keys({
name: Joi.string().required(),
age: Joi.number().required(),
bornDate: Joi.date().required(),
role: Joi.string().required(),
}),
headers:Joi.object({
'authorization' : Joi.string().required()
}).unknown()
},
tags: ['api','Employee'],
description:'Create new Employee',
notes: 'Returns newly created Employee'
}
},
{
path: '/employees/{id}',
method: 'GET',
config: {
handler: EmployeeController.findOne,
validate: {
params: Joi.object().keys({
id: Joi.string().required()
}),
headers:Joi.object({
'authorization' : Joi.string().required()
}).unknown()
},
tags: ['api','Employee'],
description:'Find a employee by id',
notes: 'Returns employee requested by id'
}
},
]; |
import $ from 'jquery'
export default class Modal {
constructor(elem) {
this.elem = elem
this.targetPhoto = this.elem.getAttribute('data-large')
this.target = document.querySelectorAll('.modal__content')[0]
this.targetWrap = this.target.querySelectorAll('.modal__wrap')[0]
this.close = this.target.querySelectorAll(`[data-modal-role="close"]`)[0]
this.overlay = document.querySelectorAll(`[data-modal-role="overlay"]`)[0]
this.photoParam = document.querySelectorAll('.modal__photo')[0]
this.showClass = 'is-show'
this.closeClass = 'is-close'
this.showFlg = false
this.init()
}
init() {
this.bindEvents()
}
bindEvents() {
this.elem.addEventListener('click', () => {
if (!this.showFlg) this.showModal()
})
// overlayが共通なので、flgで管理
this.target.addEventListener('click', () => {
if (this.showFlg) this.hideModal()
})
this.close.addEventListener('click', () => {
if (this.showFlg) this.hideModal()
})
}
showModal() {
this.showFlg = true
this.overlay.classList.add(this.showClass)
this.close.classList.add(this.showClass)
this.target.classList.add(this.showClass)
this.targetWrap.classList.add(this.showClass)
document.documentElement.style.overflow = 'hidden'
if (this.targetPhoto) {
this.addPhoto()
}
}
addPhoto() {
// const movieParam = this.movieTarget.getAttribute('data-modal-movie-param')
let addImage = document.createElement('div')
// const addElem = `
// <img src="${this.targetPhoto}" alt="">
// `
addImage.innerHTML = `
<img src="${this.targetPhoto}" alt="">
`
this.photoParam.appendChild(addImage)
/* movieParam.appendChild(addElem) */
}
hideModal() {
this.showFlg = false
// close時にで小さくする為に、closeのclassを付与
this.overlay.classList.remove(this.showClass)
this.target.classList.remove(this.showClass)
this.close.classList.remove(this.showClass)
document.documentElement.style.overflow = 'auto'
if (this.photoParam) {
this.removeMovie()
}
}
removeMovie() {
this.photoParam.textContent = null
}
}
|
import React from 'react';
import images from '../../images/index.js';
import Thumbnail from '../Thumbnail'
class TableBody extends React.Component {
render() {
return (
<tbody>
{this.props.list.map((item, index) => {
return (
<tr>
<td><Thumbnail src={images[item.img]} alt={item.alt} /></td>
<td>{item.name}</td>
<td>{item.price}</td>
<td>{item.description}</td>
<td>
<button onClick={() => this.props.onDelete(index)}>
<i>Delete</i>
</button>
</td>
</tr>
);
})}
</tbody>);
}
}
export default TableBody;
|
/** @jsxImportSource @emotion/react */
import { css } from '@emotion/react';
import styled from '@emotion/styled';
import me from '../../assets/DannySnow2.jpg';
const LandingAbout = () => {
const renderLittleBit = (float) => (
<LittleBit float={float}>
<span> A little bit </span>
{!float && <div> </div>}
<div><span css={css`color: #4AF626`}> about </span> me</div>
</LittleBit>
)
return (
<AboutWrapper>
{ renderLittleBit()}
<ImageDiv>
{ renderLittleBit(true) }
<Image width="198px" src={me} alt="me in the snow"/>
<StyledP>
I have a steady foundation of React and Javascript, as well as a solid understanding of HTML and CSS. I am well versed in Ruby on Rails, and have been using PostgreSQL. I am also familiar with Node/Express, as well as some PHP.
</StyledP>
<StyledP>
I can adapt well to new projects and work environments, and I recognize the importance of a good team dynamic. I understand that getting along well with others can be as important as solving a challenging coding problem.
</StyledP>
<StyledP>
Whether working with others in an organization, or on my own, I am motivated to produce results, and I always push myself to do better than before. Most of all, I enjoy learning new things along the way and having some fun in the process!
</StyledP>
</ImageDiv>
</AboutWrapper>
)
};
const AboutWrapper = styled.div`
padding: 0 1rem;
display: flex;
justify-content: center;
flex-direction: column;
color: white;
@media (min-width: 1024px) {
padding: 0 2rem;
}
`;
const Image = styled.img`
@media (min-width: 500px) {
float: right;
margin-left: 1rem;
}
`;
const ImageDiv = styled.div`
display: flex;
align-items: center;
flex-direction: column;
max-width: 1024px;
margin: auto;
@media (min-width: 500px) {
display: block;
}
`;
const LittleBit = styled.div`
font-family: "Sulphur Point";
font-size: 24px;
text-align: center;
padding: 1rem 0;
@media (min-width: 500px) {
font-size: 28px;
}
${props => props.float
?
`
float: left;
padding: 0rem 2rem 0 0rem;
font-size: 36px;
display: none;
@media (min-width: 1075px) {
display: block;
}
`
:
`
display: flex;
justify-content: center;
@media (min-width: 1075px) {
display: none;
}
`
}
`;
const StyledP = styled.p`
min-width: calc(320px - 2rem);
margin-top: 0;
margin-bottom: 32px;
`;
export default LandingAbout;
|
import React, {PropTypes, Component} from 'react';
export class Provider extends Component {
static childContextTypes = {
store: React.PropTypes.object
};
getChildContext() {
return {store: this.props.store};
}
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
export const connect = (mapStateToProps, mapDispatchToProps) => (WrappedComponent) => {
class ConnectInnerComponent extends Component {
static contextTypes = {
store: PropTypes.object.isRequired
};
componentDidMount() {
const {store} = this.context;
this.listener = store.subscribe(() => {
this.forceUpdate()
})
}
componentWillUnmount() {
this.listener()
}
render() {
const {store} = this.context;
return (
<WrappedComponent
{...this.props}
{...mapStateToProps(store.getState())}
{...mapDispatchToProps(store.dispatch)}
/>
)
}
}
return ConnectInnerComponent;
}; |
import { combineReducers } from "redux"
import user from "./userReducer"
//combining our reducers so they can work async
export default combineReducers({
user
});
|
/**
*
* @authors zx.wang (zx.wang1991@gmail.com)
* @date 2016-06-30 11:06:15
* @version $Id$
*/
/**
* Q:Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
* For example,
* If n = 4 and k = 2, a solution is:
*
* [
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
*/
/**
* 题目翻译:
* 给定两个整型数组n和k,要求返由k个数组成的combination,其实应该叫做组合.
* 这k个数是在n中任选k个数,由题意可得,这里的k应该小于或等于n.
*
* 解题思路:
* 首先第一想法应该是用递归来求解.如果要是用循环来求解,时间复杂度应该是比较恐怖了.
* 并且,这个递归是一层一层往深处去走的,
* 首先求得以1开始的看个数的combination,之后再求以2开始的,以此类推,
* 所以开始是对n个数做DFS, n-1个数做DFS...所以应该是对n(n-1)...*1做DFS.
* 在程序中,可以加一些剪枝条件来减少程序时间.
*
* 时间复杂度:
* 对n,n-1,...,1做DFS,所以时间复杂度是O(n!)
*/
/**
* @param {number} n
* @param {number} k
* @return {number[][]}
*/
let combine = function(n, k) {
let res = [],item = [];
if (n <= 0 || n < k) return res;
dfs(n, k, 1, item, res);
return res;
};
function dfs(n,k,start,item,res) {
if (item.length === k) {
let inner = [].concat(item);
res.push(inner);
return;
}
if(item.length > k) return;
for (let i = start; i <= n; i++) {
item.push(i);
dfs(n, k, i + 1, item, res);
item.splice(item.length - 1,1);
}
}
|
import React, { Component, PropTypes} from 'react';
import '../styles/HomePage.css';
const Footer = ({}) => {
return(
<div className="footer">
</div>
);
}
export default Footer;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.