text stringlengths 7 3.69M |
|---|
import {CENTS_PER_STANDARD_SEMITONE, HUMAN_MAX_FREQ, HUMAN_MIN_FREQ, STANDARD_A4} from 'util/music';
export const IS_TOUCH_SCREEN = 'ontouchstart' in window;
export const DEFAULT_TRANSPOSITION = 3 * CENTS_PER_STANDARD_SEMITONE;
export const DEGREES_IN_CIRCLE = 360;
export const RADIANS_IN_CIRCLE = Math.PI * 2;
export const VIRTUAL_FINGER_UNITS = {
CENTS: 'cents',
STEPS: 'steps',
};
export const EQ_FREQUENCIES = [];
let frequency = 2;
while(frequency < HUMAN_MAX_FREQ) {
frequency *= 2;
if (frequency >= HUMAN_MIN_FREQ && frequency <= HUMAN_MAX_FREQ) {
EQ_FREQUENCIES.push(frequency);
}
}
export const A4 = {
415: 'baroque',
427: 'classical',
428: 'classical',
429: 'classical',
430: 'classical',
430.54: 'scientific',
432: '“frequency of the universe”',
435: 'diapson normal',
439: 'new philharmonic',
[STANDARD_A4]: 'stuttgart',
452: 'old philharmonic',
466: 'chorton',
};
export const MODES = [
{
name: '(none)',
chords: [],
useModeForNaming: 1,
},
{
name: 'I Ionian (Major)',
chords: ['I', null, 'ii', null, 'iii', 'IV', null, 'V', null, 'vi', null, 'viiº'],
},
{
name: 'II Dorian',
chords: ['i', null, 'ii', 'III', null, 'IV', null, 'v', null, 'viº', 'VII', null],
},
{
name: 'III Phrygian',
chords: ['i', 'II', null, 'III', null, 'iv', null, 'vº', 'VI', null, 'vii', null],
},
{
name: 'IV Lydian',
chords: ['I', null, 'II', null, 'iii', null, 'ivº ', 'V', null, 'vi', null, 'vii'],
},
{
name: 'V Mixolydian',
chords: ['I', null, 'ii', null, 'iiiº', 'IV', null, 'v', null, 'vi', 'VII', null],
},
{
name: 'VI Aeolian (Minor)',
chords: ['i', null, 'iiº', 'III', null, 'iv', null, 'v', 'VI', null, 'VII', null],
},
{
name: 'VII Locrian',
chords: ['iº', 'II', null, 'iii', null, 'iv', 'V', null, 'VI', null, 'vii', null],
},
{
name: 'Major Pentatonic',
chords: ['I', null, 'ii', null, 'iii', null, null, 'V', null, 'vi', null, null],
useModeForNaming: 1,
},
{
name: 'Minor Pentatonic',
chords: ['i', null, null, 'III', null, 'iv', null, 'v', null, null, 'VII', null],
useModeForNaming: 6,
},
{
name: 'Blues Major',
chords: ['I', null, 'ii', null, null, 'IV', null, 'v', null, 'vi', null, null],
useModeForNaming: 1,
},
{
name: 'Blues Minor',
chords: ['i', null, null, 'III', null, 'iv', null, null, 'VI', null, 'vii', null],
useModeForNaming: 6,
},
];
export const OSCILLATOR_TYPES = {
SINE: 'sine',
SQUARE: 'square',
// SAWTOOTH: 'sawtooth',
TRIANGLE: 'triangle',
};
export const TEMPERMENT_TYPES = {
EQUAL: 'equal',
JUST: 'just',
MEANTONE: 'meantone',
PYTHAGOREAN: 'pythagorean',
};
export const CHORD_TYPES = [
{
name: 'major',
suffix: '',
textTransform: 'toUpperCase',
additionalPitches: [400, 700],
},
{
name: 'minor',
suffix: '',
textTransform: 'toLowerCase',
additionalPitches: [300, 700],
},
{
name: 'augmented',
suffix: '+',
textTransform: 'toUpperCase',
additionalPitches: [400, 800],
},
{
name: 'diminished',
suffix: 'º',
textTransform: 'toLowerCase',
additionalPitches: [300, 600],
},
{
name: 'major sixth',
suffix: <sup>6</sup>,
textTransform: 'toUpperCase',
additionalPitches: [400, 700, 900],
},
{
name: 'minor sixth',
suffix: <sup>6</sup>,
textTransform: 'toLowerCase',
additionalPitches: [300, 700, 900],
},
{
name: 'dominant seventh',
suffix: <sup>7</sup>,
textTransform: 'toUpperCase',
additionalPitches: [400, 700, 1000],
},
{
name: 'major seventh',
suffix: <sup>∆7</sup>,
textTransform: 'toUpperCase',
additionalPitches: [400, 700, 1100],
},
{
name: 'minor seventh',
suffix: <sup>7</sup>,
textTransform: 'toLowerCase',
additionalPitches: [300, 700, 1000],
},
{
name: 'augmented seventh',
suffix: <>+<sup>∆7</sup></>,
textTransform: 'toUpperCase',
additionalPitches: [400, 800, 1000],
},
{
name: 'minor-major seventh',
suffix: <sup>M7</sup>,
textTransform: 'toLowerCase',
additionalPitches: [300, 700, 1100],
},
{
name: 'diminished seventh',
suffix: <>º<sup>7</sup></>,
textTransform: 'toLowerCase',
additionalPitches: [300, 600, 900],
},
{
name: 'half-diminished seventh',
suffix: <sup>ø7</sup>,
textTransform: 'toLowerCase',
additionalPitches: [300, 600, 1000],
},
];
|
ko.bindingHandlers.for = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
if ($(element).attr("inner-source") == undefined) {
$(element).attr("inner-source", $(element).html());
}
$(element).empty();
},
update: function (element, valueAccessor, viewModel, bindingContext) {
var value = valueAccessor();
var valueUnwrapped = ko.utils.unwrapObservable(value);
$(element).empty();
for (var i = 0; i < parseInt(valueUnwrapped) ; i++) {
$($(element).attr("inner-source")).appendTo(element);
}
}
};
ko.bindingHandlers.count = {
update: function (element, valueAccessor, viewModel, bindingContext) {
var value = valueAccessor();
var valueUnwrapped = ko.utils.unwrapObservable(value);
$(element).html(valueUnwrapped.length);
}
};
ko.bindingHandlers.selectmenu = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
if ($(element).attr("inner-source") == undefined) {
$(element).attr("inner-source", $(element).html());
}
else {
$(element).html($(element).attr("inner-source"));
}
},
update: function (element, valueAccessor) {
ko.utils.unwrapObservable(valueAccessor());
$(element).selectmenu().selectmenu("refresh");
}
};
ko.bindingHandlers.listview = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
if ($(element).attr("inner-source") == undefined) {
$(element).attr("inner-source", $(element).html());
}
else {
$(element).html($(element).attr("inner-source"));
}
},
update: function (element, valueAccessor) {
ko.utils.unwrapObservable(valueAccessor());
$(element).listview().listview("refresh");
}
};
ko.bindingHandlers.slider = {
init: function (element, valueAccessor) {
var val = valueAccessor()();
var el = $(element);
el.slider({ value: val });
el.off("change");
el.on("change", function (event, ui) {
var value = valueAccessor()();
if (value !== el.val) {
valueAccessor()(parseInt(el.val()));
}
});
},
update: function (element, valueAccessor) {
var el = $(element);
var parents = el.parents(".ui-slider");
for (var i = 1; i < parents.size() ; i++) {
parents.eq(i).children("[role]").remove();
}
var value = ko.utils.unwrapObservable(valueAccessor()());
if (value !== el.val()) {
el.val(value);
el.slider("refresh");
}
}
};
ko.bindingHandlers.sliderPercent = {
init: function (element, valueAccessor) {
var val = valueAccessor()() * 100;
var el = $(element);
el.isLoaded = true;
el.slider({ value: val });
el.off("change");
el.on("change", function (event, ui) {
var value = valueAccessor()();
if (value !== el.val) {
valueAccessor()(parseFloat(el.val()) / 100);
}
});
},
update: function (element, valueAccessor) {
var el = $(element);
var parents = el.parents(".ui-slider");
for (var i = 1; i < parents.size() ; i++) {
parents.eq(i).children("[role]").remove();
}
var value = ko.utils.unwrapObservable(valueAccessor()()) * 100;
if (value !== el.val()) {
el.val(value);
el.slider("refresh");
}
}
};
ko.bindingHandlers.toggleSwitch = {
init: function (element, valueAccessor) {
var el = $(element);
var val = ko.utils.unwrapObservable(valueAccessor()());
if (val === true) {
// 遅延で表示を切り替え
setTimeout(function () {
el.val("true").slider('refresh');
}, 10);
}
el.slider();
el.on("change", function (event, ui) {
console.log("changed");
var value = valueAccessor()();
if (value !== el.val) {
valueAccessor()(el.val());
}
});
},
update: function (element, valueAccessor) {
var el = $(element);
var value = ko.utils.unwrapObservable(valueAccessor()());
if (value !== el.val()) {
el.val(value);
el.slider("refresh");
}
}
};
ko.bindingHandlers.checkboxradio = {
init: function (element, valueAccessor) {
var el = $(element);
el.checkboxradio();
},
update: function (element, valueAccessor) {
var el = $(element);
var value = ko.utils.unwrapObservable(valueAccessor()());
if (value !== el.val()) {
el.checkboxradio("refresh");
}
}
};
ko.bindingHandlers.select = {
init: function (element, valueAccessor) {
var val = valueAccessor()();
var el = $(element);
el.selectmenu({ value: val });
el.on("change", function (event, ui) {
var value = valueAccessor()();
if (value !== el.val) {
valueAccessor()(el.val());
}
});
},
update: function (element, valueAccessor) {
var el = $(element);
var value = ko.utils.unwrapObservable(valueAccessor()());
if (value !== el.val()) {
el.val(value);
el.selectmenu("refresh");
}
}
};
ko.bindingHandlers.backgroundImage = {
update: function (element, valueAccessor) {
var el = $(element);
var value = ko.utils.unwrapObservable(valueAccessor()());
el.css("background-image", "url(" + value + ")");
}
};
ko.bindingHandlers.hidden = {
update: function (element, valueAccessor) {
var el = $(element);
if (ko.utils.unwrapObservable(valueAccessor())) {
el.hide();
}
else {
el.show();
}
}
};
ko.bindingHandlers.half = {
update: function (element, valueAccessor) {
var el = $(element);
var value = ko.utils.unwrapObservable(valueAccessor()) / 2;
el.text(value);
}
};
ko.bindingHandlers.tap = {
init: function (element, valueAccessor) {
$(element).hammer().on("tap", function (ev) {
valueAccessor()(element);
});
},
};
ko.bindingHandlers.signed = {
update: function (element, valueAccessor) {
var el = $(element);
var value = ko.utils.unwrapObservable(valueAccessor());
if (value == 0) {
el.text("");
}
else if (value > 0) {
el.text(" +" + value);
} else {
el.text(" " + value);
}
}
};
ko.bindingHandlers.safeText =
{
update: function (element, valueAccessor) {
try {
var value = ko.utils.unwrapObservable(valueAccessor());
ko.bindingHandlers.text.update(element, function () { return value; });
} catch (e) {
console.log("safeText binding error" + e);
}
}
};
ko.bindingHandlers.enum =
{
update: function (element, valueAccessor) {
var enumKey = $(element).attr("data-enum-key");
var value = ko.utils.unwrapObservable(valueAccessor());
ko.bindingHandlers.text.update(element, function () { return CordSharp.EnumNameContainer.enumNames[enumKey][value]; });
}
};
ko.bindingHandlers.src =
{
update: function (element, valueAccessor) {
try {
var value = ko.utils.unwrapObservable(valueAccessor());
var el = $(element);
el.attr("src", value);
} catch (e) {
console.log("src binding error" + e);
}
}
};
|
import React from 'react';
import './search.style.css';
const Search = ({onChange})=>{
const onInputChange=(e)=>{
onChange(e.target.value);
}
return (
<div className="search">
<div className="container">
<h3>Search</h3>
<input type="text" placeholder='name' onChange={onInputChange}/>
</div>
</div>
)
}
export default Search; |
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import {
Grid, Paper, Button, Typography, Tooltip, Popover, IconButton, CssBaseline,
Dialog, DialogActions, DialogContent, TextField, DialogTitle, Snackbar
} from '@material-ui/core';
import DateFnsUtils from '@date-io/date-fns';
import {
MuiPickersUtilsProvider,
KeyboardDatePicker,
} from '@material-ui/pickers';
import CloseIcon from '@material-ui/icons/Close';
import BackendService from '../services/backendServices';
const timingSlots = ['08:00 AM', '08:30 AM', '09:00 AM', '09:30 AM', '10:00 AM', '10:30 AM', '11:00 AM', '11:30 AM', '12:00 PM',
'12:30 PM', '01:00 PM', '01:30 PM', '02:00 PM', '02:30 PM', '03:00 PM', '03:30 PM', '04:00 PM',
'04:30 PM', '05:00 PM', '05:30 PM', '06:00 PM', '06:30 PM', '07:00 PM', '07:30 PM'];
const weekDays = [0, 1, 2, 3, 4, 5, 6];
const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1
},
rootModal: {
margin: 0,
padding: theme.spacing(2),
},
closeButton: {
position: 'absolute',
right: theme.spacing(1),
top: theme.spacing(1),
color: theme.palette.grey[500],
},
staticGrid: {
border: '1px solid',
borderColor: theme.palette.primary.light,
color: theme.palette.secondary.main,
paddingTop: '15px',
textAlign: 'center',
},
grid: {
border: '1px solid',
borderColor: theme.palette.primary.light,
color: theme.palette.primary.dark,
height: '80px',
},
button: {
fontSize: 12,
width: '100%',
height: '80px',
border: 'none',
},
popoverButton: {
margin: theme.spacing(1),
},
}));
export default function WeekView(props) {
const { serviceId, timings, slot, booking } = props;
const classes = useStyles();
const [currentDate, setCurrentDate] = React.useState(new Date());
const [anchorEl, setAnchorEl] = React.useState(null);
const [data, setData] = React.useState({});
const [dialogOpen, setDialogOpen] = React.useState(false);
const [email, setEmail] = React.useState('');
const [mobile, setMobile] = React.useState('');
const [name, setName] = React.useState('');
const [notes, setNotes] = React.useState('');
const [bookedOpen, setBookedOpen] = React.useState(false);
const [bookingDetails, setBookingDetails] = React.useState({});
const [slots, setSlots] = React.useState([]);
const [bookings, setBookings] = React.useState([]);
const [state, setState] = React.useState({
snackOpen: false,
message: '',
vertical: 'top',
horizontal: 'right',
});
const { vertical, horizontal, snackOpen, message } = state;
const handleSnackClose = () => {
setState({ ...state, snackOpen: false });
};
React.useEffect(() => {
setSlots(slot);
setBookings(booking);
}, [props]);
const getCalenderDetails = async () => {
try {
const practiceId = localStorage.getItem('userId');
const service = serviceId;
if (practiceId) {
if (service) {
let response = await BackendService.getCalendarSlots({
practiceId: practiceId,
serviceId: service
});
let res = await BackendService.getCalendarBookings({
practiceId: practiceId,
serviceId: service
});
setBookings(res.data.data);
setSlots(response.data.data);
}
} else {
window.location.pathname = '/signin';
}
} catch (error) {
setState({ ...state, snackOpen: true, message: 'Something went wrong!' });
}
}
const handleBookedOpen = async (index, time) => {
let selectedDate = new Date(currentDate.getTime() + (index * 24 * 60 * 60 * 1000));
for (let i = 0; i < bookings.length; i++) {
let slotTime = new Date(bookings[i].startDate).toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true });
if (selectedDate.getDate() === new Date(bookings[i].startDate).getDate() && slotTime === time) {
setBookingDetails(bookings[i]);
setBookedOpen(true);
}
}
};
const handleDateChange = date => {
setCurrentDate(date);
};
const handleBookedClosed = () => {
setBookedOpen(false);
};
const openBookingDialog = () => {
setDialogOpen(true);
};
const closeBookingDialog = () => {
setDialogOpen(false);
};
const handleClick = (event, index, time) => {
setData({ index, time });
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
const open = Boolean(anchorEl);
const id = open ? 'simple-popover' : undefined;
const checkSlot = (index, time) => {
let selectedDate = new Date(currentDate.getTime() + (index * 24 * 60 * 60 * 1000)).getDate();
const selectedDay = new Date(currentDate.getTime() + (index * 24 * 60 * 60 * 1000)).toDateString().split(" ")[0];
for (let i = 0; i < timings.length; i++) {
if (selectedDay.toLowerCase() === timings[i].day.slice(0, 3)) {
const selectedTime = time.split(" ");
if (timings[i].closed) {
return 'closed';
} else if (selectedTime[1] === 'AM') {
const timeIndex = (timings[i].from.split(" ")[0]).split(":");
if (selectedTime[0].split(':')[0] < timeIndex[0] ||
(selectedTime[0].split(':')[0] === timeIndex[0] && selectedTime[0].split(':')[1] < timeIndex[1]))
return 'closed';
} else if (selectedTime[1] === 'PM') {
const timeIndex = (timings[i].to.split(" ")[0]).split(":");
const hourFormat = parseInt(timeIndex[0]) - 12;
if (parseInt(selectedTime[0].split(':')[0]) !== 12) {
if (selectedTime[0].split(':')[0] > hourFormat ||
(selectedTime[0].split(':')[0] === hourFormat && selectedTime[0].split(':')[1] > timeIndex[1]))
return 'closed';
}
}
}
}
for (let i = 0; i < bookings.length; i++) {
let bookingTime = new Date(bookings[i].startDate).toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true });
bookingTime = bookingTime.length === 7 ? '0' + bookingTime : bookingTime;
if (new Date(bookings[i].startDate).getDate() === selectedDate && bookingTime === time) {
return { status: 'booking', index: i };
}
}
for (let i = 0; i < slots.length; i++) {
let slotTime = new Date(slots[i].startDate).toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true });
slotTime = slotTime.length === 7 ? '0' + slotTime : slotTime;
if (new Date(slots[i].startDate).getDate() === selectedDate && slotTime === time) {
return 'slot';
}
}
return false;
}
const addSlot = async (index, time) => {
try {
let selectedDate = new Date(currentDate.getTime() + (index * 24 * 60 * 60 * 1000));
let hour = time.split(':')[0];
if (time.split(':')[1].split(' ')[1] === 'PM' && hour < 12) {
hour = parseInt(hour) + 12;
}
let minute = time.split(':')[1].split(' ')[0];
const fromTime = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), selectedDate.getDate(), hour, minute, 0, 0).getTime();
const practiceId = localStorage.getItem('userId');
const service = parseInt(serviceId);
let response = await BackendService.addSlot({
practiceId,
serviceId: service,
fromTime: fromTime
});
if (response.data.status) {
getCalenderDetails()
setState({ ...state, snackOpen: true, message: 'Slot added!' });
} else {
setState({ ...state, snackOpen: true, message: 'Something went wrong!' });
}
} catch (error) {
setState({ ...state, snackOpen: true, message: 'Something went wrong!' });
}
}
const deleteSlot = async () => {
let selectedDate = new Date(currentDate.getTime() + (data.index * 24 * 60 * 60 * 1000));
for (let i = 0; i < slots.length; i++) {
let slotTime = new Date(slots[i].startDate).toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true });
if (slotTime.length === 7) {
slotTime = '0' + slotTime;
}
if (selectedDate.getDate() === new Date(slots[i].startDate).getDate() && slotTime === data.time) {
const practiceId = localStorage.getItem('userId');
let response = await BackendService.deleteSlot({
practiceId,
slotId: slots[i].slotId,
fromTime: new Date(slots[i].startDate).getTime()
});
if (response.data.status) {
setAnchorEl(null);
setData({});
getCalenderDetails()
setState({ ...state, snackOpen: true, message: 'Slot removed!' });
} else {
setState({ ...state, snackOpen: true, message: 'Something went wrong!' });
}
}
}
}
const addBooking = async () => {
let selectedDate = new Date(currentDate.getTime() + (data.index * 24 * 60 * 60 * 1000));
for (let i = 0; i < slots.length; i++) {
let slotTime = new Date(slots[i].startDate).toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true });
slotTime = slotTime.length === 7 ? '0' + slotTime : slotTime;
if (selectedDate.getDate() === new Date(slots[i].startDate).getDate() && slotTime === data.time) {
const practiceId = parseInt(localStorage.getItem('userId'));
const service = parseInt(serviceId);
try {
let response = await BackendService.addBooking({
practiceId,
serviceId: service,
firstName: name,
email: email,
mobileNumber: mobile,
additionalNotes: notes.length !== 0 ? notes : 'NA',
slotId: parseInt(slots[i].slotId),
fromTime: new Date(slots[i].startDate).getTime()
});
if (response.data.status) {
setAnchorEl(null);
setEmail('');
setName('');
setMobile('');
setNotes('');
setData({});
getCalenderDetails();
closeBookingDialog();
setState({ ...state, snackOpen: true, message: 'Booking confirmed!' });
} else {
setState({ ...state, snackOpen: true, message: 'Something went wrong!' });
}
} catch (error) {
setState({ ...state, snackOpen: true, message: 'Something went wrong!' });
}
}
}
}
const cancelBooking = async () => {
const practiceId = parseInt(localStorage.getItem('userId'));
let response = await BackendService.cancelBooking({
practiceId,
slotId: bookingDetails.slotId,
bookingId: bookingDetails.bookingId
});
if (response.data.status) {
handleBookedClosed();
getCalenderDetails()
setState({ ...state, snackOpen: true, message: 'Booking cancelled!' });
} else {
setState({ ...state, snackOpen: true, message: 'Something went wrong!' });
}
}
return (
<Paper>
<CssBaseline />
<Snackbar
anchorOrigin={{ vertical, horizontal }}
key={`${vertical},${horizontal}`}
open={snackOpen}
onClose={handleSnackClose}
ContentProps={{
'aria-describedby': 'message-id',
}}
message={<span id="message-id">{message}</span>}
/>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<Grid container style={{ marginLeft: '20px' }}>
<KeyboardDatePicker
disableToolbar
variant="inline"
format="MM/dd/yyyy"
margin="normal"
id="select-date"
label="Select Date"
value={currentDate}
onChange={handleDateChange}
KeyboardButtonProps={{
'aria-label': 'change date',
}}
/>
</Grid>
</MuiPickersUtilsProvider>
<Grid container >
<Grid item xs className={classes.grid}>
{/* <Button disabled variant="outlined" className={classes.blankButton}></Button> */}
</Grid>
{weekDays.map(index => (
<Grid key={index} item xs className={classes.staticGrid}>
<Typography>{new Date(currentDate.getTime() + (index * 24 * 60 * 60 * 1000)).toDateString().split(" ")[0]}</Typography>
<Typography>{`${new Date(currentDate.getTime() + (index * 24 * 60 * 60 * 1000)).getDate()} ${new Date(currentDate.getTime() + (index * 24 * 60 * 60 * 1000)).toDateString().split(" ")[1]}`}</Typography>
</Grid>
))}
</Grid>
{timingSlots.map(time => (
<Grid container key={time} >
<Grid item xs className={classes.staticGrid}>
<Typography>{time}</Typography>
</Grid>
{weekDays.map(index => (
<Grid key={index} item xs className={classes.grid}>
{checkSlot(index, time) === 'slot' &&
<div>
<Button variant="outlined" style={{ color: 'blue' }} className={classes.button}
onClick={(e) => handleClick(e, index, time)}>Available</Button>
<Popover
id={id}
open={open}
anchorEl={anchorEl}
onClose={handleClose}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'center',
}}
transformOrigin={{
vertical: 'top',
horizontal: 'center',
}}
>
<Button
variant="outlined"
style={{ color: 'green', borderColor: 'green' }}
className={classes.popoverButton}
onClick={() => openBookingDialog()}
>
Add Booking
</Button>
<Button
variant="outlined"
className={classes.popoverButton}
onClick={() => deleteSlot(index, time)}
style={{ color: 'red', borderColor: 'red' }}
>
Delete Slot
</Button>
</Popover>
<Dialog open={dialogOpen} onClose={closeBookingDialog} aria-labelledby="form-dialog-title">
<DialogTitle id="form-dialog-title">Book an Appointment</DialogTitle>
<DialogContent>
<TextField
autoFocus
margin="dense"
required
id="name"
label="Name"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
fullWidth
/>
<TextField
autoFocus
margin="dense"
id="email"
label="Email Address"
type="email"
required
value={email}
onChange={(e) => setEmail(e.target.value)}
fullWidth
/>
<TextField
autoFocus
margin="dense"
id="mobile"
label="Mobile"
value={mobile}
onChange={(e) => setMobile(e.target.value)}
type="digit"
required
fullWidth
/>
<TextField
autoFocus
margin="dense"
id="notes"
label="Additional Notes"
type="text"
value={notes}
onChange={(e) => setNotes(e.target.value)}
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={closeBookingDialog} color="secondary">
Cancel
</Button>
<Button onClick={addBooking} color="secondary"
disabled={email.length === 0 || name.length === 0
|| mobile.length === 0}>
Submit
</Button>
</DialogActions>
</Dialog>
</div>
}
{checkSlot(index, time).status === 'booking' &&
<div>
<Button variant="outlined" style={{ color: 'green' }} className={classes.button}
onClick={() => handleBookedOpen(index, time)}>{bookings[checkSlot(index, time).index].firstName.split(" ")[0].length < 10 ? bookings[checkSlot(index, time).index].firstName.split(" ")[0] : bookings[checkSlot(index, time).index].firstName.split(" ")[0].slice(0, 10) + '...'}</Button>
<Dialog onClose={handleBookedClosed} aria-labelledby="customized-dialog-title" open={bookedOpen}>
<DialogTitle disableTypography className={classes.rootModal} >
<Typography variant="h6">Booking Details</Typography>
<IconButton aria-label="close" className={classes.closeButton} onClick={handleBookedClosed}>
<CloseIcon />
</IconButton>
</DialogTitle>
<DialogContent dividers>
<Typography gutterBottom>
Name: {bookingDetails.firstName}
</Typography>
<Typography gutterBottom>
Email: {bookingDetails.email}
</Typography>
<Typography gutterBottom>
Mobile: {bookingDetails.mobileNumber}
</Typography>
</DialogContent>
<DialogActions>
<Button autoFocus onClick={() => cancelBooking()} color="primary">
Cancel Booking
</Button>
</DialogActions>
</Dialog>
</div>
}
{checkSlot(index, time) === 'closed' &&
<Button disabled={true} className={classes.button}>Closed</Button>
}
{!checkSlot(index, time) &&
<Tooltip title="Add Slot" arrow>
<Button className={classes.button} onClick={() => addSlot(index, time)}></Button>
</Tooltip>
}
</Grid>
))}
</Grid>
))}
</Paper>
);
} |
import React from "react";
export default function ResumeBadge({ label }) {
let color = "orange";
if (label === "New Role") {
color = "green";
}
if (label === "Career Change") {
color = "purple";
}
if (label === "Industry Switch") {
color = "yellow";
}
return <span className={`resumes--badge badge--${color}`}>{label}</span>;
}
|
document.write('<p>Du texte écrit en JavaScript</p>');
alert('Hello World en JavaScript')
|
import { types } from "./CommentAction"
export default function(state = [], action) {
switch (action.type) {
case types.REQUEST_COMMENTS:
return [...action.comments];
case types.ADD_COMMENT:
return [...state, action.comment];
case types.CLEAR_STATE:
return [];
default: return state;
}
}
|
/**
* Сенсорное управление
*/ "use strict";
function Sensor() {
this.offsetx=0;
this.offsety=0;
}
Sensor.prototype.load = function() {
this.w=Map["arrow"].width;
this.h=Map["arrow"].height;
for (var i=1;i<4;i++) { //стороны
Map["arrow"][i]=new Image();
Map["arrow"][i]=Utils.rotateImage(Map["arrow"],i*90);
}
}
Sensor.prototype.joystick = function() {
for (var i=0;i<2;i++) { //влево/вправо
var x=i*2*(this.w+this.offsetx);
var y=Main.h-(this.h-this.offsety)*2;
var key=Player.KEY[2+i];
var func=(function(key) {
return function(flag) {
Player[key]=flag;
}
})(key);
Button.add(x,y,{img:Map["arrow"][3-i*2],func:func});
}
for (var i=0;i<2;i++) { //вверх/вниз
var x=(this.w+this.offsetx);
var y=Main.h-(this.h-this.offsety)*(3-i*2);
var key=Player.KEY[i];
var func=(function(key) {
return function(flag) {
Player[key]=flag;
}
})(key);
Button.add(x,y,{img:Map["arrow"][i*2],func:func});
}
//reverse
x=(this.w+this.offsetx);
y=Main.h-(this.h-this.offsety)*2;
func=function(flag) { Player.reverse=flag; }
Button.add(x,y,{img:Map["reverse"][0],func:func});
//fire
x=Main.w-(this.w+this.offsetx);
y=Main.h-(this.h-this.offsety)*2+6;
func=function(flag) { Player.fire=flag; }
Button.add(x,y,{img:Map["icons_ts2"][0],func:func});
}
Sensor.prototype.gameOverButtons = function() {
var w=Map["icons_ts"][0].width;
var h=Map["icons_ts"][0].height;
var x=(w+this.offsetx);
var y=Main.h-(h-this.offsety)*2;
var func=function(flag) { if (flag) Main.preGame(); }
Button.add(x,y,{img:Map["icons_ts"][0],func:func});
x=Main.w-(w+this.offsetx)*2;
y=Main.h-(h-this.offsety)*2;
func=function(flag) {}
Button.add(x,y,{img:Map["icons_ts"][1],func:func});
}
|
describe('stock your logical thinking and "Algorithm of an Algorithm" here.', function() {
describe('Kaprekars Constant', function() {
var stock;
beforeEach(function() {
stock = new Kaprekars();
});
it('should work when a single digit number is passed in', function() {
expect(stock.constant(9)).toEqual(4);
});
it('should work when a two digit number is passed in', function() {
expect(stock.constant(21)).toEqual(3);
});
it('should work when a three digit number is passed in', function() {
expect(stock.constant(142)).toEqual(7);
});
it('should work when a four digit number is passed in', function() {
expect(stock.constant(2705)).toEqual(6);
});
it('should work when input number begins with zeroes', function() {
expect(stock.constant(0125)).toEqual(7);
expect(stock.constant(0052)).toEqual(2);
expect(stock.constant(0005)).toEqual(6);
});
});
describe('Blackjack Highest', function() {
var a = ['king','queen','ace'];
var b = ['three', 'nine', 'ace'];
var c = ['four', 'two', 'jack'];
var d = ['seven', 'five', 'queen', 'three', 'eight'];
var e = ['ten', 'six', 'five'];
var f = ['jack', 'queen', 'ten'];
var g = ['three'];
var h = ['ace', 'two', 'three', 'four','five', 'six'];
var i = ['ace', 'jack'];
var blackjack;
beforeEach(function() {
blackjack = new BlackjackHighest();
});
it('should output "blackjack king" with input: ' + JSON.stringify(a), function() {
expect(blackjack.hitMe(a)).toEqual('blackjack king');
});
it('should output "below nine" with input: ' + JSON.stringify(b), function() {
expect(blackjack.hitMe(b)).toEqual('below nine');
});
it('should output "below jack" with input: ' + JSON.stringify(c), function() {
expect(blackjack.hitMe(c)).toEqual('below jack');
});
it('should output "above queen" with input: ' + JSON.stringify(d), function() {
expect(blackjack.hitMe(d)).toEqual('above queen');
});
it('should output "blackjack ten" with input: ' + JSON.stringify(e), function() {
expect(blackjack.hitMe(e)).toEqual('blackjack ten');
});
it('should output "above queen" with input: ' + JSON.stringify(f), function() {
expect(blackjack.hitMe(f)).toEqual('above queen');
});
it('should output "below three" with input: ' + JSON.stringify(g), function() {
expect(blackjack.hitMe(g)).toEqual('below three');
});
it('should output "blackjack six" with input: ' + JSON.stringify(h), function() {
expect(blackjack.hitMe(h)).toEqual('blackjack six');
});
it('should output "blackjack ace" with input: ' + JSON.stringify(i), function() {
expect(blackjack.hitMe(i)).toEqual('blackjack ace');
});
});
describe('Stock Picker', function() {
var stock;
var a = [4, 3, 10, 3, 4, 20];
var b = [20, 30, 10, 9, 8, 1];
var c = [10, 9, 8, 6, 4, 2];
var d = [40, 24, 25, 22, 10];
var e = [54, 35, 40, 46, 53, 20, 1, 2, 3, 6];
var f = [20, 19, 18, 16, 5, 4, 3, 2, 5];
var g = [40];
var h = [30, 50, 51];
beforeEach(function() {
stock = new StockPicker();
});
it('should return a profit of 17 if stock prices are [4, 3, 10, 3, 4, 20]', function() {
expect(stock.highestProfit(a)).toEqual(17);
});
it('should return a profit of 10 if stock prices are [20, 30, 10, 9, 8, 1]', function() {
expect(stock.highestProfit(b)).toEqual(10);
});
it('should return -1 when there is no profit', function() {
expect(stock.highestProfit(c)).toEqual(-1);
});
it('should return a profit of 1 if stock prices are [40, 24, 25, 22, 10]', function() {
expect(stock.highestProfit(d)).toEqual(1);
});
it('should return a profit of 18 if stock prices are [54, 35, 40, 46, 53, 20, 1, 2, 3, 6] ', function() {
expect(stock.highestProfit(e)).toEqual(18);
});
it('should return a profit of 3 if stock prices are [20, 19, 18, 16, 5, 4, 3, 2, 5] ', function() {
expect(stock.highestProfit(f)).toEqual(3);
});
it('should return -1 when there is only a single price', function() {
expect(stock.highestProfit(g)).toEqual(-1);
});
it('should return 21 if stock prices are [30, 50, 51]', function() {
expect(stock.highestProfit(h)).toEqual(21);
});
});
});
|
import React, { Component } from 'react';
import { Navbar, Nav,NavItem, NavDropdown, MenuItem } from 'react-bootstrap';
import './amidairNavBar.css';
class AmidairNavBar extends Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true, showExecutif: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
handleMenuClick = () => {
let copy = this.state.showExecutif;
this.setState({
showExecutif: !copy
});
this.props.onSelectMenuItem(this.state.showExecutif);
}
render() {
return (
<div className="App-navbar">
<Navbar>
<Nav>
<NavItem eventKey={1} href="/">Accueil</NavItem>
<NavDropdown eventKey={2} title="Nous Joindre" id="basic-nav-dropdown">
<MenuItem eventKey={2.1} onClick={this.handleMenuClick}>Executif</MenuItem>
<MenuItem eventKey={2.2}>Formulaires</MenuItem>
<MenuItem eventKey={2.3}>Terrain</MenuItem>
</NavDropdown>
<NavDropdown eventKey={3} title="Membres" id="basic-nav-dropdown">
<MenuItem eventKey={3.1}>Administration</MenuItem>
<MenuItem eventKey={3.2}>Annonces Classees</MenuItem>
<MenuItem eventKey={3.3}>Formation</MenuItem>
<MenuItem eventKey={3.4}>Instructeurs</MenuItem>
<MenuItem eventKey={3.5}>Liste de Membres</MenuItem>
<MenuItem eventKey={3.6}>Reglements</MenuItem>
<MenuItem eventKey={3.7}>Section Imac</MenuItem>
<MenuItem eventKey={3.8}>Trucs et Astuces</MenuItem>
</NavDropdown>
<NavItem eventKey={4} href="#">Multimedia</NavItem>
</Nav>
<Navbar.Brand>
<a href="#" onClick={this.handleClick}>AMIDAIR {this.state.isToggleOn ? 'Logued Off' : 'Carlos Logued On'}</a>
</Navbar.Brand>
</Navbar>
</div>
);
}
}
export default AmidairNavBar; |
import React from 'react';
export function Footer(){
return(
<div id='neki'>
<p>Neki text drugi</p>
<p>Neki text drugi</p>
<p>Neki text drugi</p>
<p>Neki text drugi</p>
</div>
)
} |
import React from 'react';
import Layout from './components/Layout/Layout';
import BurgerBuilder from './containers/BurgerBuilder/BurgerBuilder';
function App() {
return (
<Layout>
<BurgerBuilder />
</Layout>
);
}
export default App;
// Discount Jonas kiest ervoor om App en Layout twee aparte dingen te houden, maar zegt erbij dat je net zo goed Layout als root component kunt gebruiken ipv App. |
/*EXPECTED
1
1
2
3
5
*/
class _Main {
static function main (args : string[]) : void {
function * fib () : Generator.<void,number> {
var a = 0, b = 1;
while (true) {
var t = a;
a = b;
b = t + b;
yield a;
}
}
var g = fib();
for (var i = 0; i < 5; ++i) {
log g.next().value;
}
}
}
|
import React, { useState, useEffect } from "react";
// import { TweenMax, TimelineLite, Power3 } from "gsap";
import { Link } from "react-router-dom";
import "./Home.css";
function Home() {
return (
<div className="home">
<div className="home__links">
<Link to="/about" className="link white one">
<h1 className="text ">Hello.</h1>
<span className="hide ">About</span>
</Link>
<Link to="/work" className="link two">
<h1 className="text">I am</h1>
<span className="hide">work</span>
</Link>
<Link to="/contact" className="link three">
<h1 className="text">Rishikesh</h1>
<span className="hide">Contact</span>
</Link>
</div>
<div className="display__none" id="displayNone">
<div className="one__none">
<h1 className="white">Hello.</h1>
<h1>I am</h1>
<h1>Rishikesh</h1>
</div>
<div className="arrow"></div>
<div className="links__none">
<Link to="/about" className="link__none">
<p className="white">About</p>
</Link>
<Link to="/work" className="link__none">
<p>Work</p>
</Link>
<Link to="/contact" className="link__none">
<p>Contact</p>
</Link>
</div>
</div>
</div>
);
}
export default Home;
|
import request from '@/utils/request'
import { urlPrivilege, urlCrowd } from '@/api/commUrl'
const url = urlPrivilege
// const url = 'http://192.168.0.227:8080/admin'
//李义广本地地址
//const url = 'http://192.168.0.215:8080/fwas-privilege-admin/sys'
// 左侧(一级二级)特权数据列表展示
export function getTreeData(params) {
return request({
url: url + '/privilegeTypeRest/menu',
method: 'post',
data: params
})
}
// 一级列表显示
export function firstList(params) {
return request({
url: url + '/privilegeRest/list',
method: 'post',
data: params
})
}
// 限制条件显示
export function limitList(params) {
return request({
url: url + '/privilegeConditionsRest/list',
method: 'post',
data: params
})
}
// 一级菜单添加
export function addFirstLevel(params) {
return request({
url: url + '/privilegeRest/save',
method: 'post',
data: params
})
}
// 二级菜单添加
export function addSecondLevel(params) {
return request({
url: url + '/privilegeTypeRest/save',
method: 'post',
data: params
})
}
// 特权条件添加--添加一级菜单
export function addLimit(params) {
return request({
url: url + '/privilegeConditionsRest/save',
method: 'post',
data: params
})
}
// 新增限制条件上传文件单独接口
export function addSecondLevelAll(params) {
return request({
url: urlCrowd + 'crowdInfo/uploadFile',
// 图片地址单调(正确) https://qa-apiengine.womaoapp.com/crowd/sys/crowdInfo/uploadFile
// 现在错的:qa-apiengine.womaoapp.com/fwas-crowd-admin/sys/crowdInfo/uploadFile
method: 'post',
data: params
})
}
// 新增限制条件保存
export function addSecondLevelAllWithoutFile(params) {
return request({
url: url + '/privilegeConditionsRest/saveAll',
method: 'post',
data: params
})
}
// 根据一级查询 二级
export function getByPrivilegeId(params) {
return request({
url: '/privilegeTypeRest/getByPrivilegeId',
method: 'post',
data: params
})
}
// 特权详情
export function detail(params) {
return request({
url: url + '/privilegeConditionsRest/getById',
method: 'post',
data: params
})
}
// 批量启用和禁用
export function openMore(params) {
return request({
url: url + '/privilegeConditionsRest/updateStatus',
method: 'post',
data: params
})
}
// 编辑
export function edit(params) {
return request({
url: url + '/privilegeConditionsRest/update',
method: 'post',
data: params
})
}
// 用户id列表查询(只是调试时候用一下,以后就从别的页面查询复制过来,用作特权赠送)
export function searchId(params) {
return request({
url: url + '/userSearchRest/search',
method: 'post',
data: params
})
}
// 赠送特权
export function sendPriv(params) {
return request({
url: url + '/memberPrivilegeConditionsRest/save',
// url: 'http://192.168.0.227:8082/admin/memberPrivilegeConditionsRest/save',
method: 'post',
data: params
})
}
// 用户日志查询
export function userLog(params) {
return request({
url: url + '/memberPrivilegeConditionsLogRest/list',
// url: 'http://192.168.0.232:8080/memberPrivilegeConditionsLogRest/list',
method: 'post',
data: params
})
}
// export function testPri(channelId) {
// return request({
// url: 'http://192.168.0.227:8080/admin/privilegeTypeRest/menu',
// method: 'get',
// params: {
// channelId: channelId
// }
// })
// }
|
import React from "react"
import {Route, Switch} from "react-router-dom"
import Home from "./pages/usersHome"
import userDetails from "./pages/UserDetails"
import userUpdate from "./pages/userUpdate"
export default function(){
return (
<Switch>
<Route exact path="/" component={Home}/>
<Route exact path="/show/:id" component={userDetails}/>
<Route exact path="/update/:id" component={userUpdate}/>
</Switch>
)
} |
const pool = require("./database");
//fonction
module.exports.getMessage= async (userId_Receiver, userId_Sender, client) =>{
return await client.query("SELECT * FROM Messages WHERE userId_Receiver =$1 and userId_Sender = $2",[userId_Receiver,userId_Sender]);
}
module.exports.addMessage = async (userId_Receiver, userId_Sender, content, client) =>{
await client.query("INSERT INTO Messages(userId_Receiver, userId_Sender, content) VALUES ($1,$2,$3)",[userId_Receiver,userId_Sender,content]);
return true;
}
module.exports.updateMessage = async (id, userId_Receiver,userId_Sender,content, client) =>{
await client.query("UPDATE Messages SET content =$4 WHERE id=$1 and userId_Receiver =$2 and userId_Sender = $3 ", [id,userId_Receiver, userId_Sender, content]);
return true;
}
module.exports.deleteMessage = async (id, userId_Receiver, userId_Sender ,client) =>{
await client.query("DELETE FROM Messages WHERE id =$1 and userId_Receiver= $2 and userId_Sender =$3", [id, userId_Receiver, userId_Sender]);
return true;
} |
import React from "react";
import {
FaGithub,
FaTwitter,
FaLinkedin
} from "react-icons/fa";
// https://gorangajic.github.io/react-icons/fa.html
const SocialLinks = () => (
<ul className="social">
<li>
<a href="https://github.com/Wdifulvio523" target="_blank">
<FaGithub />
</a>
</li>
<li>
<a href="https://linkedin.com/in/william-difulvio" target="_blank">
<FaLinkedin />
</a>
</li>
<li>
<a href="https://twitter.com/billdifulvio" target="_blank">
<FaTwitter />
</a>
</li>
</ul>
);
export default SocialLinks;
|
import React, { Component } from 'react';
import { Gesture } from 'react-with-gesture';
import { Spring, animated, interpolate } from 'react-spring';
import styled from 'styled-components';
import { absolute } from 'Utilities';
import { Card } from './Elements/Cards';
const maxWith = '200px';
export default class Drag extends Component {
// if I write function like this, it is not executed when it's called
onUp = xDelta => () => {
console.log(xDelta);
if (xDelta < -300) {
alert('Remove Card');
} else if (xDelta > 300) {
alert('Add Card');
}
}
render() {
return (
<Gesture>
{({ down, xDelta }) => (
<Spring
native
to={{
x: down ? xDelta : 0,
}}
immediate={name => down && name === 'x'}
>
{({ x }) => (
<ModalWrapper>
<CardContainer
maxWith={maxWith}
style={{
background: x.interpolate({
range: [-300, 300],
output: ['#fff323', '#9A3D02'],
extrapolate: 'clamp',
}),
}}
>
<DragCard
onMouseUp={this.onUp(xDelta)} // for desktop
onTouchEnd={this.onUp(xDelta)} // for mobile
maxWith={maxWith}
style={{
opacity: x.interpolate({
range: [-300, 300],
output: [0.5, 1],
extrapolate: 'clamp',
}),
// in the array, the first x goes as position x, the second x goes as rotate value rotate, both x come from <Spring>
transform: interpolate(
[x,
x.interpolate({
range: [-300, 300],
output: [-360, 360],
extrapolate: 'clamp',
})],
(x, rotate) => `translateX(${x}px) rotate(${rotate}deg)`),
}}
>
<h1>Drag me</h1>
</DragCard>
</CardContainer>
</ModalWrapper>
)}
</Spring>
)}
</Gesture>
);
}
}
const NativeCard = Card.withComponent(animated.div);
const DragCard = NativeCard.extend`
max-width:${props => props.maxWith};
margin: 0 auto;
height: 50px;
`;
const ModalWrapper = styled.div`
${absolute({})}
width:100%;
height:100%;
display:flex;
justify-content:center;
align-items:center;
`;
const CardContainer = styled(animated.div)`
position:relative;
background:#ccc;
max-width:${props => props.maxWith};
margin:0 auto;
border-radius:5px;`;
{ /* <Gesture>
{({
down, x, y, xDelta, yDelta, xInitial, yInitial,
}) => (
<CardWithMaxWidth style={{
transform: `translate3d(${xDelta}px, ${yDelta}px,0)`,
}}
>
<h1>
{down}
,
{x}
,
{y}
,
{xDelta}
,
{yDelta}
,
{xInitial}
,
{yInitial}
</h1>
</CardWithMaxWidth>
)}
</Gesture> */ }
|
const path = require('path');
// const Datastore = require('nedb')
const nedbPromise = require('nedb-promise');
const { pathname } = require('../vars.cjs');
const initNedb = (dbnames = []) => {
const db = {};
for (const o of dbnames) {
const dbname = Array.isArray(o) ? o[0] : o;
const filename = Array.isArray(o) ? o[1] : o;
// const store = Datastore({
// filename: path.resolve(pathname.repoDatabase, 'db', `${filename}.nedb`),
// autoload: true,
// })
// const db = nedbPromise.fromInstance(store)
// db.persistence = store.persistence
// db[dbname] = db
db[dbname] = nedbPromise({
filename: path.resolve(
pathname.repoDatabase,
'db',
`${filename}.nedb`
),
autoload: true,
});
}
return db;
};
/**
* 创建数据存储空间(NeDB)
* @async
* @returns {Object} datastores
*/
module.exports = async () => {
return await initNedb([
'ships',
['shipTypes', 'ship_types'],
['shipClasses', 'ship_classes'],
['shipNamesuffix', 'ship_namesuffix'],
['shipSeries', 'ship_series'],
['equipments', 'items'],
['equipmentTypes', 'item_types'],
'entities',
'consumables',
'exillusts',
['exillustTypes', 'exillust_types'],
]);
};
|
import React from 'react';
import { Link } from "react-router-dom";
const GameItem = ({item}) => {
return (
<tr>
<td className="mdl-data-table__cell--non-numeric">{item.status}</td>
<td className="mdl-data-table__cell--non-numeric">{item.date}</td>
<td className="mdl-data-table__cell--non-numeric">
<Link to={`/game/${item.id}`}>View</Link>
</td>
</tr>
)
};
export default GameItem; |
/**
* Created by Administrator on 2018/4/13.
*/
import React,{Component} from 'react';
import ReactDOM from 'react-dom';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import moment from 'moment';
import { Carousel,PullToRefresh } from 'antd-mobile';
import 'antd-mobile/lib/pull-to-refresh/style/css.js'; //获取样式
import Header from '../items/header';
import Loading from '../items/loading';
import DetailCard from '../items/detail-card';
import {getEventType, getEventList} from "../functional/common";
import {selectDateType} from '../../action/action';
class Home extends Component{
constructor(props) {
super(props);
this.state = {
imgHeight: '3.2rem',
data: ['1', '2', '3', '4'], //存放图片的数组
week: [], //日期数组
category: [], //事件数组
dayIndex: 0,
typeIndex: 0,
detailArr: [], //存放详情参数的数组
refreshing: false,
}
}
componentWillMount() {
document.body.style.background = '#fff';
let dateArr = [];
for(let i = 0;i < 7;) {
let week = moment(new Date()).add(i, 'days').format('dddd').substring(0,3);
let date = moment(new Date()).add(i, 'days').format('MM.DD');
dateArr.push({'week': week, 'date': date});
i ++;
}
this.setState({week: dateArr});
}
componentDidMount() {
let eventArr = [];
getEventType().then(value => {
let data = value.event_type_list;
data.map(res => {
eventArr.push({'title': res});
});
this.setState({category: eventArr});
//默认初始化事件列表
let fetch = getEventList(this.state.week, eventArr, 0, 0);
this.props.selectDateType({fetchPost: fetch});
});
}
//点击切换时间
dayClick(index) {
this.setState({
dayIndex: index
});
//点击更新事件列表
let fetch = getEventList(this.state.week, this.state.category, index, this.state.typeIndex);
this.props.selectDateType({fetchPost: fetch});
}
//点击切换事件类型
typeClick(index) {
this.setState({
typeIndex: index
});
//点击更新事件列表
let fetch = getEventList(this.state.week, this.state.category, this.state.dayIndex, index);
this.props.selectDateType({fetchPost: fetch});
}
render() {
return(
<div className="home">
<Header/>
{/*轮播图*/}
<div style={{height: '3.3rem',background: '#f4f4f4'}}>
<Carousel
className="mars-carousel"
dots={true}
dotStyle={{
background: 'transparent',
width: '.12rem',
height: '.12rem',
margin: '0 .1rem',
display: 'block',
borderRadius: '50%',
border: '1px solid rgba(0,0,0,0.5)'
}}
dotActiveStyle={{
background: 'rgba(0,0,0,0.5)',
width: '.12rem',
height: '.12rem',
margin: '0 .1rem',
display: 'block',
borderRadius: '50%',
border: '1px solid transparent'
}}
selectedIndex={0}
autoplay={true}
infinite
>
{this.state.data.map(val => {
return(
<img
key={val}
style={{height: this.state.imgHeight}}
src={require(`../../../images/${val}.jpeg`)}
alt=""
onLoad={() => {
// fire window resize event to change height
window.dispatchEvent(new Event('resize'));
}}
/>
)
})}
</Carousel>
</div>
{/*中间选择区域*/}
<div className="whiteBg">
{/*日期选择*/}
<div className="week-list-box">
<ul className="week-list">
{this.state.week.map((val,i) => {
let dayStyle = i === this.state.dayIndex ? 'active' : '';
return(
<li
key={i}
className={dayStyle}
onClick={this.dayClick.bind(this,i)}
>
<p>{val.week}</p>
<p>{val.date}</p>
</li>
)
})}
</ul>
</div>
{/*品类选择*/}
<div className="category-list-box">
<ul className="category-list">
{this.state.category.map((val,i) => {
let typeStyle = i === this.state.typeIndex ? 'active' : '';
return(
<li
key={i}
className={typeStyle}
onClick={this.typeClick.bind(this,i)}
>
<span>{val.title}</span>
</li>
)
})}
</ul>
{/*底部选择线*/}
<div
className="category-line"
style={{
left: 4 + 25 * this.state.typeIndex + '%'
}}
>
</div>
</div>
</div>
{/*获取事件详情*/}
<PullToRefresh
style={{
background: '#fff',
maxHeight: '10.88rem',
overflow: 'auto'
}}
refreshing={this.state.refreshing}
direction="down"
distanceToRefresh={50}
onRefresh={() => {
this.setState({ refreshing: true });
let fetch =
getEventList(this.state.week, this.state.category, this.state.dayIndex, this.state.typeIndex);
this.props.selectDateType({isRefresh: true,fetchPost: fetch}).then(() => {
this.setState({ refreshing: false });
});
}}
indicator={{
activate: 'Release to complete',
deactivate: 'Pull to refresh',
finish: 'Refreshed',
release:
<div style={{transform: 'translateY(-20px)'}}>
<img style={{width: '30px',height: '30px'}} src={require("../../../images/loading.gif")} alt=""/>
</div>
}}
>
{(() => {
/*通过loading指针,在接口未请求到数据前显示Loading组件*/
if(this.props.loading) {
return <Loading style={{
width: '100%',
height: '5.44rem',
position: 'relative'
}}/>;
}else{
/*判断goodsList是否存在,对store里的数据进行遍历渲染*/
if(this.props.goodsList) {
if(this.props.goodsList.length > 0) {
return (this.props.goodsList.map((res,i) =>
(
<DetailCard
key={i}
imgUrl={res.imgUrl}
name={res.name}
heartNum={res.thumb_up_num}
addr={res.address}
time={res.time}
price={res.price}
eventId={res.event_id}
commodityId={res.commodity_id}
thumb_up={res.thumb_up}
join_in={res.join_in}
isProduct={false}
/>
)
))
}else{
return (
<div style={{
textAlign: 'center',
padding: '1rem 0 4rem 0',
}}>Sorry! There's no Data.</div>
)
}
}else{
return null;
}
}
})()}
</PullToRefresh>
</div>
)
}
}
const mapStateToProps = (state,props) => {
return state;
};
const mapDispatchToProps = (dispatch, ownProps) => {
return bindActionCreators({
selectDateType
},dispatch);
};
export default connect(mapStateToProps,mapDispatchToProps)(Home); |
import styled, {
css
} from "styled-components";
const sharedStyleA = css `
display: flex;
justify-content: center;
align-items: center;
color: white !important;
font-size: .94rem;
height: var(--hmenu);
padding: 1rem;
letter-spacing: 1px;
text-transform: uppercase;
text-decoration: none;
`;
export const Header = styled.header `
width: 100%;
display: block;
height: var(--hmenu);
background: var(--bgazul);
box-shadow: 0px 3px 8px 0px rgba(23, 24, 32, 0.1);
font-weight: 600;
z-index: 999;
position: fixed;
`;
export const Logo = styled.div `
display:flex;
align-items:center;
a {
text-decoration: none;
letter-spacing: 1px;
color: white;
text-transform: uppercase;
margin-left: 1rem;
@media screen and (max-width:360px) {
display: none;
}
}
img {
width: auto;
max-height: 52px;
}
`;
export const Nav = styled.nav `
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
min-height: var(--hmenu);
z-index: 999;
`;
export const NavLinks = styled.ul `
display: flex;
justify-content: space-around;
margin: 0;
a{
${sharedStyleA}
}
a:hover, .is-active {
background-color: rgba(240, 248, 255, 0.10);
cursor: pointer;
}
@media screen and (max-width:992px) {
overflow-x: hidden;
overflow-y: auto;
position: fixed;
width: 100%;
height: 100vh;
background: var(--textcolor);
right: -100%;
top: 0;
text-align: center;
padding: 80px 0;
line-height: normal;
transition: 0.7s;
flex-direction: column;
justify-content: start;
}
`;
export const DropdownMenu = styled.div`
display: none;
position: absolute;
top: 80px;
width: 100vh;
border-radius: 0 !important;
border: none !important;
background: var(--bgazul);
a {
width: 100%;
height: 50px;
text-decoration: none;
display: block;
}
`;
export const Dropdown = styled.div`
${sharedStyleA}
&:hover {
background-color: rgba(240, 248, 255, 0.10);
}
&:hover ${DropdownMenu} {
display: block;
}
label {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
min-height: 100%;
height: auto !important;
display: flex;
justify-content: center;
align-content: center;
align-items: center;
}
@media screen and (max-width:992px) {
padding: 0;
&:hover ${DropdownMenu} {
display: none;
}
${DropdownMenu} {
background: rgb(236, 236, 236);
}
${DropdownMenu} a {
color: #313450 !important;
}
}
label span {
font-size: .94rem;
}
`;
export const InputDropdownMenu = styled.input`
display: none;
@media screen and (max-width:992px) {
&:checked ~ ${DropdownMenu}{
display: block;
width:100%;
max-height:300px;
transition: max-height 250ms;
}
}
`;
export const Mobile = styled.div`
position: absolute;
display: none;
cursor: pointer;
display: flex;
justify-content: center;
align-items:center;
z-index:1;
width: 40px;
height: 40px;
right: 40px;
div {
position: relative;
width: 100%;
height: 2px;
background-color: white;
cursor: pointer;
display: none;
transition: all 0.4s ease;
}
div:before , div:after{
content: '';
position: absolute;
z-index:1;
top: -10px;
width:100%;
height:2px;
background:inherit;
}
div:after{
top: 10px;
}
@media screen and (max-width:992px) {
div {
display: block;
}
}
`;
export const CHK = styled.input`
position: absolute;
opacity:0;
height:40px;
width:40px;
right:40px;
z-index: 2;
@media screen and (max-width:992px) {
&:checked~${NavLinks} {
right: 0;
}
&:checked + ${Mobile} > div{
transform: rotate(135deg);
}
&:checked + ${Mobile} > div:before , &:checked + ${Mobile} > div:after{
top: 0;
transform: rotate(90deg);
}
&:checked:hover + ${Mobile} > div {
transform: rotate(225deg);
}
}
`; |
import React from 'react';
import Layout from '../hoc/Layout/Layout';
import * as actions from '../store/actions/general';
import axios from "../axios-site"
import SearchView from "../containers/Search/Search"
import i18n from '../i18n';
import { withTranslation } from 'react-i18next';
import PageNotFound from "../containers/Error/PageNotFound"
import PermissionError from "../containers/Error/PermissionError"
import Login from "../containers/Login/Index"
import Maintanance from "../containers/Error/Maintenance"
const Search = (props) => (
<Layout {...props} hideSmallMenu={true}>
{
props.pagenotfound ?
<PageNotFound {...props} />
: props.user_login ?
<Login {...props} />
: props.permission_error ?
<PermissionError {...props} />
: props.maintanance ?
<Maintanance {...props} />
:
<SearchView {...props} hideSmallMenu={true} />
}
</Layout>
)
const Extended = withTranslation('common', { i18n, wait: process.browser })(Search);
Extended.getInitialProps = async function (context) {
const isServer = !!context.req
if (isServer) {
const req = context.req
req.i18n.toJSON = () => null
const initialI18nStore = {}
req.i18n.languages.forEach((l) => {
initialI18nStore[l] = req.i18n.services.resourceStore.data[l];
})
await context.store.dispatch(actions.setPageInfoData(context.query))
return { pageData: context.query, initialI18nStore, i18n: req.i18n, initialLanguage: req.i18n.language }
} else {
let type = ""
let queryData = "?data=1"
if (context.query.type) {
type = `/${context.query.type}`
}
if (context.query.h) {
queryData = `${queryData}&h=${context.query.h}`
}
if (context.query.category) {
queryData = `${queryData}&category=${context.query.category}`
}
if (context.query.sort) {
queryData = `${queryData}&sort=${context.query.sort}`
}
if (context.query.filter) {
queryData = `${queryData}&filter=${context.query.filter}`
}
if (context.query.country) {
queryData = `${queryData}&country=${context.query.country}`
}
if (context.query.language) {
queryData = `${queryData}&language=${context.query.language}`
}
const pageData = await axios.get("/search" + type + queryData);
return {pageData:pageData.data.data,user_login:pageData.data.user_login,pagenotfound:pageData.data.pagenotfound,permission_error:pageData.data.permission_error,maintanance:pageData.data.maintanance}
}
}
export default Extended |
/* JavaScript Object */
/* Object Construction */
// Object Literal
var a = {}
console.log(typeof a)
// new Keyword
var b = new Object()
console.log(typeof b)
// Object.create(property)
var c = Object.create(null)
console.log(typeof c)
// new FunctionName(params)
function Man () {
return 1
}
var d = new Man()
console.log(typeof d)
/* Accessing Object Properties */
var person = {
name: 'Abdur Rahman',
age: 21,
skill: ['js', 'ts', 'php', 'dart']
}
console.log(person)
console.log(person.name)
console.log(person.age)
console.log(person.skill)
console.log(person['name'])
console.log(person['age'])
console.log(person['skill'])
/* Assigning Object Properties */
var person2 = {
name: 'Siam'
}
console.log(person2)
person2.age = 22
console.log(person2)
person2['skill'] = ['php', 'html', 'css']
console.log(person2)
/* Removing Object Properties */
// delete person2.age
delete person2.skill
console.log(person2)
/* View Object as Table */
console.table(person2)
/* Traversing Object */
for(i in person) {
console.log(person[i])
}
|
import React, { Component } from 'react';
import {
View,
Text,
FlatList,
StyleSheet,
Image,
ActivityIndicator,
} from 'react-native';
import { SearchBar } from 'react-native-elements';
import { connect } from 'react-redux';
import { listProducts } from './action';
class ProductList extends Component {
constructor(props) {
super(props);
this.state = {
hasReachedEnd: false,
searchString: '',
searched: false,
filteredProducts: []
}
}
componentDidMount() {
this.props.listProducts(this.props.start, this.props.limit);
}
static getDerivedStateFromProps = (nextProps, prevState) => {
console.log("****see here**");
console.log(nextProps);
console.log(prevState);
console.log("****end here**");
if (prevState.searchString !== '') {
console.log("****search String condition**");
console.log(prevState.searchString);
console.log(nextProps.products);
let results = nextProps.products.filter(product => product.title.includes(prevState.searchString));
console.log(results)
return {
...prevState,
filteredProducts: results,
hasReachedEnd: false
}
} else {
console.log("****New product**");
console.log(prevState);
console.log("======");
console.log(nextProps);
return {
...prevState,
filteredProducts: nextProps.products,
hasReachedEnd: false,
searched: false
}
}
}
renderFooter = () => {
const { ended } = this.props;
if (!this.props.loading && ended) return null;
if (ended) return <Text style={styles.endText}>End Of Products</Text>;
return (<View style={styles.loaderContainter}><ActivityIndicator size="large" color="#0000ff" /></View>);
};
renderHeader = () => {
return (
<SearchBar
placeholder="Type Here..."
lightTheme
round
onChangeText={text => this.searchFilterFunction(text)}
autoCorrect={false}
value={this.state.searchString}
/>
);
};
renderItem = ({ item }) => {
return <View style={styles.item}>
<Image
source={{
uri: 'https://reactjs.org/logo-og.png',
method: 'POST',
headers: {
Pragma: 'only-if-cached',
}
}}
style={styles.image}
/>
<Text style={styles.text}>{item.title}</Text>
</View>
};
searchFilterFunction = text => {
this.setState({ searchString: text, searched: true });
console.log(this.state.filteredProducts);
const newData = this.props.products.filter(item => {
const itemData = item.title.toUpperCase();
return itemData.includes(text.toUpperCase());
});
console.log(newData);
this.setState({ filteredProducts: newData });
// this.setState({ searchedString: text, filteredProducts: newData });
};
renderEmptyResults = () => {
return (
//View to show when list is empty
<View style={styles.item}>
<Text style={{ textAlign: 'center' }}>No Data Found</Text>
</View>
);
};
render() {
console.log(this.state.filteredProducts);
return (
<FlatList
styles={styles.container}
data={this.state.filteredProducts}
keyExtractor={(item, index) => item.id.toString()}
renderItem={this.renderItem}
extraData={this.state.searched}
onEndReachedThreshold={0.5}
onEndReached={({ distanceFromEnd }) => {
{ this.props.listProducts(this.props.start + this.props.limit, this.props.limit) }
}}
ListFooterComponent={this.renderFooter}
// onScroll={({ nativeEvent }) => {
// if (isCloseToBottom(nativeEvent)) {
// this.setState({ hasReachedEnd: true });
// }
// }}
// scrollEventThrottle={400}
ListHeaderComponent={this.renderHeader}
stickyHeaderIndices={[0]}
ListEmptyComponent={this.renderEmptyResults}
/>
);
}
}
const isCloseToBottom = ({ layoutMeasurement, contentOffset, contentSize }) => {
const paddingToBottom = 20;
return (
layoutMeasurement.height + contentOffset.y >=
contentSize.height - paddingToBottom
);
};
const styles = StyleSheet.create({
container: {
flex: 8
},
item: {
padding: 16,
borderBottomWidth: 1,
borderBottomColor: '#ccc',
backgroundColor: '#f7edc8',
flexDirection: 'row',
alignItems: 'center'
},
endText: {
textAlign: "center",
color: "#fff",
backgroundColor: "#ed6a6a",
padding: 10
},
loaderContainter: {
alignContent: 'center',
width: '100%',
backgroundColor: '#f7edc8'
},
image: {
width: 50,
height: 50,
borderRadius: 70
},
text: {
fontSize: 15,
color: '#24292E',
margin: 16
}
});
const mapStateToProps = state => ({
products: state.products,
loading: state.loading,
ended: state.ended,
start: state.start,
limit: state.limit
});
const mapDispatchToProps = dispatch => ({
listProducts: (start, limit) => { dispatch(listProducts(start, limit)) }
});
export default connect(mapStateToProps, mapDispatchToProps)(ProductList); |
import React, { Component } from 'react';
import { Jumbotron } from 'reactstrap';
class NotFound extends Component {
render() {
return (
<Jumbotron className="bg-white">
<h1>Page Not Found!</h1>
<p>The page you are trying to reach cannot be found. Make sure the address is correct or go back to the <a href="/">Home page</a>.</p>
</Jumbotron>
);
}
}
export default NotFound;
|
const repeatString = function(str, times) {
if( times < 0 ) return 'ERROR';
if( times === 0 ) return '';
return str + repeatString(str, times - 1);
}
module.exports = repeatString
|
const path = require('path');
const express = require('express'); //framework
const userController = require('../controllers/user');
const router = express.Router();
//trả về home mỗi khi mở lên
router.get('/', userController.getHome);
//các đường link url và các controller tương ứng để điều khiển nó
router.get('/user-register', userController.getUserRegister);
//register
router.post('/register-form', userController.postRegister);
router.get('/user-login', userController.getUserLogin);
//login
router.post('/login-user', userController.postLogin);
//add code
router.post('/add-player-code', userController.postAddCode);
///////////////////////////////////////////////////////////
//thay đổi password
router.post('/fixuserpass', userController.postFixUserPass);
//game
router.get('/game', userController.getGame);
//pokemon
router.post('/stop', userController.postStop)
router.post('/poke1', userController.poke1)
router.post('/poke2', userController.poke2)
router.post('/poke3', userController.poke3)
router.post('/poke4', userController.poke4)
router.post('/poke5', userController.poke5)
router.post('/poke6', userController.poke6)
router.post('/poke7', userController.poke7)
router.post('/poke8', userController.poke8)
router.post('/poke9', userController.poke9)
router.post('/poke10', userController.poke10)
router.post('/poke11', userController.poke11)
router.post('/poke12', userController.poke12)
//buy pokemon
router.post('/pk6', userController.pk6)
router.post('/pk8', userController.pk8)
//buy ball
router.post('/ball', userController.ball)
//12 quảng cáo
exports.routes = router; //phải có |
import React from 'react';
import { useLocation } from 'react-router-dom';
const Header = ({ title, onReset, expeditionsCount }) => {
const location = useLocation();
return (
<header className="row">
<nav className="navbar bg-primary col-12">
<a className="nav-link text-white h5" href="https://www.geektrust.in/">
GeekTrust
</a>
{location.pathname === '/' && (
<button
className="btn btn-outline-light"
onClick={onReset}
disabled={expeditionsCount === 0}
>
Reset
</button>
)}
</nav>
<h1 className="col-12 text-center my-3">{title}</h1>
</header>
);
};
export default Header;
|
const router = require("express").Router();
const Estado = require("../models/Estado");
const Pais = require("../models/Pais");
// SE USAN SOLO EN EL DASHBOARD PARA CREAR ESTADOS Y REPRESENTARLOS
router.post('/new',(req,res, next)=>{
Estado.create(req.body)
.then(estado=>{
Pais.findByIdAndUpdate(req.body.pais._id,{
$push: { estados: estado._id }
},{ 'new': true})
.then(pais=>{
console.log(pais)
})
.catch(e=>console.log(e))
res.json(estado)
})
.catch(e=>next(e))
});
router.get('/',(req,res,next)=>{
Estado.find()
.then(estados=>{
res.json(estados);
})
.catch(e=>{
res.send('No funco papu...')
})
})
module.exports = router; |
'use strict'
var num = 20;
function isEven(num) {
if ( (20 % 2) == 0) {
return 'is true'
//console.log('is true')
} else {
return 'is false'
//console.log('is false')
}
}
var resultat = (isEven(20))
console.log(resultat); |
import React, { Component } from "react";
import Header from "./Header";
import PostForm from "./posts/PostForm";
import PostImg from "./posts/PostImg";
class PostNew extends Component {
state = { showConfirm: false };
render() {
return (
<div>
<Header />
<div className="container">
<div>
<PostImg
showConfirm={this.state.showConfirm}
onCancel={() => this.setState({ showConfirm: false })}
/>
<PostForm
onPostSubmit={() => this.setState({ showConfirm: true })}
showConfirm={this.state.showConfirm}
/>
</div>
</div>
</div>
);
}
}
export default PostNew;
|
const components ={
signUp:`<section class="sign-up-container">
<form class="form-sign-up">
<div class="form-header">
<h3>MindX Chat</h3>
</div>
<div class="form-content">
<div class="name-wrapper">
<div class="input-wrapper">
<input type="text" name="firstname" placeholder="Fristname">
<div id="firstname-error" class="message-error"></div>
</div>
<div class="input-wrapper">
<input type="text" name="lastname"placeholder="Lastname">
<div id="lasttname-error" class="message-error"></div>
</div>
</div>
<div class="input-wrapper">
<input type="email" name="email"placeholder="Email">
<div id="email-error" class="message-error"></div>
</div>
<div class="input-wrapper">
<input type="password" name="password"placeholder="Password" required>
<div id="passWord1-error" class="message-error"></div>
</div>
<div class="input-wrapper">
<input type="password" name="confirmPassword"placeholder="Confirm Password">
<div id="passWord-error" class="message-error"></div>
</div>
<div id="sign-up-error" class="message-error"></div>
<div id="sign-up-success" class="message-success"></div>
</div>
<div class="form-footer">
<a id="form-sign-up-link" href="#">Already have an account? Login</a>
<button id="form-sign-up-btn" type="submit">Register</button>
<!-- <button type="reset">aaaa</button> -->
</div>
</form>
</section>
`,
signIn:`<section class="sign-in-container">
<form class="form-sign-in">
<div class="form-header">
<h3>MindX Chat</h3>
</div>
<div class="form-content">
<div class="input-wrapper">
<input type="email" name="email"placeholder="Email">
<div id="email-error" class="message-error"></div>
</div>
<div class="input-wrapper">
<input type="password" name="password"placeholder="PassWord">
<div id="firstname-error" class="message-error"></div>
</div>
</div>
<div class="form-footer">
<a id="form-sign-in-link" href="#">Not yet have a account? Register</a>
<button type="submit">Login</button>
<!-- <button type="reset">aaaa</button> -->
</div>
</form>
</section>`
} |
// Copyright (c) 2016-2018, BuckyCloud, Inc. and other BDT contributors.
// The BDT project is supported by the GeekChain Foundation.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the BDT nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'use strict';
const DHTPackage = require('../../dht/packages/package.js');
const DHTPackageFactory = require('../../dht/package_factory.js');
const CommandType = DHTPackage.CommandType;
const dhtPackageFactory = new DHTPackageFactory();
let dhtPKG = dhtPackageFactory.createPackage(CommandType.PING_REQ);
let pkgCommon = dhtPKG.common;
pkgCommon.src = {
'peeridHash': 1,
'peerid': 'source',
'eplist': ['ep1', 'ep2'],
'additionalInfo': [['isSN',true], ['isMiner',false]],
};
pkgCommon.dest = {
'peeridHash': 2,
'peerid': 'destination',
'ep': '4@192.168.0.1:1234',
};
pkgCommon.seq = 4567;
pkgCommon.ackSeq = 3456;
pkgCommon.ttl = 5;
pkgCommon.nodes = [{id:'p1', eplist:['ep3', 'ep4']}, {id:'p2', eplist:['ep5', 'ep6']}];
dhtPKG.body = {
content: 'ping',
};
console.log(`Initial package is :`);
console.log(dhtPKG);
let encoder = DHTPackageFactory.createEncoder(dhtPKG);
let buffer = encoder.encode();
let decoder = DHTPackageFactory.createDecoder(buffer, 0, buffer.length);
let decodePkg = decoder.decode();
console.log(`Decode package is :`);
console.log(decodePkg);
|
// To work correctly, these ratios need to be maintained exactly, e.g. xxSmall must be 2x tiny etc.
export default {
min: 0,
tiny: 2,
xxSmall: 4,
xSmall: 8,
small: 12,
medium: 16,
large: 24,
xLarge: 32,
xxLarge: 48,
giant: 64,
max: 88,
}
|
import { reqSpecsList} from '../../utils/request'
const state = {
list: []
}
const mutations = {
changeList(state, arr) {
state.list = arr
},
}
const actions = {
requestSpecsList(context) {
reqSpecsList({ size: 10, page: 1 }).then(res => {
res.data.list.forEach(item => {
item.attrs = JSON.parse(item.attrs)
});
context.commit('changeList', res.data.list)
})
}
}
const getters = {
list(state) {
return state.list
}
}
export default {
state,
mutations,
actions,
getters,
namespaced: true
} |
var Accessory = require('../').Accessory;
var Service = require('../').Service;
var Characteristic = require('../').Characteristic;
var uuid = require('../').uuid;
var util = require('util');
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://localhost');
var BattleStation = {
name: "Battle Station PC",
pincode: "031-45-152",
username: "FA:3C:EF:5A:1A:1A:",
manufacturer: "yobasoft",
model: "v1.1",
serialNumber: "YOBA2",
isOn: true,
outputLogs: false,
getOn: function() {
if(this.outputLogs) console.log("'%s' on is %s", this.name, this.isOn);
return this.isOn;
},
setOn: function(status) {
if(this.outputLogs) console.log("'%s' turning the PC %s", this.name, status ? "on" : "off");
this.isOn = status;
client.publish("pc/switch", this.isOn ? 'on' : 'off');
},
identify: function() {
if(this.outputLogs) console.log("Identify the '%s'", this.name);
}
}
var sensorUUID = uuid.generate('yobasoft:accessories:battle-station-pc' + BattleStation.name);
var sensor = exports.accessory = new Accessory(BattleStation.name, sensorUUID);
sensor.username = BattleStation.username;
sensor.pincode = BattleStation.pincode;
sensor
.getService(Service.AccessoryInformation)
.setCharacteristic(Characteristic.Manufacturer, BattleStation.manufacturer)
.setCharacteristic(Characteristic.Model, BattleStation.model)
.setCharacteristic(Characteristic.SerialNumber, BattleStation.serialNumber);
// listen for the "identify" event for this Accessory
sensor.on('identify', function(paired, callback) {
BattleStation.identify();
callback();
});
sensor
.addService(Service.Lightbulb, "PC")
.getCharacteristic(Characteristic.On)
.on('set', function(value, callback) {
BattleStation.setOn(value);
callback();
})
.on('get', function(callback) {
callback(null, BattleStation.getOn());
});
client.on('connect', function() {
client.subscribe("pc/status")
});
client.on('message', function(topic, message) {
if (topic =="pc/status") {
BattleStation.isOn = message.toString() == 'on';
}
if (BattleStation.outputLogs) console.log("Got '%s' data: '%s'", topic, message);
});
|
const config = {
isProd: false
}
export default config
|
var pets = require('../controllers/controllers');
var path = require('path');
module.exports = function (app) {
app.get('/', function (req, res) {
// This is where we will retrieve the users from the database and include them in the view page we will be rendering.
pets.index(req, res);
})
// Below is example of post method
app.post('/addNew', function (req, res) {
pets.addNew(req, res);
});
app.route('/pet/:_id')
.get(function (req, res) {
pets.find_pet(req, res);
})
.put(function (req, res) {
pets.update_pet(req, res);
})
.delete(function (req, res) {
pets.delete_pet(req, res);
});
app.route('/petlike/:_id')
.put(function (req, res) {
pets.update_like(req, res);
});
app.get('/all', function (req, res) {
// This is where we will retrieve the users from the database and include them in the view page we will be rendering.
pets.AllPets(req, res);
});
app.all("*", (req, res, next) => {
res.sendFile(path.resolve("./public/dist/public/index.html"))
});
} |
function logURL(requestDetails) {
var matches = requestDetails.url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
var domain = matches && matches[1];
var exeFile = Components.classes["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
exeFile.initWithPath("/tmp/parse_firefox.py");
if(exeFile.exists())
{
var process = Components.classes["@mozilla.org/process/util;1"].createInstance(Ci.nsIProcess);
process.init(exeFile);
process.run(false,[domain],1);
}
console.log("Loading: " + requestDetails.url);
console.log("testing some voodoo: " + domain);
}
browser.webRequest.onBeforeRequest.addListener(
logURL,
{urls: ["<all_urls>"]}
);
|
(function () {
'use strict';
angular
.module('0908essbar')
.config(config);
function config($stateProvider) {
$stateProvider
.state('0908essbar', {
url: '/archiv-2017/09-08-essbar',
templateUrl: 'archiv-2017/09-08-essbar/views/09-08-essbar.tpl.html',
controller: 'C0908essbarCtrl',
controllerAs: '0908essbar'
});
}
}());
|
var express = require("express"),
passport = require("passport"),
signin = require("./signin");
var app = express(),
users = new Bourne("users.json"),
photos = new Bourne("photos.json"),
comments = new Bourne("comments.json");
passport.use(signin.strategy(users));
passport.serialiceUser(signin.serialice);
passport.deserialize(signin.deserialize(users));
app.configure(function () {
app.use(express.urlencoded());
app.use(express.json());
app.use(express.multipart());
app.use(express.cookieParser());
app.use(express.session({ secret: 'photo-application' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static('public'));
});
app.get('/login', function (req, res) {
res.render('login.ejs');
});
app.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login'
}));
app.get('/logout', function (req, res) {
req.logout();
res.redirect('/');
});
app.post('/create', function (req, res, next) {
var userAttrs = {
username = req.body.username,
passwordHash: signin.hashPassword(req.body.password),
following = []
};
users.findOne({
username: userAttrs.user-name
}, function (existingUser) {
if (!existingUser) {
users.insert(userAttrs, function (user) {
req.login(user, function (err) {
res.redirect("/");
});
});
} else {
res.redirect("/");
}
});
});
app.get('/*', function (req, res) {
if (!req.user) {
res.redirect("/login");
return;
}
res.render("index.ejs", {
user: JSON.stringify(safe(req.user))
});
});
|
export const SEARCH_MOVIE_REQUESTED = "SEARCH_MOVIE_REQUESTED";
export const SEARCH_MOVIE_FINISHED = "SEARCH_MOVIE_FINISHED";
export const SEARCH_STRING_CHANGED = "SEARCH_STRING_CHANGED";
export const PAGE_CHANGED = "PAGE_CHANGED";
export const VIEW_MOVIE_SELECTED = "VIEW_MOVIE_SELECTED";
export const MOVIE_DETAILS_REQUESTED = "MOVIE_DETAILS_REQUESTED";
export const MOVIE_DETAILS_COMPLETED = "MOVIE_DETAILS_COMPLETED";
export const CLEARED_MOVIE_DETAIL = "CLEARED_MOVIE_DETAIL";
export const LOADED_GENRES_REQUESTED = "LOADED_GENRES_REQUESTED";
export const LOADED_GENRES_COMPLETED = "LOADED_GENRES_COMPLETED";
|
import React, {Component} from 'react';
import {Grid, FABButton, Icon, Dialog, DialogTitle, DialogContent, DialogActions, Button, Textfield, Chip} from 'react-mdl';
export default class PostModal extends Component {
constructor(props) {
super(props)
this.state = { category: 'sell', title: '', description: '', image: '', email: '', tags: [] };
}
handleSubmit (e) {
e.preventDefault()
this.props.createAd(this.state)
}
handleTitle (e) {
this.setState({title: e.target.value})
}
handlePrice (e) {
this.setState({price: e.target.value})
}
handleCategory (e) {
this.setState({category: e.target.value})
}
handleImage (e) {
this.setState({image: e.target.value})
}
handleDescription (e) {
this.setState({description: e.target.value})
}
handleEmail (e) {
this.setState({email: e.target.value})
}
handleTags (e) {
let input = e.currentTarget.value.split(/\s+/).filter( elem => elem !== "" );
let tags = [];
for (let i = 0; i < input.length; i++) {
tags.push( { title: input[i] } );
}
console.log("tags", tags);
this.setState({tags: tags})
}
render() {
return (
<Dialog open={this.props.openModal}>
<DialogTitle>Create a Queens List Ad</DialogTitle>
<DialogContent>
<h6>Sell Some Legit 100% FoReal Stuff</h6>
<Textfield
onChange={this.handleTitle.bind(this)}
label="Title..."
floatingLabel
style={{width: '400px'}}
/>
<Textfield
onChange={this.handleEmail.bind(this)}
label="Email..."
floatingLabel
style={{width: '400px'}}
/>
<Textfield
onChange={this.handleImage.bind(this)}
label="Image URL..."
floatingLabel
style={{width: '400px'}}
/>
<Textfield
onChange={this.handlePrice.bind(this)}
pattern="-?[0-9]*(\.[0-9]+)?"
error="Input is not a number!"
label="Price..."
floatingLabel
/>
<Textfield
onChange={this.handleDescription.bind(this)}
label="Description"
rows={3}
style={{width: '200px'}}
/>
<Textfield
onChange={this.handleTags.bind(this)}
label="Tags"
floatingLabel
style={{width: '400px'}}
/>
<div className="well">
{this.state.tags}
</div>
</DialogContent>
<DialogActions fullWidth>
<Button type='button' onClick={this.handleSubmit.bind(this)}>Post</Button>
<Button type='button' onClick={this.props.handleCloseDialog}>Discard</Button>
</DialogActions>
</Dialog>
)
}
}
|
import axios from 'axios';
class ProfileApi {
constructor() {
this.apiInstance = axios.create({
baseURL: `${process.env.REACT_APP_API_URL}`,
withCredentials: true
});
}
getUserInfo() {
return this.apiInstance.get('/profile')
.then(({ data }) => {
return data
})
}
getOtherUserInfo(id) {
return this.apiInstance.get(`/profile/${id}`)
.then(({ data }) => {
return data.user
})
}
updateProfile(info) {
return this.apiInstance.put('/profile', info)
.then(({ data }) => {
return data
})
}
}
const ProfileService = new ProfileApi();
export default ProfileService |
$('#submitBtn').on('click', function () {
var name = $('#nameInput').val().trim();
var phone = $('#phoneInput').val().trim();
var email = $('#emailInput').val().trim();
var time = $('#timeInput').val().trim();
var clientObj = {
"name": name,
"phone": phone,
"email": email,
"time": time
}//client obj
$.post('http://localhost:3000/data', function() {
clientObj;
});//post
$.get('http://localhost:3000/api/' + waitlist, function (show) {
console.log(show);
if(show) {
$('#waitlistDisplay').show();
for(var i = 0; i < show.length; i++) {
$('.name').text(show[i].name);
$('.time').text(show[i].time);
$('.phone').text(show[i].phone);
$('.email').text(show[i].email);
}//for
}//if
});//get
$.get('http://localhost:3000/api/' + tables, function(show) {
console.log(show);
if(show) {
$('#tablesDisplay').show();
for(var i = 0; i < show.length; i++) {
$('.name').text(show[i].name);
$('.time').text(show[i].time);
$('.phone').text(show[i].phone);
$('.email').text(show[i].email);
}//for
}//if
});//get
});//onclick |
Template.stub('devicesinfo');
describe("devicesinfo template", function () {
it("functions", function () {
Template.devicesinfo.created();
expect(Session.get('errorMessage')).toBe(null);
Session.set('currentdevice',1234);
var device = { _id : "1234"};
spyOn(Devices, 'findOne').andReturn(device);
expect(Template.devicesinfo.currentdevice()).toBe(device);
Session.set('recorddisplays',true);
expect(Template.devicesinfo.recorddisplay()).toBe(true);
});
it("events", function () {
Template.devicesinfo.fireEvent('click #cancel');
expect(Session.get('currentdevice')).toBe(1234);
spyOn(Devices, 'find').andReturn({ count : function () { return 0 } });
var template = { find : function(key){ return { value : key } } };
Template.devicesinfo.customEvent('click #register' , { event : {} , template : template } );
Template.devicesinfo.customEvent('click #update' , { event : {} , template : template } );
});
});
|
import express, { json, urlencoded } from 'express';
import { join } from 'path';
import cookieParser from 'cookie-parser';
import logger from 'morgan';
import session from 'express-session';
import passport from 'passport';
import passportLocal from 'passport-local';
import apiRoutes from './routes/api';
import { initializeDB } from './db';
var app = express();
app.use(logger('dev'));
app.use(json());
app.use(urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(express.static(join(__dirname, 'client/build')));
passport.use(new passportLocal.Strategy(
(username, password, done) => {
// TODO: lookup auth like this
/*
try {
const match = await findUser(username, password);
if (match.isValidUser) {
return done(null, match);
}
} catch (err) {
return done(null, false, { message: 'Invalid credentials' });
}
*/
return done(null, {username});
}
));
if (!process.env.KEYBOARD_CAT) {
console.error("No keyboard cat");
process.exit(-3);
}
app.use(session({ secret: process.env.KEYBOARD_CAT }));
app.use(passport.initialize());
app.use(passport.session());
// error handler
app.use(function (err, req, res) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.send(err.message);
});
initializeDB();
app.use('/api', apiRoutes);
export default app; |
module.exports = {
summary: 'The rule to demo AnyProxy plugin',
getWebFiles() {
return [
'./web.js',
'./web.css'
]
},
*beforeDealHttpsRequest(requestDetail) {
return true;
},
*beforeSendRequest(requestDetail) {
requestDetail.pluginData = {
requestPluginData: 'The data you set in before sending request'
}
return requestDetail;
},
/**
* 总入口
* @param requestDetail
* @param responseDetail
*/
*beforeSendResponse(requestDetail, responseDetail) {
responseDetail.pluginData = {
responsePluginData: 'The data you set in before sending response'
}
return responseDetail;
}
};
|
import React from "react";
import FormPanel from "./FormPanel.jsx"
import EthClient from "../client/ethclient.js";
import PubSub from "pubsub-js"
let WorkerPanel = React.createClass({
registerWorker(worker) {
EthClient.registerWorker(worker.maxLength, worker.price,
worker.workerName, worker.ip)
PubSub.publish('worker_registered');
},
render() {
return (
<div className="container">
<div className="page-header">
<h1>Worker frontend <small>ish</small></h1>
<div className="row">
<FormPanel onContractInteract={this.registerWorker}/>
</div>
</div>
</div>
);
}
})
export default WorkerPanel;
|
import React, { Component } from "react";
import { connect } from "react-redux";
import { getAppCustomization } from "../../lib/helpers";
import { POSITION } from './properties';
import { LayoutLeft, LayoutRight, LayoutTop, LayoutBottom } from './Positions';
import _ from 'lodash';
import "./index.css";
class SubSections extends Component {
constructor(props){
super(props);
this.state = {
subSections: [],
component: null
};
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
projectData = async (props) => {
let { subSections } = getAppCustomization();
const { location, ln } = props;
subSections = subSections.languages.find(s => s.language.isActivated === true && s.language.prefix === ln.toUpperCase());
if(!_.isEmpty(subSections)){
subSections = subSections.ids.filter(s => s.location == location);
}
this.setState({
subSections
});
}
renderSubSection = (subSection) => {
switch(subSection.position) {
case POSITION.LEFT:
return <LayoutLeft data={subSection}/>;
case POSITION.RIGHT:
return <LayoutRight data={subSection}/>;
case POSITION.TOP:
return <LayoutTop data={subSection}/>;
case POSITION.BOTTOM:
return <LayoutBottom data={subSection}/>;
}
}
render() {
const { subSections } = this.state;
if(_.isEmpty(subSections)) { return null };
return (
<div styleName="sub-sections">
{subSections.map(s => {
if(!_.isEmpty(s.title) && !_.isEmpty(s.text)) {
return this.renderSubSection(s);
}
})}
</div>
);
}
}
function mapStateToProps(state){
return {
profile: state.profile,
ln : state.language
};
}
export default connect(mapStateToProps)(SubSections);
|
var event_id = $('#event_id').val();
var event_name = $('#event_name').val();
var add_invite = $('#add_invite').val();
var invite_detail = $('#invite_detail').val();
var update_invite = $('#update_invite').val();
var delete_invite = $('#delete_invite').val();
var event_mark_incomplete = $('#event_mark_incomplete').val();
var event_mark_complete = $('#event_mark_complete').val();
var event_save_note = $('#event_save_note').val();
var edit_popup_url = $('#edit_popup_url').val();
var txt_delete_confirm = $('#txt_delete_confirm').val();
var delete_event_url = $('#delete_event_url').val();
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i);
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
$(function() {
if(!isMobile.any()) {
$('#tab_share_whatsapp').hide();
}
});
$(document).delegate('.note_wrapper .btn-edit', 'click', function() {
$note_wrapper = $(this).parents('.note_wrapper');
$note_wrapper.find('p').hide();
$note_wrapper.find('form').fadeIn();
});
$(document).delegate('.note_wrapper .btn-save', 'click', function() {
$data = $(this).parents('form').serialize();
$.post(event_save_note, $data, function(json) {
$note_wrapper.find('textarea').html(json.note);
$note_wrapper.find('p span').html(json.note);
$note_wrapper.find('p').fadeIn();
$note_wrapper.find('form').hide();
});
});
$(document).delegate('.btn-mark-incomplete', 'click', function() {
$event_id = $(this).attr('data-event-id');
$category_id = $(this).attr('data-cat-id');
$.post(event_mark_incomplete, {
event_id : $event_id,
category_id : $category_id
}, function(json) {
$('.progressbar_wrapper').html(json.progress);
$('button[data-cat-id="' + $category_id + '"]')
.html(json.btn_text)
.removeClass('btn-mark-incomplete')
.addClass('btn-mark-complete');
}
);
});
$(document).delegate('.btn-mark-complete', 'click', function() {
$event_id = $(this).attr('data-event-id');
$category_id = $(this).attr('data-cat-id');
$.post(event_mark_complete, {
event_id : $event_id,
category_id : $category_id
}, function(json) {
$('.progressbar_wrapper').html(json.progress);
$('button[data-cat-id="' + $category_id + '"]')
.html(json.btn_text)
.addClass('btn-mark-incomplete')
.removeClass('btn-mark-complete');
}
);
});
function editevent(event_id)
{
jQuery.ajax({
type:'POST',
url: edit_popup_url,
data:{
'event_id':event_id
},
success:function(data)
{
jQuery('#editeventModal').html(data);
jQuery('.selectpicker').selectpicker('refresh');
jQuery('#edit_event_date').datepicker({
format: 'dd-mm-yyyy',
startDate:'today',
autoclose:true,
});
jQuery('#EditeventModal').modal('show');
}
});
}
$(document).ready(function () {
jQuery('#collapse0').attr('aria-expanded', 'true');
jQuery('#collapse0').attr('class', 'panel-collapse collapse in');
});
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
$('label#search-labl3').click(function(){
jQuery.pjax.reload({container:'#invitee-grid'});
});
function deleteeventitem(item_link_id, category_name,category_id,event_id,tis)
{
if (confirm(txt_delete_confirm)) {
jQuery.ajax({
url: delete_event_url,
type:'POST',
data: {
'item_link_id':item_link_id,
'category_id':category_id,
'event_id':event_id
},
success:function(json)
{
if(json.success)
{
jQuery('#'+tis).parents('.panel-default').find('span#item_count').html(json.count);
jQuery('#'+tis).parents('li').remove();
jQuery('#login_success').modal('show');
jQuery('#login_success #success').html('<span class=\"sucess_close\"> </span><span class=\"msg-success\" >' + json.success + '</span>');
window.setTimeout(function() {
jQuery('#login_success').modal('hide');
},2000);
}
if(json.error)
{
jQuery('#login_success').modal('show');
jQuery('#success').html('<span class=\"sucess_close\"> </span><span class=\"msg-success\"> '+ json.error+' </span>');
window.setTimeout(function() {
jQuery('#login_success').modal('hide');
}, 2000);
}
}
})
}
} |
FvB.Sprites = (function () {
FvB.setConsts({
GFX_PATH: 'gfx'
});
// hitBoxes are relative to the entity x,y position, which is center x, bottom y
var sprites = [
{ sprite: "SPR_RYU_BACKGROUND", sheet: "RYU-STAGE.PNG", xOffset: 0, yOffset: 0, width: 640, height: 400, hitBox: null },
{ sprite: "SPR_PLAYER_HEALTH_BAR", sheet: "HEALTH.PNG", xOffset: 0, yOffset: 0, width: 640, height: 30, hitBox: null },
// Title Screen
{ sprite: "SPR_TITLE_FARTSAC", sheet: "GAME.PNG", xOffset: 1, yOffset: 1, width: 220, height: 16, hitBox: null },
{ sprite: "SPR_TITLE_VS", sheet: "GAME.PNG", xOffset: 1, yOffset: 19, width: 62, height: 16, hitBox: null },
{ sprite: "SPR_TITLE_BOOGERBOY", sheet: "GAME.PNG", xOffset: 1, yOffset: 37, width: 286, height: 16, hitBox: null },
{ sprite: "SPR_NUM_PLAYERS", sheet: "GAME.PNG", xOffset: 1, yOffset: 55, width: 142, height: 44, hitBox: null },
{ sprite: "SPR_TITLE_TURD", sheet: "FARTSAC.PNG", xOffset: 832, yOffset: 0, width: 22, height: 10, hitBox: null },
{ sprite: "SPR_TITLE_BOOG", sheet: "BOOGERBOY.PNG", xOffset: 832, yOffset: 10, width: 22, height: 10, hitBox: null },
// Choose a character
{ sprite: "SPR_CHARACTER_SELECT_TEXT", sheet: "CHARSELECT.PNG", xOffset: 0, yOffset: 0, width: 640, height: 22, hitBox: null },
{ sprite: "SPR_1P", sheet: "CHARSELECT.PNG", xOffset: 68, yOffset: 148, width: 34, height: 22, hitBox: null },
{ sprite: "SPR_2P", sheet: "CHARSELECT.PNG", xOffset: 510, yOffset: 152, width: 34, height: 22, hitBox: null },
{ sprite: "SPR_1P_SELECT", sheet: "CHARSELECT.PNG", xOffset: 8, yOffset: 42, width: 52, height: 82, hitBox: null },
{ sprite: "SPR_2P_SELECT", sheet: "CHARSELECT.PNG", xOffset: 62, yOffset: 42, width: 52, height: 82, hitBox: null },
{ sprite: "SPR_BOTH_SELECT", sheet: "CHARSELECT.PNG", xOffset: 116, yOffset: 42, width: 52, height: 82, hitBox: null },
{ sprite: "SPR_VERSUS", sheet: "CHARSELECT.PNG", xOffset: 459, yOffset: 40, width: 126, height: 94, hitBox: null },
{ sprite: "SPR_CHARACTER_SELECT_MATRIX", sheet: "CHARSELECT.PNG", xOffset: 244, yOffset: 80, width: 152, height: 82, hitBox: null },
// Round/Fight!
{ sprite: "SPR_ROUND1_SMALL", sheet: "ROUNDS.PNG", xOffset: 1, yOffset: 1, width: 50, height: 8, hitBox: null },
{ sprite: "SPR_ROUND2_SMALL", sheet: "ROUNDS.PNG", xOffset: 1, yOffset: 55, width: 50, height: 8, hitBox: null },
{ sprite: "SPR_ROUND3_SMALL", sheet: "ROUNDS.PNG", xOffset: 1, yOffset: 109, width: 50, height: 8, hitBox: null },
{ sprite: "SPR_ROUND1_MEDIUM", sheet: "ROUNDS.PNG", xOffset: 1, yOffset: 11, width: 100, height: 16, hitBox: null },
{ sprite: "SPR_ROUND2_MEDIUM", sheet: "ROUNDS.PNG", xOffset: 1, yOffset: 65, width: 106, height: 16, hitBox: null },
{ sprite: "SPR_ROUND3_MEDIUM", sheet: "ROUNDS.PNG", xOffset: 1, yOffset: 119, width: 106, height: 16, hitBox: null },
{ sprite: "SPR_ROUND1_LARGE", sheet: "ROUNDS.PNG", xOffset: 1, yOffset: 29, width: 150, height: 24, hitBox: null },
{ sprite: "SPR_ROUND2_LARGE", sheet: "ROUNDS.PNG", xOffset: 1, yOffset: 83, width: 158, height: 24, hitBox: null },
{ sprite: "SPR_ROUND3_LARGE", sheet: "ROUNDS.PNG", xOffset: 1, yOffset: 137, width: 158, height: 24, hitBox: null },
{ sprite: "SPR_FIGHT_SMALL", sheet: "ROUNDS.PNG", xOffset: 1, yOffset: 163, width: 44, height: 8, hitBox: null },
{ sprite: "SPR_FIGHT_MEDIUM", sheet: "ROUNDS.PNG", xOffset: 1, yOffset: 173, width: 88, height: 16, hitBox: null },
{ sprite: "SPR_FIGHT_LARGE", sheet: "ROUNDS.PNG", xOffset: 1, yOffset: 191, width: 132, height: 24, hitBox: null },
// You Win/Lose
{ sprite: "SPR_YOUWIN_REGULAR", sheet: "ROUNDS.PNG", xOffset: 1, yOffset: 217, width: 170, height: 24, hitBox: null },
{ sprite: "SPR_YOUWIN_INVERSE", sheet: "ROUNDS.PNG", xOffset: 1, yOffset: 243, width: 170, height: 24, hitBox: null },
{ sprite: "SPR_YOULOSE_REGULAR", sheet: "ROUNDS.PNG", xOffset: 1, yOffset: 269, width: 198, height: 24, hitBox: null },
// Character sprites must be in enum order for easier rendering
// For example: to render SPR_BOOGER_TEXT we can just to renderSprite(SPR_FARTSAC_TEXT + characterEntityNum)
{ sprite: "SPR_FARTSAC_TEXT", sheet: "CHARSELECT.PNG", xOffset: 5, yOffset: 181, width: 96, height: 14, hitBox: null },
{ sprite: "SPR_BOOGERBOY_TEXT", sheet: "CHARSELECT.PNG", xOffset: 441, yOffset: 178, width: 124, height: 14, hitBox: null },
{ sprite: "SPR_YOHAN_TEXT", sheet: "CHARSELECT.PNG", xOffset: 270, yOffset: 179, width: 72, height: 14, hitBox: null },
{ sprite: "SPR_RYU_TEXT", sheet: "CHARSELECT.PNG", xOffset: 655, yOffset: 173, width: 40, height: 14, hitBox: null },
{ sprite: "SPR_FARTSAC_MUG", sheet: "CHARSELECT.PNG", xOffset: 3, yOffset: 198, width: 202, height: 205, hitBox: null },
{ sprite: "SPR_BOOGERBOY_MUG", sheet: "CHARSELECT.PNG", xOffset: 429, yOffset: 199, width: 202, height: 205, hitBox: null },
{ sprite: "SPR_YOHAN_MUG", sheet: "CHARSELECT.PNG", xOffset: 215, yOffset: 199, width: 202, height: 205, hitBox: null },
{ sprite: "SPR_RYU_MUG", sheet: "CHARSELECT.PNG", xOffset: 646, yOffset: 199, width: 202, height: 206, hitBox: null },
// Fartsac
{ sprite: "SPR_FARTSAC_STAND_1", sheet: "FARTSAC.PNG", xOffset: 0, yOffset: 0, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -50, y2: 0 } },
{ sprite: "SPR_FARTSAC_CROUCH_1", sheet: "FARTSAC.PNG", xOffset: 64, yOffset: 0, width: 64, height: 64, hitBox: { x1: -2, x2: 12, y1: -36, y2: 0 } },
{ sprite: "SPR_FARTSAC_JUMP_1", sheet: "FARTSAC.PNG", xOffset: 128, yOffset: 0, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -64, y2: 0 } },
{ sprite: "SPR_FART_TURD_1", sheet: "FARTSAC.PNG", xOffset: 192, yOffset: 0, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -64, y2: 0 } },
{ sprite: "SPR_FART_TURD_2", sheet: "FARTSAC.PNG", xOffset: 256, yOffset: 0, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -64, y2: 0 } },
{ sprite: "SPR_FART_TURD_3", sheet: "FARTSAC.PNG", xOffset: 320, yOffset: 0, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -64, y2: 0 } },
{ sprite: "SPR_FART_TURD_4", sheet: "FARTSAC.PNG", xOffset: 384, yOffset: 0, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -64, y2: 0 } },
{ sprite: "SPR_FART_TURD_5", sheet: "FARTSAC.PNG", xOffset: 448, yOffset: 0, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -64, y2: 0 } },
{ sprite: "SPR_FART_TURD_6", sheet: "FARTSAC.PNG", xOffset: 512, yOffset: 0, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -64, y2: 0 } },
{ sprite: "SPR_FART_TURD_7", sheet: "FARTSAC.PNG", xOffset: 576, yOffset: 0, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -64, y2: 0 } },
{ sprite: "SPR_FART_TURD_8", sheet: "FARTSAC.PNG", xOffset: 640, yOffset: 0, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -64, y2: 0 } },
{ sprite: "SPR_FART_TURD_9", sheet: "FARTSAC.PNG", xOffset: 704, yOffset: 0, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -64, y2: 0 } },
{ sprite: "SPR_FART_TURD_10", sheet: "FARTSAC.PNG", xOffset: 768, yOffset: 0, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -64, y2: 0 } },
{ sprite: "SPR_FARTSAC_DAMAGED_1", sheet: "FARTSAC.PNG", xOffset: 0, yOffset: 128, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -50, y2: 0 } },
{ sprite: "SPR_FARTSAC_DAMAGED_2", sheet: "FARTSAC.PNG", xOffset: 64, yOffset: 128, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -50, y2: 0 } },
{ sprite: "SPR_FARTSAC_FARTING", sheet: "FARTSAC.PNG", xOffset: 0, yOffset: 384, width: 64, height: 64, hitbox: { x1: -5, x2: 5, y1: -50, y2: 0 } },
// Boogerboy
{ sprite: "SPR_BOOGERBOY_STAND_1", sheet: "BOOGERBOY.PNG", xOffset: 0, yOffset: 0, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -50, y2: 0 } },
{ sprite: "SPR_BOOGERBOY_CROUCH_1", sheet: "BOOGERBOY.PNG", xOffset: 64, yOffset: 0, width: 64, height: 64, hitBox: { x1: -12, x2: 14, y1: -36, y2: 0 } },
{ sprite: "SPR_BOOGERBOY_JUMP_1", sheet: "BOOGERBOY.PNG", xOffset: 128, yOffset: 0, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -64, y2: 0 } },
{ sprite: "SPR_BLOW_BOOG_1", sheet: "BOOGERBOY.PNG", xOffset: 192, yOffset: 0, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -50, y2: 0 } },
{ sprite: "SPR_BLOW_BOOG_2", sheet: "BOOGERBOY.PNG", xOffset: 256, yOffset: 0, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -64, y2: 0 } },
{ sprite: "SPR_BLOW_BOOG_3", sheet: "BOOGERBOY.PNG", xOffset: 320, yOffset: 0, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -64, y2: 0 } },
{ sprite: "SPR_BLOW_BOOG_4", sheet: "BOOGERBOY.PNG", xOffset: 384, yOffset: 0, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -64, y2: 0 } },
{ sprite: "SPR_BLOW_BOOG_5", sheet: "BOOGERBOY.PNG", xOffset: 448, yOffset: 0, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -64, y2: 0 } },
{ sprite: "SPR_BLOW_BOOG_6", sheet: "BOOGERBOY.PNG", xOffset: 512, yOffset: 0, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -64, y2: 0 } },
{ sprite: "SPR_BLOW_BOOG_7", sheet: "BOOGERBOY.PNG", xOffset: 576, yOffset: 0, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -64, y2: 0 } },
{ sprite: "SPR_BLOW_BOOG_8", sheet: "BOOGERBOY.PNG", xOffset: 640, yOffset: 0, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -64, y2: 0 } },
{ sprite: "SPR_BLOW_BOOG_9", sheet: "BOOGERBOY.PNG", xOffset: 704, yOffset: 0, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -64, y2: 0 } },
{ sprite: "SPR_BLOW_BOOG_10", sheet: "BOOGERBOY.PNG", xOffset: 768, yOffset: 0, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -64, y2: 0 } },
{ sprite: "SPR_BOOGERBOY_DAMAGED_1", sheet: "BOOGERBOY.PNG", xOffset: 0, yOffset: 128, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -50, y2: 0 } },
{ sprite: "SPR_BOOGERBOY_DAMAGED_2", sheet: "BOOGERBOY.PNG", xOffset: 64, yOffset: 128, width: 64, height: 64, hitBox: { x1: -5, x2: 5, y1: -50, y2: 0 } },
{ sprite: "SPR_BOOG_HEAD", sheet: "BOOGERBOY.PNG", xOffset: 64, yOffset: 306, width: 12, height: 14, hitBox: null },
{ sprite: "SPR_BOOG_HEADLESS", sheet: "BOOGERBOY.PNG", xOffset: 0, yOffset: 256, width: 64, height: 64, hitBox: null },
// These need to be in charEntity order as well
{ sprite: "SPR_FARTBALL", sheet: "FARTSAC.PNG", xOffset: 871, yOffset: 0, width: 6, height: 6, hitBox: null },
{ sprite: "SPR_BOOGBALL", sheet: "BOOGERBOY.PNG", xOffset: 861, yOffset: 0, width: 6, height: 6, hitBox: null },
{ sprite: "SPR_HUGE_FARTBALL", sheet: "FARTSAC.PNG", xOffset: 832, yOffset: 0, width: 22, height: 10, hitBox: null },
{ sprite: "SPR_HUGE_BOOGER", sheet: "BOOGERBOY.PNG", xOffset: 832, yOffset: 0, width: 22, height: 10, hitBox: null },
// Explosion
{ sprite: "SPR_EXPLOSION_0", sheet: "SMALLEXPLOSION.PNG", xOffset: 0, yOffset: 0, width: 20, height: 20, hitBox: null },
{ sprite: "SPR_EXPLOSION_1", sheet: "SMALLEXPLOSION.PNG", xOffset: 20, yOffset: 0, width: 20, height: 20, hitBox: null },
{ sprite: "SPR_EXPLOSION_2", sheet: "SMALLEXPLOSION.PNG", xOffset: 40, yOffset: 0, width: 20, height: 20, hitBox: null },
{ sprite: "SPR_EXPLOSION_3", sheet: "SMALLEXPLOSION.PNG", xOffset: 60, yOffset: 0, width: 20, height: 20, hitBox: null },
{ sprite: "SPR_EXPLOSION_4", sheet: "SMALLEXPLOSION.PNG", xOffset: 80, yOffset: 0, width: 20, height: 20, hitBox: null },
{ sprite: "SPR_EXPLOSION_5", sheet: "SMALLEXPLOSION.PNG", xOffset: 100, yOffset: 0, width: 20, height: 20, hitBox: null },
{ sprite: "SPR_EXPLOSION_6", sheet: "SMALLEXPLOSION.PNG", xOffset: 120, yOffset: 0, width: 20, height: 20, hitBox: null },
{ sprite: "SPR_EXPLOSION_7", sheet: "SMALLEXPLOSION.PNG", xOffset: 140, yOffset: 0, width: 20, height: 20, hitBox: null },
{ sprite: "SPR_EXPLOSION_8", sheet: "SMALLEXPLOSION.PNG", xOffset: 160, yOffset: 0, width: 20, height: 20, hitBox: null },
{ sprite: "SPR_EXPLOSION_9", sheet: "SMALLEXPLOSION.PNG", xOffset: 180, yOffset: 0, width: 20, height: 20, hitBox: null },
{ sprite: "SPR_EXPLOSION_10", sheet: "SMALLEXPLOSION.PNG", xOffset: 200, yOffset: 0, width: 20, height: 20, hitBox: null },
{ sprite: "SPR_EXPLOSION_11", sheet: "SMALLEXPLOSION.PNG", xOffset: 220, yOffset: 0, width: 20, height: 20, hitBox: null },
{ sprite: "SPR_EXPLOSION_12", sheet: "SMALLEXPLOSION.PNG", xOffset: 240, yOffset: 0, width: 20, height: 20, hitBox: null },
// Huge Explosion
{ sprite: "SPR_HUGE_EXPLOSION_0", sheet: "EXPLODEY.PNG", xOffset: 0, yOffset: 0, width: 40, height: 40, hitBox: null },
{ sprite: "SPR_HUGE_EXPLOSION_1", sheet: "EXPLODEY.PNG", xOffset: 40, yOffset: 0, width: 40, height: 40, hitBox: null },
{ sprite: "SPR_HUGE_EXPLOSION_2", sheet: "EXPLODEY.PNG", xOffset: 80, yOffset: 0, width: 40, height: 40, hitBox: null },
{ sprite: "SPR_HUGE_EXPLOSION_3", sheet: "EXPLODEY.PNG", xOffset: 120, yOffset: 0, width: 40, height: 40, hitBox: null },
{ sprite: "SPR_HUGE_EXPLOSION_4", sheet: "EXPLODEY.PNG", xOffset: 160, yOffset: 0, width: 40, height: 40, hitBox: null },
{ sprite: "SPR_HUGE_EXPLOSION_5", sheet: "EXPLODEY.PNG", xOffset: 200, yOffset: 0, width: 40, height: 40, hitBox: null },
{ sprite: "SPR_HUGE_EXPLOSION_6", sheet: "EXPLODEY.PNG", xOffset: 240, yOffset: 0, width: 40, height: 40, hitBox: null },
{ sprite: "SPR_HUGE_EXPLOSION_7", sheet: "EXPLODEY.PNG", xOffset: 280, yOffset: 0, width: 40, height: 40, hitBox: null },
{ sprite: "SPR_HUGE_EXPLOSION_8", sheet: "EXPLODEY.PNG", xOffset: 320, yOffset: 0, width: 40, height: 40, hitBox: null },
{ sprite: "SPR_HUGE_EXPLOSION_9", sheet: "EXPLODEY.PNG", xOffset: 360, yOffset: 0, width: 40, height: 40, hitBox: null },
{ sprite: "SPR_HUGE_EXPLOSION_10", sheet: "EXPLODEY.PNG", xOffset: 400, yOffset: 0, width: 40, height: 40, hitBox: null },
{ sprite: "SPR_HUGE_EXPLOSION_11", sheet: "EXPLODEY.PNG", xOffset: 440, yOffset: 0, width: 40, height: 40, hitBox: null },
{ sprite: "SPR_HUGE_EXPLOSION_12", sheet: "EXPLODEY.PNG", xOffset: 480, yOffset: 0, width: 40, height: 40, hitBox: null },
// Ryu Idle
{ sprite: "SPR_RYU_IDLE_1", sheet: "RYU.PNG", xOffset: 64, yOffset: 0, width: 64, height: 98, hitBox: { x1: -9, x2: 9, y1: -74, y2: 0 } },
{ sprite: "SPR_RYU_IDLE_2", sheet: "RYU.PNG", xOffset: 128, yOffset: 0, width: 64, height: 98, hitBox: { x1: -9, x2: 9, y1: -74, y2: 0 } },
{ sprite: "SPR_RYU_IDLE_3", sheet: "RYU.PNG", xOffset: 192, yOffset: 0, width: 64, height: 98, hitBox: { x1: -9, x2: 9, y1: -74, y2: 0 } },
{ sprite: "SPR_RYU_IDLE_4", sheet: "RYU.PNG", xOffset: 256, yOffset: 0, width: 64, height: 98, hitBox: { x1: -9, x2: 9, y1: -74, y2: 0 } },
// Ryu Walk
{ sprite: "SPR_RYU_WALK_1", sheet: "RYU.PNG", xOffset: 320, yOffset: 0, width: 64, height: 98, hitBox: null },
{ sprite: "SPR_RYU_WALK_2", sheet: "RYU.PNG", xOffset: 384, yOffset: 0, width: 64, height: 98, hitBox: null },
{ sprite: "SPR_RYU_WALK_3", sheet: "RYU.PNG", xOffset: 448, yOffset: 0, width: 64, height: 98, hitBox: null },
{ sprite: "SPR_RYU_WALK_4", sheet: "RYU.PNG", xOffset: 512, yOffset: 0, width: 64, height: 98, hitBox: null },
// Ryu Crouch
{ sprite: "SPR_RYU_CROUCH_1", sheet: "RYU.PNG", xOffset: 1088, yOffset: 0, width: 64, height: 98, hitBox: null },
// Ryu Jump
{ sprite: "SPR_RYU_JUMP_1", sheet: "RYU.PNG", xOffset: 640, yOffset: 0, width: 64, height: 98, hitBox: null },
{ sprite: "SPR_RYU_JUMP_2", sheet: "RYU.PNG", xOffset: 704, yOffset: 0, width: 64, height: 98, hitBox: null },
// Ryu Hadouken
{ sprite: "SPR_RYU_HADOUKEN_1", sheet: "RYU.PNG", xOffset: 0, yOffset: 196, width: 62, height: 98, hitBox: null },
{ sprite: "SPR_RYU_HADOUKEN_2", sheet: "RYU.PNG", xOffset: 75, yOffset: 196, width: 94, height: 98, hitBox: null },
{ sprite: "SPR_RYU_HADOUKEN_3", sheet: "RYU.PNG", xOffset: 201, yOffset: 196, width: 94, height: 98, hitBox: null },
{ sprite: "SPR_RYU_HADOUKEN_4", sheet: "RYU.PNG", xOffset: 310, yOffset: 196, width: 124, height: 98, hitBox: null },
{ sprite: "SPR_RYU_HADOUKEN_5", sheet: "RYU.PNG", xOffset: 451, yOffset: 196, width: 94, height: 98, hitBox: null },
// Ryu Damaged
{ sprite: "SPR_RYU_DAMAGED_1", sheet: "RYU.PNG", xOffset: 0, yOffset: 392, width: 64, height: 98, hitBox: null },
{ sprite: "SPR_RYU_DAMAGED_2", sheet: "RYU.PNG", xOffset: 64, yOffset: 392, width: 64, height: 98, hitBox: null },
{ sprite: "SPR_RYU_DAMAGED_3", sheet: "RYU.PNG", xOffset: 128, yOffset: 392, width: 64, height: 98, hitBox: null },
{ sprite: "SPR_RYU_DAMAGED_4", sheet: "RYU.PNG", xOffset: 192, yOffset: 392, width: 64, height: 98, hitBox: null },
// Hadouken Projectile
{ sprite: "SPR_HADOUKEN_1", sheet: "RYU.PNG", xOffset: 131, yOffset: 636, width: 68, height: 85, hitBox: null },
{ sprite: "SPR_HADOUKEN_2", sheet: "RYU.PNG", xOffset: 202, yOffset: 636, width: 96, height: 85, hitBox: null },
{ sprite: "SPR_HADOUKEN_3", sheet: "RYU.PNG", xOffset: 299, yOffset: 636, width: 72, height: 85, hitBox: null }
];
var spriteConsts = {};
for (var i = 0, n = sprites.length; i < n; i++) {
spriteConsts[sprites[i].sprite] = i;
}
FvB.setConsts(spriteConsts);
var gfxResources = {};
function loadImage(fileName) {
var img = new Image();
img.onload = function () {
gfxResources[fileName] = img;
};
gfxResources[fileName] = false;
img.src = FvB.GFX_PATH + '/' + fileName;
}
function init() {
var fileName;
for (i = 0; i < sprites.length; i++) {
if (fileName == sprites[i].sheet) {
// already did this one
continue;
} else {
fileName = sprites[i].sheet;
}
loadImage(fileName);
}
}
function isReady() {
var ready = true;
for (var k in gfxResources) {
if (gfxResources.hasOwnProperty(k) &&
!gfxResources[k]) {
ready = false;
break;
}
}
return ready;
}
function getSprite(id) {
return sprites[id];
}
function getTexture(id) {
return gfxResources[sprites[id].sheet];
}
return {
init: init,
isReady: isReady,
getTexture: getTexture,
getSprite: getSprite
};
})(); |
/**
* This test should create books and its associating models, genre model must be created to calssify books.
* Author model is created to for books that have more than one author, with its associations
* User model is created to test its -belongsToMany association with user, this associations
* takes care books borrowed by user
*
* The essence of creating other models is to test Book model associations
*/
//set env variable to test to access the test database
process.env.NODE_ENV = 'test';
//require('log-suppress').init(console, 'test');
const db = require('../../../server/models');
const testData = require('./test-data');
// import models
const User = require('../../../server/models').User;
const LocalUser = require('../../../server/models').LocalUser;
const OtherUser = require('../../../server/models').OtherUser;
const Author = require('../../../server/models').Author;
const Genre = require('../../../server/models').Genre;
const Book = require('../../../server/models').Book;
const Owner = require('../../../server/models').Ownership;
const Borrow = require('../../../server/models').Borrowed;
//import test data
let authorData = testData.Authors;
let genreData = testData.Genres;
let bookData = testData.Books;
let ownerData = testData.Owners;
let borrowData = testData.Borrowed;
let localUserData = testData.LocalUsers;
let googleUserData = testData.GoogleUsers;
const assert = require('chai').assert;
describe('BOOK MODEL', () => {
try {
before(function(done) {
this.timeout(20000);
db.sequelize.sync({ force: true, logging: false }).then(() => {
LocalUser.bulkCreate(localUserData).then((localUser) => {
OtherUser.bulkCreate(googleUserData).then((googleUser) => {
User.bulkCreate([{
userId: localUser[0].uuid,
email: localUser[0].email,
username: localUser[0].username,
createdAt: new Date(),
updatedAt: new Date()
}, {
userId: localUser[1].uuid,
email: localUser[1].email,
username: localUser[1].username,
createdAt: new Date(),
updatedAt: new Date()
}, {
userId: localUser[2].uuid,
email: localUser[2].email,
username: localUser[2].username,
createdAt: new Date(),
updatedAt: new Date()
}, {
userId: googleUser[0].guid,
email: googleUser[0].gmail,
username: googleUser[0].username,
createdAt: new Date(),
updatedAt: new Date()
}, {
userId: googleUser[1].guid,
email: googleUser[1].gmail,
username: googleUser[1].username,
createdAt: new Date(),
updatedAt: new Date()
}]);
});
Author.bulkCreate(authorData).then(() => {
Genre.bulkCreate(genreData).then(() => {
Book.bulkCreate(bookData).then(() => {
Owner.bulkCreate(ownerData).then(() => {
Borrow.bulkCreate(borrowData).then((borrow) => {
if (borrow) {
done();
}
});
});
});
});
});
});
});
});
} catch (e) {
console.log(e);
}
//USER MODEL
describe('USER Model', () => {
it('it should create a user object with its properties', (done) => {
User.findAll().then(user => {
LocalUser.findAll().then(localUser => {
assert.equal(typeof(localUser), 'object'); //an object should be returned
assert.equal(localUser.length, 3); // All user should be created
assert.isNotEmpty(localUser[0].hash && localUser[0].salt); //password should be hashed and not null
done();
});
assert.equal(typeof(user), 'object'); //an object should be returned
assert.equal(user.length, 5); // All user should be created with google users
});
}).timeout(5000);
it('it should have association -belongsToMany for user borrowed books', (done) => {
User.findOne({ where: { id: 1 } }).then(user => {
user.getBooks().then(userBooks => {
assert.equal(userBooks.length, 2); //authorOne should return an array of two books
assert.equal(userBooks[0].get().title, bookData[0].title); //borrowed book with id:1
assert.equal(userBooks[1].get().title, bookData[2].title); //borrowed book with id:3
//find book id:2 in returned arrays
let check = userBooks.filter((object) => {
return object.get().title === bookData[1].title;
});
assert.deepEqual(check, []); //book id:2 should not be present in returned user books
done();
});
});
}).timeout(5000);
});
//AUTHOR MODEL
describe('AUTHOR Model', () => {
it('it should create author object with its properties', (done) => {
Author.findAll().then((authors) => {
let fullName = authorData[0].firstName + ' ' + authorData[0].lastName;
let [, ...otherKeys] = Object.keys(authors[0].dataValues);
try {
assert.equal(typeof(authors), 'object'); // object should be created
assert.equal(authors.length, 2); //all two authors should be returned
// getter methods should be functional
assert.equal(authors[0].fullName, fullName);
assert.equal(typeof(authors[0].lifeSpan), 'number');
assert.deepEqual(otherKeys, Object.keys(authorData[0])); //all object properties should persist to database
done();
} catch (error) {
console.log(error.message);
}
});
}).timeout(5000);
it('it should have -belongsToMany association and only author\'s books', (done) => {
Author.findOne({ where: { id: 1 } }).then(author => {
author.getBooks().then(authorBooks => {
assert.equal(authorBooks.length, 2); //authorOne should return an array of two books
assert.equal(authorBooks[0].get().id, 2);
assert.equal(authorBooks[1].get().id, 3);
let check = authorBooks.filter((object) => {
return object.get().id === 1;
});
assert.deepEqual(check, []); //book id:1 should not be present for author id:1 book published
done();
});
});
}).timeout(5000);
});
//GENRE MODEL
describe('GENRE Model', () => {
it('it should create genre object with its properties', (done) => {
Genre.findAll().then((genres) => {
let [, ...otherKeys] = Object.keys(genres[0].dataValues);
try {
assert.equal(typeof(genres), 'object'); // object should be created
assert.equal(genres.length, 3); //all three genres should be returned
assert.deepEqual(otherKeys, Object.keys(genreData[0])); //all object properties should persist to database
done();
} catch (error) {
console.log(error.message);
}
});
}).timeout(5000);
it('it should have -hasMany association and only books in that category', (done) => {
Genre.findOne({
where: { name: 'Data Science' },
include: { model: Book, as: 'books' }
}).then(genre => {
let genreBook = genre.books;
assert.equal(typeof(genreBook), 'object'); // object should be returned
assert.equal(genreBook.length, 2); // total books in category should be 2
// The right books categorise should be returned
assert.equal(genreBook[0].dataValues.title, 'Fundamentals of Statistics for Data Scientist');
assert.equal(genreBook[1].dataValues.title, 'R - the tool for data science');
let check = genreBook.filter((object) => {
return object.get().title === 'Java programming for beginners';
});
// it should not return a book not in that category
assert.deepEqual(check, []);
done();
});
}).timeout(5000);
});
//BOOK MODEL
describe('BOOK Model', () => {
it('it should create a book object with its properties', (done) => {
Book.findAll().then(books => {
assert.equal(typeof(books), 'object'); // type returned should be an object
assert.equal(books.length, 3); //all book object should persist to database
let [, ...otherKeys] = Object.keys(books[0].dataValues); // destructure book object to remove id
assert.deepEqual(otherKeys, Object.keys(bookData[0])); // Ensure all book keys persist to database
done();
});
}).timeout(5000);
//belongsToMany association users - borrowed book
it('it should have association -belongsToMany for all users with the same book', (done) => {
//Use book with id:3 with multiple users(that have borrowed it)
Book.findOne({ where: { id: 3 } }).then(book => {
book.getUsers().then(bookUsers => {
assert.equal(typeof(bookUsers), 'object');
assert.equal(bookUsers.length, 2);
assert.equal(bookUsers[0].get().id, 1);
assert.equal(bookUsers[1].get().id, 2);
let check = bookUsers.filter((object) => {
return object.get().id === 3;
});
assert.deepEqual(check, []); //user id:3 should not be present in for book id:3 borrowed
done();
});
});
}).timeout(5000);
//belongsToMany association authors
it('it should have association -belongsToMany for all authors with the same book', (done) => {
//Use book with id:3 with multiple authors(that owns it)
Book.findOne({ where: { id: 3 } }).then(book => {
book.getAuthors().then(bookAuthors => {
assert.equal(typeof(bookAuthors), 'object');
assert.equal(bookAuthors.length, 2);
assert.equal(bookAuthors[0].get().id, 1);
assert.equal(bookAuthors[1].get().id, 2);
let check = bookAuthors.filter((object) => {
return object.get().id === 3;
});
assert.deepEqual(check, []); //author id:3 should not be present in for book id:3 published
done();
});
});
}).timeout(5000);
//belongsTo association Gnere
it('it should have association -belongsTo one Genre', (done) => {
Book.findOne({
where: { title: 'R - the tool for data science' },
include: { model: Genre, as: 'genre' }
}).then(book => {
let bookGenre = book.genre;
/**This removes key id from returned genre data
* so it's content can be compared with the input data */
function remove(key, obj) {
let copy = Object.assign({}, obj);
delete copy[key];
return copy;
}
assert.equal(typeof(bookGenre), 'object');
assert.equal(book.genre.length, undefined); // book should belong to only one genre and not return an array of Genre
assert.deepEqual(remove('id', bookGenre.dataValues), genreData[2]); //book should return the right category
done();
});
}).timeout(5000);
});
//OWNER MODEL
describe('OWNER Model', () => {
it('it should create a join table for book owners', (done) => {
Owner.findAll().then(owner => {
assert.equal(owner.length, 4);
let testCompoundkey = {
authorId: owner[0].authorId,
bookId: owner[0].bookId,
createdAt: new Date(),
updatedAt: new Date()
};
//Should not create if compound-authorId,bookId key already exist
Owner.create(testCompoundkey).then().catch(error => {
assert.equal(error.original.detail, 'Key ("authorId", "bookId")=(2, 1) already exists.');
done();
});
});
}).timeout(5000);
});
//BORROW MODEL
describe('BORROWED Model', () => {
it('it should create a join table for borrowed books', (done) => {
Borrow.findAll().then(borrow => {
assert.equal(borrow.length, 3);
let testCompoundkey = {
userId: borrow[0].userId,
bookId: borrow[0].bookId,
createdAt: new Date(),
updatedAt: new Date()
};
//Should not create if compound-userId,bookId key already exist
Borrow.create(testCompoundkey).then().catch(error => {
assert.equal(error.original.detail, 'Key ("userId", "bookId")=(1, 1) already exists.');
done();
});
});
}).timeout(5000);
});
}); |
const path = require("path");
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const bcrypt = require("bcryptjs");
const User = require("./models/Users");
const { Client } = require("ssh2");
const port = 5555;
const app = express();
app.use(bodyParser.json());
require("dotenv").config({ path: path.join(__dirname, ".env") });
//================================================================================================================================================================================
//================================================================================================================================================================================
//~~DB OPERATIONS~~
//================================================================================================================================================================================
//================================================================================================================================================================================
app.post(
"/users/signup",
async ({ body: { firstName, lastName, username, password, email } }, res) => {
User.findOne({ username: username }, "username").then((resultant) => {
if (resultant) {
res.send("Username already exists!");
} else {
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(password, salt, (err, hash) => {
const newUser = new User({
firstName: firstName,
lastName: lastName,
username: username,
hash: hash,
email: email,
servers: [],
});
newUser
.save()
.then(() => res.send("User created."))
.catch((err) => res.send(err));
});
});
}
});
}
);
//================================================================================================================================================================================
//================================================================================================================================================================================
/*app.post("/users/signin", ({ body: { username, password } }, res) => {
User.findOne({ username: username }, "username hash")
.then(async ({ hash }) => {
const result = await bcrypt.compare(password, hash);
result
? res.send("Authentication Successful")
: res.send("Authenication Failed");
})
.catch((err) => res.send(err)); REMOVE THIS COMMENTED CODE ONCE VERIFIED FRONTEND FUNCTIONALITY.
});*/
app.post("/users/signin", ({ body: { username, password } }, res) => {
User.findOne({ username: username }, "username hash").exec(
async (err, result) => {
if (result) {
const { hash, servers } = result;
const authenticationSuccessful = await bcrypt.compare(password, hash);
if (authenticationSuccessful) {
res.send("Authentication Successful");
} else {
res.send("Authentication Failed");
}
} else {
res.send("Authentication Failed");
}
}
);
});
//================================================================================================================================================================================
//================================================================================================================================================================================
app.post(
"/users/addserver",
({ body: { username, user, serverName, ipAddr, sshKey, password } }, res) => {
User.findOne({ username: username }).exec((err, resultant) => {
if (err) {
throw err;
res.send("An error occurred.");
} else {
if (resultant) {
if (resultant.servers.length === 0) {
resultant.servers.push({
user: user,
serverName: serverName,
ipAddr: ipAddr,
sshKey: sshKey,
password: password,
});
resultant.save();
res.send("Added user's first server!");
} else {
const checkNameAvailable = (server) =>
server.serverName === serverName;
const nameNotAvailable = resultant.servers
.map(checkNameAvailable)
.some((el) => el === true);
if (nameNotAvailable) {
res.send(
"Server with that name already exists. Did not add server."
);
} else {
const newServer = {
serverName: serverName,
ipAddr: ipAddr,
sshKey: sshKey,
password: password,
user: user,
};
resultant.servers.push(newServer);
resultant.save();
res.send("Added server.");
}
//addpasswordencryption for server passwords
}
} else {
res.send("User not found. Failed to add server.");
}
}
});
}
);
//================================================================================================================================================================================
//================================================================================================================================================================================
app.post("/users/removeserver", ({ body: { username, serverName } }, res) => {
User.findOne({ username: username }).exec((err, resultant) => {
if (err) {
res.send("An error ocurred");
} else {
const serverExists = resultant.servers
.map((el) => el.serverName === serverName)
.some((el) => el === true);
if (serverExists) {
const serverIndex = resultant.servers
.map((el) => el.serverName === serverName)
.indexOf(true);
resultant.servers.splice(serverIndex, 1);
resultant.save();
res.send(`Server : ${serverName} was deleted successfully.`);
} else {
res.send("Server with that name does not exist.");
}
}
});
});
//================================================================================================================================================================================
//================================================================================================================================================================================
app.post("/users/getservers", ({ body: { username, password } }, res) => {
User.findOne({ username: username }).exec(async (err, resultant) => {
if (err) {
res.send("An error ocurred.");
} else {
if (resultant) {
const { hash, servers } = resultant;
const authenticationSuccessful = await bcrypt.compare(password, hash);
if (authenticationSuccessful) {
res.send(servers);
} else {
res.send("Authentication failed. Did not retrieve servers.");
}
} else {
res.send("Authentication failed. Did not retrieve servers.");
}
}
});
});
//================================================================================================================================================================================
//================================================================================================================================================================================
app.post(
"/health/setupserver",
({ body: { username, password, serverName } }, res) => {
User.findOne({ username: username }).exec(async (err, resultant) => {
if (resultant) {
const { servers, hash } = resultant;
const authenticationSuccessful = await bcrypt.compare(password, hash);
if (authenticationSuccessful) {
const serverIndex = servers
.map((el, index) => el.serverName === serverName)
.indexOf(true);
const { user, password, ipAddr } = servers[serverIndex];
const command = await sshInit(user, password, ipAddr, res);
} else {
res.send("Authentication failed.");
}
} else {
res.send("User not found.");
}
});
}
);
//================================================================================================================================================================================
//================================================================================================================================================================================
//~~END OF DB OPERATIONS
//================================================================================================================================================================================
//================================================================================================================================================================================
//================================================================================================================================================================================
//~ SSH OPERATIONS
//================================================================================================================================================================================
async function sshInit(username, password, host, res) {
const connectionDetails = {
host: host,
port: 22,
username: username,
password: password,
};
const conn = new Client();
let log = "";
conn.on("ready", () => {
log += "\nPyLot connected to user's remote server\n";
conn.exec("ls", (err, stream) => {
if (err) {
log += "\nCommand execution failed\n";
}
stream.stdout.on("data", (data) => {
log += `\n***\n STDOUT : \n${data.toString()}\n***`;
});
stream.stderr.on("data", (data) => {
log += `\n***\n STDERR : \n${data.toString()}\n***`;
});
stream.on("close", () => {
log += "\nConnection closed from server\n";
conn.end();
});
});
});
conn.on("end", () => {
log += "\nDisconnected to server.\n";
res.send(`\nLog:\n${log}`);
});
conn.on("error", () => {
log += "\nConnection error.\n";
});
conn.connect(connectionDetails);
}
//================================================================================================================================================================================
//~CONNECTIING TO MONGODB SERVER
//================================================================================================================================================================================
mongoose
.connect(
process.env.DB_CONNECTION, //environment variable
{ useNewUrlParser: true, useUnifiedTopology: true }
)
.then(() => console.log("Connected to MongoDB cluster..."))
.catch((err) => console.error(err));
//================================================================================================================================================================================
//~ STARTTING NODE JS SERVER AND SETTING TO LISTEN ON PORT
//================================================================================================================================================================================
const server = app.listen(port, () => {
console.log(`listening on port ... ${port}`);
});
//================================================================================================================================================================================
//================================================================================================================================================================================
|
exports.currentUser = (req, res) => {
res.send(req.user);
}
exports.logout = (req, res) => {
req.logout();
res.redirect("/");
}
exports.login = (req, res) => {
res.redirect("/notes");
} |
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const nodemailer = require("nodemailer");
import isEmail from "validator/lib/isEmail";
import isLength from "validator/lib/isLength";
import generateInline from "../../../templates/verifyEmail";
import baseUrl from "../../../utils/baseUrl";
import connectDb from "../../../utils/connectDb";
import User from "../../../models/User";
import Message from "../../../models/Message";
connectDb();
const handler = async (req, res) => {
switch (req.method) {
case "POST":
await handlePostRequest(req, res);
break;
default:
res.status(405).send(`Method ${req.method} not allowed`);
break;
}
};
// @route POST api/auth/register
// @desc register new account in db (username, email, password, role)
// @res jwt
// @access Public
async function handlePostRequest(req, res) {
const { username, email, password, confirmPassword, role } = req.body;
try {
//validate username email and password
if (!isLength(username, { min: 3, max: 15 })) {
return res.status(422).send("Username must be 3-15 characters");
} else if (!isLength(password, { min: 6 })) {
return res
.status(422)
.send("Password must be at least 6 characters long");
} else if (!isEmail(email)) {
return res.status(422).send("Invalid email");
} else if (password !== confirmPassword) {
return res.status(422).send("Passwords do not match");
}
//check if user already exists
let user = await User.findOne({ email });
if (user) {
return res.status(422).send("Email is already registered to an account");
}
//create user
user = new User({
username,
email,
password,
role,
date: Date.now(),
});
//encrypt password
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
//send welcome message to user from BoardRack
const messageBody =
"Hello, welcome to BoardRack! \n" +
"Before you get started theres a few things you should know. \n\n" +
" - This website is only demo! Thus, any posts you view should not be considered real and are only for demonstrative purposes. \n" +
" - Filtering by location has been disabled as all demostrative posts will be located in the San Francisco Bay Area. \n" +
" - All posts flagged for deletion will not be removed after the designated 7 day wait. Instead, deleted posts will remain visible, but marked as 'Sold' or 'Post Removed' (NOTE: all guest data is wiped on a bi-weekly basis.)\n" +
" - Email verification is enabled and all emails will be sent to your registered email address. \n\n " +
"Thank you for visiting the site! Feel free to create an account, create a new post, and interact with the site. If you have any questions, encounter any bugs, or just want say hi, please respond here!";
const message = {
from: "5fb86b4e6e10cf407c3dc204",
body: messageBody,
timeSent: Date.now(),
};
const newMessageThread = {
type: "support",
users: [user._id, "5fb86b4e6e10cf407c3dc204"],
post: null,
dateCreated: Date.now(),
lastUpdated: Date.now(),
isRead: false,
messages: [message],
};
let messageThread = new Message(newMessageThread);
await messageThread.save();
//save to users messages[]
user.messages = [messageThread._id];
//save user to db
await user.save();
//send "verify your email" to user's email address
try {
const verifyEmailPayload = {
verifyUserId: user._id,
};
const verificationToken = jwt.sign(
verifyEmailPayload,
process.env.JWT_SECRET
);
const verificationLink = `${baseUrl}/verify/email?token=${verificationToken}`;
let htmlBody = generateInline(verificationLink);
const transporter = nodemailer.createTransport({
service: process.env.EMAIL_SERVICE,
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS,
},
});
const mailOptions = {
from: `BoardRack <${process.env.EMAIL_USER}>`,
to: user.email,
subject: "Verify your email",
html: htmlBody,
};
//send email
await transporter.sendMail(mailOptions);
} catch (err) {
console.log("Failed to send verification email");
}
//create JWT
const payload = {
user: {
id: user.id,
role: user.role,
},
};
jwt.sign(
payload,
process.env.JWT_SECRET,
{ expiresIn: "7d" },
(err, token) => {
if (err) throw err;
res.status(200).json({ token });
}
);
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error");
}
}
export default handler;
|
import { StyleSheet, Platform } from 'react-native';
import Dimensions from 'Dimensions';
export default StyleSheet.create({
feedPage:{
marginBottom: 48,
backgroundColor: '#F1F3F5',
},
feedWrapper: {
flex: 1,
backgroundColor: '#F1F3F5',
flexDirection: 'column',
justifyContent: 'space-between'
// marginBottom: 50,
},
feedRendering: {
justifyContent: 'center',
alignItems: 'center',
},
feedRenderingText: {
fontSize: 15,
},
slide1: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
slide2: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
slide3: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
text: {
color: '#fff',
fontSize: 30,
fontWeight: 'bold',
},
notiWrapper: {
paddingTop: 5,
paddingBottom: 5,
},
notiContent: {
backgroundColor: '#fff',
borderWidth: .5,
borderColor: '#e9e9e9'
},
notiText: {
flex:1,
justifyContent: 'center',
alignItems: 'center',
fontWeight: '400'
},
flexRow: {
padding: 10,
backgroundColor: '#fff',
flexDirection: 'row'
},
red: {
color: 'red'
},
userImage: {
width: 34,
height: 34,
borderWidth: 1,
borderColor: '#e9e9e9',
borderRadius: 17
},
feedListView: {
backgroundColor: '#fff',
borderWidth: 1,
borderColor: '#d9d9d9',
},
feedContainer: {
padding: 15,
paddingBottom:0,
},
feedTopContainer: {
flexDirection: 'row',
alignItems: 'center'
},
feedInfoContainer: {
marginLeft: 10
},
feedUser: {
fontWeight: '500',
marginBottom: 5
},
feedUserUniv: {
color: '#a7a7a7',
fontWeight: '100',
fontSize: 13,
},
feedUserTime: {
color: '#ccc',
fontWeight: '200',
fontSize: 13,
},
feedTopRight: {
flexDirection: 'row',
alignItems:'center',
},
ctxContainer: {
marginTop: 15
},
likeAndComment: {
height: 40,
width: Dimensions.get('window').width,
flexDirection: 'row',
alignItems:'center',
},
feedBtmIcon: {
flexDirection: 'row',
marginLeft: 15,
alignItems:'center',
},
iconButton: {
color: '#e9e9e9',
marginRight: 5,
},
shareButton:{
right:30,
bottom:2,
position:'absolute',
},
textAlign: {
textAlign: 'center',
color: '#bfbfbf',
fontWeight: '500',
marginRight: 15,
},
spaceBetween: {
flexDirection: 'row',
justifyContent: 'space-between'
},
readMore: {
color: '#d6d6d6',
fontWeight: "500"
},
postedImg:{
// flex: 1,
width: Dimensions.get('window').width/1.1,
height: Dimensions.get('window').width/1.1,
resizeMode: 'contain',
marginTop: 15
},
detail_view:{
flex: 1,
justifyContent: 'space-between',
},
comment_input_cont:{
height: 50,
backgroundColor: '#fff',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems:'center',
paddingHorizontal:10,
borderTopColor: '#dbdbdb',
borderTopWidth: 1,
borderBottomColor: '#dbdbdb',
borderBottomWidth: 1
},
comment_btn:{
fontWeight: '600'
},
comment_input:{
fontSize: 15,
alignItems:'center',
width: Dimensions.get('window').width/1.2,
height: 48,
},
comment_box:{
padding: 15,
flexDirection: 'row',
justifyContent: 'space-between',
backgroundColor: '#fff',
},
separator: {
height: 5,
backgroundColor: '#F1F3F5',
},
time_text:{
fontWeight: '100',
fontSize:10,
},
})
|
let color1Class = document.querySelectorAll('.color1');
const color1Length = color1Class.length;
let colorPicker = document.querySelector('.colorPicker');
let drawingColor = "black"; // initial pen lnk color
let penSize = 1; // initial pen size
// handle color picker
colorPicker.addEventListener('input', e => {
drawingColor = e.target.value;
});
// --------------- Add Event Listener to color Plate -------------------
for (let i = 0; i < color1Length; i++) {
let selectedClass = document.querySelectorAll('.color1')[i];
selectedClass.addEventListener('click', e => {
let color = selectedClass.attributes[1].value;
drawingColor = color;
})
}
// --------------- Add Event Listener to color Plate -------------------
let color2Class = document.querySelectorAll('.color2');
const color2Length = color2Class.length;
for (let i = 0; i < color2Length; i++) {
let selectedClass = document.querySelectorAll('.color2')[i];
selectedClass.addEventListener('click', e => {
let color = selectedClass.attributes[1].value;
drawingColor = color;
})
}
// --------------- Add Event Listener to Pen Plate -------------------
let penControl = document.querySelectorAll('.pen1');
const penLength = penControl.length;
function erageAll() {
context.clearRect(0, 0, canvas.width, canvas.height); // clean canva
penSize = 1;
}
for (let i = 0; i < penLength; i++) {
let selectedClass = document.querySelectorAll('.pen1')[i];
selectedClass.addEventListener('click', e => {
let getPenSize = selectedClass.attributes[1].value;
drawingColor = "black";
document.querySelector('canvas').style.cursor = "default"
if (getPenSize == 0) {
erageAll();
} else penSize = getPenSize; // update pen size
// erage line by line using white color
if (getPenSize == 2) {
penSize = 12;
drawingColor = "white";
document.querySelector('canvas').style.cursor = "cell";
}
})
}
// ==================== Canvas Work Start =================
let canvas = document.querySelector('canvas');
let context = canvas.getContext('2d');
let drawing = false;
let oldX = 0;
let oldY = 0;
canvas.addEventListener('mousedown', e => {
drawing = true;
oldX = e.offsetX;
oldY = e.offsetY;
context.lineWidth = penSize; // update drawing color
context.strokeStyle = `${drawingColor}`;
});
canvas.addEventListener('mouseup', e => {
drawing = false;
});
canvas.addEventListener('mousemove', e => {
if (!drawing) return false;
context.beginPath();
context.moveTo(oldX, oldY);
context.lineTo(e.offsetX, e.offsetY);
context.stroke();
oldX = e.offsetX;
oldY = e.offsetY;
})
// ========================= Canvas Work End ========================= |
/*
the date input is the MM/dd/yyyy and the time input is military time HH:mm
This creates a Calendar event entry with the specified name, start time, and duration
*/
function createCal(name, date, time) {
var duration = 60; //duration of event in minutes
var startTime = new Date(date + ' ' + time);
var endTime = new Date(startTime.getTime() + (duration*60*1000)); //sets endTime to be __min after startTime ( __min * 60 sec/min * 1000 ms/sec)
var event = CalendarApp.getDefaultCalendar().createEvent(name, startTime, endTime); //name is the name of the Event
}
|
export { Layout } from "./layout/layout"
export Modal from "./modal/modal"
|
/* @flow */
import React from 'react';
import first from 'lodash/first';
import type { Element } from 'react';
type Props<T> = {
array: T[],
render: T => ?Element<*>,
container?: React$ElementType,
className?: ?string,
id?: ?string,
};
export default function First<T>({
array,
render,
container,
className,
id,
// eslint-disable-next-line object-curly-spacing
}: Props<T>) {
const item = first(array);
if (!item) {
return null;
}
const contents = render(item);
if (!container) {
return (
<div className={className} id={id}>
{contents}
</div>
);
}
const Container = container;
return (
<Container className={className} id={id}>
{contents}
</Container>
);
}
|
import palette from 'palette';
import exif from 'exif2';
import convert from 'color-convert';
import Canvas, {Image as CanvasImage} from 'canvas';
export default class Image {
constructor(props) {
this.root = props.root;
this.path = props.path;
this.folder = props.folder;
}
getImagedata() {
var imageData = {};
return new Promise((resolve, reject) => {
exif(this.path, (err, obj) => {
if(err) {
return reject(err);
} else {
var category = !!obj["directory"] ? obj["directory"].slice(this.root.length) : '';
imageData.id = this.path;
imageData.category = category;
imageData.orientation = obj["orientation"];
imageData.flash = obj["flash"];
imageData.lens = obj["lens"];
imageData.aperture = obj["aperture"];
imageData.megapixels = obj["megapixels"];
imageData.file_name = obj["file name"];
imageData.directory = obj["directory"];
imageData.file_size = obj["file size"];
imageData.make = obj["make"];
imageData.camera_model_name = obj["camera model name"];
imageData.x_resolution = obj["x resolution"];
imageData.y_resolution = obj["y resolution"];
imageData.resolution_unit = obj["resolution unit"];
imageData.create_Date = obj["create date"];
imageData.focal_length = obj["focal length"];
imageData.focus_position = obj["focus position"];
imageData.focus_distance = obj["focus distance"];
imageData.lens_f_stops = obj["lens f stops"];
imageData.shutter_speed = obj["shutter speed"];
imageData.depth_of_field = obj["depth of field"];
imageData.GPS_Altitude = obj["gps altitude"];
imageData.GPS_Date_Time = obj["gps date/time"];
imageData.GPS_Latitude = obj["gps latitude"];
imageData.GPS_Longitude = obj["gps longitude"];
imageData.gps_altitude = obj["gps altitude"];
obj["gps position"] >"" ? imageData.location = this._gpstodd(obj["gps position"]): 1;
return this._makePalette(this.path)
.then(rgb => {
imageData.colors = rgb;
return resolve(imageData);
})
}
});
});
}
_gpstodd (input) {
input = input.replace(/\'/g," min").replace(/\"/g,' sec').replace(/\,/g,"").split(" ")
var lat= (parseFloat(input[0])+parseFloat(input[2]/60)+parseFloat(input[4]/(60*60)) )* (input[6] =="S" ? -1 : 1);
var lng=(parseFloat(input[7])+parseFloat(input[9]/60)+parseFloat(input[11]/(60*60)) ) * (input[13] =="W" ? -1 : 1);
return {"lat": lat, "lon":lng}
}
_makePalette(file) {
return new Promise((resolve, reject) => {
var img = new CanvasImage;
img.src = file;
var canvas = new Canvas(img.width, img.height);
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, img.width/4, img.height/4);
var colors = palette(canvas, 2);
var rgb = colors.map(color => ({
r: color[0],
g: color[1],
b: color[2]
}));
return resolve(rgb);
});
}
}
|
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import PastTraining from './training'
import axios from 'axios'
import { setPastTrainings, addPastTraining } from '../../actions/index'
import styled from 'styled-components'
const Container = styled.div`
display: grid;
.training{
grid-column-start: 2;
grid-column-end: 6;
}
`
class PastTrainingsContainer extends React.Component {
componentDidMount() {
axios.get('http://private-fb7a77-kbtracker.apiary-mock.com/past-trainings/1')
.then(response => response.data).then(data => {
this.props.actions.setPastTrainings(data)
})
.catch(error => {
console.log(error)
})
this.render()
}
render() {
return (
<Container>
{this.props.trainings.map(training =>
<PastTraining className="training" key={training.id} training={training}/>)}
</Container>)
}
}
PastTrainingsContainer.propTypes = { actions: PropTypes.object.isRequired,
trainings: PropTypes.array.isRequired }
const mapStateToProps = state => ({ trainings: state.pastTrainings })
const mapDispatchToProps = dispatch => ({ actions: bindActionCreators({ setPastTrainings,
addPastTraining }, dispatch) })
export default connect(mapStateToProps, mapDispatchToProps)(PastTrainingsContainer)
|
var SceneOver = Director.createScene(function() {
this.count = 0;
this.score = 0;
this.distance = 0;
this.bestDistance = 0;
this.bestScore = 0;
if (UserDefault.getValueForKey('bestDistance', 0) < UserDefault.getValueForKey('distance', 0)) {
UserDefault.setValueForKey('bestDistance', UserDefault.getValueForKey('distance', 0));
}
if (UserDefault.getValueForKey('bestScore', 0) < UserDefault.getValueForKey('score', 0)) {
UserDefault.setValueForKey('bestScore', UserDefault.getValueForKey('score', 0));
}
UserDefault.saveValueToSystemKey();
this.startButton = new Sprite('graphics/start.png');
this.startButton.setX(50);
this.startButton.setY(300);
this.startButton.addEventListener('click', () => {
Director.replaceScene(new SceneGame());
});
this.homeButton = new Sprite('graphics/home.png');
this.homeButton.setX(350);
this.homeButton.setY(300);
this.homeButton.addEventListener('click', () => {
Director.replaceScene(new SceneTitle());
});
this.addChild(this.startButton);
this.addChild(this.homeButton);
});
SceneOver.prototype.update = function(delta) {
if (InputSystem.hasKeyTrigger(keyCodes.ENTER)) {
Director.pushScene(new SceneGame());
}
if (this.bestDistance != UserDefault.getValueForKey('bestDistance', 0))
this.bestDistance = parseInt(this.count / 30 * UserDefault.getValueForKey('bestDistance', 0));
if (this.distance != UserDefault.getValueForKey('distance', 0))
this.distance = parseInt(this.count / 30 * UserDefault.getValueForKey('distance', 0));
if (this.bestScore != UserDefault.getValueForKey('bestScore', 0))
this.bestScore = parseInt(this.count / 30 * UserDefault.getValueForKey('bestScore', 0));
if (this.score != UserDefault.getValueForKey('score', 0))
this.score = parseInt(this.count / 30 * UserDefault.getValueForKey('score', 0));
this.count++;
};
SceneOver.prototype.render = function() {
Graphics.setFontColor('#000');
Graphics.drawText('최고 이동 거리: ' + commaValue(this.bestDistance) + 'M', 100, 60);
Graphics.drawText('이동 거리: ' + commaValue(this.distance) + 'M', 100, 100);
Graphics.drawText('최고 점수: ' + commaValue(this.bestScore), 100, 140);
Graphics.drawText('점수: ' + commaValue(this.score), 100, 180);
};
|
const io = require('socket.io')
const _ = require('lodash')
const moment = require('moment')
const uuid = require('uuid')
const Player = require('./Entities/Player')
const Game = require('./Game')
let socketIo = null
const connect = function(server) {
socketIo = io.listen(server)
let game = new Game(socketIo)
socketIo.on('connection', function(socket) {
const player = new Player({ socket, game })
console.log(`${moment().format('HH:mm:ss')} :: SocketIO :: Player connect :: ${player.id}`)
game.addEntity(player)
socket.on('disconnect', function () {
console.log(`${moment().format('HH:mm:ss')} :: SocketIO :: Player disconnect :: ${player.id}`)
game.removeEntity(player)
})
})
}
module.exports = {
connect,
}
|
const Main = (input) => {
const N = input.split('\n')[0]
const a = input.split('\n')[1].split(' ')
const numbers = a.map(str => parseInt(str)).sort((a, b) => b - a)
alice = 0;
bob = 0;
numbers.reduce((prev, current, index) => {
if (index % 2) {
bob += current
} else {
alice += current
}
}, 0)
console.log(alice - bob)
return alice - bob
}
module.exports = Main
|
import { connect } from "react-redux";
import withStyles from "@material-ui/core/styles/withStyles";
import componentsStyle from "../assets/jss/material-kit-react/views/components";
import VendorComponent from "../views/VendorPage/Vendor";
import { getShopLocation } from "../routes/routingSystem";
const mapStateToProps = state => ({
front: state.front,
shopLocation: getShopLocation(),
});
const Vendor = connect(
mapStateToProps,
)(VendorComponent);
export default withStyles(componentsStyle)(Vendor);
|
module.exports = {
'url' : 'mongodb://jeffomland:einstein@ds023560.mlab.com:23560/iceman'
} |
angular.module('favorTrip', []);
|
const express = require('express')
const webpack = require('webpack')
const webpackDevMiddleware = require('webpack-dev-middleware')
const app = express()
const config = require('./webpack.config.js')
const compiler = webpack(config)
app.use(webpackDevMiddleware(compiler, {
publicPush: config.output.publicPath
}))
const port = 3000
app.listen(port, () => {
console.log(`应用正在监听本机${port}端口。`)
}) |
const getUser = cb => {
setTimeout(() => {
cb({
id: 1,
name: 'Guillermo A. Sanchez',
message: '👋',
});
}, 2000);
};
getUser(user => {
console.log(user);
});
// Talk about
// onSucces
// handleUser
|
/* eslint-disable no-console */
require('dotenv').config();
const express = require('express');
const path = require('path');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
const db = require('../db/index.js');
const port = process.env.PORT;
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, '../public/dist')));
app.get('/images', (req, res) => {
db.getAllImages((err, results) => {
if (err) {
return res.json({ error: err });
}
return res.json({ rows: results });
});
});
app.get('/products', (req, res) => {
db.getRandomProduct((err, result) => {
if (err) {
return res.json({ error: err });
}
// there has got to be a better way of doing this.
// Could this be destructured/reassigned at the component level?
const response = {
productName: result.product_name,
companyName: result.company_name,
itemNumber: result.item_number,
color: result.color,
price: result.price,
rating: result.rating,
noRatings: result.no_ratings,
shoeSizes: result.shoe_sizes.map(x => x.size),
};
return res.json({ row: response });
});
});
app.listen(port, (err) => {
if (err) {
return console.log(err);
}
return console.log(`listening on port ${port}`);
});
|
import * as React from 'react'
import * as ReactDOM from 'react-dom'
import { Application,PageLayout } from '@retool/app'
import * as standardControls from '@retool/standard-controls'
import * as controls from './controls'
var app = new Application("SampleApp");
app.controls.import(controls);
import * as templates from "./templates"
app.templates.import(templates);
import * as objects from "./objects/index"
app.objects.import(objects);
const launchAppBuilder = () => {
app.launchAppBuilder()
}
const LaunchButton = (props) =>
<button className="slds-button" style={{ position: "absolute", top: 5, right: 5}} onClick={launchAppBuilder}>
Launch App Builder</button>
ReactDOM.render(<div>
<PageLayout app={app} route={{ object: "Contact" }} />
{!app.hasOpenBuilder ? <LaunchButton /> : null}
</div>, document.getElementById('root'));
|
/* global $ */
$(document).ready(function(){
$('#men').click(function(event){
event.preventDefault();
$('#men').addClass('active');
$('.men').removeClass('hidden');
$('#women').removeClass('active');
$('.women').addClass('hidden');
});
$('#women').click(function(event){
event.preventDefault();
$('#women').addClass('active');
$('.women').removeClass('hidden');
$('#men').removeClass('active');
$('.men').addClass('hidden');
});
}); |
import React from 'react'
import {Link} from 'react-router-dom'
import './header.less'
const Header = () => {
return (
<header className="top-panel">
<div className="top-panel__container">
<div className="top-panel__title">
интернет магазин недвижимости
</div>
<div className="top-panel__favourites">
<Link to="/favourites" className="btn-show-favourites mr-5">
<i className="fas fa-heart"></i> Избранное
</Link>
<Link to="/bids" className="btn-show-favourites">
<i className="fas fa-file-alt"></i> Заявки
</Link>
</div>
</div>
</header>
)
}
export default Header |
const express = require('express'),
app = express(),
cookieParser = require('cookie-parser'),
{ config } = require('dotenv'),
logger = require('morgan'),
{ urlencoded, json } = express;
// parses incoming requests with JSON payloads
app.use(urlencoded({ extended: true }));
app.use(json());
// load env variable
config();
// parse cookies and puts information onto req object
// encodes and decrypts with provided SECRET
app.use(cookieParser(process.env.SECRET));
// ============ MongoDB config ==============
require('./config/connection');
// log response status
app.use(logger('dev'));
// ============= ROUTES ==========================
app.use('/api/users', require('./routes/userRoutes.js'));
app.listen(process.env.PORT || 3001);
|
import React from "react";
import Link from "gatsby-link";
import "./navButton.css";
import { navigateTo } from "gatsby-link";
export default props => {
return (
<div className={`${props.position} relative`}>
<a
onClick={() => navigateTo(`${props.path}`)}
className={`bttn color-${props.style}`}
>
{props.text}
</a>
</div>
);
};
|
'use strict';
angular.module('oprum')
.service('loginService', ['$http', '$q',
function ($http, $q) {
function getExternalLogins() {
var deferred = $q.defer();
$http({
method: "GET",
url: "api/Account/ExternalLogins",
headers: { 'Content-Type': 'application/json' }
}).then(
function (result) {
console.log('logins returned');
deferred.resolve(result.data);
},
function (result) {
deferred.reject();
console.log(result.status);
}
);
return deferred.promise;
}
function getUserInfo() {
var deferred = $q.defer();
$http({
method: "GET",
url: "api/Account/UserInfo",
headers: { 'Content-Type': 'application/json' }
}).then(
function (result) {
console.log('principals returned');
deferred.resolve(result.data);
},
function (result) {
deferred.reject();
console.log(result.status);
}
);
return deferred.promise;
};
function login() {
var deferred = $q.defer();
$http({
method: "GET",
url: "/api/Account/ExternalLogin?provider=Google&response_type=token&client_id=self&redirect_uri=http%3A%2F%2Flocalhost%3A64320%2F&state=wVBy5yLu7s7HcoL88rVVisfVXNNDAzhWDmi3G_rBcBY1",
headers: { 'Content-Type': 'application/json' }
}).then(
function (result) {
console.log('principals returned');
deferred.resolve(result.data);
},
function (result) {
deferred.reject();
console.log(result.status);
}
);
return deferred.promise;
};
return ({
getExternalLogins: getExternalLogins,
getUserInfo: getUserInfo,
login: login
});
}]);
|
import React, { useRef, useState } from 'react';
import { View, StyleSheet, SafeAreaView, Text, TextInput, Dimensions, Animated } from 'react-native';
import { FlatList, TouchableOpacity } from 'react-native-gesture-handler';
const PollingScreen = (props) => {
const [question, setQuestion] = useState(props.route.params.userChoosenQuestion);
const [isPercentageVisible, setIsPercentageVisible] = useState(false);
const pollAnimOptionA = useRef(new Animated.Value(320)).current;
const pollAnimOptionB = useRef(new Animated.Value(320)).current;
const pollAnimOptionC = useRef(new Animated.Value(320)).current;
const pollAnimOptionD = useRef(new Animated.Value(320)).current;
const pollAnimOptionE = useRef(new Animated.Value(320)).current;
const pollInOptionA = (votes) => {
Animated.timing(pollAnimOptionA, {
toValue: 200 + votes,
duration: 1000,
}).start();
};
const pollInOptionB = (votes) => {
Animated.timing(pollAnimOptionB, {
toValue: 200 + votes,
duration: 1000,
}).start();
};
const pollInOptionC = (votes) => {
Animated.timing(pollAnimOptionC, {
toValue: 200 + votes,
duration: 1000,
}).start();
};
const pollInOptionD = (votes) => {
Animated.timing(pollAnimOptionD, {
toValue: 200 + votes,
duration: 1000,
}).start();
};
const pollInOptionE = (votes) => {
Animated.timing(pollAnimOptionE, {
toValue: 200 + votes,
duration: 1000,
}).start();
};
const getCorrectAnimWidth = (id) => {
if (id === 'a') {
return pollAnimOptionA;
}
if (id === 'b') {
return pollAnimOptionB;
}
if (id === 'c') {
return pollAnimOptionC;
}
if (id === 'd') {
return pollAnimOptionD;
}
if (id === 'e') {
return pollAnimOptionE;
}
}
const executeAllAnim = (optionsArray) => {
for (let i = 0; i < optionsArray.length; i++) {
if(i === 0){pollInOptionA(optionsArray[0].votes)}
if(i === 1){pollInOptionB(optionsArray[1].votes)}
if(i === 2){pollInOptionC(optionsArray[2].votes)}
if(i === 3){pollInOptionD(optionsArray[3].votes)}
if(i === 4){pollInOptionE(optionsArray[4].votes)}
}
}
// `meals` is the reducer identifier (see in App.js)
// const favMeals = useSelector((state) => state.meals.favoriteMeals);
// if (favMeals.length === 0 || !favMeals) {
// return (
// <View style={styles.content}>
// <DefaultText>No favorite meals found.</DefaultText>
// </View>
// );
// }
const touchableBgColor = '#005792'
return (
<SafeAreaView style={{ flex: 1, alignItems: 'center' }}>
<View style={{ marginTop: 50 }}>
<Text style={{ fontSize: 20, margin: 10 }}>{question.name}</Text>
{/* <FlatList
data={question.choices}
contentContainerStyle={{marginTop : 20,alignSelf : 'center'}}
keyExtractor={(item,index) => item.id }
renderItem={(item,index) => {
let touchableBgColor = item.index % 2 === 0 ? '#005792' : 'grey';
return(
<View style={{flexDirection : 'row',alignItems : 'center',marginBottom : 10}}>
<View style={{justifyContent : 'center',alignItems : 'center',width : 30, height : 30,borderColor : '#005792',borderWidth : 1,borderRadius : 25,backgroundColor : touchableBgColor}}>
<Text style={{color : 'white'}}>{(item.item.id).toUpperCase()}</Text>
</View>
<View>
<TouchableOpacity style={{marginLeft : 10,justifyContent : 'center',alignItems : 'center',width : 250, minHeight : 50,borderColor : touchableBgColor,borderWidth : 1,borderRadius : 10,backgroundColor :touchableBgColor,padding : 5}}>
<Text style={{color : 'white'}}>{item.item.choice}</Text>
</TouchableOpacity>
</View>
</View>
)
}}
/> */}
{/* question.choices.filter(opt => opt.choice == null).map(opt => someNewObject) */}
{question !== undefined && question.choices.filter((filteredData) => filteredData.choice !== null).map((item, index) => {
let bgColor = index % 2 === 0 ? '#005792' : 'grey';
return (
<View key={index} style={{ flexDirection: 'row', alignItems: 'center', marginVertical: 10, justifyContent: 'space-evenly' }}>
<View style={{ justifyContent: 'center', alignItems: 'center', width: 30, height: 30, borderColor: bgColor, borderWidth: 1, borderRadius: 25, backgroundColor: bgColor }}>
<Text style={{ color: 'white' }}>{(item.id).toUpperCase()}</Text>
</View>
<TouchableOpacity onPress={() => { setIsPercentageVisible(true); executeAllAnim(question.choices)}} style={{ marginLeft: 10, justifyContent: 'space-evenly', width: Dimensions.get('window').width - 80, minHeight: 50, borderColor: bgColor, borderWidth: 1, borderRadius: 10, backgroundColor: 'white', }}>
{isPercentageVisible && (
<Animated.View style={{ justifyContent: 'center', alignItems: 'center', width: getCorrectAnimWidth(item.id), minHeight: 50, backgroundColor: 'powderblue', borderRadius: 10 }}>
<Text style={{paddingLeft : 5, fontSize: 18, color: 'green', fontWeight: 'bold' }}>{item.votes}%</Text>
<Text style={{paddingLeft : 5, fontSize: 18 }}>{item.choice}</Text>
</Animated.View>)}
{!isPercentageVisible && (<Text style={{ fontSize: 18,paddingLeft : 5 }}>{item.choice}</Text>)}
</TouchableOpacity>
</View>
)
}
)}
</View>
</SafeAreaView>
)
};
const styles = StyleSheet.create({
});
export default PollingScreen;
|
describe('tests in the file test.js', () => {
test('should be a equals to strings ', () => {
// 1. Initialization
const message = 'Hello word!'
// 2. Stimulus
const message2 = `Hello word!`
// 3. Observe Behavior
expect( message ).toBe(message2)
})
})
|
Polymer.NeonAnimatableBehavior = {
properties: {
animationConfig: {
type: Object
},
entryAnimation: {
observer: "_entryAnimationChanged",
type: String
},
exitAnimation: {
observer: "_exitAnimationChanged",
type: String
}
},
_entryAnimationChanged: function() {
this.animationConfig = this.animationConfig || {}, this.animationConfig.entry = [{
name: this.entryAnimation,
node: this
}]
},
_exitAnimationChanged: function() {
this.animationConfig = this.animationConfig || {}, this.animationConfig.exit = [{
name: this.exitAnimation,
node: this
}]
},
_copyProperties: function(i, n) {
for (var t in n) i[t] = n[t]
},
_cloneConfig: function(i) {
var n = {
isClone: !0
};
return this._copyProperties(n, i), n
},
_getAnimationConfigRecursive: function(i, n, t) {
if (this.animationConfig) {
if (this.animationConfig.value && "function" == typeof this.animationConfig.value) return void this._warn(this._logf("playAnimation", "Please put 'animationConfig' inside of your components 'properties' object instead of outside of it."));
var o;
if (o = i ? this.animationConfig[i] : this.animationConfig, Array.isArray(o) || (o = [o]), o)
for (var e, a = 0; e = o[a]; a++)
if (e.animatable) e.animatable._getAnimationConfigRecursive(e.type || i, n, t);
else if (e.id) {
var r = n[e.id];
r ? (r.isClone || (n[e.id] = this._cloneConfig(r), r = n[e.id]), this._copyProperties(r, e)) : n[e.id] = e
} else t.push(e)
}
},
getAnimationConfig: function(i) {
var n = {},
t = [];
this._getAnimationConfigRecursive(i, n, t);
for (var o in n) t.push(n[o]);
return t
}
};
Polymer.NeonAnimationRunnerBehaviorImpl = {
_configureAnimations: function(n) {
var i = [];
if (n.length > 0)
for (var e, t = 0; e = n[t]; t++) {
var o = document.createElement(e.name);
if (o.isNeonAnimation) {
var a = null;
try {
a = o.configure(e), "function" != typeof a.cancel && (a = document.timeline.play(a))
} catch (n) {
a = null, console.warn("Couldnt play", "(", e.name, ").", n)
}
a && i.push({
neonAnimation: o,
config: e,
animation: a
})
} else console.warn(this.is + ":", e.name, "not found!")
}
return i
},
_shouldComplete: function(n) {
for (var i = !0, e = 0; e < n.length; e++)
if ("finished" != n[e].animation.playState) {
i = !1;
break
}
return i
},
_complete: function(n) {
for (var i = 0; i < n.length; i++) n[i].neonAnimation.complete(n[i].config);
for (var i = 0; i < n.length; i++) n[i].animation.cancel()
},
playAnimation: function(n, i) {
var e = this.getAnimationConfig(n);
if (e) {
this._active = this._active || {}, this._active[n] && (this._complete(this._active[n]), delete this._active[n]);
var t = this._configureAnimations(e);
if (0 == t.length) return void this.fire("neon-animation-finish", i, {
bubbles: !1
});
this._active[n] = t;
for (var o = 0; o < t.length; o++) t[o].animation.onfinish = function() {
this._shouldComplete(t) && (this._complete(t), delete this._active[n], this.fire("neon-animation-finish", i, {
bubbles: !1
}))
}.bind(this)
}
},
cancelAnimation: function() {
for (var n in this._animations) this._animations[n].cancel();
this._animations = {}
}
}, Polymer.NeonAnimationRunnerBehavior = [Polymer.NeonAnimatableBehavior, Polymer.NeonAnimationRunnerBehaviorImpl];
Polymer.IronFitBehavior = {
properties: {
sizingTarget: {
type: Object,
value: function() {
return this
}
},
fitInto: {
type: Object,
value: window
},
noOverlap: {
type: Boolean
},
positionTarget: {
type: Element
},
horizontalAlign: {
type: String
},
verticalAlign: {
type: String
},
dynamicAlign: {
type: Boolean
},
horizontalOffset: {
type: Number,
value: 0,
notify: !0
},
verticalOffset: {
type: Number,
value: 0,
notify: !0
},
autoFitOnAttach: {
type: Boolean,
value: !1
},
_fitInfo: {
type: Object
}
},
get _fitWidth() {
var t;
return t = this.fitInto === window ? this.fitInto.innerWidth : this.fitInto.getBoundingClientRect().width
},
get _fitHeight() {
var t;
return t = this.fitInto === window ? this.fitInto.innerHeight : this.fitInto.getBoundingClientRect().height
},
get _fitLeft() {
var t;
return t = this.fitInto === window ? 0 : this.fitInto.getBoundingClientRect().left
},
get _fitTop() {
var t;
return t = this.fitInto === window ? 0 : this.fitInto.getBoundingClientRect().top
},
get _defaultPositionTarget() {
var t = Polymer.dom(this).parentNode;
return t && t.nodeType === Node.DOCUMENT_FRAGMENT_NODE && (t = t.host), t
},
get _localeHorizontalAlign() {
if (this._isRTL) {
if ("right" === this.horizontalAlign) return "left";
if ("left" === this.horizontalAlign) return "right"
}
return this.horizontalAlign
},
attached: function() {
"undefined" == typeof this._isRTL && (this._isRTL = "rtl" == window.getComputedStyle(this).direction), this.positionTarget = this.positionTarget || this._defaultPositionTarget, this.autoFitOnAttach && ("none" === window.getComputedStyle(this).display ? setTimeout(function() {
this.fit()
}.bind(this)) : this.fit())
},
fit: function() {
this.position(), this.constrain(), this.center()
},
_discoverInfo: function() {
if (!this._fitInfo) {
var t = window.getComputedStyle(this),
i = window.getComputedStyle(this.sizingTarget);
this._fitInfo = {
inlineStyle: {
top: this.style.top || "",
left: this.style.left || "",
position: this.style.position || ""
},
sizerInlineStyle: {
maxWidth: this.sizingTarget.style.maxWidth || "",
maxHeight: this.sizingTarget.style.maxHeight || "",
boxSizing: this.sizingTarget.style.boxSizing || ""
},
positionedBy: {
vertically: "auto" !== t.top ? "top" : "auto" !== t.bottom ? "bottom" : null,
horizontally: "auto" !== t.left ? "left" : "auto" !== t.right ? "right" : null
},
sizedBy: {
height: "none" !== i.maxHeight,
width: "none" !== i.maxWidth,
minWidth: parseInt(i.minWidth, 10) || 0,
minHeight: parseInt(i.minHeight, 10) || 0
},
margin: {
top: parseInt(t.marginTop, 10) || 0,
right: parseInt(t.marginRight, 10) || 0,
bottom: parseInt(t.marginBottom, 10) || 0,
left: parseInt(t.marginLeft, 10) || 0
}
}
}
},
resetFit: function() {
var t = this._fitInfo || {};
for (var i in t.sizerInlineStyle) this.sizingTarget.style[i] = t.sizerInlineStyle[i];
for (var i in t.inlineStyle) this.style[i] = t.inlineStyle[i];
this._fitInfo = null
},
refit: function() {
var t = this.sizingTarget.scrollLeft,
i = this.sizingTarget.scrollTop;
this.resetFit(), this.fit(), this.sizingTarget.scrollLeft = t, this.sizingTarget.scrollTop = i
},
position: function() {
if (this.horizontalAlign || this.verticalAlign) {
this._discoverInfo(), this.style.position = "fixed", this.sizingTarget.style.boxSizing = "border-box", this.style.left = "0px", this.style.top = "0px";
var t = this.getBoundingClientRect(),
i = this.__getNormalizedRect(this.positionTarget),
e = this.__getNormalizedRect(this.fitInto),
n = this._fitInfo.margin,
o = {
width: t.width + n.left + n.right,
height: t.height + n.top + n.bottom
},
h = this.__getPosition(this._localeHorizontalAlign, this.verticalAlign, o, i, e),
s = h.left + n.left,
l = h.top + n.top,
r = Math.min(e.right - n.right, s + t.width),
a = Math.min(e.bottom - n.bottom, l + t.height);
s = Math.max(e.left + n.left, Math.min(s, r - this._fitInfo.sizedBy.minWidth)), l = Math.max(e.top + n.top, Math.min(l, a - this._fitInfo.sizedBy.minHeight)), this.sizingTarget.style.maxWidth = Math.max(r - s, this._fitInfo.sizedBy.minWidth) + "px", this.sizingTarget.style.maxHeight = Math.max(a - l, this._fitInfo.sizedBy.minHeight) + "px", this.style.left = s - t.left + "px", this.style.top = l - t.top + "px"
}
},
constrain: function() {
if (!this.horizontalAlign && !this.verticalAlign) {
this._discoverInfo();
var t = this._fitInfo;
t.positionedBy.vertically || (this.style.position = "fixed", this.style.top = "0px"), t.positionedBy.horizontally || (this.style.position = "fixed", this.style.left = "0px"), this.sizingTarget.style.boxSizing = "border-box";
var i = this.getBoundingClientRect();
t.sizedBy.height || this.__sizeDimension(i, t.positionedBy.vertically, "top", "bottom", "Height"), t.sizedBy.width || this.__sizeDimension(i, t.positionedBy.horizontally, "left", "right", "Width")
}
},
_sizeDimension: function(t, i, e, n, o) {
this.__sizeDimension(t, i, e, n, o)
},
__sizeDimension: function(t, i, e, n, o) {
var h = this._fitInfo,
s = this.__getNormalizedRect(this.fitInto),
l = "Width" === o ? s.width : s.height,
r = i === n,
a = r ? l - t[n] : t[e],
f = h.margin[r ? e : n],
g = "offset" + o,
p = this[g] - this.sizingTarget[g];
this.sizingTarget.style["max" + o] = l - f - a - p + "px"
},
center: function() {
if (!this.horizontalAlign && !this.verticalAlign) {
this._discoverInfo();
var t = this._fitInfo.positionedBy;
if (!t.vertically || !t.horizontally) {
this.style.position = "fixed", t.vertically || (this.style.top = "0px"), t.horizontally || (this.style.left = "0px");
var i = this.getBoundingClientRect(),
e = this.__getNormalizedRect(this.fitInto);
if (!t.vertically) {
var n = e.top - i.top + (e.height - i.height) / 2;
this.style.top = n + "px"
}
if (!t.horizontally) {
var o = e.left - i.left + (e.width - i.width) / 2;
this.style.left = o + "px"
}
}
}
},
__getNormalizedRect: function(t) {
return t === document.documentElement || t === window ? {
top: 0,
left: 0,
width: window.innerWidth,
height: window.innerHeight,
right: window.innerWidth,
bottom: window.innerHeight
} : t.getBoundingClientRect()
},
__getCroppedArea: function(t, i, e) {
var n = Math.min(0, t.top) + Math.min(0, e.bottom - (t.top + i.height)),
o = Math.min(0, t.left) + Math.min(0, e.right - (t.left + i.width));
return Math.abs(n) * i.width + Math.abs(o) * i.height
},
__getPosition: function(t, i, e, n, o) {
var h = [{
verticalAlign: "top",
horizontalAlign: "left",
top: n.top + this.verticalOffset,
left: n.left + this.horizontalOffset
}, {
verticalAlign: "top",
horizontalAlign: "right",
top: n.top + this.verticalOffset,
left: n.right - e.width - this.horizontalOffset
}, {
verticalAlign: "bottom",
horizontalAlign: "left",
top: n.bottom - e.height - this.verticalOffset,
left: n.left + this.horizontalOffset
}, {
verticalAlign: "bottom",
horizontalAlign: "right",
top: n.bottom - e.height - this.verticalOffset,
left: n.right - e.width - this.horizontalOffset
}];
if (this.noOverlap) {
for (var s = 0, l = h.length; s < l; s++) {
var r = {};
for (var a in h[s]) r[a] = h[s][a];
h.push(r)
}
h[0].top = h[1].top += n.height, h[2].top = h[3].top -= n.height, h[4].left = h[6].left += n.width, h[5].left = h[7].left -= n.width
}
i = "auto" === i ? null : i, t = "auto" === t ? null : t;
for (var f, s = 0; s < h.length; s++) {
var g = h[s];
if (!this.dynamicAlign && !this.noOverlap && g.verticalAlign === i && g.horizontalAlign === t) {
f = g;
break
}
var p = !(i && g.verticalAlign !== i || t && g.horizontalAlign !== t);
if (this.dynamicAlign || p) {
f = f || g, g.croppedArea = this.__getCroppedArea(g, e, o);
var d = g.croppedArea - f.croppedArea;
if ((d < 0 || 0 === d && p) && (f = g), 0 === f.croppedArea && p) break
}
}
return f
}
};
|
import React, { useState } from "react";
import styled from "styled-components";
const defaultValue = "placeholder";
const StyledInput = styled.input`
border: none;
outline: none;
&,
&::focus,
&::active {
border: none;
outline: none;
}
`;
export const NoBorderInput = ({ value, onChange, validate, ...otherProps }) => {
const [isActive, setIsActive] = useState(false);
const handleChange = ({ target }) => {
if (!validate) {
onChange(target.value);
} else if (validate(target.value)) {
onChange(target.value);
}
};
const handleFocus = ({ target }) => {
setIsActive(true);
if (target.value === defaultValue) {
target.value = "";
}
};
const handleBlur = ({ target }) => {
setIsActive(false);
if (target.value === "") {
target.value = defaultValue;
}
};
const getCurrentValue = () =>
value && value.length ? value : isActive ? "" : defaultValue;
return (
<StyledInput
type="text"
onChange={handleChange}
onBlur={handleBlur}
onFocus={handleFocus}
value={getCurrentValue()}
/>
);
};
|
var args = require('aargs')
var logger = require('./lib/logger')
var app = require('./lib/app')
// Arguments from CLI
var PORT = args.port || 1337
var HOST = args.host || '127.0.0.1'
// Start server
app.listen(PORT, HOST, () => {
logger.info(`Listening on http://${HOST}:${PORT}`)
}) |
var vertices;
var animFrame;
var zArray = false;
var zBuffer;
var val = 1;
var canCalc = false;
var stages, speeds;
var needsUpdate = true;
var values;
var smoothVal = 1;
//t = current time, b = start val, c = change in val, d= duration
var inOutQuart = function (t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t + b; return -c/2 * ((t-=2)*t*t*t - 2) + b; };
self.initZ = function (buffer){
zBuffer = buffer;
zArray = new Float32Array(zBuffer);
values = Array(zArray.length);
var message = {type:'initialised'};
canCalc = true;
self.postMessage(message);
}
self.setZArray = function(buffer){
zBuffer = buffer;
zArray = new Float32Array(zBuffer);
canCalc = true;
}
self.calculate = function(){
if(!zArray || !canCalc || !needsUpdate) return;
var l = zArray.length;
smoothVal += (val-smoothVal) / 10;
var pos = smoothVal*4;
var newVal = (smoothVal*4) % 1;
var next = Math.ceil(pos);
var prev = Math.floor(pos);
var animVal,speedVal,easedVal;
for (var i = 0; i < l; i ++ ) {
animVal = stages[i][prev] + (stages[i][next]-stages[i][prev]) * newVal;
speedVal = Math.max(0,Math.min(1, - speeds[i] + (1 + speeds[i]) * animVal));
easedVal = inOutQuart(speedVal, 0, 1, 1);
zArray[i] = (stages[i][next] < stages[i][prev]) ? -300 + 2000* easedVal : -300 - 3000* (easedVal > 0? 1 : 0);
}
var buffers = [zBuffer];
var message = {buffers: buffers, type:'zBuff'};
canCalc = false;
self.postMessage(message, buffers);
if(Math.floor(smoothVal*1000) == Math.floor(val*1000)) needsUpdate = false;
if(Math.ceil(val *1000)/1000 == Math.ceil(smoothVal *1000)/1000 || Math.floor(val *1000)/1000 == Math.floor(smoothVal *1000)/1000 ){
self.postMessage({type:'stop'});
}
}
self.addEventListener('message', function(e) {
if(e.data.type == 'val'){
if(val == e.data.val) return;
val = e.data.val;
needsUpdate = true;
}else if(e.data.type == 'returnBuffer') self.setZArray(e.data.buffers[0]);
else if(e.data.type == 'init'){
self.initZ(e.data.buffers[0]);
stages = e.data.stages;
speeds = e.data.speeds;
}else if(e.data.type == 'start') setInterval(self.calculate, 1000/60);
}, false); |
/************ 전역변수 *************/
var datas;
var mainNow = 0;
var mainPrev, mainNext, mainLast;
var infoChk = true; // info-wrap의 애니메이션 진행여부(true면 진행, flase면 무시)
/************ 사용자 함수 *************/
function mainAjax() {
$.get("../json/banner.json", function(res){
datas = res.banners;
mainLast = datas.length - 1;
mainPager();
mainInit();
});
}
function mainInit() {
mainPrev = (mainNow == 0) ? mainLast : mainNow - 1;
mainNext = (mainNow == mainLast) ? 0 : mainNow + 1;
$(".main-wrap").find(".slide").remove();
$(htmlMaker(mainNow)).appendTo(".main-wrap").css({
"position": "relative",
"transition": "transform 0.5s"
});
$(htmlMaker(mainPrev)).appendTo(".main-wrap").css("top", "-100%");
$(htmlMaker(mainNext)).appendTo(".main-wrap").css("top", "100%");
$(".main-wrap .pager").removeClass("active");
$(".main-wrap .pager").eq(mainNow).addClass("active");
setTimeout(function(){
$(".main-wrap").find(".slide").eq(0).find(".ani-trans").css("transform", "translateX(0)");
}, 300);
}
function htmlMaker(n) {
html = '<div class="slide">';
html += '<img src="'+datas[n].src+'" class="img">';
html += '<div class="mask"></div>';
html += '<div class="slide-content '+datas[n].class+'">';
html += '<h2 class="title ani-trans">'+datas[n].title+'<span>.</span></h2>';
html += '<h3 class="desc ani-trans">'+datas[n].desc+'</h3>';
html += '<div class="bts">';
for(var i=0, bt; i<datas[n].buttons.length; i++) {
bt = datas[n].buttons[i];
html += '<a href="'+bt.link+'" class="'+bt.class+' ani-trans">'+bt.title+'</a>';
}
html += '</div>';
html += '</div>';
html += '</div>';
return html;
}
function mainPager() {
for(var i=0; i<=mainLast; i++) {
$('<span class="pager"></span>').appendTo(".main-wrap .pagers").click(onPagerClick);
}
}
function onMainPrev() {
$(".main-wrap > .slide").eq(0).css("transform", "translateY(100px)");
$(".main-wrap > .slide").eq(1).stop().animate({"top": 0}, 500, function() {
mainNow = (mainNow == 0) ? mainLast : mainNow - 1;
mainInit();
});
}
function onMainNext() {
$(".main-wrap > .slide").eq(0).css("transform", "translateY(-100px)");
$(".main-wrap > .slide").eq(2).stop().animate({"top": 0}, 500, function() {
mainNow = (mainNow == mainLast) ? 0 : mainNow + 1;
mainInit();
});
}
function onPagerClick() {
var target = [];
var old = mainNow;
mainNow = $(this).index();
if(mainNow > old) {
// console.log("아래거 올라옴");
target[0] = "100%";
target[1] = "-100px";
}
else if(mainNow < old) {
// console.log("위에거 내려옴");
target[0] = "-100%";
target[1] = "100px";
}
else {
return false;
}
$(".main-wrap > .slide").not($(".main-wrap > .slide").eq(0)).remove();
$(htmlMaker(mainNow)).appendTo(".main-wrap").css("top", target[0]);
$(".main-wrap > .slide").eq(0).css("transform", "translateY("+target[1]+")");
$(".main-wrap > .slide").eq(1).stop().animate({"top": 0}, 500, mainInit);
}
function onMasonry(){
/************ 이벤트 선언 *************/
$(".main-wrap > .bt-prev").click(onMainPrev);
$(".main-wrap > .bt-next").click(onMainNext); |
(function () {
'use strict';
angular
.module('wizardApp')
.controller('MetricsController', MetricsController);
MetricsController.$inject = ['$scope', '$state', '$location', '$stateParams'];
function MetricsController($scope, $state, $location, $stateParams) {
var vm = this;
vm.title = 'Let\'s set up your metrics!';
$scope.metricsState = 0;
$scope.currentState = function(param) {
if ($scope.validateForm()) {
$scope.metricsState = param;
}
}
$scope.goToNext = function() {
if ($scope.validateForm()) {
$state.go("form.result")
}
}
$scope.goToPrev = function(state) {
if ($scope.validateForm()) {
$location.path("/form/company/4")
}
}
$scope.validateForm = function(){
return true;
}
activate();
////////////////
function activate() {
}
}
})(); |
import Translator from "../containers/Translator";
import "../styles/css/styles.css";
const TranslationPage = () => {
return (
<div>
<h1 className="center-basic">Basic UI for Translation (Dev)</h1>
<Translator></Translator>
</div>
);
};
export default TranslationPage;
|
/* @flow */
/* **********************************************************
* File: containers/DeveloperContainer.js
*
* Brief: Container for holding the DeveloperPage
*
* Authors: Craig Cheney
*
* 2017.10.10 CC - Document created
*
********************************************************* */
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import DeveloperPage from '../components/Developer/DeveloperPage';
import { setDeviceName, initiateOtaUpdate } from '../actions/developerActions';
function mapStateToProps(state) {
return {
devices: state.devices
};
}
/* Action creators to be used in the component */
const mapDispatchToProps = (dispatcher: *) => bindActionCreators({
setDeviceName,
initiateOtaUpdate
}, dispatcher);
export default connect(mapStateToProps, mapDispatchToProps)(DeveloperPage);
/* [] - END OF FILE */
|
// returns a single tile to be used in the tile view menu
// routing, color, and title can be set via the path, backcolor, and cardTtile props
import React from 'react';
import PropTypes from 'prop-types';
import {withStyles} from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardActionArea from '@material-ui/core/CardActionArea';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import {ButtonBase} from '@material-ui/core';
import {BrowserRouter as Router, Route, Link} from "react-router-dom";
var styles = {
card: {
minWidth: 210,
minHeight: 210,
maxWidth: 210,
maxHeight: 210,
//height: '10vw',
// background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
},
bullet: {
display: 'inline-block',
margin: '0 2px',
transform: 'scale(0.8)',
},
title: {
fontSize: 14,
},
pos: {
marginBottom: 12,
},
};
function TileCard(props) {
const {classes} = props;
const bull = <span className={classes.bullet}>•</span>;
if (props.path) {
return (
<Link style={{textDecoration: 'none'}} to={props.path}>
<CardActionArea className={classes.card}>
<Card className={classes.card} style={props.backColor}>
<CardContent align="center">
<Typography align="center" variant="h5">{props.cardTitle}</Typography>
<CardMedia
style={{height: 0, width: 130, paddingBottom: '70.25%'}}
image={props.image}
>
</CardMedia>
</CardContent>
</Card>
</CardActionArea>
</Link>
);
} else {
return (
<CardActionArea className={classes.card}>
<Card className={classes.card} style={props.backColor}>
<CardContent align="center">
<Typography align="center" variant="h5">{props.cardTitle}</Typography>
<CardMedia
style={{height: 0, width: 130, paddingBottom: '70.25%'}}
image={props.image}
>
</CardMedia>
</CardContent>
</Card>
</CardActionArea>
);
}
}
TileCard.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(TileCard);
|
var c, w, h, m, p = {},
{
min,
floor,
PI,
cos,
sin,
pow,
random,
round,
ceil
} = Math,
T_PI = PI * 2
var BOT_SPEED = 1
function roundRect(ctx, x, y, width, height, radius, fill, stroke) {
if (typeof stroke === 'undefined') {
stroke = true;
}
if (typeof radius === 'undefined') {
radius = 5;
}
if (typeof radius === 'number') {
radius = {
tl: radius,
tr: radius,
br: radius,
bl: radius
};
} else {
var defaultRadius = {
tl: 0,
tr: 0,
br: 0,
bl: 0
};
for (var side in defaultRadius) {
radius[side] = radius[side] || defaultRadius[side];
}
}
ctx.beginPath();
ctx.moveTo(x + radius.tl, y);
ctx.lineTo(x + width - radius.tr, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius.tr);
ctx.lineTo(x + width, y + height - radius.br);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius.br, y + height);
ctx.lineTo(x + radius.bl, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius.bl);
ctx.lineTo(x, y + radius.tl);
ctx.quadraticCurveTo(x, y, x + radius.tl, y);
ctx.closePath();
if (fill) {
ctx.fill();
}
if (stroke) {
ctx.stroke();
}
}
function Game() {
this.canvas = document.getElementById('canvas')
this.ctx = c = this.canvas.getContext('2d')
this.dimension = 3;
let focus;
Object.defineProperty(this, 'focus', {
get() {
return focus
},
set(v) {
if (typeof v != 'number' || v < 0 || v > this.values.length || v === focus) return false
focus = v
this.draw()
}
})
let foc_btn = 0
Object.defineProperty(this, 'foc_btn', {
get() {
return foc_btn
},
set(v) {
foc_btn = v
this.draw()
}
})
new Ads(document.getElementById('ad-container'), document.getElementById('video-element'), function () {
this.resize()
this.restart()
}.bind(this))
}
p.draw = function () {
c.clearRect(0, 0, w, h)
switch (this.game_state) {
case 0:
this.drawDesk()
break;
default:
this.drawUI()
break;
}
this.drawText()
}
p.drawText = function () {
c.save()
c.font = "48px serif";
c.textAlign = 'center'
c.fillText(this.text, w / 2, 50);
c.restore()
}
p.drawDesk = function () {
this.drawBounds()
this.drawValues()
}
p.drawBounds = function () {
let
step = this.soket_size,
s_h = step / 2,
ctx = this
let drawSocet = function (pos, color, width, blureColor) {
c.save()
if (color)
c.strokeStyle = color
if (blureColor) {
c.shadowColor = blureColor;
c.shadowBlur = width;
}
c.lineWidth = width
c.beginPath()
c.moveTo(pos.x - s_h, pos.y - s_h)
c.lineTo(pos.x + s_h, pos.y - s_h)
c.lineTo(pos.x + s_h, pos.y + s_h)
c.lineTo(pos.x - s_h, pos.y + s_h)
c.closePath()
c.stroke()
c.restore()
}
let focus_draw
for (let i = 0; i < this.values.length; i++) {
if (i === this.focus) {
focus_draw = function () {
drawSocet(ctx.getPosByIndex(i), '#f7fff5', ctx.border_width * 1.2)
}
continue;
} else
drawSocet(this.getPosByIndex(i), '#7b02cc', this.border_width, '#D955FE')
}
focus_draw && focus_draw()
}
p.drawValues = function () {
let step = this.soket_size,
pos,
r = step / 2.5
let draw_O = function (color) {
c.save()
c.strokeStyle = color
c.beginPath()
c.lineWidth = step * .05
c.shadowColor = color;
c.shadowBlur = c.lineWidth * .5;
c.arc(pos.x, pos.y, r, 0, T_PI * 2)
c.stroke()
c.restore()
}
let draw_X = function (color) {
c.save()
c.strokeStyle = color
c.beginPath()
c.lineWidth = step * .05
c.shadowColor = color;
c.shadowBlur = c.lineWidth * .5;
c.moveTo(pos.x + cos(PI / 4) * r, pos.y - sin(PI / 4) * r)
c.lineTo(pos.x - cos(PI / 4) * r, pos.y + sin(PI / 4) * r)
c.moveTo(pos.x - cos(PI / 4) * r, pos.y - sin(PI / 4) * r)
c.lineTo(pos.x + cos(PI / 4) * r, pos.y + sin(PI / 4) * r)
c.stroke()
c.restore()
return true
}
this.values.forEach((e, i) => {
pos = this.getPosByIndex(i);
if (e === 'x') draw_X(this.player_index === 'x' ? '#00ff11' : '#ff0000')
else draw_O(this.player_index === 'o' ? '#00ff11' : '#ff0000')
});
}
p.getPosByIndex = function (i) {
let g_s = this.desk_size - this.border_width
return {
x: this.margin[0] + this.border_width / 2 + g_s * (i % this.dimension + .5) / this.dimension,
y: this.margin[1] + this.border_width / 2 + g_s * (floor(i / this.dimension) + .5) / this.dimension
}
}
p.setPlayListeners = function () {
this.text = 'Your move'
let cb = function (e) {
let f_v,
col = floor(this.focus / this.dimension);
switch (e.keyCode) {
case 37:
f_v = this.focus - 1
this.focus = floor(f_v / this.dimension) != col ? col * this.dimension + this.dimension - 1 : f_v
break;
case 38:
f_v = this.focus - this.dimension
this.focus = f_v < 0 ? this.values.length - (this.dimension - this.focus % this.dimension) : f_v
break;
case 39:
f_v = this.focus + 1
this.focus = floor(f_v / this.dimension) != col ? col * this.dimension : f_v
break;
case 40:
f_v = this.focus + this.dimension
this.focus = f_v > this.values.length - 1 ? this.focus % this.dimension : f_v
break;
case 13:
if (this.values[this.focus]) return false
this.setValue(this.focus, this.player_index, function () {
this.botPlay()
}.bind(this))
this.removeListeners()
break;
}
}.bind(this)
window.addEventListener('keyup', cb)
this.removeListeners = function () {
window.removeEventListener('keyup', cb)
}
}
p.botPlay = function () {
let text_arr = ['😱', '🤯', '🤯']
this.text = text_arr[ceil(text_arr.length * random()) - 1]
let cache_focus = this.focus
this.focus = NaN
let i, state;
(state = this.findRange([this.bot_win_pattern.slice(0, this.dimension - 1)])) ||
(state = this.findRange([this.player_win_pattern.slice(0, this.dimension - 1)])) ||
(state = this.findRange([this.bot_win_pattern.slice(0, this.dimension - 2)])) ||
(state = {
range: (function (ctx) {
let arr = []
for (let i = 0; i < ctx.values.length; i++) {
arr.push(i)
}
return arr
}(this))
})
for (i = 0; i < state.range.length; i++) {
if (this.values[state.range[i]]) continue
i = state.range[i]
break;
}
setTimeout(function () {
this.setValue(i, this.bot_index, function () {
this.setPlayListeners()
this.focus = isNaN(cache_focus) ? 4 : cache_focus
}.bind(this))
}.bind(this), BOT_SPEED * 1000)
}
p.setValue = function (i, value, cb) {
this.values[i] = value
let w_s = this.findRange([this.bot_win_pattern, this.player_win_pattern])
if (!w_s && this.values.reduce(function (s, c) {
return ++s
}, 0) != this.values.length)
cb && cb()
else {
c.save()
if (w_s) {
if (w_s.math_pattern.slice(0, 1) === this.bot_index) {
this.text = 'Bot is win!'
c.strokeStyle = '#ff0000'
} else {
this.text = 'You are win!'
c.strokeStyle = '#00ff11'
}
} else {
this.text = 'Dead heat!'
}
this.focus = NaN
setTimeout(function () {
this.text = ''
this.game_state = 1
this.setUIListeners()
this.draw()
}.bind(this), 3000)
if (!w_s.range) return false
let f_pos = this.getPosByIndex(w_s.range[0]),
s_pos = this.getPosByIndex(w_s.range[w_s.range.length - 1]),
r = this.soket_size * .48
c.beginPath()
c.lineWidth = this.soket_size * .1
c.moveTo(f_pos.x + cos(w_s.angle) * r, f_pos.y - sin(w_s.angle) * r)
c.lineTo(s_pos.x + cos(w_s.angle + PI) * r, s_pos.y - sin(w_s.angle + PI) * r)
c.stroke()
c.restore()
}
}
p.findRange = function (patterns) {
let
v_sum,
h_sum,
d_f_sum = '',
d_s_sum = '',
v_range,
h_range,
d_f_range = [],
d_s_range = [],
math_pattern
function matchCheck(val) {
for (let i = 0; i < patterns.length; i++) {
if (val != patterns[i]) continue
math_pattern = patterns[i]
return true
}
}
for (let r = 0; r < this.dimension; r++) {
v_sum = h_sum = '';
v_range = [];
h_range = [];
for (let c = 0; c < this.dimension; c++) {
h_range.push(this.dimension * r + c)
h_sum += this.values[h_range[h_range.length - 1]] || ''
v_range[v_range.length] = c * this.dimension + r
v_sum += this.values[v_range[v_range.length - 1]] || ''
}
if (matchCheck(v_sum)) {
return {
range: v_range,
angle: PI / 2,
math_pattern
}
} else if (matchCheck(h_sum)) {
return {
range: h_range,
angle: PI,
math_pattern
}
} else {
d_f_range[d_f_range.length] = this.dimension * r + r
d_f_sum += this.values[d_f_range[d_f_range.length - 1]] || '';
d_s_range[d_s_range.length] = this.dimension * r + (this.dimension - 1) - r
d_s_sum += this.values[d_s_range[d_s_range.length - 1]] || '';
if (r === this.dimension - 1) {
if (matchCheck(d_f_sum)) {
return {
range: d_f_range,
angle: PI / 2 + PI / 4,
math_pattern
}
} else if (matchCheck(d_s_sum)) {
return {
range: d_s_range,
angle: PI / 4,
math_pattern
}
}
}
}
}
return false
}
p.drawUI = function () {
c.save()
c.fillStyle = '#ffffff';
if (this.foc_btn) {
let p = this.f_btn.width * .05;
roundRect(c, this.f_btn.x - p / 2, this.f_btn.y - p / 2, this.f_btn.width + p, this.f_btn.height + p, this.f_btn.r, true)
} else {
let p = this.s_btn.width * .05;
roundRect(c, this.s_btn.x - p / 2, this.s_btn.y - p / 2, this.s_btn.width + p, this.s_btn.height + p, this.s_btn.r, true)
}
c.fillStyle = '#00ff00';
roundRect(c, this.f_btn.x, this.f_btn.y, this.f_btn.width, this.f_btn.height, this.f_btn.r, true)
c.font = this.f_btn.height * .8 + "px Comic Sans MS";
c.fillStyle = "white";
c.textAlign = 'center';
c.fillText('Download', this.f_btn.x + this.f_btn.width / 2, this.s_btn.y + this.s_btn.height / 2 + this.f_btn.height * .2);
c.fillStyle = '#de0d4f';
roundRect(c, this.s_btn.x, this.s_btn.y, this.s_btn.width, this.s_btn.height, this.s_btn.r, true)
c.font = this.s_btn.height * .8 + "px Comic Sans MS";
c.fillStyle = "white";
c.textAlign = 'center';
c.fillText('Restart', this.s_btn.x + this.s_btn.width / 2, this.s_btn.y + this.s_btn.height / 2 + this.s_btn.height * .2);
c.restore()
}
p.setUIListeners = function () {
let ctx = this
let key_cb = function (e) {
switch (e.keyCode) {
case 37:
ctx.foc_btn = ctx.foc_btn - 1 < 0 && 1 || 0
break;
case 39:
ctx.foc_btn = ctx.foc_btn + 1 < 2 && 1 || 0
break;
case 13:
fin_cb()
break;
}
}
let checkIntersection = function (e, btn) {
let x = e.clientX - ctx.bounds.x
let y = e.clientY - ctx.bounds.top
return !(x < btn.x || x > btn.x + btn.width || y < btn.y || y > btn.y + btn.height)
}
let move_cb = function (e) {
let btn = !ctx.foc_btn && ctx.f_btn || ctx.s_btn
ctx.foc_btn = checkIntersection(e, btn) ? 1 - ctx.foc_btn : ctx.foc_btn
}
let click_cb = function (e) {
checkIntersection(e, ctx.s_btn) && fin_cb()
}
let fin_cb = function () {
if (ctx.foc_btn) return false
new Ads(document.getElementById('ad-container'), document.getElementById('video-element'), function () {
ctx.restart()
}.bind(this))
window.removeEventListener('keyup', key_cb)
window.removeEventListener('mousemove', move_cb)
window.removeEventListener('click', click_cb)
}
window.addEventListener('keyup', key_cb)
window.addEventListener('mousemove', move_cb)
window.addEventListener('click', click_cb)
}
p.restart = function () {
this.game_state = 0
this.values = new Array(pow(this.dimension, 2));
if (random() > .5) {
this.player_index = 'x'
this.bot_index = 'o'
} else {
this.player_index = 'o'
this.bot_index = 'x'
}
this.bot_win_pattern = '';
this.player_win_pattern = '';
for (let i = 0; i < this.dimension; i++) {
this.bot_win_pattern += this.bot_index
this.player_win_pattern += this.player_index
}
if (this.player_index === 'x') {
this.setPlayListeners()
this.focus = 4
} else {
this.focus = NaN
this.botPlay()
}
}
p.resize = function () {
w = this.canvas.width = 1280,
h = this.canvas.height = 720
this.bounds = this.canvas.getBoundingClientRect()
this.desk_size = min(h - 100, w);
this.border_width = this.desk_size * .04 / this.dimension;
this.margin = [(w - this.desk_size) / 2, (h - this.desk_size - 100) / 2 + 100];
this.soket_size = (this.desk_size - this.border_width) / this.dimension
this.f_btn = {
x: w / 2 - 250,
y: h / 2 - 25,
width: 200,
height: 50,
r: 10
}
this.s_btn = {
x: w / 2 + 50,
y: h / 2 - 25,
width: 200,
height: 50,
r: 10
}
}
Object.assign(Game.prototype, p) |
const Cropper = require('cropperjs/dist/cropper.min') ;
var $modal;
var $btnValidateCrop;
var $image;
var cropper;
var aspectRatio = 1;
module.exports = {
init: function(){
$modal = $("#modal-cropper-tool");
$btnValidateCrop = $("#validate-crop");
$image = $("#crop-image");
$modal.on('shown.bs.modal', function () {
cropper = new Cropper($image[0], {
aspectRatio: aspectRatio,
autoCropArea: 0.8,
strict: true,
ready: function () {
}
});
}).on('hidden.bs.modal', function () {
cropper.destroy();
});
$btnValidateCrop.click(function (e) {
e.preventDefault();
cropper.getCroppedCanvas().toBlob(function (blob) {
$modal.modal("hide");
$(module.exports).trigger("crop", blob);
}, 'image/jpeg');
})
},
show: function(image, ratio) {
aspectRatio = ratio;
$image.attr("src", image);
$modal.modal("show");
}
};
|
SerialPort = Npm.require('serialport');
|
/*-------------------------------------------------------------
| THE MOST FKIN BEAUTIFUL |
| THING I HAVE EVER SEEN |
| IN MY LIFE |
| THANK YOU DANC-SENPAI |
--------------------------------------------------------------*/
var $ = document.querySelector.bind(document);
var $$ = document.querySelectorAll.bind(document);
/*-------------------------------------------
| Notice |
--------------------------------------------*/
const collapse = function() {
$('.notice').style.display = "none";
}
$('.notice').addEventListener('click', collapse);
/*-------------------------------------------
| Bootup |
--------------------------------------------*/
const choices = function() {
$('.bootup').style.display = "none";
$('#c1').removeEventListener('click', choices);
$('#c2').removeEventListener('click', sorry);
$('#c3').removeEventListener('click', sorry);
$('#c4').removeEventListener('click', sorry);
}
const sorry = function() {
$('.sorryw').style.display = "block";
$('.sorryw').addEventListener('click', returnn);
}
const returnn = function() {
$('.sorryw').style.display = "none";
$('.sorryw').removeEventListener('click', returnn);
}
$('#c1').addEventListener('click', choices);
$('#c2').addEventListener('click', sorry);
$('#c3').addEventListener('click', sorry);
$('#c4').addEventListener('click', sorry);
|
import React,{Component} from "react";
import "./index.css";
import axios from "axios";
import DDDD from "../dddd"
class Cinema extends Component{
constructor(){
super();
this.state = {
cinemalist:[],
ddddShow:false,
}
}
render(){
return <div>
<div className="navbg">
<span className="left">大连<i></i></span>
<input className="right" placeholder="搜影院"/>
</div>
<div className="navbg2">
<ul>
<li className="left" onClick={this.dddd.bind(this)}>全城<i></i></li>
<li className="left">品牌<i></i></li>
<li className="left">特色<i></i></li>
</ul>
</div>
<DDDD ddShow={this.state.ddddShow}/>
<ul className="cinema">
{
this.state.cinemalist.map(item=>
<li key={item.id} onClick={this.hand.bind(this,item.id)}>
<p>{item.nm} <span className="cinemaprice"><span className="s1">{item.sellPrice}</span><span className="s2">元起</span></span></p>
<p className="cinemaAddr">{item.addr}<span>{item.distance}</span></p>
<div className="cinemaAll">
<div className={item.tag.allowRefund==1?"allowRefund":"pp"}>{item.tag.allowRefund==1?"退":""}</div>
<div className={item.tag.endorse==1?"endorse":"pp"}>{item.tag.endorse==1?"改签":""}</div>
<div className={item.tag.snack==1?"snack":"pp"}>{item.tag.snack==1?"小吃":""}</div>
<div className={item.tag.vipTag==null?"pp":"vipTag"}>{item.tag.vipTag}</div>
<div className={item.tag.hallType==null?"pp":"hallType"}>{item.tag.hallType}</div>
</div>
<p className="cinemacardPromotionTag">{item.promotion.cardPromotionTag}</p>
</li>
)
}
</ul>
</div>
}
hand(id){
this.props.history.push(`/shows/${id}`)
}
dddd(){
this.setState({
ddddShow:!this.state.ddddShow
})
}
componentDidMount(){
axios.get("/ajax/cinemaList?day=2018-07-17&offset=0&limit=20&districtId=-1&lineId=-1&hallType=-1&brandId=-1&serviceId=-1&areaId=-1&stationId=-1&item=&updateShowDay=true&reqId=1531813012829&cityId=65").then(res=>{
console.log(res.data.cinemas)
this.setState({
cinemalist:res.data.cinemas
})
})
}
}
export default Cinema
|
import React from 'react';
import PhotoManager from './components/PhotoManager';
import './App.css';
function App() {
return (
<PhotoManager />
);
}
export default App;
|
/* @flow */
import * as React from 'react';
import { Form, Formik } from '../dist/formik';
import Mutation from './controls/Mutation';
import Input from './controls/Input';
import NumberInput from './controls/NumberInput';
import bind from './bind';
import someApiMutation from './mutations/someApiMutation';
type Props = {
data: {|
+id: string,
+name: string,
+age: number,
+deep: {|
+id: number,
+value: string,
|},
+arr: Array<{| +title: string |}>,
|},
parentId: string,
};
// We must declare initialValues type
const mapData = (data): $ElementType<Props, 'data'> => ({
...data,
});
class BasicForm extends React.Component<Props> {
render() {
const { data, parentId } = this.props;
return (
<Form>
<Mutation mutation={someApiMutation}>
{({ onSubmit, error: apiError }) => (
<Formik
initialValues={mapData(data)}
validate={values => {
if (values.age < 10) {
return { age: 'Too young' };
}
if (values.age > 20) {
return { age: 'Too old' };
}
/* $ExpectError "Cannot create `Formik` element
because property `unknown` is missing in object type [1]
in the indexer property's key of the return value
of property `validate`."*/
return { unknown: 'xxx' };
}}
onSubmit={(values, formikActions) => {
// non converted values are passed to make errors
// can be shown in this form (api error keys can be different)
onSubmit({ ...values, parentId }, values, formikActions);
/* $ExpectError Cannot call `onSubmit` with object literal bound to `input`
because property `parentId` is missing in object literal [1] but exists in object type [2].
*/
onSubmit(values, values, formikActions);
onSubmit(
/* $ExpectError Cannot call `onSubmit`
with object literal bound to `input`
because property `hello` is missing in object type [1]
but exists in object literal [2].*/
{ ...values, parentId, hello: 'world' },
values,
formikActions
);
}}
>
{formProps => {
const {
values,
errors,
touched,
handleChange,
handleBlur,
handleReset,
setErrors,
setTouched,
dirty,
isSubmitting,
isValid,
} = formProps;
return (
<React.Fragment>
{apiError != null && <div>{apiError}</div>}
<Input {...bind(formProps, 'name')} />
<NumberInput {...bind(formProps, 'age')} />
{/* $ExpectError Cannot create `Input` element because number
[1] is incompatible with string [2] in property `value`. */}
<Input {...bind(formProps, 'age')} />
{/* Trying to bind to unknown property will cause a lot of errors so ExpectError will not help,
uncomment to see effect */}
{/* <Input {...bind(formProps, 'unknown')} /> */}
<Input
name={'name'}
value={values.name}
onChange={handleChange}
// error={Boolean(touched.name === true && errors.name)}
/>
<Input
name={'age'}
/* $ExpectError Cannot create `Input`
element because number [1] is incompatible with string [2] in property `value`
*/
value={values.age}
onChange={handleChange}
/>
<Input
name={'unknown'}
/*
$ExpectError Cannot get `values.unknown` because property `unknown` is missing in object type [1].
*/
value={values.unknown}
onChange={handleChange}
/>
<div>
{/* Show errors, and deep errors */}
{errors.name}
{errors.deep && errors.deep.value}
{errors.arr && errors.arr[0] && errors.arr[0].title};
</div>
<div>
{/* Check touched */}
{touched.name && 'name is touched'}
{touched.deep &&
touched.deep.value &&
'deep.value is touched'}
{touched.arr &&
touched.arr[0] &&
touched.arr[0].title &&
'arr 0 titlw is touched'};
</div>
<button
onClick={() => {
setErrors({ name: '2fff' });
// Not sure this is needed to set error on whole subobject
// setErrors({ deep: 'error' });
setErrors({ deep: { value: 'error' } });
// setErrors({ arr: 'error' });
setErrors({
arr: [{ title: 'error' }, { title: 'error2' }],
});
/* $ExpectError 'Cannot call `setErrors`
with object literal bound to `errors`
because property `unknown` is missing
in object literal [1] but exists in `FormikErrors`"*/
setErrors({ unknown: 'eeee' });
/* $ExpectError Cannot call `setErrors`
with object literal bound to `errors` because property
`unknownValue` is missing in object literal [1]
but exists in `FormikErrors` [2] in property `deep`.
*/
setErrors({ deep: { unknownValue: 'error' } });
/*
$ExpectError Cannot call `setErrors` with object literal
bound to `errors` because property `unknown` is missing
in object literal [1] but exists in `FormikErrors` [2] in array element of property `arr`.
*/
setErrors({
arr: [{ unknown: 'error' }],
});
}}
/>
<button
onClick={() => {
setTouched({ name: true });
// Not sure this is needed to set error on whole subobject
// setTouched({ deep: 'error' });
setTouched({ deep: { value: true } });
// setTouched({ arr: 'error' });
setTouched({
arr: [{ title: false }, { title: true }],
});
/* $ExpectError Cannot call `setTouched` with
object literal bound to `touched` because
property `unknown` is missing in object literal
[1] but exists in `FormikTouched` [2]*/
setTouched({ unknown: true });
/* $ExpectError Cannot call `setTouched` with object literal
bound to `touched` because property `unknownValue` is missing
in object literal [1] but exists in `FormikTouched` [2] in property `deep`.
*/
setTouched({ deep: { unknownValue: 'error' } });
/*
$ExpectError Cannot call `setTouched` with object
literal bound to `touched` because property `unknown`
is missing in object literal [1] but exists in
`FormikTouched` [2] in array element of property `arr`
*/
setTouched({
arr: [{ unknown: 'error' }],
});
}}
/>
<button
onClick={handleReset}
disabled={!dirty || isSubmitting}
>
{'Cancel'}
</button>
<button
type="submit"
disabled={!dirty || isSubmitting || !isValid}
>
{'Save'}
</button>
</React.Fragment>
);
}}
</Formik>
)}
</Mutation>
</Form>
);
}
}
|
X.define("model.authorityModel",function () {
//临时测试数据
var query = "js/data/mockData/purchasers.json";
var authorityModel = X.model.create("model.authorityModel",{service:{ query:query}});
return authorityModel;
});
|
var contentDoc = 'https://docs.google.com/spreadsheets/d/1Wc7hkoh0T32zDRtcJIVGw1pKqTjHASAlj92vz6Qz5zs/pubhtml';
function loadPeople() {
$(document).ready(function() {
Tabletop.init({
key: contentDoc,
wanted: ["People"],
callback: showPeople,
orderby: 'title',
parseNumbers: false
});
});
function showPeople(data, tabletop) {
var source = $("#people-template").html();
var template = Handlebars.compile(source);
$.each( tabletop.sheets("People").all(), function(i, detail) {
var html = template(detail);
$("#people").append(html);
});
$("#search-people").hideseek({
highlight: true,
ignore_accents: true,
nodata: 'No people found'
});
$(".people-content .loading").hide();
$(".search-box").show();
$(".list-actions").show();
};
};
loadPeople(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.