text stringlengths 7 3.69M |
|---|
import "bootstrap";
import "components/slide";
import "components/confirm";
import "plugins/flatpickr";
import "plugins/inputmask";
import "components/modal";
import "components/select2";
import "components/scroll-text.js";
import { bindDisablePanelForm, bindDisableCampaignForm } from "components/disabling.js";
if (document.getElementById("order_duration")) {
import("components/total-price.js")
}
import swal from 'sweetalert';
import { initUpdateNavbarOnScroll } from '../components/navbar';
if (document.querySelector('.navbar-wagon')) {
initUpdateNavbarOnScroll();
}
if (document.getElementById('add-panel')) {
bindDisablePanelForm()
}
if (document.getElementById('add-campaign')) {
bindDisableCampaignForm()
}
if (document.querySelector(".dropzone")) {
Dropzone.options.artUpload = {
dictDefaultMessage: "Arraste sua arte para fazer o upload",
paramName: "art", // The name that will be used to transfer the art
maxFilesize: 2, // MB
maxFiles: 1, // MB
addRemoveLinks: true,
init: function() {
this.on("complete", function(file) {
const currentElement = this.element.parentElement;
const imageElement = currentElement.querySelectorAll("img")[1];
const pendent = currentElement.querySelector("#pendent")
const send = currentElement.querySelector("#art-status")
if (imageElement) {
imageElement.remove()
} else if (pendent) {
pendent.remove()
} else {
send.remove()
}
currentElement.insertAdjacentHTML('beforeend', `<img class="dropzone-art" src="${this.files[0].dataURL}" alt="${this.files[0].name}" width="230">`)
currentElement.insertAdjacentHTML('beforeend', `<p id="art-status" class="text-center"><i class="fa fa-clock-o" aria-hidden="true">Aguardando aprovação</p>`)
this.element.remove()
const a = () => {
currentElement.querySelector("#art-status").remove()
}
const b = () => {
currentElement.insertAdjacentHTML('beforeend', `<p id="art-status" class="text-center <%= dom_id(order) %>"><i class="fa fa-check-circle" aria-hidden="true"></i> Arte aprovada</p>`)
}
setInterval(a, 5000)
setInterval(b, 5000)
})
}
}
}
|
import React, { Component } from 'react'
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import { Link } from 'react-router-dom'
import axios from 'axios'
export default class InventoryCard extends Component {
state = {
customerInfo: ''
}
componentDidMount() {
this.refreshInvoice()
}
refreshInvoice = () => {
const customerId = this.props.customerId
axios.get(`/api/customer/${customerId}`)
.then((res) => {
this.setState({ customerInfo: res.data.singleCustomer })
})
}
render() {
const customerInfo = this.state.customerInfo
const isPaid = this.props.paid
return (
<Card className={isPaid ? 'card-paid' : 'card-not-paid'} variant="outlined">
<CardContent>
<Typography className='title' color="textSecondary" gutterBottom>
Invoice
</Typography>
<Typography variant="h5" component="h2">
<Link to={this.props.invoiceLink}>
{this.props.note}
</Link>
</Typography>
<Typography className='pos' color="textSecondary">
Client:
</Typography>
<Typography variant="body1" component="p">
{customerInfo.firstName} {customerInfo.lastName}
</Typography>
<Typography className='pos' color="textSecondary">
Amount:
</Typography>
<Typography variant="body1" component="p">
${this.props.amount}
</Typography>
</CardContent>
<CardActions>
<Button
size="small"
onClick={this.props.deleteInvoice}
>Delete Invoice</Button>
</CardActions>
</Card>
)
}
}
|
'use strict';
// let slider = document.getElementById("myRange");
// let price = document.getElementById("price");
// price.innerHTML = slider.value;
// slider.oninput = function() {
// price.innerHTML = this.value;
// }
function initMap() {
let map, coords, styles, marker, info, content;
coords = {
lat: 64.14311360365512,
lng: -21.926393842068492
}
map = new google.maps.Map(document.getElementById("map"), {
center: coords,
zoom: 13,
styles: styles,
disableDefaultUI: true,
zoomControl: false,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_BOTTOM,
},
streetViewControl: true,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
mapTypeIds: ["roadmap", "satellite"],
},
});
marker = new google.maps.Marker({
position: coords,
map: map,
title: "This is here!",
animation: google.maps.Animation.DROP,
// draggable: true,
icon: 'images/marker.png',
});
content = `<h1 class="map__title">Hello</h1>
<p class="map__txt">This is your place!</p>`;
info = new google.maps.InfoWindow({
content: content,
});
marker.addListener("click", () => {
info.open(map, marker);
});
}
new Swiper('.slider__items', {
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
pagination: {
el: '.swiper-pagination',
dynamicBullets: true,
},
clickable: true,
slidesPerView: 1,
spaceBetween: 45,
loop: true,
freeMode: false,
// autoplay: {
// delay: 2500,
// disableOnInteractive: false
// },
speed: 800,
breakpoints: {
768: {
slidesPerView: 3,
spaceBetween: 100,
width: 970
},
480: {
slidesPerView: 1
}
}
});
new Swiper('.swiper__container', {
navigation: {
nextEl: '.swiper__next',
prevEl: '.swiper__prev',
},
loop: true,
slidesPerView: 1,
// effect: 'fade',
pagination: {
el: '.swiper-pagination',
clickable: true
},
breakpoints: {
768: {
slidesPerView: 3,
}
},
});
(function ($) {
$(document).ready(function () {
// Code
$('.menu').on('click', function () {
$(this).toggleClass('menu__open');
$('.navigation__wrapper').toggleClass('navigation__open');
});
$('.carousel__items').slick({
slidesToShow: 1,
slidesToScroll: 1,
arrows: false,
fade: true,
dots: true,
asNavFor: '.booking__content',
});
$('.booking__content').slick({
slidesToShow: 3,
slidesToScroll: 1,
asNavFor: '.carousel__items',
focusOnSelect: true,
centerMode: true,
centerPadding: 50,
prevArrow: '<div class="booking__arrow booking__prev"><i class="icon-arrow"></div>',
nextArrow: '<div class="booking__arrow booking__next"><i class="icon-arrow"></div>'
});
AOS.init();
});
$(window).scroll(() => {
if ($(window).scrollTop() > 5) {
$('.booking__navigation').addClass('booking__navigation--active');
$('.booking__menu-link').addClass('booking__menu-link--scroll');
}
else {
$('.booking__navigation').removeClass('booking__navigation--active');
$('.booking__menu-link').removeClass('booking__menu-link--scroll');
}
});
$('.tours__subtitle').on('click', function () {
$(this).toggleClass('tours__subtitle--open');
$('.tours__open').toggleClass('tours__open--open');
});
})(jQuery);
|
import { IS_DESKTOP, IS_TABLET, IS_MOBILE } from './responsive-utils'
import { screenWidth } from '../screen/screen-utils'
jest.mock('../screen/screen-utils')
describe('responsive utils', () => {
it('IS DESKTOP should return true on desktop', () => {
// Given
screenWidth.mockReturnValue(2240)
// When
const boolean = IS_DESKTOP()
// Then
expect(boolean).toBe(true)
})
it('should handle correctly the high limit', () => {
// Given
screenWidth.mockReturnValue(1000)
// When
const isDesktop = IS_DESKTOP()
const isTablet = IS_TABLET()
// Then
expect(isDesktop).toBe(false)
expect(isTablet).toBe(true)
})
it('IS TABLET should return true on tablet', () => {
// Given
screenWidth.mockReturnValue(999)
// When
const boolean = IS_TABLET()
// Then
expect(boolean).toBe(true)
})
it('should handle correctly the low limit', () => {
// Given
screenWidth.mockReturnValue(640)
// When
const isMobile = IS_MOBILE()
const isTablet = IS_TABLET()
// Then
expect(isMobile).toBe(true)
expect(isTablet).toBe(false)
})
it('IS MOBILE should return true on mobile', () => {
// Given
screenWidth.mockReturnValue(500)
// When
const boolean = IS_MOBILE()
// Then
expect(boolean).toBe(true)
})
})
|
// The following function returns true if the parameter age is greater than 18.
// Otherwise returns false:
checkAge = (age) => {
if (age >= 18) {
isItTrue = true;
} else {
isItTrue = false;
}
return isItTrue
};
console.log(checkAge(18))
// Write a function min(a,b) which returns the least of two numbers a and b.
function min(a, b) {
return Math.min(a, b);
}
console.log(min(5, 3));
// Write a function pow(x,n) that returns x in power n. Or, in other words, multiplies x by itself n times and returns the result.
function pow(x, n){
return x ** n
};
console.log(pow(3, 3));
|
window.onload = makeInitialGraphs()
function makeInitialGraphs(){
getGraphAvgFinalInternet();
getGraphGradesAndHealth();
getGraphTravelTime();
}
/******************
*
* Graph Building Functions
* comprised of pairs
*
* 1) Function triggered on button click event
* -sends http request
* 2) Callback function for http request
* -inserts graph into DOM
*/
function getGraphAvgFinalInternet(){
getData({
G3: {
condition: false,
},
internet: {
condition: false,
},
callback: buildGraphAvgFinalInternet
});
cleanLabels();
}
function buildGraphAvgFinalInternet(data){
data = data.data;
let averages = getFinalAveragesInternet(data);
let chartData = [{
values: [averages[0] / 20, (1 - (averages[0] / 20))],
domain: {column: 0},
text: averages[0] + "/" + 20,
textinfo: 'none',
name: 'With Internet',
hoverinfo: 'percent+name',
hole: .7,
type: 'pie',
marker: {
colors: ['#67e580', '#cecece']
}
},{
values: [averages[1] / 20, (1- (averages[1] / 20))],
domain: {column: 1},
text: averages[1] + "/" + 20,
textinfo: 'none',
name: "Without Internet",
hoverinfo: 'percent+name',
hole: .7,
type: 'pie',
marker: {
colors: ['#e76d62', '#cecece']
},
rotation: 169
}];
let layout = {
height: 400,
width: 650,
showlegend: false,
title: 'Final Grade Based On Internet Access',
grid: {rows: 1, columns: 2},
annotations: [
{
font: {size: 20},
text: (Math.round(averages[0] * 100) / 100) + "/" + 20,
x: .14,
y: .5,
showarrow: false
},
{
font: {size: 20},
text: (Math.round(averages[1] * 100) / 100) + "/" + 20,
x: .85,
y: .5,
showarrow: false
}
]
};
Plotly.newPlot('average-final', chartData, layout);
let parentContainer = document.getElementById('average-final');
if(!document.getElementById('chartLabel')){
labelTextWith = document.createElement('p');
labelTextWith.setAttribute('class', 'chartLabel');
labelTextWith.setAttribute('style', 'position: absolute; left: 610px; top: 350px;');
labelTextWith.innerHTML = "With Internet";
labelTextWithout = document.createElement('p');
labelTextWithout.setAttribute('class', 'chartLabel')
labelTextWithout.setAttribute('style', 'position: absolute; left: 860px; top: 350px;');
labelTextWithout.innerHTML = "Without Internet";
parentContainer.appendChild(labelTextWith);
parentContainer.appendChild(labelTextWithout);
}
//console.log(document.getElementById('chart-label'))
setFinalGradeButtonStyles(document.getElementById('avg-final-internet'));
}
function getGraphAvgFinalPastFail(){
getData({
G3: {
condition: false,
},
failures: {
condition: false
},
callback: buildGraphAvgFinalPastFail
})
cleanLabels();
}
function buildGraphAvgFinalPastFail(data){
data = data.data;
let averages = getFinalAveragesPastFail(data);
let trace = {
x: ['0', '1', '2', '3 or more'],
y: averages,
type: 'bar',
};
let chartData = [trace]
let layout = {
height: 400,
width: 650,
showlegend: false,
title: 'Final Grade vs Past Absences',
xaxis: {
title: 'Number of past failures',
type: 'category',
},
yaxis: {
title: 'Average final grade',
autorange: 'false',
range: [0,14]
}
}
Plotly.newPlot('average-final', chartData, layout);
setFinalGradeButtonStyles(document.getElementById('avg-final-pastfail'))
}
function getGraphAvgFinalStudyTime(){
getData({
G3: {
condition: false
},
studytime: {
condition: false
},
callback: buildGraphAvgFinalStudyTime
})
cleanLabels();
}
function buildGraphAvgFinalStudyTime(data){
setFinalGradeButtonStyles(document.getElementById('avg-final-studytime'));
data = data.data;
let averages = getFinalAveragesStudyTime(data);
let trace = {
x: ['1 (<2 Hours)', '2 (2-5 Hours)', '3 (5-10 Hours)', '4 (>10 Hours)'],
y: averages,
type: 'bar',
}
let chartData = [trace];
let layout = {
height: 400,
width: 650,
showlegend: false,
title: 'Final Grade vs Study Time',
xaxis: {
title: 'Study time',
type: 'category',
},
yaxis: {
title: 'Average final grade',
autorange: 'false',
range: [0,14]
}
}
Plotly.newPlot('average-final', chartData, layout);
}
function getGraphAvgFinalAbsences(){
getData({
G3: {
condition: false
},
absences: {
condition: false
},
callback: buildGraphAvgFinalAbsences
})
cleanLabels();
}
function buildGraphAvgFinalAbsences(data){
setFinalGradeButtonStyles(document.getElementById('avg-final-absences'));
data = data.data;
let averages = getFinalAveragesAbsences(data);
let traceData = {
x: [],
y: [],
counts: []
};
for (let i = 0; i < averages.sums.length; i++){
if(averages.counts[i] != 0){
traceData.x.push(i);
traceData.y.push(averages.averages[i]);
traceData.counts.push("n = " + averages.counts[i]);
}
}
let trace = {
x: traceData.x,
y: traceData.y,
type: 'scatter',
mode: 'markers',
text: [traceData.counts],
};
let chartData = [trace];
let layout = {
height: 400,
width: 650,
showlegend: false,
title: 'Final Grade vs Absences',
xaxis: {
title: 'Absences',
},
yaxis: {
title: 'Average final grade',
autorange: 'false',
range: [0,14]
},
};
Plotly.newPlot('average-final', chartData, layout);
}
function getGraphGradesAndHealth(){
getData({
G1: {
condition: false
},
G2: {
condition: false
},
G3: {
condition: false
},
health: {
condition: false
},
callback: buildGraphGradesAndHealth
})
}
function buildGraphGradesAndHealth(data){
data = data.data;
let averages = getGradeAveragesHealth(data);
let healthScale = [1,2,3,4,5]
let trace1 = {
x: healthScale,
y: averages.G1.averages,
name: 'Average G1',
type: 'bar'
},
trace2 = {
x: healthScale,
y: averages.G2.averages,
name: 'Average G2',
type: 'bar'
},
trace3 = {
x: healthScale,
y: averages.G3.averages,
name: 'Average G3',
type: 'bar'
};
let chartData = [trace1, trace2, trace3];
let layout = {
barmode: 'group',
height: 600,
width: 1000,
showlegend: true,
title: 'Average Grades Based on Health',
xaxis: {
title: 'Health Rating (1-5)',
},
yaxis: {
title: 'Average Grade',
autorange: 'false',
range: [0,14]
}
}
Plotly.newPlot('health-graph', chartData, layout);
}
function getGraphTravelTime(){
getData({
traveltime: {
condition: false,
},
G1:{
condition: false,
},
G2: {
condition: false,
},
G3: {
condition: false,
},
callback: buildGraphTravelTime
});
}
function buildGraphTravelTime(data){
data = data.data;
let averages = getGradeAveragesTravel(data);
let G1 = averages.G1.averages;
let G2 = averages.G2.averages;
let G3 = averages.G3.averages;
let trace1 = {
x: ['1 (<15 min)', '2 (15-30 min)', '3 (30 min to 1 hour)', '4 (>1 hour)'],
y: G1,
type: 'bar',
name: 'G1',
text: G1.map((num) => {return Math.round(num * 100) / 100}),
textposition: 'auto',
hoverinfo: 'none'
}
let trace2 = {
x: ['1 (<15 min)', '2 (15-30 min)', '3 (30 min to 1 hour)', '4 (>1 hour)'],
y: G2,
type: 'bar',
name: 'G2',
text: G2.map((num) => {return Math.round(num * 100) / 100}),
textposition: 'auto',
hoverinfo: 'none'
}
let trace3 = {
x: ['1 (<15 min)', '2 (15-30 min)', '3 (30 min to 1 hour)', '4 (>1 hour)'],
y: G3,
type: 'bar',
name: 'G3',
text: G3.map((num) => {return Math.round(num * 100) / 100}),
textposition: 'auto',
hoverinfo: 'none'
}
let chartData = [trace1, trace2, trace3];
let layout = {
height: 500,
width: 1000,
showlegend: true,
title: 'Overall Grades vs Travel Time',
xaxis: {
title: 'Travel time',
type: 'category',
},
yaxis: {
title: 'Average grades',
autorange: 'false',
range: [0,40]
},
barmode: 'stack'
}
Plotly.newPlot('travel-graph', chartData, layout);
}
/****************
* Average Calculations
*****************/
function getFinalAveragesInternet(data){
let sumWithInternet = 0,
sumWithoutInternet = 0,
countWithInternet = 0,
countWithoutInternet = 0;
for(let i = 0; i < data.length; i++){
student = data[i];
if(student.internet == "yes"){
sumWithInternet += student.G3;
countWithInternet++;
}
else if(student.internet == "no"){
sumWithoutInternet += student.G3;
countWithoutInternet++;
}
}
let avgWithInternet = sumWithInternet/countWithInternet;
let avgWithoutInternet = sumWithoutInternet/countWithoutInternet;
return [avgWithInternet, avgWithoutInternet];
}
function getFinalAveragesPastFail(data){
let sums = [0, 0, 0, 0];
let counts = [0, 0, 0, 0];
for(let i = 0; i < data.length; i++){
let student = data[i];
sums[student.failures] += student.G3;
counts[student.failures]++;
}
let averages = [0,0,0,0];
for(let i = 0; i < 4; i++){
averages[i] = sums[i]/counts[i]
}
return averages;
}
function getFinalAveragesStudyTime(data){
let sums = [0, 0, 0, 0];
let counts = [0, 0, 0, 0];
for(let i = 0; i < data.length; i++){
let student = data[i];
sums[student.studytime - 1] += student.G3;
counts[student.studytime - 1]++;
}
let averages = [0,0,0,0];
for(let i = 0; i < 4; i++){
averages[i] = sums[i]/counts[i]
}
return averages;
}
function getFinalAveragesAbsences(data){
let sums = new Array(94).fill(0);
let counts = new Array(94).fill(0);
for(let i = 0; i < data.length; i++){
sums[data[i].absences] += data[i].G3;
counts[data[i].absences]++;
}
let averages = new Array(94).fill(0);
for(let i = 0; i < sums.length; i++){
averages[i] = sums[i]/counts[i];
}
return {
sums: sums,
counts: counts,
averages: averages
};
}
function getGradeAveragesHealth(data){
let result = {
G1: {
sums: new Array(5).fill(0),
counts: new Array(5).fill(0),
averages: new Array(5).fill(0),
},
G2: {
sums: new Array(5).fill(0),
counts: new Array(5).fill(0),
averages: new Array(5).fill(0),
},
G3: {
sums: new Array(5).fill(0),
counts: new Array(5).fill(0),
averages: new Array(5).fill(0),
}
}
for(let i = 0; i < data.length; i++){
result.G1.sums[data[i].health - 1]+= data[i].G1;
result.G1.counts[data[i].health - 1]++;
result.G2.sums[data[i].health - 1]+= data[i].G2;
result.G2.counts[data[i].health - 1]++;
result.G3.sums[data[i].health - 1]+= data[i].G3;
result.G3.counts[data[i].health - 1]++;
}
for(let i = 0; i < 5; i++){
result.G1.averages[i] = result.G1.sums[i]/result.G1.counts[i];
result.G2.averages[i] = result.G2.sums[i]/result.G2.counts[i];
result.G3.averages[i] = result.G3.sums[i]/result.G3.counts[i];
}
return result;
}
function getGradeAveragesTravel(data){
let result = {
G1: {
sums: new Array(4).fill(0),
counts: new Array(4).fill(0),
averages: new Array(4).fill(0),
},
G2: {
sums: new Array(4).fill(0),
counts: new Array(4).fill(0),
averages: new Array(4).fill(0),
},
G3: {
sums: new Array(4).fill(0),
counts: new Array(4).fill(0),
averages: new Array(4).fill(0),
}
}
for(let i = 0; i < data.length; i++){
result.G1.sums[data[i].traveltime - 1]+= data[i].G1;
result.G1.counts[data[i].traveltime - 1]++;
result.G2.sums[data[i].traveltime - 1]+= data[i].G2;
result.G2.counts[data[i].traveltime - 1]++;
result.G3.sums[data[i].traveltime - 1]+= data[i].G3;
result.G3.counts[data[i].traveltime - 1]++;
}
for(let i = 0; i < 5; i++){
result.G1.averages[i] = result.G1.sums[i]/result.G1.counts[i];
result.G2.averages[i] = result.G2.sums[i]/result.G2.counts[i];
result.G3.averages[i] = result.G3.sums[i]/result.G3.counts[i];
}
return result;
}
/************************
*
* Style and DOM Changes
*/
function setFinalGradeButtonStyles(selection){
let list = document.getElementById('avg-final-buttons');
let listItems = list.children;
for(let i= 0; i < listItems.length; i++){
listItems[i].children[0].setAttribute("style", "background: #ffffff;");
}
selection.setAttribute("style", "background: #cecece;")
}
function cleanLabels(){
let labels = document.getElementsByClassName('chartLabel');
let parent = document.getElementById('average-final');
for(let i = 0; i < labels.length; i++){
parent.removeChild(labels.item(i));
i--;
}
}
//Build and dispatch http request
function getData(options){
let baseURL = "http://127.0.0.1:5000/gmt?"
let query = "query"
if(options.school){
query += "&school"
if(options.school.condition) query += "=" + options.school.criteria;
}
if(options.sex){
query += "&sex"
if(options.sex.condition) query += "=" + options.sex.criteria;
}
if(options.age){
query += "&age"
if(options.age.condition) query += "=" + options.age.criteria;
}
if(options.address){
query += "&address"
if(options.address.condition) query += "=" + options.address.criteria;
}
if(options.famsize){
query += "&famsize"
if(options.famsize.condition) query += "=" + options.famsize.criteria;
}
if(options.Pstatus){
query += "&Pstatus"
if(options.Pstatus.condition) query += "=" + options.Pstatus.criteria;
}
if(options.Medu){
query += "&Medu"
if(options.Medu.condition) query += "=" + options.Medu.criteria;
}
if(options.Fedu){
query += "&Fedu"
if(options.Fedu.condition) query += "=" + options.Fedu.criteria;
}
if(options.Mjob){
query += "&Mjob"
if(options.Mjob.condition) query += "=" + options.Mjob.criteria;
}
if(options.Fjob){
query += "&Fjob"
if(options.Fjob.condition) query += "=" + options.Fjob.criteria;
}
if(options.reason){
query += "&reason"
if(options.reason.condition) query += "=" + options.reason.criteria;
}
if(options.guardian){
query += "&guardian"
if(options.guardian.condition) query += "=" + options.guardian.criteria;
}
if(options.traveltime){
query += "&traveltime"
if(options.traveltime.condition) query += "=" + options.traveltime.criteria;
}
if(options.studytime){
query += "&studytime"
if(options.studytime.condition) query += "=" + options.studytime.criteria;
}
if(options.failures){
query += "&failures"
if(options.failures.condition) query += "=" + options.failures.criteria;
}
if(options.schoolsup){
query += "&schoolsup"
if(options.schoolsup.condition) query += "=" + options.schoolsup.criteria;
}
if(options.famsup){
query += "&famsup"
if(options.famsup.condition) query += "=" + options.famsup.criteria;
}
if(options.paid){
query += "&paid"
if(options.paid.condition) query += "=" + options.paid.criteria;
}
if(options.activities){
query += "&activities"
if(options.activities.condition) query += "=" + options.activities.criteria;
}
if(options.nursery){
query += "&nursery"
if(options.nusery.condition) query += "=" + options.nusery.criteria;
}
if(options.higher){
query += "&higher"
if(options.higher.condition) query += "=" + options.higher.criteria;
}
if(options.internet){
query += "&internet"
if(options.internet.condition) query += "=" + options.internet.criteria;
}
if(options.romantic){
query += "&romantic"
if(options.romantic.condition) query += "=" + options.romantic.criteria;
}
if(options.famrel){
query += "&famrel"
if(options.famrel.condition) query += "=" + options.famrel.criteria;
}
if(options.freetime){
query += "&freetime"
if(options.freetime.condition) query += "=" + options.freetime.criteria;
}
if(options.goout){
query += "&goout"
if(options.goout.condition) query += "=" + options.goout.criteria;
}
if(options.Dalc){
query += "&Dalc"
if(options.Dalc.condition) query += "=" + options.Dalc.criteria;
}
if(options.Walc){
query += "&Walc"
if(options.Walc.condition) query += "=" + options.Walc.criteria;
}
if(options.health){
query += "&health"
if(options.health.condition) query += "=" + options.health.criteria;
}
if(options.absences){
query += "&absences"
if(options.absences.condition) query += "=" + options.absences.criteria;
}
if(options.G1){
query += "&G1"
if(options.G1.condition) query += "=" + options.G1.criteria;
}
if(options.G2){
query += "&G2"
if(options.G2.condition) query += "=" + options.G2.criteria;
}
if(options.G3){
query += "&G3"
if(options.G3.condition) query += "=" + options.G3.criteria;
}
let request = new XMLHttpRequest();
request.open("GET", baseURL + query)
request.send();
request.onreadystatechange = function(){
if(request.status == "200" && request.readyState == 4) {
let responseData = request.response;
let data_json = JSON.parse(responseData);
options.callback(data_json);
}
}
}
|
import React, { useState } from "react";
import { IoIosSearch } from "react-icons/io";
import { MdClear } from "react-icons/md";
import { IconContext } from "react-icons";
import "./SearchBar.scss";
const SearchBar = (props) => {
const [isClearButtonVisible, setClearButtonVisibility] = useState(false);
const [query, setQuery] = useState("");
const clearInput = () => {
setQuery("");
props.onChangeText("");
};
const handleInputChange = (text) => {
setQuery(text);
props.onChangeText(text);
};
return (
<div className="search_bar">
<IconContext.Provider
value={{
color: "#9e9e9e ",
size: "1.8em",
className: "search_icon",
title: "search_icon",
}}
>
<IoIosSearch />
</IconContext.Provider>
<input
value={query}
id="search_input"
autoComplete="off"
spellCheck="false"
placeholder="Search for a city"
autoFocus
onChange={(text) => handleInputChange(text.target.value)}
onFocus={() => setClearButtonVisibility(true)}
></input>
{isClearButtonVisible && (
<IconContext.Provider
value={{
color: "#9e9e9e ",
size: "1.8em",
title: "search_icon",
}}
>
<button onClick={() => clearInput()} id="clear_button">
<MdClear />
</button>
</IconContext.Provider>
)}
</div>
);
};
export default SearchBar;
|
let taula = document.getElementById ('taula');
let valor = 98;
for (let i=0 ; i<5; i++ ) {
let fila = taula.insertRow(i);
for ( let j=0 ; j<=9 ; j++ ){
let cella = fila.insertCell(-1);
cella.style.width = '30px';
cella.style.textAlign='right';
cella.innerHTML = valor;
valor=valor-2;
}
}
// if ( i%20==18 ) document.write( '<tr>') ;
// document.write( '<td align="center" bgcolor="#FFCC99" >' + i + '</td>' ) ;
// if ( i%20==0) document.write( '</tr>' ) ;
// } |
// Div içindeki değerleri tıklayarak toplama
$(function () {
$(".kutu h3").on("click", function () {
// aktif olan nesneyi ifade eder
let sayi1 = Number($(this).html());
// tıkladığımız nesneyi seçer
let sayi2 = Number($("#yaz").html());
$("#yaz").html(sayi1 + sayi2);
});
});
|
// 存放数据 使用订阅发布模式来实现数据的发放
const DataSource = {
data:{
comments:[
{id:1,title:'新的一天新的烦恼'},
{id:2,title:'今天也是元气满满的一天'},
],
blogs:[
{id:1,title:'史莱姆'},
{id:2,title:'参见萌王'}
]
},
getComments(){
return this.data.comments
},
getBlogs(){
return this.data.blogs
},
handlders: [], // 用来存放一些监听函数
// 可以写一个对象 键名是触发的函数名 键值是函数
addEventListen(hander){ // 绑定监听事件
this.handlders.push(hander)
},
removeEventListen(hander){
this.handlders = this.handlders.filter(item=>item!==hander)
},
addComment(){
console.log(this)
this.data.comments.push({id:3,title:'ojbk'})
this.emit() // 触发监听事件
},
addBlog(){
this.data.blogs.push({id:3,title:'ok'})
this.emit()
},
emit(){
this.handlders.forEach(hander=>hander())
}
}
DataSource.addComment = DataSource.addComment.bind(DataSource) // 点击按钮 调用的时候this丢失 先绑定好
DataSource.addBlog = DataSource.addBlog.bind(DataSource)
export default DataSource
|
let randomNumber1=Math.floor(Math.random()*6+1);
let randomNumber2=Math.floor(Math.random()*6+1);
let imgPath1="images/dice"+randomNumber1+".png";
let imgPath2="images/dice"+randomNumber2+".png";
document.getElementsByClassName("img1")[0].setAttribute("src",imgPath1);
document.getElementsByClassName("img2")[0].setAttribute("src",imgPath2);
if(randomNumber1>randomNumber2)
{
document.querySelector("h1").textContent="Player 1 Wins!🚩"
}
else if(randomNumber1<randomNumber2)
{
document.querySelector("h1").textContent="Player 2 Wins🚩"
}
else{
document.querySelector("h1").textContent="Draw!"
} |
(function(){
angular.module('QforQuants')
.config(function($stateProvider){
$stateProvider.state('Home.Login',{
url : 'login',
templateUrl : 'app/login/login.html',
controller : 'loginController',
controllerAs : 'login',
authenticate : false
})
.state('Home.Register',{
url : 'register',
templateUrl : 'app/login/register.html',
controller : 'registerController',
controllerAs : 'register',
authenticate : false
});
});
})(); |
/* eslint-disable react/jsx-filename-extension */
/* eslint-disable react/jsx-props-no-spreading */
import React from 'react';
import Hand from '../components/Hand';
export default {
title: 'Hand',
component: Hand,
};
const HandStory = (args) => <Hand {...args} />;
export const Default = HandStory.bind({});
Default.args = {
cards: [
{
suit: 'batons',
number: 1,
},
{
suit: 'swords',
number: 1,
},
{
suit: 'cups',
number: 3,
},
],
};
|
import React, { Component } from "react";
import axios from "axios";
const CancelToken = axios.CancelToken;
let cancel;
const APP_ID = "quEBN5y1RpIs0j412mWa";
const APP_CODE = "DyCA3Z89Utyz48Z1XogqmA";
export default class PlacePicker extends Component {
state = {
name: "",
autocomplete: []
};
cancelRequest = () => {
if (cancel) cancel();
cancel = null;
};
componentWillUnmount() {
this.cancelRequest();
}
updateAutocompleteList = name => {
this.cancelRequest();
if (name.length < 2) {
this.setState({ autocomplete: [] });
return;
}
const url = encodeURI(
`http://autocomplete.geocoder.api.here.com/6.2/suggest.json?app_id=${APP_ID}&app_code=${APP_CODE}&query=${name}`
);
axios
.get(url, {
cancelToken: new CancelToken(function executor(c) {
cancel = c;
})
})
.then(result => {
if (result.status === 200) {
console.log(result);
const places = result.data.suggestions.map(e => ({
label: e.label,
locationId: e.locationId,
city: e.city
}));
this.setState({ autocomplete: places });
}
})
.catch(err => {
console.error("Error getting info for place ", name, "\nError: ", err);
this.setState({ autocomplete: [] });
});
};
handleChange = event => {
this.setState({ name: event.target.value });
this.updateAutocompleteList(event.target.value);
};
handleSelectedPlace = event => {
const placeId = event.currentTarget.attributes.id.value;
const userSelected = this.state.autocomplete.find(
element => element.locationId === placeId
);
if (userSelected) {
this.cancelRequest();
this.setState({ name: userSelected.label, autocomplete: [] });
this.props.onPlaceSelected(userSelected.label);
} else {
alert("Cannot find place ", placeId);
}
};
handleKayDown = event => {
if (event.key === "Enter") {
event.preventDefault();
this.props.onPlaceSelected(this.state.name);
console.log(event.key);
} else if (event.key === "Esc") {
console.log(event.key);
event.preventDefault();
}
};
render() {
const divStyle = {
width: "300px"
};
return (
<div>
<form autoComplete="off">
<div className="autocomplete" style={divStyle}>
<span>Type name of place</span>
<input
type="search"
autoFocus={true}
placeholder="Type name of your place"
value={this.state.name}
id="placePickerId"
onChange={this.handleChange}
onKeyDown={this.handleKayDown}
/>
<div id={"autocomplete-list"} className="autocomplete-items">
{this.state.autocomplete.map(element => (
<div
onClick={this.handleSelectedPlace}
key={element.locationId}
id={element.locationId}
>
{element.label}
</div>
))}
</div>
</div>
</form>
</div>
);
}
}
|
import validator from '@/utils/validator'
export default {
schema: {
type: { // 组件类型
type: 'string',
default: 'Table'
},
title: 'string', // 标题
titleLocation: 'string', // 标题位置
hasPagination: { // 分页 1 显示 2 隐藏
type: 'number',
default: 1
},
buttonList: 'array', // 表格按钮配置
tableSelect: { // 表格勾选 0 关 1 开
type: 'number',
default: 0
},
tableThSelect: { // 选择列 0 关 1 开
type: 'number',
default: 0
},
optionsType: { // 数据来源:1 独立接口获取 2 页面接口获取
type: 'number',
default: 2
},
height: 'string', // 高度
layout: { // 表格配置
type: 'array',
default: [
{
label: '列1',
key: 'key1',
fixed: false,
openType: 0
}
]
}
},
rules: {
key: [
{ required: true, message: '请输入字段名', trigger: 'blur' },
validator.rule.keyCode
],
totalKey: [
{ required: true, message: '请输入字段名', trigger: 'blur' },
validator.rule.keyCode
],
apiUrl: [{
validator(rule, value, callback) {
if (this.optionsType === 1 && !value) {
callback(new Error('请输入请求地址'))
}
callback()
},
trigger: 'blur'
}]
}
}
|
import React, { Component } from "react";
import Main from "./components/Routes/Routes";
import Header from "./components/Header/Header";
import Footer from "./components/Footer/Footer";
class App extends Component {
constructor(props) {
super(props);
console.log(props)
this.state = {
loggeduser : "",
recruiter : false
};
//this.handleLoggedUserChange = this.handleLoggedUserChange.bind(this)
this.handleRecruiterChange = this.handleRecruiterChange.bind(this);
//this.onChange = this.onChange.bind(this);
//this.onSubmit = this.onSubmit.bind(this);
}
handleRecruiterChange () {
this.setState({recruiter: true});
alert("yes");
};
render() {
return (
<div className="App">
<div>
<Header />
</div>
<div className="container"><Main handler= {this.handleRecruiterChange}/></div>
<Footer />
</div>
);
}
}
export default App;
|
import React from 'react'
import Navbar from 'react-bootstrap/lib/Navbar'
import Nav from 'react-bootstrap/lib/Nav'
import NavItem from 'react-bootstrap/lib/NavItem'
import FormGroup from 'react-bootstrap/lib/FormGroup'
import FormControl from 'react-bootstrap/lib/FormControl'
import Button from 'react-bootstrap/lib/Button'
import MdAccountBox from 'react-icons/lib/md/account-box'
import MdSearch from 'react-icons/lib/md/search'
export default class TopBar extends React.Component {
render() {
return (
<header>
<Navbar>
<Navbar.Header>
<Navbar.Brand>
<a href="#">HHP</a>
</Navbar.Brand>
</Navbar.Header>
<Nav>
<Navbar.Form>
<FormGroup>
<FormControl type="text" placeholder="Search"/>
</FormGroup>
<Button type="submit"><MdSearch /></Button>
</Navbar.Form>
</Nav>
<Nav pullRight>
<NavItem eventKey={1} href="#"><MdAccountBox /></NavItem>
<NavItem eventKey={2} href="#"><MdAccountBox /></NavItem>
</Nav>
</Navbar>
</header>
)
}
} |
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import {
ADD_NOTE,
DELETE_NOTE,
CLOSE_RESET_CONFIRM_DIALOG,
} from '../../actions/file';
const initialState = {};
export const resetDb = createAsyncThunk(
'backend/resetDb',
async (data, thunkAPI) => {
const fileState = thunkAPI.getState().file;
const { dataApi } = fileState;
await dataApi.DeleteAllDocuments();
await dataApi.DeleteAllNotes();
await dataApi.DeleteAllTodos();
await dataApi.DeleteSettings();
thunkAPI.dispatch({
type: CLOSE_RESET_CONFIRM_DIALOG,
confirmed: true,
});
}
);
// some of these should go to the note slice
export const updateNote = createAsyncThunk(
'backend/updateNote',
async (data, thunkAPI) => {
const fileState = thunkAPI.getState().file;
const { dataApi } = fileState;
const { noteId, note } = data;
const ret = await dataApi.UpdateNote(noteId, note);
return ret;
}
);
export const updateEditingNoteRect = createAsyncThunk(
'backend/updateEditingNoteRect',
async (data, thunkAPI) => {
const fileState = thunkAPI.getState().file;
const { dataApi } = fileState;
const n = dataApi.GetNoteById(fileState.editingNid);
n.top = fileState.rect.top;
n.left = fileState.rect.left;
n.width = fileState.rect.width;
n.height = fileState.rect.height;
n.image = null;
n.imageFile = null;
dataApi.UpdateNote(fileState.editingNid, n);
}
);
export const deleteNote = createAsyncThunk(
'backend/deleteNote',
async (data, thunkAPI) => {
const { noteId } = data;
const fileState = thunkAPI.getState().file;
const { dataApi } = fileState;
await dataApi.DeleteNote(noteId);
thunkAPI.dispatch({
type: DELETE_NOTE,
noteId,
});
}
);
export const createNote = createAsyncThunk(
'backend/createNote',
async (data, thunkAPI) => {
const { x, y, pageNum } = data;
const fileState = thunkAPI.getState().file;
const { dataApi } = fileState;
const now = new Date();
const defaultNote = {
fileId: fileState.currentFile.id,
page: pageNum,
width: 100,
height: 100,
top: (y * 100) / fileState.scale,
left: (x * 100) / fileState.scale,
angle: 0,
text: 'new note',
todoDependency: [],
scale: fileState.scale,
image: null,
imageFile: null,
created: now,
lastModified: now,
};
console.log('create default note ', defaultNote);
const newNid = await dataApi.CreateNote(defaultNote);
console.log('new note id is ', newNid);
thunkAPI.dispatch({
type: ADD_NOTE,
newNid,
note: defaultNote,
});
}
);
const backendSlice = createSlice({
name: 'backend',
initialState,
reducers: {},
extraReducers: {
[updateNote.fulfilled]: (state, action) => {
console.log('got update note fulfiled');
},
[createNote.fulfilled]: (state, action) => {
console.log('got create note fulfiled');
},
},
});
export default backendSlice.reducer;
// should put the dataApi here too?
|
import React, { useContext, useState} from 'react';
import Budgetedit from './Budgetedit';
import Viewbudget from './Viewbudget';
import { Context } from '../Context/Context';
const Budget = () => {
const { budget, dispatch } = useContext(Context);
const [editing, setEditing] = useState(false);
const handleEditClick = () => {
setEditing(true);
};
const handleSaveClick = (value) => {
dispatch({
type: 'SET_BUDGET',
payload: value,
});
setEditing(false);
};
return(
<div className="">
{editing ? (
<Budgetedit handleSaveClick = {handleSaveClick} budget = {budget}/>
): (
<Viewbudget handleEditClick= {handleEditClick} budget={budget}/>
)}
</div>
);
};
export default Budget; |
var db = require('../db'),
Q = require('q');
var dal = {
findByEmail: function(email) {
return db.findOne('users', { email: email });
},
create: function(row) {
return db.insert('users', row);
},
updateByEmail: function(email, data) {
var criteria = { email: email };
return db.update('users', criteria, data);
}
};
module.exports = dal;
|
import Ember from 'ember';
export default Ember.Component.extend({
favoritesList: Ember.inject.service(),
inFavoritesList: Ember.computed('favoritesList.items.[]', function(){
return this.get('favoritesList').includes(this.get('cart'));
}),
ratingAverage: Ember.computed('comments.@each.rating', function(){
var total = 0;
(this.get('comments')).forEach(function(comment){
total += comment.get('rating');
});
return Math.round(total/this.get('comments').get('length'));
}),
actions: {
addToFavorites(item) {
this.get('favoritesList').add(item);
},
removeFromFavorites(item) {
this.get('favoritesList').remove(item);
}
}
});
|
/**
* Created by 严俊东 on 2017/3/16.
*/
require('./a');
require.ensure(['./b'], function (require) {
require('./c');
console.log('done!');
});
/*
require.ensure(['./c'], function (require) {
require('./c');
console.log('done!');
});
webpackJsonp([0], {
88: (function (module, exports) {
console.log('***** I AM c *****');
})
});
*/
|
const { v4: uuidv4 } = require("uuid");
const { Meal } = require("../models/meal");
const getAllMeals = async (req, res, next) => {
let meals = [];
try {
meals = res.user.meals;
res.meals = meals;
} catch (err) {
res.meals = meals;
return res.status(500).json({ message: err.message });
}
next();
};
const getMeal = async (req, res, next) => {
let meal = {};
try {
const mealId = req.params.mealId;
meal = res.user.meals.find((meal) => meal.id === mealId);
res.meal = meal;
} catch (err) {
res.meal = meal;
return res.status(500).json({ message: err.message });
}
next();
};
const createMeal = async (req, res, next) => {
try {
let meals = res.meals;
const date = new Date();
meals.push(
new Meal({
id: uuidv4(),
name: req.body.name,
date: date.toISOString(),
foods: [],
})
);
let user = res.user;
user.meals = meals;
await user.save();
} catch (err) {
return res.status(500).json({ message: err.message });
}
next();
};
const updateMeal = async (req, res, next) => {
try {
let meals = res.meals;
const mealId = req.params.mealId;
const targetMeal = meals.find((meal) => meal.id === mealId);
for (const field of Object.entries(req.body)) {
targetMeal[field[0]] = field[1];
}
let user = res.user;
user.meals = meals;
await user.save();
} catch (err) {
return res.status(500).json({ message: err.message });
}
next();
};
const deleteMeal = async (req, res, next) => {
try {
let meals = res.meals;
const mealId = req.params.mealId;
const targettargetMealIndex = meals.findIndex((meal) => meal.id === mealId);
meals.splice(targettargetMealIndex, 1);
let user = res.user;
user.meals = meals;
await user.save();
} catch (err) {
return res.status(500).json({ message: err.message });
}
next();
};
module.exports = {
getAllMeals: getAllMeals,
getMeal: getMeal,
createMeal: createMeal,
updateMeal: updateMeal,
deleteMeal: deleteMeal,
};
|
$(function() {
var info = L.control();
info.onAdd = function (map) {
this._div = L.DomUtil.create('div', 'info');
this._div.innerHTML = '<h3>Adgangsadresser oprettet/nedlagt</h3>'+'<p>' + fra.format('DD.MM.YYYY') + ' - ' + til.format('DD.MM.YYYY') + '</p>' +
"<p>Et eksempel på brug af <a href='http://dawa.aws.dk/replikeringdok'>DAWA's replikerings API</a></p>";
//this.update();
return this._div;
};
var fra= moment(getQueryVariable('fra'),'YYYYMMDD');
if (!fra.isValid()) {
alert('fra=' + getQueryVariable('fra') + ' er ikke en gyldig dato');
return;
}
var til= moment(getQueryVariable('til'),'YYYYMMDD');
if (!til.isValid()) {
alert('til=' + getQueryVariable('til') + ' er ikke en gyldig dato');
return;
}
var tilplus= til.clone()
tilplus.add({days: 1});
if (!fra.isBefore(tilplus)) {
alert('fra dato er senere end til dato');
return;
}
proj4.defs([
[
'EPSG:4326',
'+title=WGS 84 (long/lat) +proj=longlat +ellps=WGS84 +datum=WGS84 +units=degrees'],
[
'EPSG:25832',
'+proj=utm +zone=32 +ellps=GRS80 +units=m +no_defs'
]
]);
var visData= function() {
var options= {};
options.data= {tidspunktfra: fra.utc().toISOString(), tidspunkttil: tilplus.utc().toISOString()};
options.url= encode('https://dawa.aws.dk/replikering/adgangsadresser/haendelser');
if (corssupported()) {
options.dataType= "json";
options.jsonp= false;
}
else {
options.dataType= "jsonp";
}
$.ajax(options)
.then( function ( data ) {
for (var i= 0; i<data.length; i++) {
if (data[i].operation === 'update') continue;
var wgs84= proj4('EPSG:25832','EPSG:4326', {x:data[i].data.etrs89koordinat_øst, y:data[i].data.etrs89koordinat_nord});
var color= 'blue';
switch (data[i].operation) {
case 'insert':
color= 'red';
break;
case 'update':
color= 'yellow';
break;
case 'delete':
color= 'black';
break;
}
var marker= L.circleMarker(L.latLng(wgs84.y, wgs84.x), {color: color, fillColor: color, stroke: false, fillOpacity: 1.0, radius: 3}).addTo(map);//defaultpointstyle);
marker.bindPopup("<a target='_blank' href='https://dawa.aws.dk/replikering/adgangsadresser/haendelser?id="+data[i].data.id+"'>" + data[i].data.id + "'s hændelser </a>");
}
})
.fail(function( jqXHR, textStatus, errorThrown ) {
alert(jqXHR.responseText);
});
}
var ticketurl= '/getticket';
$.ajax({
url: ticketurl
})
.then( function ( ticket ) {
//visOSMKort(ticket);
visKort(ticket);
info.addTo(map);
visData();
})
.fail(function( jqXHR, textStatus, errorThrown ) {
alert('Ingen ticket: ' + jqXHR.statusCode() + ", " + textStatus + ", " + jqXHR.responseText);
});
}); |
$.fn.Sliding=function(obj){
//开始啦
var that=$(this);
//设置全屏
function fullScreen(){
var w=$(window).innerWidth();
var h=$(window).innerHeight();
if(transverse){
if(h>w){
zwidth=h;
state=false;
var z_top=(h-w)/2;
var z_left=0-(h-w)/2;
$(".Sliding-wrap").css({"width":h,"height":w,'position':'absolute','top':z_top,'left':z_left,'overflow':'hidden','transform':'rotate(90deg)'});
}else{
zwidth=w;
state=true;
$(".Sliding-wrap").css({"width":w,"height":h,'position':'absolute','top':0,'left':0,'overflow':'hidden','transform':'rotate(0deg)'});
}
}
that.css({
'transition-duration': '0ms',
'transform':'translate3d('+(-zwidth*zindex)+'px, 0px, 0px)'
});
return;
}
////判断是否支持touch
//var sunscreen="ontouchstart" in document ? true : false;
//if(sunscreen){
// ztrigger={
// start:'touchstart',
// move:'touchmove',
// end:'touchend'
// };
//}else{
// ztrigger={
// start:'mousedown',
// move:'mousemove',
// end:'mouseup'
// };
//}
//指向标
var zindex=0;
//宽度
var zwidth=0;
//子集数量
var slide=that.find(obj.slide);
var zleng=slide.length;
//滑动距离
var zdistance=obj.distance||100;
//边缘阻力
var resistance=obj.resistance||0.3;
//强制横屏
var transverse=obj.transverse;
//横竖屏状态,false=竖屏,true=横屏
var state=false;
var local={
//开始X/Y值
sX:0,
sY:0,
//结束X/Y值
eX:0,
eY:0
}
////手指触摸或鼠标按下
//slide.on(ztrigger.start,function(e){
// if(sunscreen){
// var touch = e.originalEvent.targetTouches[0];
// local.sX=touch.pageX;
// local.sY=touch.pageY;
// }else{
// local.sX=e.pageX;
// local.sY=e.pageY;
// };
//});
//
////手指滑动或鼠标移动
//slide.on(ztrigger.move,function(e){
// e.preventDefault();
// console.log(resistance)
// if(sunscreen){
// var touch = e.originalEvent.targetTouches[0];
// local.eX=touch.pageX-local.sX;
// local.eY=touch.pageY-local.sY;
// }else{
// if(local.sX==0&&local.sY==0)return;
// local.eX=e.pageX-local.sX;
// local.eY=e.pageY-local.sY;
// };
// if(state){
// var move=(-zwidth*zindex)+local.eX;
// }else{
// var move=(-zwidth*zindex)+local.eY;
// };
// if(zindex==0&&move>0){
// move=move*resistance;
// };
// if(zindex==zleng-1&&move<(-zwidth*zindex)){
// if(state){
// move=(-zwidth*zindex)+local.eX*resistance;
// }else{
// move=(-zwidth*zindex)+local.eY*resistance;
// }
// };
// //拖动效果
// that.css({
// 'transition-duration': '0ms',
// 'transform':'translate3d('+move+'px, 0px, 0px)'
// });
//});
//
////手指离开或鼠标松开
//slide.on(ztrigger.end,function(){
//
// if(state){
// var dis=local.eX;
// }else{
// var dis=local.eY;
// }
// if(dis<(-zdistance)){
// if(zindex!=zleng-1){
// zindex+=1;
// }
// }else if(dis>zdistance){
// if(zindex!=0){
// zindex--;
// }
// };
// local.sX=0;local.sY=0;local.eX=0;local.eY=0;
// that.css({
// 'transition-duration': '300ms',
// 'transform':'translate3d('+(-zwidth*zindex)+'px, 0px, 0px)'
// });
//});
//初始化啦
//添加个外框
that.wrap('<div class="Sliding-wrap"></div>');
//初始化全屏设置
fullScreen();
//浏览器大小绑定fullScreen
$(window).resize(fullScreen);
//初始化样式
that.css({
'position':'relative',
'display':'flex',
width:'100%',
height:'100%',
'transition-duration': '0ms',
'transform':'translate3d(0px, 0px, 0px)'
});
slide.css({
width:'100%',
height:'100%',
'flex-shrink':0
});
};
//api 参数
//子元素class slide 必填 例如 slide:'.slide'
//触发翻页的滑动距离 distance 默认100
//是否强制横屏 transverse 默认为false
//首尾边缘阻力系数 resistance '0'为不可拖动,1为没有阻力,默认0.3 |
/*jslint browser: true, undef: true *//*global Ext*/
Ext.define('Slate.cbl.view.teacher.skill.OverviewWindow', {
extend: 'Ext.window.Window',
xtype: 'slate-cbl-teacher-skill-overviewwindow',
requires: [
'Slate.cbl.view.teacher.skill.OverviewWindowController',
'Slate.cbl.model.Skill',
'Ext.form.field.ComboBox',
'Ext.data.ChainedStore'
],
controller: 'slate-cbl-teacher-skill-overviewwindow',
config: {
student: null,
competency: null,
skill: null
},
title: 'Skill Overview',
width: 700,
minWidth: 700,
// constrainHeader: true,
autoScroll: true,
dockedItems: [
{
dock: 'top',
xtype: 'toolbar',
items: [
'Competency:',
{
reference: 'competencyCombo',
flex: 1,
xtype: 'combobox',
store: {
type: 'chained',
source: 'cbl-competencies-loaded'
},
queryMode: 'local',
displayField: 'Descriptor',
valueField: 'Code',
forceSelection: true
},
'Skill:',
{
reference: 'skillCombo',
flex: 1,
xtype: 'combobox',
store: {
model: 'Slate.cbl.model.Skill'
},
queryMode: 'local',
displayField: 'Descriptor',
valueField: 'ID',
forceSelection: true
}
]
},
{
dock: 'top',
xtype: 'toolbar',
items: [
{
flex: 1,
reference: 'studentCombo',
xtype: 'combobox',
emptyText: 'Start typing student\'s name',
store: {
type: 'chained',
source: 'cbl-students-loaded'
},
queryMode: 'local',
displayField: 'FullName',
valueField: 'ID',
forceSelection: true,
autoSelect: true
}
]
},
{
dock: 'bottom',
xtype: 'toolbar',
items: [
{
xtype: 'button',
action: 'override',
text: 'Override'
},
'->',
{
xtype: 'button',
action: 'demonstration-create',
text: 'Log a Demonstration'
}
]
}
],
items: [
{
reference: 'skillStatement',
xtype: 'component',
autoEl: 'p',
padding: '16 32 0'
},
{
reference: 'demonstrationsTable',
xtype: 'component',
minHeight: 200,
tpl: [
'<table class="skill-grid">',
'<thead>',
'<tr class="skill-grid-header-row">',
'<th class="skill-grid-header skill-grid-demo-index"> </th>',
'<th class="skill-grid-header skill-grid-demo-date">Date</th>',
'<th class="skill-grid-header skill-grid-demo-level">Level</th>',
'<th class="skill-grid-header skill-grid-demo-experience">Experience</th>',
'<th class="skill-grid-header skill-grid-demo-context">Context</th>',
'<th class="skill-grid-header skill-grid-demo-task">Performance Task</th>',
// '<th class="skill-grid-header skill-grid-demo-artifact">Artifact</th>',
'</tr>',
'</thead>',
'<tpl if="values && values.length">',
'<tpl for=".">',
'<tr class="skill-grid-demo-row" data-demonstration="{ID}">',
'<td class="skill-grid-demo-data skill-grid-demo-index">{[xindex]}</td>',
'<td class="skill-grid-demo-data skill-grid-demo-date">{Demonstration.Demonstrated:date("M j, Y")}</td>',
'<td class="skill-grid-demo-data skill-grid-demo-level"><div class="cbl-level-{Level}"><tpl if="Level==0">M<tpl else>{Level}</tpl></div></td>',
'<td class="skill-grid-demo-data skill-grid-demo-type">{Demonstration.ExperienceType:htmlEncode}</td>',
'<td class="skill-grid-demo-data skill-grid-demo-context">{Demonstration.Context:htmlEncode}</td>',
'<td class="skill-grid-demo-data skill-grid-demo-task">{Demonstration.PerformanceType:htmlEncode}</td>',
// '<td class="skill-grid-demo-data skill-grid-demo-artifact"><tpl if="Demonstration.ArtifactURL"><a href="{Demonstration.ArtifactURL:htmlEncode}">{Demonstration.ArtifactURL:htmlEncode}</a></tpl></td>',
'</tr>',
'<tr class="skill-grid-demo-detail-row" data-demonstration="{ID}">',
'<td class="skill-grid-demo-detail-data" colspan="6">',
'<div class="skill-grid-demo-detail-ct">',
'<tpl if="Demonstration.ArtifactURL">',
'<div class="skill-grid-demo-artifact">',
'<strong>Artifact: </strong>',
'<a href="{Demonstration.ArtifactURL:htmlEncode}" target="_blank">{Demonstration.ArtifactURL:htmlEncode}</a>',
'</div>',
'</tpl>',
'<tpl if="Demonstration.Comments">',
'<div class="skill-grid-demo-comments">',
'<strong>Comments: </strong>',
'{[this.escapeAndNewline(values.Demonstration.Comments)]}',
'</div>',
'</tpl>',
'<div class="skill-grid-demo-meta">',
'Demonstration #{Demonstration.ID} · ',
'<tpl for="Demonstration.Creator"><a href="/people/{Username}">{FirstName} {LastName}</a></tpl> · ',
'{[fm.date(new Date(values.Demonstration.Created * 1000), "F j, Y, g:i a")]} · ',
'<a href="#demonstration-edit" data-demonstration="{Demonstration.ID}">Edit</a>',
'</div>',
'</div>',
'</td>',
'</tr>',
'</tpl>',
'<tpl else>',
'<tr class="skill-grid-emptytext-row">',
'<td class="skill-grid-emptytext-cell" colspan="6">No demonstrations are logged yet for this skill</td>',
'</tr>',
'</tpl>',
'</table>',
{
escapeAndNewline: function(s) {
s = Ext.util.Format.htmlEncode(s);
return Ext.util.Format.nl2br(s);
}
}
]
}
],
listeners: {
scope: 'this',
click: {
fn: 'onGridClick',
element: 'el',
delegate: '.skill-grid-demo-row, a[href="#demonstration-edit"]'
}
},
applyStudent: function(student) {
return student ? Ext.getStore('cbl-students-loaded').getById(student) : null;
},
applyCompetency: function(competency) {
return competency ? Ext.getStore('cbl-competencies-loaded').getById(competency) : null;
},
applySkill: function(skill) {
if (Ext.isString(skill)) {
skill = parseInt(skill, 10);
}
return skill ? skill : null;
},
onGridClick: function(ev, t) {
var me = this,
targetEl;
if (targetEl = ev.getTarget('.skill-grid-demo-row', me.el, true)) {
me.fireEvent('demorowclick', me, ev, targetEl);
} else if (targetEl = ev.getTarget('a[href="#demonstration-edit"]', me.el, true)) {
ev.stopEvent();
me.fireEvent('editdemonstrationclick', me, parseInt(targetEl.getAttribute('data-demonstration'), 10), ev, targetEl);
}
}
}); |
'use strict';
let express = require('express');
let router = express.Router();
let stripe = require("stripe")(process.env.STRIPE_SECRET);
let User = require('../models/user');
function updateUser(userId, cart) {
let bookIds = cart.map((book) => book._id);
console.log(bookIds);
User.findOneAndUpdate({_id: userId},
{ $pullAll: { cart: bookIds } },
{new: true}, (err, doc) => {
if (err) {
console.err('Filed to update user', userId, err);
}
});
}
router.post('/', function(req, res) {
let tokenObj = req.body.token;
let cart = req.body.cart;
if (!tokenObj || !cart) {
res.status(400).send('Error');
return;
}
let total = cart.reduce((total, book) => total + book.price, 0);
console.log('total: ', total);
let charge = stripe.charges.create({
amount: Math.round(total * 100),
currency: "USD",
source: tokenObj.id,
description: 'Books order'
}, function(err, charge) {
if (err) {
console.log('payment failed:', err);
res.status(400).send('Error');
}
else {
updateUser(req.userId, cart);
res.status(200).send('OK');
}
});
});
module.exports = router;
|
var cart = new Map();
var addToCart = function (product) {
cart.set(product.id, product.name);
};
var submitCart = function (obj) {
var keys = Array.from( cart.keys() );
console.log(keys)
var json = JSON.stringify({'listOfProducts': keys});
$.ajax({
url: api_endpoint + "/orders",
type:"POST",
data:json,
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){
alert("Order is send")
cart.clear();
location.reload();
}
})
};
var getCartProducts = function () {
cart.forEach(function (value, key, mapObj) {
$('cart').append("Product name: ").append(value)
.append("<br>");
});
$("#sendOrderButton").click(submitCart);
};
|
'use strict';
function Welcome(props) {
return React.createElement(
"h1",
null,
"Hello, ",
props.name
);
}
function App() {
return React.createElement(
"div",
null,
React.createElement(Welcome, { name: "Betsy" }),
React.createElement(Welcome, { name: "Tanner" }),
React.createElement(Welcome, { name: "Pets" })
);
}
ReactDOM.render(React.createElement(App, null), document.getElementById('props-example')); |
var searchData=
[
['insertword',['InsertWord',['../classTrie.html#a960ae86ba5e1b78eac1701156e0533e3',1,'Trie']]]
];
|
'use strict';
class Warrior {
constructor(name, health, power) {
this._name = name;
this._health = health || 100;
this._power = power || Math.round(Math.random() * 50);
}
get health() {
return this._health;
}
set health(newHealth) {
this._health = newHealth;
}
get power() {
return this._power;
}
set power(newPower) {
this._power = newPower;
}
} |
import simplify from "../funcs/simplify.js";
let cache = {};
function load(type, i = 0, callback) {
let storage;
if (type == "true") {
storage = this.t;
} else if (type == "false") {
storage = this.f;
}
let asset = true;
let assetPath = "./sets/" + type + "/" + i + ".png";
if (cache[assetPath]) {
let img = cache[assetPath];
storage.push(img);
i++;
load.apply(this, [type, i, callback]);
} else {
asset = loadImage(
assetPath,
img => {
if (img.type != "error") {
cache[assetPath] = img;
storage.push(img);
i++;
load.apply(this, [type, i, callback]);
} else {
if (callback) callback();
}
}
);
}
}
class ImageDataSet {
constructor(callback, settings = {}) {
this.settings = settings;
this.t = [];
this.f = [];
let state = 0;
load.apply(this, [
"true",
0,
() => {
state++;
if (state == 2) {
if (callback) callback(this);
}
}
]);
load.apply(this, [
"false",
0,
() => {
state++;
if (state == 2) {
if (callback) callback(this);
}
}
]);
}
}
export default ImageDataSet;
|
require('normalize.css/normalize.css');
require('styles/App.css');
import React from 'react';
import ReactDOM from 'react-dom';
import ImgFigure from './ImgFigure';
import ControllerUnit from './ControllerUnit';
//获取图片相关数据
let imageDatas = require('json!../data/imageDatas.json');
//利用自执行函数,将图片名信息转成图片URL路径信息
imageDatas = (function genImageURL(imageDataArr){
for (var i = 0,j = imageDataArr.length; i < j; i++) {
var singleImageData = imageDataArr[i];
singleImageData.imageURL = require('../images/' + singleImageData.fileName);
singleImageData[i] = singleImageData;
}
return imageDataArr;
})(imageDatas);
function getRangeRandom(low, high){
return Math.ceil(Math.random() * (high - low) + low);
}
/*
* 获取0-30度任意一个度数正负值
*/
function get30DegRandom(){
return (Math.random() > 0.5? '' : '-') + Math.ceil(Math.random()*30);
}
class AppComponent extends React.Component {
constructor(props) {
super(props);
this.Constant = {
centerPos:{
left:0,
top:0
},
hPosRange : {//水平方向取值范围
leftSecX:[0,0],
rightSecX:[0,0],
y:[0,0]
},
vPosRange:{//垂直方向取值范围
x:[0,0],
topY:[0,0]
}
}
// 初始化state,图片的left、top位置
this.state = {
imgsArrangeArr: [
// {
// pos:{
// left: 0,
// top: 0
// },
// rotate: 0, // 图片的旋转角度
// isInverse: false // 设置图片是否翻转的状态
// isCenter: false // 默认图片不居中
// }
]
}
}
//组件加载后为每张图片初始化范围
componentDidMount(){
//拿到舞台大小
var stageDOM = ReactDOM.findDOMNode(this.refs.stage),
//scrollWidth是对象的实际宽度,不包含滚动条等边线宽度,会随对象中内容可视区域超过边线内容而扩大;
//clientWidth是对象内容的可视区域内容,不包含滚动条等边线,会随对象显示大小改变
//offsetWidth是对象整体实际宽度,包含滚动条等边线,会随对象显示大小变化而改变
stageW = stageDOM.scrollWidth,
stageH = stageDOM.scrollHeight,
halfStageW = Math.ceil( stageW / 2),
halfStageH = Math.ceil( stageH / 2);
//拿到一个imgFigure的大小
var imgFigureDOM = ReactDOM.findDOMNode(this.refs.imgFigure0),
imgW = imgFigureDOM.scrollWidth,
imgH = imgFigureDOM.scrollHeight,
halfImgW = Math.ceil( imgW / 2),
halfImgH = Math.ceil( imgH / 2);
//计算中心图片的位置点
this.Constant.centerPos = {
left : halfStageW - halfImgW,
top : halfStageH - halfImgH
}
//计算左侧右侧区域范围
this.Constant.hPosRange.leftSecX[0] = - halfImgW;
this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW*3;
this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW;
this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW;
this.Constant.hPosRange.y[0] = -halfImgH;
this.Constant.hPosRange.y[1] = stageH - halfImgH;
//计算上侧区域范围
this.Constant.vPosRange.topY[0] = -halfImgH;
this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3;
this.Constant.vPosRange.x[0] = halfStageW - imgW;
this.Constant.vPosRange.x[1] = halfStageW;
this.rearrange(0);
}
/*
* 翻转图片
@ param index 输入当前被执行inverse操作执行的图片对应的图片数组信息的index值
@ return {Function} 这是一个闭包函数,其内return一个待被执行的函数
*/
inverse(index){
return function(){
var imgsArrangeArr = this.state.imgsArrangeArr;
imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse;
this.setState({
imgsArrangeArr: imgsArrangeArr
});
}.bind(this);
}
/*
* 利用rearrange函数居中相应index的图片
*/
center(index){
return function(){
this.rearrange(index);
}.bind(this);
}
//重新布局所有图片
rearrange (centerIndex) {
var imgsArrangeArr = this.state.imgsArrangeArr,
Constant = this.Constant,
centerPos = Constant.centerPos,
hPosRange = Constant.hPosRange,
vPosRange = Constant.vPosRange,
hPosRangeLeftSecX = hPosRange.leftSecX,
hPosRangeRightSecX = hPosRange.rightSecX,
hPosRangeY = hPosRange.y,
vPosRangeTopY = vPosRange.topY,
vPosRangeX = vPosRange.x,
imgsArrangeTopArr = [],
topImgNum = Math.floor((Math.random()*2)),//取一个或不取
topImgSpliceIndex = 0,
imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex,1);
//首先居中centerIndex图片,居中的图片不需要旋转
imgsArrangeCenterArr[0] = {
pos : centerPos,
rotate : 0,
isCenter:true
};
//取出要布局上侧的图片的状态信息
topImgSpliceIndex = Math.ceil(Math.random() * (imgsArrangeArr.length - topImgNum));
imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex,topImgNum);
//布局位于上侧的图片
imgsArrangeTopArr.forEach(function(value,index){
imgsArrangeTopArr[index] = {
pos:{
top:getRangeRandom(vPosRangeTopY[0],vPosRangeTopY[1]),
left:getRangeRandom(vPosRangeX[0],vPosRangeX[1])
},
rotate:get30DegRandom(),
isCenter:false
};
});
//布局两侧图片
for (var i = 0, j = imgsArrangeArr.length, k = j/2; i < j; i++) {
var hPosRangeLOrRX = null;
//前半部分布局左边,后半部分布局右边
if(i < k){
hPosRangeLOrRX = hPosRangeLeftSecX;
} else {
hPosRangeLOrRX = hPosRangeRightSecX;
}
imgsArrangeArr[i] = {
pos : {
top: getRangeRandom(hPosRangeY[0],hPosRangeY[1]),
left:getRangeRandom(hPosRangeLOrRX[0],hPosRangeLOrRX[1])
},
rotate:get30DegRandom(),
isCenter:false
};
}
if(imgsArrangeTopArr && imgsArrangeTopArr[0]){
imgsArrangeArr.splice(topImgSpliceIndex,0,imgsArrangeTopArr[0]);
}
imgsArrangeArr.splice(centerIndex,0,imgsArrangeCenterArr[0]);
this.setState({
imgsArrangeArr: imgsArrangeArr
});
}
render() {
var controllerUnits = [],
imgFigures = [];
imageDatas.forEach(function(value,index){
if(!this.state.imgsArrangeArr[index]){
this.state.imgsArrangeArr[index] = {
pos:{
left:0,
top :0
},
rotate : 0,
isInverse : false,
isCenter:false
}
}
//加入key帮助react提升性能
imgFigures.push(
<ImgFigure
key={index}
data={value}
ref={'imgFigure' + index}
arrange={this.state.imgsArrangeArr[index]}
inverse={this.inverse(index)}
center={this.center(index)}
/>
);
controllerUnits.push(
<ControllerUnit
key={index}
arrange={this.state.imgsArrangeArr[index]}
inverse={this.inverse(index)}
center={this.center(index)}
/>
);
}.bind(this));
return (
<section className="stage" ref="stage">
<section className='img-sec'>
{imgFigures}
</section>
<nav className='controller-nav'>
{controllerUnits}
</nav>
</section>
);
}
}
AppComponent.defaultProps = {
};
export default AppComponent;
|
/**
* @module cp
*/
var cp = cp || {};
/**
* @class Test
*/
cp.Test = {
/**
* @method fight
*/
fight : function (
)
{
},
/**
* @method print
*/
print : function (
)
{
},
/**
* @method getCount
* @return {int}
*/
getCount : function (
)
{
return 0;
},
/**
* @method getArrayLength
* @param {Array} arg0
* @return {int}
*/
getArrayLength : function (
array
)
{
return 0;
},
/**
* @method staticTestFunc
*/
staticTestFunc : function (
)
{
},
/**
* @method Test
* @constructor
*/
Test : function (
)
{
},
};
|
// Initialize echart object, based on the prepared DOM.
var myChart = echarts.init(document.getElementById('main'));
// var myChart = echarts.init($('#main').get(0));
// Costumize the options and data of the chart.
var option = {};
// Render the chart on page, using the former data and options.
myChart.setOption(option); |
import clone from 'clone';
import types from '../actionTypes';
import { requestCourses, requestTemplates, createTemplate, getCourseById, createSection, removeSection } from '../../services/courseService';
import { broadcast } from '../broadcastActions/broadcastActions';
import { loading, loadingSuccess } from '../loaderActions/loaderActions';
export function updateCourses(courses, settings = { includeTemplates: true }) {
let newCourses = clone(courses);
if (settings.includeTemplates === false) {
newCourses = courses.filter(course => course.template !== true);
}
return {
type: types.UPDATE_COURSES,
courses: newCourses,
};
}
export function updateTemplates(templates) {
return {
type: types.UPDATE_TEMPLATES,
templates,
};
}
export function getTemplates() {
return (dispatch) => {
return requestTemplates()
.then(response => response.json())
.then(({ course }) => {
dispatch(updateTemplates(course));
})
.catch((error) => {
throw (error);
});
};
}
export function getCourses() {
return (dispatch) => {
return requestCourses()
.then(response => response.json())
.then(({ course }) => {
dispatch(updateCourses(course, { includeTemplates: false }));
})
.catch((error) => {
throw (error);
});
};
}
export function createTemplateThunk(template) {
return (dispatch) => {
dispatch(loading());
return createTemplate(template)
.then(response => response.json())
.then(() => {
dispatch(loadingSuccess());
dispatch(getTemplates());
dispatch(broadcast('Template successfully created.', 'success'));
});
};
}
export function getCourse(id) {
return (dispatch) => {
return getCourseById(id)
.then(response => response.json())
.then((data) => {
dispatch(updateCourses(data.course));
});
};
}
export function createNewSection(section, id) {
return (dispatch) => {
return createSection(section, id)
.then(response => response.json())
.then((data) => {
dispatch(updateCourses(data.course));
dispatch(loadingSuccess());
dispatch(broadcast('User successfully created.', 'success'));
});
};
}
export function deleteSection(courseId, sectionId) {
return (dispatch) => {
dispatch(loading());
return removeSection(courseId, sectionId)
.then(response => response.json())
.then(() => {
dispatch(loadingSuccess());
dispatch(broadcast('User successfully deleted.', 'success'));
});
};
}
|
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const envConfigs = require('../config/config');
const userDef = require('./user');
const habitDef = require('./habit');
const completedTaskDef = require('./completedTask');
const completedGoalDef = require('./completedGoal');
const env = process.env.NODE_ENV || 'development';
const config = envConfigs[env];
const db = {};
const sequelize = new Sequelize(config.url, config);
db.sequelize = sequelize;
db.Sequelize = Sequelize;
const User = sequelize.define('User', userDef);
const Habit = sequelize.define('Habit', habitDef);
const CompletedTask = sequelize.define('CompletedTask', completedTaskDef);
const CompletedGoal = sequelize.define('CompletedGoal', completedGoalDef);
Habit.hasMany(CompletedTask, {
onDelete: 'CASCADE'
});
Habit.hasMany(CompletedGoal, {
onDelete: 'CASCADE'
});
CompletedTask.belongsTo(Habit);
CompletedGoal.belongsTo(Habit);
User.hasMany(Habit, {
onDelete: 'CASCADE'
});
Habit.belongsTo(User);
//sequelize.sync({ alter: true })
db.Habit = Habit;
db.CompletedTask = CompletedTask;
db.CompletedGoal = CompletedGoal;
db.User = User;
module.exports = db; |
import React, { Component } from "react";
import { Menu } from "semantic-ui-react";
import { Link } from "react-router-dom";
import "./styles.css";
export default class header extends Component {
// state variable
state = { activeItem: "home" };
handleItemClick = (e, { name }) => this.setState({ activeItem: name });
render() {
const { activeItem } = this.state;
return (
<div className="header">
<Menu inverted>
<Menu.Menu position="right">
{/* home */}
<Menu.Item
name="home"
active={activeItem === "home"}
onClick={this.handleItemClick}
>
<Link to="/" style={{ textDecoration: "none" }}>
Home
</Link>
</Menu.Item>
{/* teams */}
<Menu.Item
name="team"
active={activeItem === "team"}
onClick={this.handleItemClick}
>
<Link to="/teams" style={{ textDecoration: "none" }}>
Teams
</Link>
</Menu.Item>
{/* players */}
<Menu.Item
name="player"
active={activeItem === "player"}
onClick={this.handleItemClick}
>
<Link to="/players">Players</Link>
</Menu.Item>
{/* Matches */}
<Menu.Item
name="match"
active={activeItem === "match"}
onClick={this.handleItemClick}
>
<Link to="/matchs">Matches</Link>
</Menu.Item>
</Menu.Menu>
</Menu>
</div>
);
}
}
|
const express = require("express");
const app = express();
const server = require("http").createServer(app);
const PORT = 8000;
const io = require('socket.io')(server);
const cors = require("cors");
const {sequelize, Sensing1} = require("./models");
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
sequelize.sync({ force: false })
.then(() => console.log("db 접속 성공"))
.catch((err) => console.log(err));
app.get("/", (req, res) => {
return res.json({connection: "this server is running "});
});
server.listen(PORT, () => console.log(`this server listening on ${PORT}`));
io.on("connection", function(socket){
let offset = 0;
setInterval(async() => {
try{
// const dataLength = await Sensing1.findAndCountAll({
// arrtibutes: [sequelize.fn("COUNT", sequelize.col("id"))],
// });
const data = await Sensing1.findAll({
limit: 24,
//offset: offset,
order: [
['time', 'DESC'],
],
});
offset += 24;
let array = data.reduce((acc, cur) => {
acc.push({time: cur.dataValues.time, num1: cur.dataValues.num1,
num2: cur.dataValues.num2});
return acc;
},[]);
array.reverse();
socket.emit("chat", array);
// if(offset > dataLength.count - 24){
// offset = 0;
// }
}
catch(error){
console.log(error)
}
}, 1000)
socket.on("chat", function(data){
console.log(`message from Client : ${data}`);
})
}) |
module.exports = {
daysUntilStale: 60,
daysUntilClose: 7,
exemptLabels: ['pinned', 'security'],
staleLabel: 'wontfix',
perform: !process.env.DRY_RUN,
markComment: 'This issue has been automatically marked as stale because ' +
'it has not had recent activity. It will be closed if no further ' +
'activity occurs. Thank you for your contributions.',
unmarkComment: false,
closeComment: false
}
|
$('#tt').tabs({
onSelect:function(title,index){
switch (index){
//console.log(index);
case 1:
$('#pn_dettagliomagaz').panel('setTitle','Dettaglio Magazzino');
$('#orainmagazzino').panel('setTitle','Ora in Magazzino');
$('#grid_prodotti').datagrid('reload');
$('#grid_prelievomagazzino').datagrid('reload',{ id: 0 });
$('#grid_prodottoinmagazzino').datagrid('reload',{ id: 0 });
$('#grid_venditeaiclienti').datagrid('reload',{ id: 0 });
break;
case 4:
$('#grid_statistichegestione').datagrid('reload');
$('#grid_statisticheanno').datagrid('reload');
$('#grid_statistichemese').datagrid('reload');
$('#grid_statisticheclientibad').datagrid('reload');
$('#grid_statisticheclientitop').datagrid('reload');
break;
case 5:
if (typeof oggi_inv == 'function'){
oggi_inv();
}
break;
}
}
});
|
let express = require('express');
//路由的实例
let router = express.Router();
let util = require('../util');
let auth = require('../middleWare/auth');
let models = require('../models');
/* GET users listing. 注册*/
router.get('/reg',auth.checkNotLogin, function(req, res, next) {
res.render('./user/reg',{title: '注册'});
});
router.post('/reg',auth.checkNotLogin,function(req,res,next){
//保存对象有两种方法,model.create;entity.save
let user = req.body;
if (user.password != user.repassword) {
req.flash('error','用户注册失败');
res.redirect('back');
} else {
req.body.password = util.md5(req.body.password);
//增加一个头像图片
req.body.avator = "https://secure.gravatar.com/avatar/"+util.md5(req.body.email)+"?s=48";
console.log(req.body,'req.body===');
models.User.create(req.body, function (err,doc) {
req.flash('success','用户注册成功');
res.redirect('/users/login');
});
}
});
router.get('/login',auth.checkNotLogin, function(req, res, next) {
res.render('./user/login',{title: '登陆'});
});
router.post('/login', auth.checkNotLogin,function(req,res,next){
req.body.password = util.md5(req.body.password);
models.User.findOne({username:req.body.username,password:req.body.password},function(err,doc){
if (err) {
req.flash('error','用户登录失败');
res.redirect('back');
} else {
if (doc) {//如果有值表示找到了对应的用户,表示登陆成功了
//如果登陆成功后,把查询到的user用户赋给session属性
req.flash('success','用户登陆成功');
req.session.user = doc;
res.redirect('/');
} else {//找不到表示登陆失败
req.flash('error','用户登录失败');
res.redirect('back')
}
}
});
});
router.get('/logout',auth.checkLogin, function(req, res, next) {
req.session.user = null;
req.flash('success','用户退出成功');
res.redirect('/');
});
module.exports = router;
|
var searchData=
[
['y',['Y',['../struct_date_time.html#ad39449618b2a15128e32766a208753cf',1,'DateTime']]],
['yy0',['yy0',['../union_y_y_m_i_n_o_r_t_y_p_e.html#a827d6a1bc7ac8df062b3f419db3f50ac',1,'YYMINORTYPE']]],
['yy122',['yy122',['../union_y_y_m_i_n_o_r_t_y_p_e.html#a42df0f01a945b0edd4c2d444383271c6',1,'YYMINORTYPE']]],
['yy159',['yy159',['../union_y_y_m_i_n_o_r_t_y_p_e.html#a9f223bea5f91f81654ec73b44da4e9e2',1,'YYMINORTYPE']]],
['yy180',['yy180',['../union_y_y_m_i_n_o_r_t_y_p_e.html#a85f445ea34e555f9fe590d7bf009ebe5',1,'YYMINORTYPE']]],
['yy207',['yy207',['../union_y_y_m_i_n_o_r_t_y_p_e.html#a16941245c1164b46217b91c7b4f56124',1,'YYMINORTYPE']]],
['yy258',['yy258',['../union_y_y_m_i_n_o_r_t_y_p_e.html#a7550aa923cb83eba5ea5ca4d2c425f36',1,'YYMINORTYPE']]],
['yy318',['yy318',['../union_y_y_m_i_n_o_r_t_y_p_e.html#a981c25f9db81ef6dd0b1a09ae1eace9b',1,'YYMINORTYPE']]],
['yy327',['yy327',['../union_y_y_m_i_n_o_r_t_y_p_e.html#a0cf3fb7c57ebedcfdfc0271524c22465',1,'YYMINORTYPE']]],
['yy342',['yy342',['../union_y_y_m_i_n_o_r_t_y_p_e.html#a3adf1325462a9fecaa520711ac543eb2',1,'YYMINORTYPE']]],
['yy347',['yy347',['../union_y_y_m_i_n_o_r_t_y_p_e.html#ac7e3d77993d8c117ecf7274c935d6ce1',1,'YYMINORTYPE']]],
['yy392',['yy392',['../union_y_y_m_i_n_o_r_t_y_p_e.html#a022e706c47bf19b5baedc3bd4f448784',1,'YYMINORTYPE']]],
['yy410',['yy410',['../union_y_y_m_i_n_o_r_t_y_p_e.html#aafb633841243d9820fc85ebdac0323ee',1,'YYMINORTYPE']]],
['yy442',['yy442',['../union_y_y_m_i_n_o_r_t_y_p_e.html#a60690037786cf4178493b8463f7c76d2',1,'YYMINORTYPE']]],
['yy487',['yy487',['../union_y_y_m_i_n_o_r_t_y_p_e.html#a565d289fa56f79ebd699d4e7decea365',1,'YYMINORTYPE']]],
['yy64',['yy64',['../union_y_y_m_i_n_o_r_t_y_p_e.html#aeb6b77e9a54a740178f47c10d2263f39',1,'YYMINORTYPE']]],
['yyerrcnt',['yyerrcnt',['../structyy_parser.html#ac0350933aa515a3a756dfa742d04ee59',1,'yyParser']]],
['yyidx',['yyidx',['../structyy_parser.html#a19abcf4780515fd2debd1ce7a2e29f95',1,'yyParser']]],
['yyinit',['yyinit',['../union_y_y_m_i_n_o_r_t_y_p_e.html#a6cec97309f473b42b70a9738d7cbd5ba',1,'YYMINORTYPE']]],
['yystack',['yystack',['../structyy_parser.html#ae8bc1531d6ae56020a7ee33a40783672',1,'yyParser']]]
];
|
import React, { useContext } from 'react';
import { Switch, Route } from 'react-router-dom';
import BillsContext from '../context/bills-context';
import Home from './containers/Home.jsx';
import SignUp from './SignUp.jsx'
import Bills from './containers/Bills.jsx';
import UserInfo from './containers/UserInfo.jsx'
import SignIn from "./SignIn.jsx";
import Header from './containers/Header.jsx'
const Main = () => {
const { state } = useContext(BillsContext);
return (
<Switch>
{!state.loggedIn ? (
<>
<Route path="/"
component={SignIn}
/>
<Route path="/signup"
component={SignUp}
/>
</>
) : (
<>
<Header />
<Switch>
<Route exact path="/" component={Home} />
<Route path="/signup" component={SignUp} />
<Route path="/bills" component={Bills} />
<Route path="/userinfo" component={UserInfo} />
</Switch>
</>
)}
</Switch>
);
}
export default Main; |
import React, { useState } from "react";
import {
Collapse,
Navbar,
NavbarToggler,
NavbarBrand,
Nav,
NavItem,
NavLink,
Container,
Dropdown,
DropdownItem,
DropdownToggle,
DropdownMenu
} from "reactstrap";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
function Navigation(props) {
const [isOpen, toggleOpen] = useState(false);
const [dropdownOpen, toggleDropdownOpen] = useState(false);
const navLinks = [
{ name: "Upload Photos", link: "/UploadView" },
{ name: "View Photos", link: "/Categories" },
{ name: "Profile", link: "/ProfileView" }
];
function getDropDown() {
if (props.authed) {
return (
<Dropdown
navbar="true"
isOpen={dropdownOpen}
toggle={() => toggleDropdownOpen(!dropdownOpen)}
>
<DropdownToggle navbar="true" caret>
{props.user.userInfo.email}
</DropdownToggle>
<DropdownMenu dark="true">
<DropdownItem>
<NavLink
onClick={() => props.handleLogout()}
href="/login">
Log out
</NavLink>
</DropdownItem>
</DropdownMenu>
</Dropdown>
);
}
}
return (
<Navbar color="dark" dark={true} expand="sm">
<Container>
<NavbarBrand href="/">Photo Share</NavbarBrand>
<Collapse isOpen={isOpen} navbar={true}>
<Nav className="mr-auto" navbar>
{props.authed && navLinks.map((option, index) => {
return (
<NavItem key={index}>
<NavLink tag={Link} to={option.link}>{option.name}</NavLink>
</NavItem>
);
})}
</Nav>
<Nav className="ml-auto" nav="true">
{getDropDown()}
</Nav>
</Collapse>
<NavbarToggler onClick={() => toggleOpen(!isOpen)} />
</Container>
</Navbar>
);
}
const mapStateToProps = state => ({
user: state.user
});
export default connect(mapStateToProps)(Navigation);
|
export const addProdcutToCartHelper = (product) => {
if(!JSON.parse(localStorage.getItem('cart'))){
localStorage.setItem('cart', JSON.stringify([]));
}
const cart = JSON.parse(localStorage.getItem('cart'));
const updatedCart = [...cart, {...product, quantity: 1}];
localStorage.setItem('cart', JSON.stringify(updatedCart));
return updatedCart;
}
export const decreaseProductQuantityHelper = (id) => {
const cart = JSON.parse(localStorage.getItem('cart'));
const updatedCart = cart.map(product => product.id === id ? {
...product,
quantity: product.quantity-1
} : product)
localStorage.setItem('cart', JSON.stringify(updatedCart));
return updatedCart;
}
export const increaseProductQuantityHelper = (id) => {
const cart = JSON.parse(localStorage.getItem('cart'));
const updatedCart = cart.map(product => product.id === id ? {
...product,
quantity: product.quantity+1
} : product)
localStorage.setItem('cart', JSON.stringify(updatedCart));
return updatedCart;
}
export const removeProductFromCartHelper = (id) => {
const cart = JSON.parse(localStorage.getItem('cart'));
const updatedCart = cart.filter(item => item.id !== id);
localStorage.setItem('cart', JSON.stringify(updatedCart));
return updatedCart;
}
|
$(function() {
$('#login-form-link').click(function(e) {
$("#login-form").delay(100).fadeIn(100);
$("#register-form").fadeOut(100);
$('#register-form-link').removeClass('active');
$(this).addClass('active');
e.preventDefault();
});
$('#register-form-link').click(function(e) {
$("#register-form").delay(100).fadeIn(100);
$("#login-form").fadeOut(100);
$('#login-form-link').removeClass('active');
$(this).addClass('active');
e.preventDefault();
});
});
function dosubmit(){
document.forms["register-form"].action = "offer.html?"
window.event.returnValue = true;
}
function dosubmitLog(){
document.forms["login-form"].action = "offer.html?"
window.event.returnValue = true;
}
// + document.forms["unos"]["ime"].value + document.forms["unos"]["prezime"].value + document.forms["unos"]["member"].checked + " " + document.forms["unos"]["type"].value; |
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import activate from '@/components/activate'
import findkey1 from '@/components/findkey1'
import findkey2 from '@/components/findkey2'
import HomePage from '@/components/HomePage'
import CoursePage from '@/components/Courses/CoursePage'
import Seminaring from '@/components/Courses/Seminaring/Seminaring'
import download from '@/components/Courses/Seminaring/download'
import present from '@/components/Courses/Seminaring/present'
import BeforeSeminar from '@/components/Courses/BeforeSeminar/BeforeSeminar'
import signInfo from '@/components/Courses/BeforeSeminar/signInfo'
import AfterSign from '@/components/Courses/BeforeSeminar/AfterSign'
import ChangeSign from '@/components/Courses/BeforeSeminar/ChangeSign'
import ChangeSign2 from '@/components/Courses/BeforeSeminar/ChangeSign2'
import CheckGrade from '@/components/Courses/BeforeSeminar/CheckGrade'
import TotalSeminars from '@/components/Courses/TotalSeminars'
import SeminarInfo from '@/components/Courses/AfterSeminar/SeminarInfo'
import CheckInfo from '@/components/Courses/AfterSeminar/CheckInfo'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/activate',
name: 'activate',
component: activate
},
{
path: '/findkey1',
name: 'findkey1',
component: findkey1
},
{
path: '/findkey2',
name: 'findkey2',
component: findkey2
},
{
path: '/HomePage',
name: 'HomePage',
component: HomePage
},
{
path: '/Courses/CoursePage',
name: 'CoursePage',
component: CoursePage
},
{
path: '/Courses/Seminaring/Seminaring',
name: 'Seminaring',
component: Seminaring
},
{
path: '/Courses/BeforeSeminar/BeforeSeminar',
name: 'BeforeSeminar',
component: BeforeSeminar
},
{
path: '/Courses/Seminaring/download',
name: 'download',
component: download
},
{
path: '/Courses/Seminaring/present',
name: 'present',
component: present
},
{
path: '/Courses/BeforeSeminar/signInfo',
name: 'signInfo',
component: signInfo
},
{
path: '/Courses/BeforeSeminar/AfterSign',
name: 'AfterSign',
component: AfterSign
},
{
path: '/Courses/BeforeSeminar/ChangeSign',
name: 'ChangeSign',
component: ChangeSign
},
{
path: '/Courses/BeforeSeminar/ChangeSign2',
name: 'ChangeSign2',
component: ChangeSign2
},
{
path: '/Courses/BeforeSeminar/CheckGrade',
name: 'CheckGrade',
component: CheckGrade
},
{
path: '/Courses/TotalSeminars',
name: 'TotalSeminars',
component: TotalSeminars
},
{
path: '/Courses/AfterSeminar/SeminarInfo',
name: 'SeminarInfo',
component: SeminarInfo
},
{
path: '/Courses/AfterSeminar/CheckInfo',
name: 'CheckInfo',
component: CheckInfo
}
]
})
|
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import TeamList from './TeamList.js';
import AddPlayer from './AddPlayer.js';
class App extends Component {
constructor(){
super();
this.state = {
team1: ['jack', 'peter', 'Loren'],
team2: ['steven', 'josh', 'paul', 'Barry'],
selectedTeam: 1,
userInput: ''
}
this.addPlayer = this.addPlayer.bind(this);
this.updateUserInput = this.updateUserInput.bind(this);
}
updateUserInput(val){
this.setState({
userInput: val
})
}
addPlayer(){
var newPlayer = this.state.userInput;
var {selectedTeam} = this.state;
if (selectedTeam === 1){
var newRoster = this.state.team1.slice();
newRoster.push(newPlayer);
this.setState({
team1: newRoster
})
}
}
render() {
return (
<div className="App">
<div className="buttons">
<button>T1</button>
<button>T2</button>
</div>
<AddPlayer add={ this.addPlayer }
updateInput={ this.updateUserInput }/>
<div className='lists'>
<TeamList teamRoster={ this.state.team1 } />
<TeamList teamRoster={ this.state.team2 } idName='bob'/>
</div>
</div>
);
}
}
export default App;
|
// components/warm/warm.js
import {
relateapp
} from '../../api/request.js'
import {
setStoragePromisify,
showLoadingPromisify,
} from '../../api/promisify.js'
import regeneratorRuntime from '../../api/regeneratorRuntime.js'
const app = getApp();
Component({
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
closeLogin: function() {
this.triggerEvent('bindWarm', 'close')
},
bindSubmit: async function(e) {
let {
formId
} = e.detail;
formId && app.data.formID.push(formId);
let phone = wx.getStorageSync('phone');
showLoadingPromisify();
let result = await relateapp({
type: 1,
save_type: parseInt(e.detail.value.saveType),
phone: phone
})
if (result.statusCode === 200) {
let {
token,
id
} = result.data;
setStoragePromisify({ Token: token, userId:id})
}
this.triggerEvent('bindWarm', result.statusCode)
}
}
}) |
import { combineReducers } from 'redux';
import sidebar from './sidebarReducer';
import confirmModal from './confirmModalReducer';
import flash from './flashReducer';
import projects from './projectsReducer';
import projectPanel from './projectPanelReducer';
import projectModal from './projectModalReducer';
import tasks from './tasksReducer';
import taskPanel from './taskPanelReducer';
import taskModal from './taskModalReducer';
export default combineReducers({
sidebar,
confirmModal,
flash,
projects,
projectPanel,
projectModal,
tasks,
taskPanel,
taskModal
}); |
const baseUrl = '/api/login';
export default class AuthService {
static login(credentials) {
return axios.post(`${baseUrl}`, credentials);
}
}
|
const api = {};
/**************************************************************************************************/
api.admin = {};
api.admin.clear_sessions =
function clear_sessions(callback)
{
return http.post({
url: "/admin/clear_sessions",
callback: callback,
});
}
api.admin.reload_config =
function reload_config(callback)
{
return http.post({
url: "/admin/reload_config",
callback: callback,
});
}
api.admin.uncache =
function uncache(callback)
{
return http.post({
url: "/admin/uncache",
callback: callback,
});
}
/**************************************************************************************************/
api.albums = {};
api.albums._add_remove_photos =
function _add_remove_photos(album_id, photo_ids, add_or_remove, callback)
{
let url;
if (add_or_remove === "add")
{ url = `/album/${album_id}/add_photo`; }
else if (add_or_remove === "remove")
{ url = `/album/${album_id}/remove_photo`; }
else
{ throw `should be 'add' or 'remove', not ${add_or_remove}.`; }
if (Array.isArray(photo_ids))
{ photo_ids = photo_ids.join(","); }
return http.post({
url: url,
data: {"photo_id": photo_ids},
callback: callback
});
}
api.albums.add_child =
function add_child(album_id, child_id, callback)
{
return http.post({
url: `/album/${album_id}/add_child`,
data: {"child_id": child_id},
callback: callback,
});
}
api.albums.add_photos =
function add_photos(album_id, photo_ids, callback)
{
return api.albums._add_remove_photos(album_id, photo_ids, "add", callback);
}
api.albums.create =
function create(title, parent_id, callback)
{
return http.post({
url: "/albums/create_album",
data: {"title": title, "parent_id": parent_id},
callback: callback,
});
}
api.albums.delete =
function _delete(album_id, callback)
{
return http.post({
url: `/album/${album_id}/delete`,
callback: callback,
});
}
api.albums.get_all_albums =
function get_all_albums(callback)
{
return http.get({
url: "/all_albums.json",
callback: callback,
});
}
api.albums.edit =
function edit(album_id, title, description, callback)
{
return http.post({
url: `/album/${album_id}/edit`,
data: {"title": title, "description": description},
callback: callback,
});
}
api.albums.refresh_directories =
function refresh_directories(album_id, callback)
{
return http.post({
url: `/album/${album_id}/refresh_directories`,
callback: callback,
});
}
api.albums.remove_child =
function remove_child(album_id, child_id, callback)
{
return http.post({
url: `/album/${album_id}/remove_child`,
data: {"child_id": child_id},
callback: callback,
});
}
api.albums.remove_photos =
function remove_photos(album_id, photo_ids, callback)
{
return api.albums._add_remove_photos(album_id, photo_ids, "remove", callback);
}
api.albums.remove_thumbnail_photo =
function remove_thumbnail_photo(album_id, callback)
{
return http.post({
url: `/album/${album_id}/remove_thumbnail_photo`,
data: {},
callback: callback,
});
}
api.albums.set_thumbnail_photo =
function set_thumbnail_photo(album_id, photo_id, callback)
{
return http.post({
url: `/album/${album_id}/set_thumbnail_photo`,
data: {"photo_id": photo_id},
callback: callback,
});
}
api.albums.show_in_folder =
function show_in_folder(album_id, callback)
{
return http.post({
url: `/album/${album_id}/show_in_folder`,
callback: callback,
});
}
api.albums.callback_follow =
function callback_follow(response)
{
if ((response.meta.status !== 200) || (! response.meta.json_ok) || (! response.data.id))
{
alert(JSON.stringify(response));
return;
}
window.location.href = "/album/" + response.data.id;
}
api.albums.callback_go_to_albums =
function callback_go_to_albums(response)
{
if (response.meta.status !== 200)
{
alert(JSON.stringify(response));
return;
}
window.location.href = "/albums";
}
/**************************************************************************************************/
api.bookmarks = {};
api.bookmarks.create =
function create(b_url, title, callback)
{
return http.post({
url: "/bookmarks/create_bookmark",
data: {"url": b_url.trim(), "title": title},
callback: callback,
});
}
api.bookmarks.delete =
function _delete(bookmark_id, callback)
{
return http.post({
url: `/bookmark/${bookmark_id}/delete`,
data: {},
callback: callback,
});
}
api.bookmarks.edit =
function edit(bookmark_id, title, b_url, callback)
{
return http.post({
url: `/bookmark/${bookmark_id}/edit`,
data: {"title": title.trim(), "url": b_url.trim()},
callback: callback,
});
}
/**************************************************************************************************/
api.photos = {};
api.photos.add_tag =
function add_tag(photo_id, tagname, callback)
{
return http.post({
url: `/photo/${photo_id}/add_tag`,
data: {"tagname": tagname},
callback: callback,
});
}
api.photos.batch_add_tag =
function batch_add_tag(photo_ids, tagname, callback)
{
return http.post({
url: "/batch/photos/add_tag",
data: {"photo_ids": photo_ids.join(","), "tagname": tagname},
callback: callback,
});
}
api.photos.batch_generate_thumbnail =
function batch_generate_thumbnail(photo_ids, callback)
{
return http.post({
url: "/batch/photos/generate_thumbnail",
data: {"photo_ids": photo_ids.join(",")},
callback: callback,
});
}
api.photos.batch_refresh_metadata =
function batch_refresh_metadata(photo_ids, callback)
{
return http.post({
url: "/batch/photos/refresh_metadata",
data: {"photo_ids": photo_ids.join(",")},
callback: callback,
});
}
api.photos.batch_remove_tag =
function batch_remove_tag(photo_ids, tagname, callback)
{
return http.post({
url: "/batch/photos/remove_tag",
data: {"photo_ids": photo_ids.join(","), "tagname": tagname},
callback: callback,
});
}
api.photos.batch_set_searchhidden =
function batch_set_searchhidden(photo_ids, callback)
{
return http.post({
url: "/batch/photos/set_searchhidden",
data: {"photo_ids": photo_ids.join(",")},
callback: callback,
});
}
api.photos.batch_unset_searchhidden =
function batch_unset_searchhidden(photo_ids, callback)
{
return http.post({
url: "/batch/photos/unset_searchhidden",
data: {"photo_ids": photo_ids.join(",")},
callback: callback,
});
}
api.photos.copy_tags =
function copy_tags(photo_id, other_photo, callback)
{
return http.post({
url: `/photo/${photo_id}/copy_tags`,
data: {"other_photo": other_photo},
callback: callback,
});
}
api.photos.delete =
function _delete(photo_id, delete_file, callback)
{
return http.post({
url: `/photo/${photo_id}/delete`,
data: {"delete_file": delete_file},
callback: callback,
});
}
api.photos.generate_thumbnail =
function generate_thumbnail(photo_id, special, callback)
{
return http.post({
url: `/photo/${photo_id}/generate_thumbnail`,
data: special,
callback: callback,
});
}
api.photos.get_download_zip_token =
function get_download_zip_token(photo_ids, callback)
{
return http.post({
url: "/batch/photos/download_zip",
data: {"photo_ids": photo_ids.join(",")},
callback: callback,
});
}
api.photos.download_zip =
function download_zip(zip_token)
{
const url = `/batch/photos/download_zip/${zip_token}.zip`;
window.location.href = url;
}
api.photos.callback_download_zip =
function callback_download_zip(response)
{
let zip_token = response.data.zip_token;
api.photos.download_zip(zip_token);
}
api.photos.refresh_metadata =
function refresh_metadata(photo_id, callback)
{
return http.post({
url: `/photo/${photo_id}/refresh_metadata`,
callback: callback,
});
}
api.photos.remove_tag =
function remove_tag(photo_id, tagname, callback)
{
return http.post({
url: `/photo/${photo_id}/remove_tag`,
data: {"tagname": tagname},
callback: callback,
});
}
api.photos.search =
function search(parameters, callback)
{
parameters = parameters.toString();
let url = "/search.json";
if (parameters !== "" )
{
url += "?" + parameters;
}
return http.get({
url: url,
callback: callback,
});
}
api.photos.set_searchhidden =
function set_searchhidden(photo_id, callback)
{
return http.post({
url: `/photo/${photo_id}/set_searchhidden`,
callback: callback,
});
}
api.photos.unset_searchhidden =
function unset_searchhidden(photo_id, callback)
{
return http.post({
url: `/photo/${photo_id}/unset_searchhidden`,
callback: callback,
});
}
api.photos.show_in_folder =
function show_in_folder(photo_id, callback)
{
return http.post({
url: `/photo/${photo_id}/show_in_folder`,
callback: callback,
});
}
api.photos.callback_go_to_search =
function callback_go_to_search(response)
{
if (response.meta.status !== 200)
{
alert(JSON.stringify(response));
return;
}
window.location.href = "/search";
}
/**************************************************************************************************/
api.tags = {};
api.tags.add_child =
function add_child(tag_name, child_name, callback)
{
return http.post({
url: `/tag/${tag_name}/add_child`,
data: {"child_name": child_name},
callback: callback,
});
}
api.tags.add_synonym =
function add_synonym(tag_name, syn_name, callback)
{
return http.post({
url: `/tag/${tag_name}/add_synonym`,
data: {"syn_name": syn_name},
callback: callback,
});
}
api.tags.create =
function create(name, description, callback)
{
return http.post({
url: `/tags/create_tag`,
data: {"name": name, "description": description},
callback: callback,
});
}
api.tags.delete =
function _delete(tag_name, callback)
{
return http.post({
url: `/tag/${tag_name}/delete`,
callback: callback,
});
}
api.tags.easybake =
function easybake(easybake_string, callback)
{
return http.post({
url: "/tags/easybake",
data: {"easybake_string": easybake_string},
callback: callback,
});
}
api.tags.edit =
function edit(tag_name, name, description, callback)
{
return http.post({
url: `/tag/${tag_name}/edit`,
data: {"name": name, "description": description},
callback: callback,
});
}
api.tags.get_all_tags =
function get_all_tags(callback)
{
return http.get({
url: "/all_tags.json",
callback: callback,
});
}
api.tags.remove_child =
function remove_child(tag_name, child_name, callback)
{
return http.post({
url: `/tag/${tag_name}/remove_child`,
data: {"child_name": child_name},
callback: callback,
});
}
api.tags.remove_synonym =
function remove_synonym(tag_name, syn_name, callback)
{
return http.post({
url: `/tag/${tag_name}/remove_synonym`,
data: {"syn_name": syn_name},
callback: callback,
});
}
api.tags.callback_go_to_tags =
function callback_go_to_tags(response)
{
if (response.meta.status !== 200)
{
alert(JSON.stringify(response));
return;
}
window.location.href = "/tags";
}
/**************************************************************************************************/
api.users = {};
api.users.edit =
function edit(username, display_name, callback)
{
return http.post({
url: `/user/${username}/edit`,
data: {"display_name": display_name},
callback: callback,
});
}
api.users.login =
function login(username, password, callback)
{
return http.post({
url: "/login",
data: {"username": username, "password": password},
callback: callback,
});
}
api.users.logout =
function logout(callback)
{
return http.post({
url: "/logout",
callback: callback,
});
}
api.users.register =
function register(username, display_name, password_1, password_2, callback)
{
const data = {
"username": username,
"display_name": display_name,
"password_1": password_1,
"password_2": password_2,
};
return http.post({
url: "/register",
data: data,
callback: callback,
});
}
|
/*****************************************************************************
*
* Copyright (c) 2003-2004 Kupu Contributors. All rights reserved.
*
* This software is distributed under the terms of the Kupu
* License. See LICENSE.txt for license text. For a list of Kupu
* Contributors see CREDITS.txt.
*
*****************************************************************************/
// $Id$
function StartKupu(organization, url, contextTemplateName) {
this.organization = organization;
this.url = url;
this.contextTemplateName=contextTemplateName;
this.getInnerText = function(text, tagName){
tagName = tagName.toLowerCase();
var startTag = "<"+tagName+">";
var endTag = "</"+tagName+">";
var start = text.indexOf(startTag);
if (start < 0)
start = text.indexOf(startTag.toUpperCase());
if (start < 0 ) {
alert("The content contains no "+startTag+"-element");
window.close();
}
var end = text.indexOf(endTag);
if (end < 0)
end = text.indexOf(endTag.toUpperCase());
if (end < 0 ) {
alert("The content contains no closing "+startTag+"-element");
window.close();
}
return text.substring(start+startTag.length,end);
}
this.handleStart = function(request, kupu){
if(request.readyState == 4) {
var htmltext="";
var xhtmldoc = Sarissa.getDomDocument();
var head = this.getInnerText(request.responseText,"head");
var body = this.getInnerText(request.responseText,"body");
/*var doc = kupu.getInnerDocument();
var newBody = doc.createElement("body");
newBody.innerHTML = body;
var mediafilter = new ReverseMediaObjectFilter();
mediafilter.initialize(kupu);
mediafilter.filter(xhtmldoc, newBody);*/
htmltext = "<html><head>"+head+"</head><body>"+body+"</body></html>";
kupu.getInnerDocument().open();
kupu.getInnerDocument().write(htmltext);
kupu.getInnerDocument().close();
window.setTimeout(
new ContextFixer(
this._initFirefox,
this, kupu).execute,
1);
}
}
this._initFirefox = function(kupu) {
if (kupu.getInnerDocument().getElementById('kupu-editable')==null)
window.setTimeout(
new ContextFixer(
this._initFirefox,
this, kupu).execute,
1);
else {
/////////////////////////
var xhtmldoc = Sarissa.getDomDocument();
var mediafilter = new ReverseMediaObjectFilter();
mediafilter.initialize(kupu);
mediafilter.filter(xhtmldoc, kupu.getInnerDocument());
//////////////////////////////
kupu.initialize();
var tool = kupu.getTool('contextchoosertool');
tool.setCurrentContextTemplateName(this.contextTemplateName);
}
}
this.getKupu = function(){
var frame = document.getElementById('kupu-editor');
var kupu = initKupu(frame, organization);
var xmlhttp = Sarissa.getXmlHttpRequest();
xmlhttp.open("GET",url , true);
var call = new ContextFixer(this.handleStart,this,xmlhttp,kupu);
xmlhttp.onreadystatechange = call.execute;
xmlhttp.send(null);
return kupu;
};
};
|
/**
* @license
* Copyright (c) 2018 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
// Import LitElement base class and html helper function
import { LitElement, html } from 'lit-element';
export class LoginElement extends LitElement {
/**
* Define properties. Properties defined here will be automatically
* observed.
*/
static get properties() {
return {
userName: {type:String},
userPassword:{type:String},
userAccess:{type:Boolean}
};
}
/**
* In the element constructor, assign default property values.
*/
constructor() {
// Must call superconstructor first.
super();
this.userName='';
this.userPassword='';
this.userAccess=false;
// Initialize properties
this.users=[
{
name:'Kris Jaje',
login:'KrisJaje',
pw:'Kris Jaje',
id:1,
gender:'M'
},
{
name:'Kenneth Curtis',
login:'KennethCurtis',
pw:'Kenneth Curtis',
id:2,
gender:'M'
},
{
name:'Cristian Vega',
login:'CristianVega',
pw:'Cristian Vega',
id:3,
gender:'M'
},
{
name:'Kris Jaje',
login:'k',
pw:'k',
id:4,
gender:'M'
}
];
}
checkAccess(){
this.user=this.users.filter(user => user.login===this.userName);
if(this.user.length===1 && this.user[0].pw===this.userPassword){
this.onLoginAccess(true,this.user[0]);
this.userAccess=true;
}
else{
this.onLoginAccess(false,false);
this.userAccess=false;
}
}
mapInput(e){
let inputTmp=e.target;
if(inputTmp.id==='userName'){
this.userName=inputTmp.value;
}
else if(inputTmp.id==='userPassword'){
this.userPassword=inputTmp.value;
}
}
onLoginAccess(access,user){
let loginEvent = new CustomEvent('login-event', {
detail: {
access: access,
user:user
}
}
);
this.dispatchEvent(loginEvent);
}
/**
/**
* Define a template for the new element by implementing LitElement's
* `render` function. `render` must return a lit-html TemplateResult.
*/
render() {
return html`
<link rel="stylesheet" href="./src/css/login.css">
<style>
:host { display: block; }
:host([hidden]) { display: none; }
</style>
<form >
<div class="container">
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" id="userName" @change="${this.mapInput}" .value="${this.userName}" name="uname" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" @change="${this.mapInput}" id="userPassword" .value="${this.userPassword}" name="psw" required>
<button type="button" @click="${this.checkAccess}">Login</button>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" class="cancelbtn">Cancel</button>
<span class="psw">Forgot <a href="#">password?</a></span>
</div>
</form>
`;
}
}
// Register the element with the browser
customElements.define('login-element', LoginElement); |
// // Dependencies
// const fs = require('fs');
// const path = require('path');
// const notes = require('../db/db')
// module.exports = app => {
// // View Routes
// // -------------------------------------------------------------
// // On Load Page-> Start with index.html
// app.get('/', (req, res) =>
// res.sendFile(path.join(__dirname, '/public/index.html')));
// // Notes html page and the 'url' for the page.
// app.get('/notes', (req, res) =>
// res.sendFile(path.join(__dirname, '/public/notes.html')));
// // API Routes
// // -------------------------------------------------------
// // setup api get
// app.route('/api/notes')
// .get(function (req, res) {
// res.json(notes)
// })
// // setup api post
// .post(function (req, res) {
// let jsonPath = path.join(__dirname, "/db/db.json");
// let newNotes = req.body;
// let newId = 99;
// // Loop through array to find highest ID
// for (let i = 0; i < notes.length; i++) {
// const singleNote = notes[i];
// if (singleNote.id > newID) {
// newId = singleNote.id;
// }
// }
// // Assign ID to new Note
// newNotes.id = newId + 1;
// // Push to the db.json
// notes.push(newNotes);
// // write db. json file
// fs.writeFile(jsonPath, JSON.stringify(notes), err => {
// if (err) {
// return console.log(err);
// }
// console.log("Your note was saved");
// });
// res.json(newNotes)
// }
// }
// app.get('api/notes:id', (req, res) => {
// notes.splice(req.params.id, 1);
// updateDb()
// });
// Delete note?
// fs.readFile(notes, 'utf8', (err, data) => {
// if (err) throw err;
// let notes = JSON.parse(data); |
var num = 2;
// num = 4;
var obj = {
name: 'Vinicius'
};
obj.name = 'marcos';
|
(function(){
console.log('init newsite');
})(); |
OC.L10N.register(
"federatedfilesharing",
{
"Federated sharing" : "שיתוף מאוגד",
"Add to your ownCloud" : "הוספה ל- ownCloud שלך",
"Invalid Federated Cloud ID" : "זיהוי ענן מאוגד לא חוקי",
"Sharing %s failed, because this item is already shared with %s" : "שיתוף %s נכשל, כיוון שפריט זה כבר משותף עם %s",
"Not allowed to create a federated share with the same user" : "אסור ליצור שיתוף מאוגד עם אותו משתמש",
"File is already shared with %s" : "הקובץ כבר משותף עם %s",
"Sharing %s failed, could not find %s, maybe the server is currently unreachable." : "שיתוף %s נכשל, לא ניתן לאתר %s, ייתכן שהשרת לא ניתן להשגה כרגע.",
"Federated Sharing failed: %s" : "שיתוף מאוגד נכשל: %s",
"\"%1$s\" shared \"%3$s\" with you (on behalf of \"%2$s\")" : "\"%1$s\" משתף \"%3$s\" אתך (בשם \"%2$s\")",
"\"%1$s\" shared \"%3$s\" with you" : "\"%1$s\" משתף \"%3$s\" אתך",
"\"%1$s\" invited you to view \"%3$s\" (on behalf of \"%2$s\")" : "\"%1$s\" מזמין אותך לצפות ב- \"%3$s\" (בשם \"%2$s\")",
"\"%1$s\" invited you to view \"%3$s\"" : "\"%1$s\" מזמין אותך לצפות ב- \"%3$s\"",
"Accept" : "אישור",
"Decline" : "סירוב",
"Share with me through my #ownCloud Federated Cloud ID, see %s" : "שיתוף איתי באמצעות מספר זהות שרת ה- #ownCloud המאוגד שלי, ניתן לראות %s",
"Share with me through my #ownCloud Federated Cloud ID" : "שיתוף איתי באמצעות מספר זהות שרת ה- #ownCloud המאוגד שלי",
"Federated Cloud Sharing" : "ענן שיתוף מאוגד",
"Open documentation" : "תיעוד פתוח",
"Periodically synchronize outdated federated shares for active users" : "תקופתית מסנכרן שיתופים מאוגדים ישנים למשתמשים פעילים",
"Allow users on this server to send shares to other servers" : "מאפשר למשתמשים בשרת זה לשלוח שיתופים לשרתים אחרים",
"Allow users on this server to receive shares from other servers" : "מאפשר למשתמשים בשרת זה לקבל שיתופים משרתים אחרים",
"Automatically accept remote shares from trusted servers" : "אישור אוטומטי לשיתוף מרוחק משרתים מהימנים",
"Federated Cloud" : "ענן מאוגד",
"Your Federated Cloud ID:" : "מספר זיהוי הענן המאוגד שלך:",
"Share it:" : "שיתוף שלו:",
"Add to your website" : "הוספה לאתר האינטרנט שלך",
"Share with me via ownCloud" : "שיתוף איתי באמצעות ownCloud",
"HTML Code:" : "קוד HTML:",
"Nothing to configure." : "אין שום דבר להגדיר."
},
"nplurals=4; plural=(n == 1 && n % 1 == 0) ? 0 : (n == 2 && n % 1 == 0) ? 1: (n % 10 == 0 && n % 1 == 0 && n > 10) ? 2 : 3;");
|
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 2) + fibonacci(n - 1);
}
// https://github.com/sockjs/sockjs-client/
var endpoint = 'http://localhost:9999/echo';
var whitelist = ["websocket"];
function log(message) {
$("#messages").append(message+"<br/>");
}
function lag(message) {
$("#messages").append(message);
}
var sock = init();
function init() {
var soc = new SockJS(endpoint, null, {devel:true, protocols_whitelist: whitelist});
soc.onopen = function() {
log("<i class=\"icon-thumbs-up\"></i> Open");
};
soc.onmessage = function(e) {
log("<i>Message:"+e.data+"</i>");
};
soc.onclose = function() {
log("<i class=\"icon-thumbs-down\"></i> Close");
//soc.open();
};
return soc;
}
$("#send").live("click", function(event) {
log("sending message");
sock.send(JSON.stringify({"type":"info", "data": "The time is now:"+moment().format()}));
});
$("#block").live("click", function(event) {
log("sending block message");
sock.send(JSON.stringify({"type":"block"}));
});
$("#close").live("click", function(event) {
log("closing sockjs");
sock.close();
});
$("#open").live("click", function(event) {
log("Endpoint is:"+endpoint+": whitelist:"+whitelist);
sock = init();
});
$("#rec").live("click", function(event) {
log("Reconnect");
sock.close();
// sock.open();
sock = init();
});
function getI() {
var i = parseInt($("#numbers").val());
if(i > 0)
return i;
return 10;
}
$("#bigsend").live("click", function(event) {
var count = getI();
log("sending "+count+" messages");
var now1 = moment();
for(i=0;i<count;i++) {
lag(".");
// setTimeout(function() {
sock.send(JSON.stringify({type:'hello', data: "small message"}));
// }, 1000*i);
}
var now2 = moment();
log("<br/>finish sending plenty of messages:" + (now2-now1) + " ms");
});
$("#protocol").live("change", function(event) {
whitelist = []
var newv = $("#protocol").val();
whitelist.push(newv);
log("Selecting:"+newv);
init();
});
var conns = [];
$("#new").live("click", function(event) {
var c = getI();
log("Starting new connections ["+c+"]");
for (i=0;i<c;i++) {
// lag(".");
setTimeout(function() {
conns.push(init());
}, i*5);
}
log("Finished new connections");
});
$("#fib").live("click", function(event) {
log("Starting fib");
log(fibonacci(30));
log("Finishing fib");
});
$("#clean").live("click", function(event) {
$("#messages").html("");
});
|
import React, { useState ,useRef, useEffect} from 'react';
import './App.css';
import TodoList from './components/TodoList';
import {v4 as uuid} from 'uuid';
const LOCAL_STORAGE_KEY = 'todoApp.todos'
function App() {
const [todos, setTodos] = useState([
{
id:1,
name: "Get Python black belt",
complete:false
},
{
id:2,
name: "Get Java red belt",
complete:false
},
{
id:3,
name: "Get Mern pink belt",
complete:false
}
]);
const todoNameRef = useRef()
useEffect(() => {
const storedTodos = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY))
if(storedTodos) setTodos(storedTodos)
}, [])
useEffect(() => {
localStorage.setItem(LOCAL_STORAGE_KEY,JSON.stringify(todos))
}, [todos])
function toggleTodo(id){
const newTodos = [...todos]
const todo = newTodos.find(todo=>todo.id === id)
todo.complete = !todo.complete
setTodos(newTodos)
}
function deleteTodo(id){
const newTodos = todos.filter(todo => todo.id !==id)
console.log(id);
console.log(newTodos);
setTodos(newTodos)
}
function handleAddTodo(e){
const name = todoNameRef.current.value
if (name ==='') return
setTodos(preTodos => {
return [...preTodos,{id:uuid(), name:name,complete:false}]
})
todoNameRef.current.value = null
}
function handleClearTodo(e){
const newTodos = todos.filter(todo => !todo.complete)
setTodos(newTodos)
}
return (
<div className="App">
<h1>To do list</h1>
<h2>-------------------</h2>
<TodoList todos={todos} toggleTodo={toggleTodo} deleteTodo={deleteTodo}/>
<input ref={todoNameRef} type="text"/>
<button onClick={handleAddTodo} className="btn btn-primary btn-sm">Add Todo</button>
<button onClick={handleClearTodo} className="btn btn-success btn-sm">Clear Completed Todos</button>
<h4 style={{color:'purple'}}> {todos.filter(todo => !todo.complete).length} left to do</h4>
</div>
);
}
export default App;
|
const {
getProductionHouse,
postProductionHouse,
putProductionHouse,
deleteProductionHouse
} = require('../models/productionHouse')
const helper = require('../helper')
module.exports = {
getProductionHouse: async(req, res) => {
const result = await getProductionHouse()
return helper.response(res, 200, null, result)
},
createProductionHouse: async(req, res) => {
try {
const name = req.body.name
const result = await postProductionHouse(name)
const message = 'Data berhasil ditambahkan'
return helper.response(res, 200, message, result)
} catch (error) {
const message = 'Data gagal ditambahkan'
return helper.response(res, 400, message, error)
}
},
editProductionHouse: async(req, res) => {
try {
const name = req.body.name
const id = req.params.id
const result = await putProductionHouse(name, id)
const message = 'Data berhasil diedit'
return helper.response(res, 200, message, result)
} catch (error) {
console.log(error);
const message = 'Data gagal diedit'
return helper.response(res, 400, message, error)
}
},
deleteProductionHouse: async(req, res)=>{
try {
const id = req.params.id
const result = await deleteProductionHouse(id)
const message = 'Data berhasil dihapus'
return helper.response(res, 200, message, result)
} catch (error) {
const message = 'Data gagal dihapus'
return helper.response(res, 400, message, error)
}
}
} |
import React from 'react'
import styles from './ClubPage.module.css'
const ClubPage = () => {
return <div className={styles.root}>Club Page details</div>
}
export default ClubPage
|
var fs = require('fs');
var s300_raw = require('./SAT300.json'),
s6000_raw = require('./SAT6000.json');
var s300 = {}, s6000 = {};
var transform = (input, output)=>input.forEach((e)=>{output[e.word]=e.def});
transform(s300_raw, s300);
transform(s6000_raw, s6000);
var combined = Object.assign({}, s6000, s300);
var combined_json = JSON.stringify(combined);
fs.writeFileSync('./combined.json', combined_json);
|
export class Node {
constructor( o = {} ) {
this.id = o.id || 0;
this.name = o.name || 'node-'+ this.id;
this.points = [];
this.w = o.w || 80;
this.h = o.h || 20;
this.x = 10;
this.y = 10;
this.p = null;
if( o.x ) this.x = o.x - (this.w * 0.5);
if( o.y ) this.y = o.y - (this.h * 0.5);
this.color = '#666';
this.border = '#888';
this.borderSel = '#AAA';
this.select = false;
}
draw( ctx ) {
ctx.lineWidth = 1;
ctx.strokeStyle = this.select ? this.borderSel : this.border;
ctx.fillStyle = this.color;
ctx.fillRect( this.x, this.y, this.w, this.h );
ctx.strokeRect( this.x, this.y, this.w, this.h );
let i = this.points.length;
while( i-- ){
if(i === 0) this.points[i].move( this.x, this.y + this.h*0.5 );
if(i === 1) this.points[i].move( this.x + this.w, this.y + this.h*0.5 );
this.points[i].draw( ctx );
}
//ctx.font = "11px Lucida Console";
ctx.font = 'normal ' + 9 + 'px Helvetica,Arial,sans-serif';
ctx.textBaseline = 'middle';
ctx.fillStyle = "#FFF";
ctx.textAlign = "center";
ctx.fillText( this.name, this.x + this.w*0.5, this.y + this.h * 0.5 );
}
over( x, y ) {
let i = this.points.length;
this.p = null;
while( i-- ){
if( this.points[i].over( x, y ) ) this.p = this.points[i];
}
if( this.p !== null ){
this.select = true;
return 'link' + (this.p.start ? 'Start' : 'End');
} else {
this.select = (this.x <= x) && (this.x + this.w >= x) && (this.y <= y) && (this.y + this.h >= y);
if( this.select ) return 'node';// (this.x <= x) && (this.x + this.w >= x) && (this.y <= y) && (this.y + this.h >= y);
}
return '';
}
move( x, y ) {
this.x = x;
this.y = y;
}
}
|
function makeSlide(url, className) {
return (`
<div class='slider__item ${className || ''}'>
<img class='slider__item--image' alt='' src='${url}'>
</div>
`)
};
var images = ['images/boy_1.png', 'images/boy_2.png'];
function slider() {
const slidesCount = 3;
let image = 0
for (let i = 0; i < slidesCount; i++) {
$('.slider__item--container').append(makeSlide(images[+image]))
image = !(image)
};
$('.button__right').on('click', () => {
$('.slider__item').last().addClass('move-right');
window.setTimeout(function() {
$('.slider__item--container').prepend(makeSlide(images[+image], 'move-left abs'))
image = !(+image)
window.setTimeout(function() {
$('.slider__item:eq( 1 ), .slider__item:eq( 2 )').css({right: "187px"});
$('.slider__item').first().removeClass('move-left')
$('.slider__item').first().removeClass('abs')
$('.slider__item').last().remove()
$('.slider__item:eq( 1 ), .slider__item:eq( 2 )').animate({right: "0px"}, 500, function() {
$('.slider__item').css({'right': ''})
});
}, 200)
}, 100)
})
$('.button__left').on('click', () => {
$('.slider__item').first().addClass('move-left');
window.setTimeout(function() {
$('.slider__item--container').append(makeSlide(images[+image], 'move-right abs'))
image = !(+image)
window.setTimeout(function() {
console.log($('.slider__item:eq( 1 ), .slider__item:eq( 2 )'));
$('.slider__item:eq( 1 ), .slider__item:eq( 2 )').css({left: "187px"});
$('.slider__item').last().removeClass('move-right abs')
$('.slider__item').first().remove()
$('.slider__item:eq( 0 ), .slider__item:eq( 1 )').animate({left: "0px"}, 500, function() {
$('.slider__item').css({'left': ''})
});
}, 200)
}, 100)
})
}
$(document).ready(slider); |
'use strict';
/**
* @workInProgress
* @ngdoc overview
* @name angular.widget
* @description
*
* An angular widget can be either a custom attribute that modifies an existing DOM element or an
* entirely new DOM element.
*
* During html compilation, widgets are processed after {@link angular.markup markup}, but before
* {@link angular.directive directives}.
*
* Following is the list of built-in angular widgets:
*
* * {@link angular.widget.@ng:format ng:format} - Formats data for display to user and for storage.
* * {@link angular.widget.@ng:non-bindable ng:non-bindable} - Blocks angular from processing an
* HTML element.
* * {@link angular.widget.@ng:repeat ng:repeat} - Creates and manages a collection of cloned HTML
* elements.
* * {@link angular.widget.@ng:required ng:required} - Verifies presence of user input.
* * {@link angular.widget.@ng:validate ng:validate} - Validates content of user input.
* * {@link angular.widget.HTML HTML input elements} - Standard HTML input elements data-bound by
* angular.
* * {@link angular.widget.ng:view ng:view} - Works with $route to "include" partial templates
* * {@link angular.widget.ng:switch ng:switch} - Conditionally changes DOM structure
* * {@link angular.widget.ng:include ng:include} - Includes an external HTML fragment
*
* For more information about angular widgets, see {@link guide/dev_guide.compiler.widgets
* Understanding Angular Widgets} in the angular Developer Guide.
*/
/**
* @workInProgress
* @ngdoc widget
* @name angular.widget.HTML
*
* @description
* The most common widgets you will use will be in the form of the
* standard HTML set. These widgets are bound using the `name` attribute
* to an expression. In addition, they can have `ng:validate`, `ng:required`,
* `ng:format`, `ng:change` attribute to further control their behavior.
*
* @usageContent
* see example below for usage
*
* <input type="text|checkbox|..." ... />
* <textarea ... />
* <select ...>
* <option>...</option>
* </select>
*
* @example
<doc:example>
<doc:source>
<table style="font-size:.9em;">
<tr>
<th>Name</th>
<th>Format</th>
<th>HTML</th>
<th>UI</th>
<th ng:non-bindable>{{input#}}</th>
</tr>
<tr>
<th>text</th>
<td>String</td>
<td><tt><input type="text" name="input1"></tt></td>
<td><input type="text" name="input1" size="4"></td>
<td><tt>{{input1|json}}</tt></td>
</tr>
<tr>
<th>textarea</th>
<td>String</td>
<td><tt><textarea name="input2"></textarea></tt></td>
<td><textarea name="input2" cols='6'></textarea></td>
<td><tt>{{input2|json}}</tt></td>
</tr>
<tr>
<th>radio</th>
<td>String</td>
<td><tt>
<input type="radio" name="input3" value="A"><br>
<input type="radio" name="input3" value="B">
</tt></td>
<td>
<input type="radio" name="input3" value="A">
<input type="radio" name="input3" value="B">
</td>
<td><tt>{{input3|json}}</tt></td>
</tr>
<tr>
<th>checkbox</th>
<td>Boolean</td>
<td><tt><input type="checkbox" name="input4" value="checked"></tt></td>
<td><input type="checkbox" name="input4" value="checked"></td>
<td><tt>{{input4|json}}</tt></td>
</tr>
<tr>
<th>pulldown</th>
<td>String</td>
<td><tt>
<select name="input5"><br>
<option value="c">C</option><br>
<option value="d">D</option><br>
</select><br>
</tt></td>
<td>
<select name="input5">
<option value="c">C</option>
<option value="d">D</option>
</select>
</td>
<td><tt>{{input5|json}}</tt></td>
</tr>
<tr>
<th>multiselect</th>
<td>Array</td>
<td><tt>
<select name="input6" multiple size="4"><br>
<option value="e">E</option><br>
<option value="f">F</option><br>
</select><br>
</tt></td>
<td>
<select name="input6" multiple size="4">
<option value="e">E</option>
<option value="f">F</option>
</select>
</td>
<td><tt>{{input6|json}}</tt></td>
</tr>
</table>
</doc:source>
<doc:scenario>
it('should exercise text', function(){
input('input1').enter('Carlos');
expect(binding('input1')).toEqual('"Carlos"');
});
it('should exercise textarea', function(){
input('input2').enter('Carlos');
expect(binding('input2')).toEqual('"Carlos"');
});
it('should exercise radio', function(){
expect(binding('input3')).toEqual('null');
input('input3').select('A');
expect(binding('input3')).toEqual('"A"');
input('input3').select('B');
expect(binding('input3')).toEqual('"B"');
});
it('should exercise checkbox', function(){
expect(binding('input4')).toEqual('false');
input('input4').check();
expect(binding('input4')).toEqual('true');
});
it('should exercise pulldown', function(){
expect(binding('input5')).toEqual('"c"');
select('input5').option('d');
expect(binding('input5')).toEqual('"d"');
});
it('should exercise multiselect', function(){
expect(binding('input6')).toEqual('[]');
select('input6').options('e');
expect(binding('input6')).toEqual('["e"]');
select('input6').options('e', 'f');
expect(binding('input6')).toEqual('["e","f"]');
});
</doc:scenario>
</doc:example>
*/
function modelAccessor(scope, element) {
var expr = element.attr('name');
var exprFn, assignFn;
if (expr) {
exprFn = parser(expr).assignable();
assignFn = exprFn.assign;
if (!assignFn) throw new Error("Expression '" + expr + "' is not assignable.");
return {
get: function() {
return exprFn(scope);
},
set: function(value) {
if (value !== undefined) {
assignFn(scope, value);
}
}
};
}
}
function modelFormattedAccessor(scope, element) {
var accessor = modelAccessor(scope, element),
formatterName = element.attr('ng:format') || NOOP,
formatter = compileFormatter(formatterName);
if (accessor) {
return {
get: function() {
return formatter.format(scope, accessor.get());
},
set: function(value) {
return accessor.set(formatter.parse(scope, value));
}
};
}
}
function compileValidator(expr) {
return parser(expr).validator()();
}
function compileFormatter(expr) {
return parser(expr).formatter()();
}
/**
* @workInProgress
* @ngdoc widget
* @name angular.widget.@ng:validate
*
* @description
* The `ng:validate` attribute widget validates the user input. If the input does not pass
* validation, the `ng-validation-error` CSS class and the `ng:error` attribute are set on the input
* element. Check out {@link angular.validator validators} to find out more.
*
* @param {string} validator The name of a built-in or custom {@link angular.validator validator} to
* to be used.
*
* @element INPUT
* @css ng-validation-error
*
* @example
* This example shows how the input element becomes red when it contains invalid input. Correct
* the input to make the error disappear.
*
<doc:example>
<doc:source>
I don't validate:
<input type="text" name="value" value="NotANumber"><br/>
I need an integer or nothing:
<input type="text" name="value" ng:validate="integer"><br/>
</doc:source>
<doc:scenario>
it('should check ng:validate', function(){
expect(element('.doc-example-live :input:last').prop('className')).
toMatch(/ng-validation-error/);
input('value').enter('123');
expect(element('.doc-example-live :input:last').prop('className')).
not().toMatch(/ng-validation-error/);
});
</doc:scenario>
</doc:example>
*/
/**
* @workInProgress
* @ngdoc widget
* @name angular.widget.@ng:required
*
* @description
* The `ng:required` attribute widget validates that the user input is present. It is a special case
* of the {@link angular.widget.@ng:validate ng:validate} attribute widget.
*
* @element INPUT
* @css ng-validation-error
*
* @example
* This example shows how the input element becomes red when it contains invalid input. Correct
* the input to make the error disappear.
*
<doc:example>
<doc:source>
I cannot be blank: <input type="text" name="value" ng:required><br/>
</doc:source>
<doc:scenario>
it('should check ng:required', function(){
expect(element('.doc-example-live :input').prop('className')).
toMatch(/ng-validation-error/);
input('value').enter('123');
expect(element('.doc-example-live :input').prop('className')).
not().toMatch(/ng-validation-error/);
});
</doc:scenario>
</doc:example>
*/
/**
* @workInProgress
* @ngdoc widget
* @name angular.widget.@ng:format
*
* @description
* The `ng:format` attribute widget formats stored data to user-readable text and parses the text
* back to the stored form. You might find this useful, for example, if you collect user input in a
* text field but need to store the data in the model as a list. Check out
* {@link angular.formatter formatters} to learn more.
*
* @param {string} formatter The name of the built-in or custom {@link angular.formatter formatter}
* to be used.
*
* @element INPUT
*
* @example
* This example shows how the user input is converted from a string and internally represented as an
* array.
*
<doc:example>
<doc:source>
Enter a comma separated list of items:
<input type="text" name="list" ng:format="list" value="table, chairs, plate">
<pre>list={{list}}</pre>
</doc:source>
<doc:scenario>
it('should check ng:format', function(){
expect(binding('list')).toBe('list=["table","chairs","plate"]');
input('list').enter(',,, a ,,,');
expect(binding('list')).toBe('list=["a"]');
});
</doc:scenario>
</doc:example>
*/
function valueAccessor(scope, element) {
var validatorName = element.attr('ng:validate') || NOOP,
validator = compileValidator(validatorName),
requiredExpr = element.attr('ng:required'),
formatterName = element.attr('ng:format') || NOOP,
formatter = compileFormatter(formatterName),
format, parse, lastError, required,
invalidWidgets = scope.$service('$invalidWidgets') || {markValid:noop, markInvalid:noop};
if (!validator) throw "Validator named '" + validatorName + "' not found.";
format = formatter.format;
parse = formatter.parse;
if (requiredExpr) {
scope.$watch(requiredExpr, function(scope, newValue) {
required = newValue;
validate();
});
} else {
required = requiredExpr === '';
}
element.data($$validate, validate);
return {
get: function(){
if (lastError)
elementError(element, NG_VALIDATION_ERROR, null);
try {
var value = parse(scope, element.val());
validate();
return value;
} catch (e) {
lastError = e;
elementError(element, NG_VALIDATION_ERROR, e);
}
},
set: function(value) {
var oldValue = element.val(),
newValue = format(scope, value);
if (oldValue != newValue) {
element.val(newValue || ''); // needed for ie
}
validate();
}
};
function validate() {
var value = trim(element.val());
if (element[0].disabled || element[0].readOnly) {
elementError(element, NG_VALIDATION_ERROR, null);
invalidWidgets.markValid(element);
} else {
var error, validateScope = inherit(scope, {$element:element});
error = required && !value
? 'Required'
: (value ? validator(validateScope, value) : null);
elementError(element, NG_VALIDATION_ERROR, error);
lastError = error;
if (error) {
invalidWidgets.markInvalid(element);
} else {
invalidWidgets.markValid(element);
}
}
}
}
function checkedAccessor(scope, element) {
var domElement = element[0], elementValue = domElement.value;
return {
get: function(){
return !!domElement.checked;
},
set: function(value){
domElement.checked = toBoolean(value);
}
};
}
function radioAccessor(scope, element) {
var domElement = element[0];
return {
get: function(){
return domElement.checked ? domElement.value : null;
},
set: function(value){
domElement.checked = value == domElement.value;
}
};
}
function optionsAccessor(scope, element) {
var formatterName = element.attr('ng:format') || NOOP,
formatter = compileFormatter(formatterName);
return {
get: function(){
var values = [];
forEach(element[0].options, function(option){
if (option.selected) values.push(formatter.parse(scope, option.value));
});
return values;
},
set: function(values){
var keys = {};
forEach(values, function(value){
keys[formatter.format(scope, value)] = true;
});
forEach(element[0].options, function(option){
option.selected = keys[option.value];
});
}
};
}
function noopAccessor() { return { get: noop, set: noop }; }
/*
* TODO: refactor
*
* The table below is not quite right. In some cases the formatter is on the model side
* and in some cases it is on the view side. This is a historical artifact
*
* The concept of model/view accessor is useful for anyone who is trying to develop UI, and
* so it should be exposed to others. There should be a form object which keeps track of the
* accessors and also acts as their factory. It should expose it as an object and allow
* the validator to publish errors to it, so that the the error messages can be bound to it.
*
*/
var textWidget = inputWidget('keydown change', modelAccessor, valueAccessor, initWidgetValue(), true),
INPUT_TYPE = {
'text': textWidget,
'textarea': textWidget,
'hidden': textWidget,
'password': textWidget,
'checkbox': inputWidget('click', modelFormattedAccessor, checkedAccessor, initWidgetValue(false)),
'radio': inputWidget('click', modelFormattedAccessor, radioAccessor, radioInit),
'select-one': inputWidget('change', modelAccessor, valueAccessor, initWidgetValue(null)),
'select-multiple': inputWidget('change', modelAccessor, optionsAccessor, initWidgetValue([]))
// 'file': fileWidget???
};
function initWidgetValue(initValue) {
return function (model, view) {
var value = view.get();
if (!value && isDefined(initValue)) {
value = copy(initValue);
}
if (isUndefined(model.get()) && isDefined(value)) {
model.set(value);
}
};
}
function radioInit(model, view, element) {
var modelValue = model.get(), viewValue = view.get(), input = element[0];
input.checked = false;
input.name = this.$id + '@' + input.name;
if (isUndefined(modelValue)) {
model.set(modelValue = null);
}
if (modelValue == null && viewValue !== null) {
model.set(viewValue);
}
view.set(modelValue);
}
/**
* @workInProgress
* @ngdoc directive
* @name angular.directive.ng:change
*
* @description
* The directive executes an expression whenever the input widget changes.
*
* @element INPUT
* @param {expression} expression to execute.
*
* @example
* @example
<doc:example>
<doc:source>
<div ng:init="checkboxCount=0; textCount=0"></div>
<input type="text" name="text" ng:change="textCount = 1 + textCount">
changeCount {{textCount}}<br/>
<input type="checkbox" name="checkbox" ng:change="checkboxCount = 1 + checkboxCount">
changeCount {{checkboxCount}}<br/>
</doc:source>
<doc:scenario>
it('should check ng:change', function(){
expect(binding('textCount')).toBe('0');
expect(binding('checkboxCount')).toBe('0');
using('.doc-example-live').input('text').enter('abc');
expect(binding('textCount')).toBe('1');
expect(binding('checkboxCount')).toBe('0');
using('.doc-example-live').input('checkbox').check();
expect(binding('textCount')).toBe('1');
expect(binding('checkboxCount')).toBe('1');
});
</doc:scenario>
</doc:example>
*/
function inputWidget(events, modelAccessor, viewAccessor, initFn, textBox) {
return annotate('$defer', function($defer, element) {
var scope = this,
model = modelAccessor(scope, element),
view = viewAccessor(scope, element),
ngChange = element.attr('ng:change') || noop,
lastValue;
if (model) {
initFn.call(scope, model, view, element);
scope.$eval(element.attr('ng:init') || noop);
element.bind(events, function(event){
function handler(){
var value = view.get();
if (!textBox || value != lastValue) {
model.set(value);
lastValue = model.get();
scope.$eval(ngChange);
}
}
event.type == 'keydown' ? $defer(handler) : scope.$apply(handler);
});
scope.$watch(model.get, function(scope, value) {
if (!equals(lastValue, value)) {
view.set(lastValue = value);
}
});
}
});
}
function inputWidgetSelector(element){
this.directives(true);
this.descend(true);
return INPUT_TYPE[lowercase(element[0].type)] || noop;
}
angularWidget('input', inputWidgetSelector);
angularWidget('textarea', inputWidgetSelector);
/**
* @workInProgress
* @ngdoc directive
* @name angular.directive.ng:options
*
* @description
* Dynamically generate a list of `<option>` elements for a `<select>` element using an array or
* an object obtained by evaluating the `ng:options` expression.
*
* When an item in the select menu is select, the value of array element or object property
* represented by the selected option will be bound to the model identified by the `name` attribute
* of the parent select element.
*
* Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
* be nested into the `<select>` element. This element will then represent `null` or "not selected"
* option. See example below for demonstration.
*
* Note: `ng:options` provides iterator facility for `<option>` element which must be used instead
* of {@link angular.widget.@ng:repeat ng:repeat}. `ng:repeat` is not suitable for use with
* `<option>` element because of the following reasons:
*
* * value attribute of the option element that we need to bind to requires a string, but the
* source of data for the iteration might be in a form of array containing objects instead of
* strings
* * {@link angular.widget.@ng:repeat ng:repeat} unrolls after the select binds causing
* incorect rendering on most browsers.
* * binding to a value not in list confuses most browsers.
*
* @element select
* @param {comprehension_expression} comprehension in one of the following forms:
*
* * for array data sources:
* * `label` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`for`** `value` **`in`** `array`
* * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array`
* * for object data sources:
* * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`group by`** `group`
* **`for` `(`**`key`**`,`** `value`**`) in`** `object`
*
* Where:
*
* * `array` / `object`: an expression which evaluates to an array / object to iterate over.
* * `value`: local variable which will refer to each item in the `array` or each property value
* of `object` during iteration.
* * `key`: local variable which will refer to a property name in `object` during iteration.
* * `label`: The result of this expression will be the label for `<option>` element. The
* `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
* * `select`: The result of this expression will be bound to the model of the parent `<select>`
* element. If not specified, `select` expression will default to `value`.
* * `group`: The result of this expression will be used to group options using the `<optgroup>`
* DOM element.
*
* @example
<doc:example>
<doc:source>
<script>
function MyCntrl(){
this.colors = [
{name:'black', shade:'dark'},
{name:'white', shade:'light'},
{name:'red', shade:'dark'},
{name:'blue', shade:'dark'},
{name:'yellow', shade:'light'}
];
this.color = this.colors[2]; // red
}
</script>
<div ng:controller="MyCntrl">
<ul>
<li ng:repeat="color in colors">
Name: <input name="color.name">
[<a href ng:click="colors.$remove(color)">X</a>]
</li>
<li>
[<a href ng:click="colors.push({})">add</a>]
</li>
</ul>
<hr/>
Color (null not allowed):
<select name="color" ng:options="c.name for c in colors"></select><br>
Color (null allowed):
<div class="nullable">
<select name="color" ng:options="c.name for c in colors">
<option value="">-- chose color --</option>
</select>
</div><br/>
Color grouped by shade:
<select name="color" ng:options="c.name group by c.shade for c in colors">
</select><br/>
Select <a href ng:click="color={name:'not in list'}">bogus</a>.<br>
<hr/>
Currently selected: {{ {selected_color:color} }}
<div style="border:solid 1px black; height:20px"
ng:style="{'background-color':color.name}">
</div>
</div>
</doc:source>
<doc:scenario>
it('should check ng:options', function(){
expect(binding('color')).toMatch('red');
select('color').option('0');
expect(binding('color')).toMatch('black');
using('.nullable').select('color').option('');
expect(binding('color')).toMatch('null');
});
</doc:scenario>
</doc:example>
*/
// 00001111100000000000222200000000000000000000003333000000000000044444444444444444000000000555555555555555550000000666666666666666660000000000000007777
var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/;
angularWidget('select', function(element){
this.descend(true);
this.directives(true);
var isMultiselect = element.attr('multiple'),
expression = element.attr('ng:options'),
onChange = expressionCompile(element.attr('ng:change') || ""),
match;
if (!expression) {
return inputWidgetSelector.call(this, element);
}
if (! (match = expression.match(NG_OPTIONS_REGEXP))) {
throw Error(
"Expected ng:options in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
" but got '" + expression + "'.");
}
var displayFn = expressionCompile(match[2] || match[1]),
valueName = match[4] || match[6],
keyName = match[5],
groupByFn = expressionCompile(match[3] || ''),
valueFn = expressionCompile(match[2] ? match[1] : valueName),
valuesFn = expressionCompile(match[7]),
// we can't just jqLite('<option>') since jqLite is not smart enough
// to create it in <select> and IE barfs otherwise.
optionTemplate = jqLite(document.createElement('option')),
optGroupTemplate = jqLite(document.createElement('optgroup')),
nullOption = false; // if false then user will not be able to select it
return function(selectElement){
// This is an array of array of existing option groups in DOM. We try to reuse these if possible
// optionGroupsCache[0] is the options with no option group
// optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
var optionGroupsCache = [[{element: selectElement, label:''}]],
scope = this,
model = modelAccessor(scope, element),
inChangeEvent;
// find existing special options
forEach(selectElement.children(), function(option){
if (option.value == '')
// User is allowed to select the null.
nullOption = {label:jqLite(option).text(), id:''};
});
selectElement.html(''); // clear contents
selectElement.bind('change', function(){
var optionGroup,
collection = valuesFn(scope) || [],
key = selectElement.val(),
tempScope = scope.$new(),
value, optionElement, index, groupIndex, length, groupLength;
// let's set a flag that the current model change is due to a change event.
// the default action of option selection will cause the appropriate option element to be
// deselected and another one to be selected - there is no need for us to be updating the DOM
// in this case.
inChangeEvent = true;
try {
if (isMultiselect) {
value = [];
for (groupIndex = 0, groupLength = optionGroupsCache.length;
groupIndex < groupLength;
groupIndex++) {
// list of options for that group. (first item has the parent)
optionGroup = optionGroupsCache[groupIndex];
for(index = 1, length = optionGroup.length; index < length; index++) {
if ((optionElement = optionGroup[index].element)[0].selected) {
if (keyName) tempScope[keyName] = key;
tempScope[valueName] = collection[optionElement.val()];
value.push(valueFn(tempScope));
}
}
}
} else {
if (key == '?') {
value = undefined;
} else if (key == ''){
value = null;
} else {
tempScope[valueName] = collection[key];
if (keyName) tempScope[keyName] = key;
value = valueFn(tempScope);
}
}
if (isDefined(value) && model.get() !== value) {
model.set(value);
onChange(scope);
}
scope.$root.$apply();
} finally {
tempScope = null; // TODO(misko): needs to be $destroy
inChangeEvent = false;
}
});
scope.$watch(function(scope) {
var optionGroups = {'':[]}, // Temporary location for the option groups before we render them
optionGroupNames = [''],
optionGroupName,
optionGroup,
option,
existingParent, existingOptions, existingOption,
values = valuesFn(scope) || [],
keys = values,
key,
groupLength, length,
fragment,
groupIndex, index,
optionElement,
optionScope = scope.$new(),
modelValue = model.get(),
selected,
selectedSet = false, // nothing is selected yet
isMulti = isMultiselect,
lastElement,
element;
try {
if (isMulti) {
selectedSet = new HashMap();
if (modelValue && isNumber(length = modelValue.length)) {
for (index = 0; index < length; index++) {
selectedSet.put(modelValue[index], true);
}
}
} else if (modelValue === null || nullOption) {
// if we are not multiselect, and we are null then we have to add the nullOption
optionGroups[''].push(extend({selected:modelValue === null, id:'', label:''}, nullOption));
selectedSet = true;
}
// If we have a keyName then we are iterating over on object. Grab the keys and sort them.
if(keyName) {
keys = [];
for (key in values) {
if (values.hasOwnProperty(key))
keys.push(key);
}
keys.sort();
}
// We now build up the list of options we need (we merge later)
for (index = 0; length = keys.length, index < length; index++) {
optionScope[valueName] = values[keyName ? optionScope[keyName]=keys[index]:index];
optionGroupName = groupByFn(optionScope) || '';
if (!(optionGroup = optionGroups[optionGroupName])) {
optionGroup = optionGroups[optionGroupName] = [];
optionGroupNames.push(optionGroupName);
}
if (isMulti) {
selected = !!selectedSet.remove(valueFn(optionScope));
} else {
selected = modelValue === valueFn(optionScope);
selectedSet = selectedSet || selected; // see if at least one item is selected
}
optionGroup.push({
id: keyName ? keys[index] : index, // either the index into array or key from object
label: displayFn(optionScope) || '', // what will be seen by the user
selected: selected // determine if we should be selected
});
}
optionGroupNames.sort();
if (!isMulti && !selectedSet) {
// nothing was selected, we have to insert the undefined item
optionGroups[''].unshift({id:'?', label:'', selected:true});
}
// Now we need to update the list of DOM nodes to match the optionGroups we computed above
for (groupIndex = 0, groupLength = optionGroupNames.length;
groupIndex < groupLength;
groupIndex++) {
// current option group name or '' if no group
optionGroupName = optionGroupNames[groupIndex];
// list of options for that group. (first item has the parent)
optionGroup = optionGroups[optionGroupName];
if (optionGroupsCache.length <= groupIndex) {
// we need to grow the optionGroups
optionGroupsCache.push(
existingOptions = [
existingParent = {
element: optGroupTemplate.clone().attr('label', optionGroupName),
label: optionGroup.label
}
]
);
selectElement.append(existingParent.element);
} else {
existingOptions = optionGroupsCache[groupIndex];
existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
// update the OPTGROUP label if not the same.
if (existingParent.label != optionGroupName) {
existingParent.element.attr('label', existingParent.label = optionGroupName);
}
}
lastElement = null; // start at the begining
for(index = 0, length = optionGroup.length; index < length; index++) {
option = optionGroup[index];
if ((existingOption = existingOptions[index+1])) {
// reuse elements
lastElement = existingOption.element;
if (existingOption.label !== option.label) {
lastElement.text(existingOption.label = option.label);
}
if (existingOption.id !== option.id) {
lastElement.val(existingOption.id = option.id);
}
if (!inChangeEvent && existingOption.selected !== option.selected) {
lastElement.prop('selected', (existingOption.selected = option.selected));
}
} else {
// grow elements
// jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
// in this version of jQuery on some browser the .text() returns a string
// rather then the element.
(element = optionTemplate.clone())
.val(option.id)
.attr('selected', option.selected)
.text(option.label);
existingOptions.push(existingOption = {
element: element,
label: option.label,
id: option.id,
selected: option.selected
});
if (lastElement) {
lastElement.after(element);
} else {
existingParent.element.append(element);
}
lastElement = element;
}
}
// remove any excessive OPTIONs in a group
index++; // increment since the existingOptions[0] is parent element not OPTION
while(existingOptions.length > index) {
existingOptions.pop().element.remove();
}
}
// remove any excessive OPTGROUPs from select
while(optionGroupsCache.length > groupIndex) {
optionGroupsCache.pop()[0].element.remove();
}
} finally {
optionScope.$destroy();
}
});
};
});
/**
* @workInProgress
* @ngdoc widget
* @name angular.widget.ng:include
*
* @description
* Fetches, compiles and includes an external HTML fragment.
*
* Keep in mind that Same Origin Policy applies to included resources
* (e.g. ng:include won't work for file:// access).
*
* @param {string} src angular expression evaluating to URL. If the source is a string constant,
* make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`.
* @param {Scope=} [scope=new_child_scope] optional expression which evaluates to an
* instance of angular.scope to set the HTML fragment to.
* @param {string=} onload Expression to evaluate when a new partial is loaded.
*
* @example
<doc:example>
<doc:source jsfiddle="false">
<select name="url">
<option value="examples/ng-include/template1.html">template1.html</option>
<option value="examples/ng-include/template2.html">template2.html</option>
<option value="">(blank)</option>
</select>
url of the template: <tt><a href="{{url}}">{{url}}</a></tt>
<hr/>
<ng:include src="url"></ng:include>
</doc:source>
<doc:scenario>
it('should load template1.html', function(){
expect(element('.doc-example-live ng\\:include').text()).
toBe('Content of template1.html\n');
});
it('should load template2.html', function(){
select('url').option('examples/ng-include/template2.html');
expect(element('.doc-example-live ng\\:include').text()).
toBe('Content of template2.html\n');
});
it('should change to blank', function(){
select('url').option('');
expect(element('.doc-example-live ng\\:include').text()).toEqual('');
});
</doc:scenario>
</doc:example>
*/
angularWidget('ng:include', function(element){
var compiler = this,
srcExp = element.attr("src"),
scopeExp = element.attr("scope") || '',
onloadExp = element[0].getAttribute('onload') || ''; //workaround for jquery bug #7537
if (element[0]['ng:compiled']) {
this.descend(true);
this.directives(true);
} else {
element[0]['ng:compiled'] = true;
return extend(function(xhr, element){
var scope = this,
changeCounter = 0,
releaseScopes = [],
childScope,
oldScope;
function incrementChange(){ changeCounter++;}
this.$watch(srcExp, incrementChange);
this.$watch(function(scope){
var newScope = scope.$eval(scopeExp);
if (newScope !== oldScope) {
oldScope = newScope;
incrementChange();
}
});
this.$watch(function(){return changeCounter;}, function(scope) {
var src = scope.$eval(srcExp),
useScope = scope.$eval(scopeExp);
while(releaseScopes.length) {
releaseScopes.pop().$destroy();
}
if (src) {
xhr('GET', src, null, function(code, response){
element.html(response);
if (useScope) {
childScope = useScope;
} else {
releaseScopes.push(childScope = scope.$new());
}
compiler.compile(element)(childScope);
scope.$eval(onloadExp);
}, false, true);
} else {
childScope = null;
element.html('');
}
});
}, {$inject:['$xhr.cache']});
}
});
/**
* @workInProgress
* @ngdoc widget
* @name angular.widget.ng:switch
*
* @description
* Conditionally change the DOM structure.
*
* @usageContent
* <any ng:switch-when="matchValue1">...</any>
* <any ng:switch-when="matchValue2">...</any>
* ...
* <any ng:switch-default>...</any>
*
* @param {*} on expression to match against <tt>ng:switch-when</tt>.
* @paramDescription
* On child elments add:
*
* * `ng:switch-when`: the case statement to match against. If match then this
* case will be displayed.
* * `ng:switch-default`: the default case when no other casses match.
*
* @example
<doc:example>
<doc:source>
<select name="switch">
<option>settings</option>
<option>home</option>
<option>other</option>
</select>
<tt>switch={{switch}}</tt>
</hr>
<ng:switch on="switch" >
<div ng:switch-when="settings">Settings Div</div>
<span ng:switch-when="home">Home Span</span>
<span ng:switch-default>default</span>
</ng:switch>
</code>
</doc:source>
<doc:scenario>
it('should start in settings', function(){
expect(element('.doc-example-live ng\\:switch').text()).toEqual('Settings Div');
});
it('should change to home', function(){
select('switch').option('home');
expect(element('.doc-example-live ng\\:switch').text()).toEqual('Home Span');
});
it('should select deafault', function(){
select('switch').option('other');
expect(element('.doc-example-live ng\\:switch').text()).toEqual('default');
});
</doc:scenario>
</doc:example>
*/
angularWidget('ng:switch', function (element) {
var compiler = this,
watchExpr = element.attr("on"),
changeExpr = element.attr('change'),
casesTemplate = {},
defaultCaseTemplate,
children = element.children(),
length = children.length,
child,
when;
if (!watchExpr) throw new Error("Missing 'on' attribute.");
while(length--) {
child = jqLite(children[length]);
// this needs to be here for IE
child.remove();
when = child.attr('ng:switch-when');
if (isString(when)) {
casesTemplate[when] = compiler.compile(child);
} else if (isString(child.attr('ng:switch-default'))) {
defaultCaseTemplate = compiler.compile(child);
}
}
children = null; // release memory;
element.html('');
return function(element){
var changeCounter = 0;
var childScope;
var selectedTemplate;
this.$watch(watchExpr, function(scope, value) {
element.html('');
if ((selectedTemplate = casesTemplate[value] || defaultCaseTemplate)) {
changeCounter++;
if (childScope) childScope.$destroy();
childScope = scope.$new();
childScope.$eval(changeExpr);
}
});
this.$watch(function(){return changeCounter;}, function() {
element.html('');
if (selectedTemplate) {
selectedTemplate(childScope, function(caseElement) {
element.append(caseElement);
});
}
});
};
});
/*
* Modifies the default behavior of html A tag, so that the default action is prevented when href
* attribute is empty.
*
* The reasoning for this change is to allow easy creation of action links with ng:click without
* changing the location or causing page reloads, e.g.:
* <a href="" ng:click="model.$save()">Save</a>
*/
angularWidget('a', function() {
this.descend(true);
this.directives(true);
return function(element) {
var hasNgHref = ((element.attr('ng:bind-attr') || '').indexOf('"href":') !== -1);
// turn <a href ng:click="..">link</a> into a link in IE
// but only if it doesn't have name attribute, in which case it's an anchor
if (!hasNgHref && !element.attr('name') && !element.attr('href')) {
element.attr('href', '');
}
if (element.attr('href') === '' && !hasNgHref) {
element.bind('click', function(event){
event.preventDefault();
});
}
};
});
/**
* @workInProgress
* @ngdoc widget
* @name angular.widget.@ng:repeat
*
* @description
* The `ng:repeat` widget instantiates a template once per item from a collection. The collection is
* enumerated with the `ng:repeat-index` attribute, starting from 0. Each template instance gets
* its own scope, where the given loop variable is set to the current collection item, and `$index`
* is set to the item index or key.
*
* Special properties are exposed on the local scope of each template instance, including:
*
* * `$index` – `{number}` – iterator offset of the repeated element (0..length-1)
* * `$position` – `{string}` – position of the repeated element in the iterator. One of:
* * `'first'`,
* * `'middle'`
* * `'last'`
*
* Note: Although `ng:repeat` looks like a directive, it is actually an attribute widget.
*
* @element ANY
* @param {string} repeat_expression The expression indicating how to enumerate a collection. Two
* formats are currently supported:
*
* * `variable in expression` – where variable is the user defined loop variable and `expression`
* is a scope expression giving the collection to enumerate.
*
* For example: `track in cd.tracks`.
*
* * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
* and `expression` is the scope expression giving the collection to enumerate.
*
* For example: `(name, age) in {'adam':10, 'amalie':12}`.
*
* @example
* This example initializes the scope to a list of names and
* then uses `ng:repeat` to display every person:
<doc:example>
<doc:source>
<div ng:init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]">
I have {{friends.length}} friends. They are:
<ul>
<li ng:repeat="friend in friends">
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
</li>
</ul>
</div>
</doc:source>
<doc:scenario>
it('should check ng:repeat', function(){
var r = using('.doc-example-live').repeater('ul li');
expect(r.count()).toBe(2);
expect(r.row(0)).toEqual(["1","John","25"]);
expect(r.row(1)).toEqual(["2","Mary","28"]);
});
</doc:scenario>
</doc:example>
*/
angularWidget('@ng:repeat', function(expression, element){
element.removeAttr('ng:repeat');
element.replaceWith(jqLite('<!-- ng:repeat: ' + expression + ' -->'));
var linker = this.compile(element);
return function(iterStartElement){
var match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/),
lhs, rhs, valueIdent, keyIdent;
if (! match) {
throw Error("Expected ng:repeat in form of '_item_ in _collection_' but got '" +
expression + "'.");
}
lhs = match[1];
rhs = match[2];
match = lhs.match(/^([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\)$/);
if (!match) {
throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" +
keyValue + "'.");
}
valueIdent = match[3] || match[1];
keyIdent = match[2];
var childScopes = [];
var childElements = [iterStartElement];
var parentScope = this;
this.$watch(function(scope){
var index = 0,
childCount = childScopes.length,
collection = scope.$eval(rhs),
collectionLength = size(collection, true),
fragment = document.createDocumentFragment(),
addFragmentTo = (childCount < collectionLength) ? childElements[childCount] : null,
childScope,
key;
for (key in collection) {
if (collection.hasOwnProperty(key)) {
if (index < childCount) {
// reuse existing child
childScope = childScopes[index];
childScope[valueIdent] = collection[key];
if (keyIdent) childScope[keyIdent] = key;
childScope.$position = index == 0
? 'first'
: (index == collectionLength - 1 ? 'last' : 'middle');
childScope.$eval();
} else {
// grow children
childScope = parentScope.$new();
childScope[valueIdent] = collection[key];
if (keyIdent) childScope[keyIdent] = key;
childScope.$index = index;
childScope.$position = index == 0
? 'first'
: (index == collectionLength - 1 ? 'last' : 'middle');
childScopes.push(childScope);
linker(childScope, function(clone){
clone.attr('ng:repeat-index', index);
fragment.appendChild(clone[0]);
// TODO(misko): Temporary hack - maybe think about it - removed after we add fragment after $digest()
// This causes double $digest for children
// The first flush will couse a lot of DOM access (initial)
// Second flush shuld be noop since nothing has change hence no DOM access.
childScope.$digest();
childElements[index + 1] = clone;
});
}
index ++;
}
}
//attach new nodes buffered in doc fragment
if (addFragmentTo) {
// TODO(misko): For performance reasons, we should do the addition after all other widgets
// have run. For this should happend after $digest() is done!
addFragmentTo.after(jqLite(fragment));
}
// shrink children
while(childScopes.length > index) {
// can not use $destroy(true) since there may be multiple iterators on same parent.
childScopes.pop().$destroy();
childElements.pop().remove();
}
});
};
});
/**
* @workInProgress
* @ngdoc widget
* @name angular.widget.@ng:non-bindable
*
* @description
* Sometimes it is necessary to write code which looks like bindings but which should be left alone
* by angular. Use `ng:non-bindable` to make angular ignore a chunk of HTML.
*
* Note: `ng:non-bindable` looks like a directive, but is actually an attribute widget.
*
* @element ANY
*
* @example
* In this example there are two location where a simple binding (`{{}}`) is present, but the one
* wrapped in `ng:non-bindable` is left alone.
*
* @example
<doc:example>
<doc:source>
<div>Normal: {{1 + 2}}</div>
<div ng:non-bindable>Ignored: {{1 + 2}}</div>
</doc:source>
<doc:scenario>
it('should check ng:non-bindable', function(){
expect(using('.doc-example-live').binding('1 + 2')).toBe('3');
expect(using('.doc-example-live').element('div:last').text()).
toMatch(/1 \+ 2/);
});
</doc:scenario>
</doc:example>
*/
angularWidget("@ng:non-bindable", noop);
/**
* @ngdoc widget
* @name angular.widget.ng:view
*
* @description
* # Overview
* `ng:view` is a widget that complements the {@link angular.service.$route $route} service by
* including the rendered template of the current route into the main layout (`index.html`) file.
* Every time the current route changes, the included view changes with it according to the
* configuration of the `$route` service.
*
* This widget provides functionality similar to {@link angular.widget.ng:include ng:include} when
* used like this:
*
* <ng:include src="$route.current.template" scope="$route.current.scope"></ng:include>
*
*
* # Advantages
* Compared to `ng:include`, `ng:view` offers these advantages:
*
* - shorter syntax
* - more efficient execution
* - doesn't require `$route` service to be available on the root scope
*
*
* @example
<doc:example>
<doc:source jsfiddle="false">
<script>
function MyCtrl($route) {
$route.when('/overview',
{ controller: OverviewCtrl,
template: 'partials/guide/dev_guide.overview.html'});
$route.when('/bootstrap',
{ controller: BootstrapCtrl,
template: 'partials/guide/dev_guide.bootstrap.auto_bootstrap.html'});
};
MyCtrl.$inject = ['$route'];
function BootstrapCtrl(){}
function OverviewCtrl(){}
</script>
<div ng:controller="MyCtrl">
<a href="overview">overview</a> |
<a href="bootstrap">bootstrap</a> |
<a href="undefined">undefined</a>
<br/>
The view is included below:
<hr/>
<ng:view></ng:view>
</div>
</doc:source>
<doc:scenario>
it('should load templates', function(){
element('.doc-example-live a:contains(overview)').click();
expect(element('.doc-example-live ng\\:view').text()).toMatch(/Developer Guide: Overview/);
element('.doc-example-live a:contains(bootstrap)').click();
expect(element('.doc-example-live ng\\:view').text()).toMatch(/Developer Guide: Initializing Angular: Automatic Initiialization/);
});
</doc:scenario>
</doc:example>
*/
angularWidget('ng:view', function(element) {
var compiler = this;
if (!element[0]['ng:compiled']) {
element[0]['ng:compiled'] = true;
return annotate('$xhr.cache', '$route', function($xhr, $route, element){
var template;
var changeCounter = 0;
this.$on('$afterRouteChange', function(){
changeCounter++;
});
this.$watch(function(){return changeCounter;}, function() {
var template = $route.current && $route.current.template;
if (template) {
//xhr's callback must be async, see commit history for more info
$xhr('GET', template, function(code, response) {
element.html(response);
compiler.compile(element)($route.current.scope);
});
} else {
element.html('');
}
});
});
} else {
compiler.descend(true);
compiler.directives(true);
}
});
/**
* @ngdoc widget
* @name angular.widget.ng:pluralize
*
* @description
* # Overview
* ng:pluralize is a widget that displays messages according to en-US localization rules.
* These rules are bundled with angular.js and the rules can be overridden
* (see {@link guide/dev_guide.i18n Angular i18n} dev guide). You configure ng:pluralize by
* specifying the mappings between
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
* plural categories} and the strings to be displayed.
*
* # Plural categories and explicit number rules
* There are two
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
* plural categories} in Angular's default en-US locale: "one" and "other".
*
* While a pural category may match many numbers (for example, in en-US locale, "other" can match
* any number that is not 1), an explicit number rule can only match one number. For example, the
* explicit number rule for "3" matches the number 3. You will see the use of plural categories
* and explicit number rules throughout later parts of this documentation.
*
* # Configuring ng:pluralize
* You configure ng:pluralize by providing 2 attributes: `count` and `when`.
* You can also provide an optional attribute, `offset`.
*
* The value of the `count` attribute can be either a string or an {@link guide/dev_guide.expressions
* Angular expression}; these are evaluated on the current scope for its binded value.
*
* The `when` attribute specifies the mappings between plural categories and the actual
* string to be displayed. The value of the attribute should be a JSON object so that Angular
* can interpret it correctly.
*
* The following example shows how to configure ng:pluralize:
*
* <pre>
* <ng:pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
* 'one': '1 person is viewing.',
* 'other': '{} people are viewing.'}">
* </ng:pluralize>
*</pre>
*
* In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
* specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
* would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
* other numbers, for example 12, so that instead of showing "12 people are viewing", you can
* show "a dozen people are viewing".
*
* You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted
* into pluralized strings. In the previous example, Angular will replace `{}` with
* <span ng:non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
* for <span ng:non-bindable>{{numberExpression}}</span>.
*
* # Configuring ng:pluralize with offset
* The `offset` attribute allows further customization of pluralized text, which can result in
* a better user experience. For example, instead of the message "4 people are viewing this document",
* you might display "John, Kate and 2 others are viewing this document".
* The offset attribute allows you to offset a number by any desired value.
* Let's take a look at an example:
*
* <pre>
* <ng:pluralize count="personCount" offset=2
* when="{'0': 'Nobody is viewing.',
* '1': '{{person1}} is viewing.',
* '2': '{{person1}} and {{person2}} are viewing.',
* 'one': '{{person1}}, {{person2}} and one other person are viewing.',
* 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
* </ng:pluralize>
* </pre>
*
* Notice that we are still using two plural categories(one, other), but we added
* three explicit number rules 0, 1 and 2.
* When one person, perhaps John, views the document, "John is viewing" will be shown.
* When three people view the document, no explicit number rule is found, so
* an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
* In this case, plural category 'one' is matched and "John, Marry and one other person are viewing"
* is shown.
*
* Note that when you specify offsets, you must provide explicit number rules for
* numbers from 0 up to and including the offset. If you use an offset of 3, for example,
* you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
* plural categories "one" and "other".
*
* @param {string|expression} count The variable to be bounded to.
* @param {string} when The mapping between plural category to its correspoding strings.
* @param {number=} offset Offset to deduct from the total number.
*
* @example
<doc:example>
<doc:source>
Person 1:<input type="text" name="person1" value="Igor" /><br/>
Person 2:<input type="text" name="person2" value="Misko" /><br/>
Number of People:<input type="text" name="personCount" value="1" /><br/>
<!--- Example with simple pluralization rules for en locale --->
Without Offset:
<ng:pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
'one': '1 person is viewing.',
'other': '{} people are viewing.'}">
</ng:pluralize><br>
<!--- Example with offset --->
With Offset(2):
<ng:pluralize count="personCount" offset=2
when="{'0': 'Nobody is viewing.',
'1': '{{person1}} is viewing.',
'2': '{{person1}} and {{person2}} are viewing.',
'one': '{{person1}}, {{person2}} and one other person are viewing.',
'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
</ng:pluralize>
</doc:source>
<doc:scenario>
it('should show correct pluralized string', function(){
expect(element('.doc-example-live .ng-pluralize:first').text()).
toBe('1 person is viewing.');
expect(element('.doc-example-live .ng-pluralize:last').text()).
toBe('Igor is viewing.');
using('.doc-example-live').input('personCount').enter('0');
expect(element('.doc-example-live .ng-pluralize:first').text()).
toBe('Nobody is viewing.');
expect(element('.doc-example-live .ng-pluralize:last').text()).
toBe('Nobody is viewing.');
using('.doc-example-live').input('personCount').enter('2');
expect(element('.doc-example-live .ng-pluralize:first').text()).
toBe('2 people are viewing.');
expect(element('.doc-example-live .ng-pluralize:last').text()).
toBe('Igor and Misko are viewing.');
using('.doc-example-live').input('personCount').enter('3');
expect(element('.doc-example-live .ng-pluralize:first').text()).
toBe('3 people are viewing.');
expect(element('.doc-example-live .ng-pluralize:last').text()).
toBe('Igor, Misko and one other person are viewing.');
using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live .ng-pluralize:first').text()).
toBe('4 people are viewing.');
expect(element('.doc-example-live .ng-pluralize:last').text()).
toBe('Igor, Misko and 2 other people are viewing.');
});
it('should show data-binded names', function(){
using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live .ng-pluralize:last').text()).
toBe('Igor, Misko and 2 other people are viewing.');
using('.doc-example-live').input('person1').enter('Di');
using('.doc-example-live').input('person2').enter('Vojta');
expect(element('.doc-example-live .ng-pluralize:last').text()).
toBe('Di, Vojta and 2 other people are viewing.');
});
</doc:scenario>
</doc:example>
*/
angularWidget('ng:pluralize', function(element) {
var numberExp = element.attr('count'),
whenExp = element.attr('when'),
offset = element.attr('offset') || 0;
return annotate('$locale', function($locale, element) {
var scope = this,
whens = scope.$eval(whenExp),
whensExpFns = {};
forEach(whens, function(expression, key) {
whensExpFns[key] = compileBindTemplate(expression.replace(/{}/g,
'{{' + numberExp + '-' + offset + '}}'));
});
scope.$watch(function() {
var value = parseFloat(scope.$eval(numberExp));
if (!isNaN(value)) {
//if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise,
//check it against pluralization rules in $locale service
if (!whens[value]) value = $locale.pluralCat(value - offset);
return whensExpFns[value](scope, element, true);
} else {
return '';
}
}, function(scope, newVal) {
element.text(newVal);
});
});
});
|
/*global Bridge, View, expandToken, i18n */
// Minimizer define
var escapeExpression = Handlebars.Utils.escapeExpression,
SafeString = Handlebars.SafeString,
// the galaxy note sometimes crashes when the user clicks on a number type field
_supportsInputNumber = navigator.userAgent.indexOf('SAMSUNG-SGH-I717') < 0;
function formField(options, content) {
var className = escapeExpression(options.hash.fieldClass) || '';
return new SafeString('<div class="form-field ' + className + '">' + content + '</div>');
}
function inputNumber(options, form, scope) {
if (!exports.isDesktop && _supportsInputNumber) {
var isiOS = Bridge.nativeHost ? (Bridge.nativeHost === 'iphone' || Bridge.nativeHost === 'ipad') : Phoenix.Data.isIphone || Phoenix.Data.isIpad;
// chrome and iOS like to format "number" fields with commas
// pattern will still bring up the numeric keyboard
if (!options.hash.type) {
options.hash.type = isiOS ? 'text' : 'number';
}
options.hash.pattern = "[0-9]*";
}
return inputText(options, form, scope);
}
function inputText(options, form, scope) {
options.hash.type = options.hash.type || 'text';
options.hash.id = options.hash.id ? Thorax.Util.expandToken(options.hash.id, scope) : _.uniqueId('txt');
var label = '',
labelClass = options.hash.labelClass === undefined? 'text-label' : options.hash.labelClass;
if (form && options.hash.label) {
label = i18n(options.hash.label);
options.hash.placeholder = options.hash.placeholder || label;
label = '<label class="' + labelClass + '" for="' + escapeExpression(options.hash.id) + '">' + label + '</label>';
}
var attributes = [];
for (var key in options.hash) {
var value = options.hash[key];
if (key === 'placeholder') {
value = i18n.call(scope, value);
}
if (key === 'disabled') {
if (value) {
attributes.push(key);
}
} else if (key !== 'label') {
attributes.push(key + '="' + escapeExpression(value) + '"');
}
}
var html = options.hash.type === 'textarea' ?
label + '\n<textarea ' + attributes.join(' ') + '></textarea>' :
label + '\n<input ' + attributes.join(' ') + '>';
if (form) {
return formField(options, html);
} else {
return new SafeString(html);
}
}
var helpers = {
nameAndAddress: function(nameAndAddress) {
return new SafeString(nameAndAddress.name + '<br>' + this.address(nameAndAddress.address));
},
address: function(address) {
if (!address) {
return;
}
var components = [address.street1];
if (address.street2 && address.street2) {
components.push(address.street2);
}
components.push(address.city + ', ' + address.state + ' ' + address.zip);
components = _.map(components, escapeExpression);
return new SafeString('<div>' + components.join('</div><div>') + '</div>');
},
'directions-link': function(address) {
// Android will default to current location, iOS < 6 needs 'Current Location' explicitly
// iOS 6 does not support passing the current location flag but the user can select
// this easily if we do not include it.
var start = '';
if ($.os.ios && parseFloat($.os.version) < 6) {
start = 'saddr=Current+Location&';
}
return 'http://maps.apple.com/maps?' + start + 'daddr=' + encodeURIComponent([
address.street1 + (address.street2 ? ' ' + address.street2 : ''),
address.city,
address.state,
address.zip
].join(','));
},
'search-location': function(search) {
if (search.city && search.state) {
return search.city + ', ' + search.state;
} else if (search.zipcode) {
return search.zipcode;
} else {
return i18n('your current location');
}
},
// show a loading indicator while an image is loading.
// param can either be image src or named params (src, alt, loadingText).
// content can a nested block or nothing for a simple image
'loaded-image': function(options, block) {
var src = _.isString(options) && options;
var alt = "";
var loadingText = "Loading...";
if (options && options.hash) {
// if parameters were named
src = (options.hash.src && options.hash.src) || src;
alt = options.hash.alt || alt;
loadingText = options.hash.loadingText || loadingText;
block = options;
}
// functions to return content to display
var id;
function getLoading() {
id = _.uniqueId('img_');
if (options.hash && options.hash.hidden) {
return '<div id="' + id + '"></div>';
}
return '<div id="' + id + '" class="loading-image">' + Thorax.Util.getTemplate('inline-loading-indicator')({label: loadingText}) + '</div>';
}
var content = options && options.fn && options.fn(this) || '<img src="' + src + '" alt="' + alt + '">';
// write the image/inner block or a loading indicator to be replaced when image is loaded
if (!src || !content) {
// if the value is empty, assume the template will be re-rendered later
return new SafeString(getLoading());
} else {
var img = new Image();
img.onload = function() {
// reset the element
$('#' + id).replaceWith(content);
};
img.onerror = function() {
$('#' + id).remove();
exports.trackError('image-error', src);
};
img.src = src;
if (img.complete) {
// it's already loaded
return new SafeString(content);
} else {
// onload will reset
return new SafeString(getLoading());
}
}
},
date: function(date) {
if (_.isString(date)) {
// Manually parse iso8061 date strings as not all implementations support this
var iso8061 = /(\d{4})(?:-(\d{2})(?:-(\d{2})))/.exec(date);
if (iso8061) {
var year = iso8061[1],
month = iso8061[2],
day = iso8061[3];
// Manually format The short dates numerically for now. We may want to revisit
// this when examinging proper i18n
if (!month) {
return year;
}
if (!day) {
return i18n.call({month: month, year: year}, '{{month}}/{{year}}', {'expand-tokens': true});
}
date = new Date(year, parseInt(month, 10)-1, day);
}
}
if (date && !_.isDate(date)) {
date = new Date(date);
}
return date && date.toLocaleDateString();
},
hasCCExpirationDate: function(options) {
if (!exports.checkout.isStoreCard(this.type)) {
return options.fn(this);
}
},
isMweb: function(options) {
if (!Bridge.nativeHost) {
return options.fn(this);
} else {
return options.inverse(this);
}
},
isAndroid: function(options) {
if (Bridge.nativeHost === 'android') {
return options.fn(this);
} else {
return options.inverse(this);
}
},
isiPhone: function(options) {
if (Bridge.nativeHost === 'iphone') {
return options.fn(this);
} else {
return options.inverse(this);
}
},
isiPad: function(options) {
if (Bridge.nativeHost === 'ipad') {
return options.fn(this);
} else {
return options.inverse(this);
}
},
ifHasBundle: function(options) {
if (this.bundleConfig && this.bundleConfig.components && this.bundleConfig.components.length) {
return options.fn(this);
} else {
return options.inverse(this);
}
},
bundleNameLink: function() {
var link = "<a href='" + Phoenix.View.url("ip/" + this.itemId) + "'>" + this.name + "</a>";
return new SafeString(i18n.call({name: link}, "Your {{name}} includes", {'expand-tokens': true}));
},
'star-rating': function(rating) {
rating = parseFloat(rating);
if (isNaN(rating) || rating < 0) {
return;
}
var rounded = Math.round(rating * 10),
tenths = rounded % 10;
rounded = rounded/10;
var stars = [1,2,3,4,5].map(function(index) {
return '<span class="star' + (index <= rounded ? ' rated' : (index === Math.floor(rounded+1) && tenths) ? ' partial partial' + tenths : '') + '"></span>';
}).join('');
return new SafeString('<div class="stars">'
+ stars
+ '<span class="rating">' + i18n.call({rating: rounded}, '{{rating}} star rating', {'expand-tokens': true}) + '</span>'
+ '</div>');
},
'input-tagged-text': function(options) {
var className = options.hash['class'] || '',
tagClass = options.hash['tag-class'] || '',
tagText = options.hash['tag-text'] || '';
delete options.hash['class'];
delete options.hash['tag-class'];
delete options.hash['tag-text'];
var html =
'<div class="tagged-text ' + className + '">'
+ inputText(options, false, this)
+ '<button type="button" class="' + tagClass + '">' + i18n.call(this, tagText) + '</button>'
+ '</div>';
return new SafeString(html);
},
'view-form': function(options) {
var className = (options.hash && escapeExpression(options.hash['class'])) || '';
return '<form action="#" class="' + className + '">'
+ options.fn(this)
+ '<input class="hidden-submit" type="submit" value="' + i18n('Submit') + '">'
+ '</form>';
},
'form-section': function(options) {
var className = (options.hash && escapeExpression(options.hash['class'])) || '';
return '<div class="form-section ' + className + '">'
+ '<div class="form-layout">'
+ options.fn(this)
+ '</div>'
+ '</div>';
},
'form-checkbox': function(options) {
var label = escapeExpression(options.hash.label),
name = escapeExpression(options.hash.name),
value = escapeExpression(options.hash.value),
id = escapeExpression(options.hash.id) || _.uniqueId('txt'),
input = '<input type="checkbox" id="' + id + '"' + (name ? ' name="' + name + '"' : '') + (value ? ' value="' + value + '"' : '');
// Used to signal that the checked boolean value should be serialized as opposed to the string field value.
if (options.hash.onOff) {
input += ' data-onOff="true"';
}
input += '>',
label = '<label class="checkbox-label" for="' + id + '">' + i18n(label) + '</label>';
var nativeHost = Bridge.nativeHost;
return formField(options, nativeHost === 'iphone' || nativeHost === 'ipad' ? label + '\n' + input : input + label);
},
'form-textarea': function(options) {
options.hash.type = 'textarea';
return inputText(options, true, this);
},
'form-text': function(options) {
return inputText(options, true, this);
},
'form-email': function(options) {
options.hash.type = 'email';
return inputText(options, true, this);
},
'form-password': function(options) {
options.hash.type = 'password';
options.hash.autocorrect = "off";
options.hash.autocomplete = "off";
options.hash.autocapitalize = "off";
return inputText(options, true, this);
},
'form-number': function(options) {
return inputNumber(options, true, this);
},
'form-telephone': function(options) {
options.hash.type = 'tel';
return inputText(options, true, this);
},
'input-text': function(options) {
return inputText(options, false, this);
},
'input-number': function(options) {
return inputNumber(options, false, this);
},
'radio-item': function(options) {
var label = escapeExpression(options.hash.label),
name = escapeExpression(options.hash.name),
value = escapeExpression(options.hash.value),
selected = options.hash.selected,
disabled = options.hash.disabled,
editUrl = escapeExpression(options.hash.editUrl) || '',
id = escapeExpression(options.hash.id) || _.uniqueId('txt'),
itemClass = options.hash.itemClass ? ' ' + escapeExpression(options.hash.itemClass) : '',
labelClass = options.hash.labelClass ? ' ' + escapeExpression(options.hash.labelClass) : '';
if (disabled) {
labelClass = 'disabled' + labelClass;
}
if (editUrl) {
editUrl = '<div class="edit"><a href="' + editUrl + '" class="button">' + i18n('Edit') + '</a></div>';
}
if (!label) {
label = options.fn(_.extend({radioId: id}, this));
}
if (label && !options.hash.customLabel) {
label = '<label' + (labelClass ? ' class="' + labelClass + '"' : '') + ' for="' + id + '">' + i18n(label) + '</label>';
} else if (label) {
label = '<span class="radio-item-descriptor' + (disabled ? ' disabled' : '') + '">' + label + '</span>';
}
return new SafeString(
'<div class="radio-item item' + itemClass + '">'
+ '<div>'
+ '<input type="radio" id="' + id + '"'
+ (name ? ' name="' + name + '"' : '')
+ (selected ? ' checked' : '')
+ (disabled ? ' disabled' : '')
+ (value ? ' value="' + value + '"' : '')
+ '>'
+ '</div>'
+ label
+ editUrl
+ '</div>');
},
'variant-list': function(items) {
var rtn = "";
if (items && items.length) {
rtn += '<div class="variant-list">';
_.each(items, function(item) {
rtn += '<span class="variant">';
rtn += item.name;
rtn += ': ';
// look for i18n values 'variant.{type}.{value}
var key = "variant." + item.type + "." + item.value;
var value = i18n(key);
if (value === key) {
// no match - use the item variant data as the value
rtn += item.value;
} else {
rtn += value;
}
rtn += "</span>";
});
rtn += "</div>";
}
return new SafeString(rtn);
},
'bundle-component-display': function(bundleConfigComponents) {
//hide item name if they are all the same and have variants
var output = '';
bundleConfigComponents.forEach(function(component){
component.componentChildren.forEach(function(child) {
var rowOutput = child.itemName + (child.variants ? '<br>' : '');
if (child.variants && child.variants.length) {
rowOutput += '<span class="variant-list">';
child.variants.forEach(function(variant) {
rowOutput += '<span class="variant">' + variant.name + ': ' + variant.value + '</span>';
});
rowOutput += '</span>';
}
if (rowOutput !== '') {
output += '<li class="bundle-item">' + rowOutput + '</li>';
}
});
});
return new SafeString(output);
},
'encodeURIComponent': function(value) {
return new SafeString(encodeURIComponent(value));
},
'flag-list': function(flags) {
if (!flags || _.keys(flags).length === 0) {
return '';
}
var output = '<div class="flags">';
_.each(flags, function(flag) {
output += '<div class="flag ' + flag.type + '">' + flag.name + '</div>';
});
return new SafeString(output + '</div>');
},
'dasherize': exports.Util.dasherize,
'location-collection': function(options) {
var collection = options.data.view.collection;
options = options.hash;
var loadingText = options['loading-text'];
var ret = '<div class="' + (options['class'] || 'collection') + '">';
if (loadingText) {
if (!collection.isPopulated() || options['show-loading-indicator']) {
ret += '<div class="collection-loading">'
+ Thorax.Util.getTemplate('inline-loading-indicator')({})
+ '<div>' + i18n(loadingText) + '</div>'
+ '</div>';
}
}
return new SafeString(ret + '</div>');
},
openTarget: function(block) {
return Phoenix.openTarget;
}
};
for(var helper_name in helpers) {
View[helper_name] = helpers[helper_name];
Handlebars.registerHelper(helper_name, helpers[helper_name]);
}
View.url = Handlebars.helpers.url;
Handlebars.registerHelper('options-list', function(currentValue, options) {
var ret = '',
isArray = _.isArray(options);
_.each(options, function(display, data) { // display is the value in the source hash. data is the key
var value;
if (_.isArray(display)) {
value = display[0];
display = display[1];
} else {
value = isArray ? display : data;
}
ret += '<option value="' + escapeExpression(value) + '"';
if (data === currentValue) {
ret += ' selected';
}
ret += '>' + escapeExpression(i18n(display)) + '</option>';
});
return new SafeString(ret);
});
Handlebars.registerHelper('desktop', function(options) {
return exports.isDesktop ? options.fn(this) : options.inverse(this);
}); |
import React from 'react'
// import Navbar from './components/navbar/Navbar'
import AppRouter from './router/AppRouter';
const App = () => {
return (
<AppRouter/>
)
}
export default App;
|
'use strict';
class User {
constructor(lastName, middleName, firstName, username, password, birthDate, idPassport, idRole) {
this.lastName = lastName;
this.middleName = middleName;
this.firstName = firstName;
this.username = username;
this.password = password;
this.birthDate = birthDate;
this.idPassport = idPassport;
this.idRole = idRole;
}
} |
import { findbyId } from '../common/utils.js';
import adventures from '../data/adventures-data.js';
const test = QUnit.test;
test('test to see if we can return an object from an id', function(assert) {
//Arrange
// Set up your parameters and expectations
const party = {
id: 'party',
title: 'After-party time!',
map: {
top: '35%',
left: '30%'
},
image: 'party.jpg',
audio: '',
description: 'It\'s time for a bout after-party. Your roller derby idol is there. What do you do?',
choices: [{
id: 'interrupt',
description: 'Interrupt their conversation and tell them how amazing you think they are.',
result: 'I guess you got your point across! It\'s super awkward, but maybe less weird because you got it out of the way. Next time, try and act cool.',
bp: 20,
cp: 10
}, {
id: 'creep',
description: 'Get creepy about it and "happen" to be in every conversation they are in.',
result: 'Dude, you need to let it go.',
bp: -20,
cp: -20
}, {
id: 'stay-cool',
description: 'Just hang out with your friends. Maybe they will come over and say hi!',
result: 'Nice work holding a boundary! Your derby idols are people too.',
bp: -20,
cp: 30
}]
};
//Act
// Call the function you're testing and set the result to a const
const partyObjectFromId = findbyId(adventures, 'party');
//Assert
// Make assertions about what is expected valid result
assert.deepEqual(partyObjectFromId, party);
});
|
import SuperFeature from './superFeature.js'
import DateHelper from '../../helper/dateHelper.js'
class AgreementFeature extends SuperFeature {
static getIcon() {
return 'images/mapIcons/agreement.png'
}
static getCaptionInfo(info) {
return `${info.kind}. ${info.place}`
}
static getPopupInfo(feature) {
const info = feature.get('info')
return {
icon: this.getIcon(),
date: info.startDate,
caption: this.getCaptionInfo(info),
}
}
static getHtmlInfo(info) {
window.CURRENT_ITEM = info
const dates = DateHelper.twoDateToStr2(info.startDateStr, info.endDateStr)
const html = `<div class="agreement-info panel-info">
<h1>${info.place}. ${info.kind}</h1>
<h2>${dates}</h2>
<table class="table table-sm table-borderless" id="table-info">
<tbody>
<tr><td>Участники</td><td>${info.player1}</td></tr>
<tr><td></td><td>${info.player2}</td></tr>
</tbody>
</table>
<p>${info.results}</p>
<div class="source-info">
<a target='_blank' rel='noopener noreferrer' href=${info.srcUrl}>Источник информации</a>
</div>
</div>
`
return html
}
static fillAgreementFeature(info) {
return info.agreements.map((elem) => {
return {
...elem,
icon: AgreementFeature.getIcon(),
popupFirst: elem.kind,
popupSecond: DateHelper.twoDateToStr(elem.startDate, elem.endDate),
popupThird: elem.place,
oneLine: elem.kind,
}
})
}
}
module.exports = AgreementFeature
|
var Cucumber = require('cucumber');
var Given = Cucumber.Given;
Given(/^I go to the (homepage|url)$/, function(page) {
browser.url(page == 'homepage' ? '/' : url);
});
|
import React, { useState } from 'react';
import Layout from '../layout';
import classes from './contact.module.css';
import ContactForm from './contactForm';
import {contactUtil} from '../../util-functions';
const { encode, validate } = contactUtil;
const Contact = () => {
const [submitted, setSubmitted] = useState(false);
const [failed, setFailed] = useState(false);
const [showErrorText, setShowErrorText] = useState(false);
const [formData, setFormData] = useState({
name: {
fieldName: 'name',
value: '',
type: 'text',
placeholder: 'name',
valid: false,
rules: {
required: true,
min: 2,
max: 50,
},
},
email: {
fieldName: 'email',
value: '',
type: 'email',
placeholder: 'email',
valid: false,
rules: {
required: true,
min: 6,
max: 50,
isProbablyEmail: true,
},
},
msg: {
fieldName: 'msg',
value: '',
type: 'textarea',
placeholder: '...',
valid: false,
rules: {
required: true,
min: 2,
max: 10000,
},
},
});
const [formIsValid, setFormIsValid] = useState(false);
const clearForm = () => {
const copy = { ...formData };
for (let i in copy) {
copy[i].value = '';
copy[i].valid = false;
}
setFormData(copy);
};
const handleChange = (e, id) => {
setShowErrorText(false);
const copy = { ...formData };
const relevantField = { ...copy[id] };
relevantField.value = e.target.value;
relevantField.valid = validate(relevantField.value, relevantField.rules);
copy[id] = relevantField;
let formValid = true;
for (let i in copy) {
formValid = copy[i].valid && formValid;
}
setFormIsValid(formValid);
setFormData(copy);
};
const handleSubmit = (e) => {
e.preventDefault();
if (!formIsValid) {
setShowErrorText(true);
return;
}
setSubmitted(false);
setFailed(false);
const data = {};
for (let key in formData) {
data[key] = formData[key].value;
}
fetch('/', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: encode({ 'form-name': 'contact-stats', ...data }),
})
.then(() => {
setSubmitted(true);
clearForm();
})
.catch((error) => {
// console.log('Error: ', error);
setFailed(true);
});
};
return (
<Layout>
<section className={classes.section}>
<ContactForm
formData={formData}
classes={classes}
showErrorText={showErrorText}
handleSubmit={handleSubmit}
handleChange={handleChange}
/>
{submitted ? <p className={classes.formSuccess}>Thank You!</p> : null}
{failed ? (
<p className={classes.formFail}>Something went wrong.</p>
) : null}
</section>
</Layout>
);
};
export default Contact;
|
import React from "react";
import "./ChatterBox.css";
const ChatterBox = (props) => {
return (
<div className="chat">
<div>{props.username.replace(/</g, "<").replace(/>/g, ">")}</div>
<div>{props.roomname.replace(/</g, "<").replace(/>/g, ">")}</div>
<div>{props.date}</div>
<div>{props.text.replace(/</g, "<").replace(/>/g, ">")}</div>
</div>
);
};
export default ChatterBox;
|
import styled from 'styled-components';
export const AboutSec = styled.div`
padding: 25px 0px;
background: linear-gradient(to top, rgba(0, 0, 0, 0.7), rgb(0, 43, 43));
@media screen and (max-width: 1000px) {
background: linear-gradient(to top, rgba(0, 0, 0, 0.7), rgb(0, 43, 43));
}
`
export const AboutRow = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
@media screen and (max-width: 800px) {
flex-direction: column;
justify-content: start;
}
`
export const DescriptionContainer = styled.div`
width: 50%;
display: flex;
flex-direction: column;
justify-content: center;
@media screen and (max-width: 1000px) {
width: 100%;
}
`
export const Heading = styled.h1`
font-size: 35px;
margin-bottom: 30px;
font-weight: 300;
letter-spacing: 2px;
/* color: rgb(165,165,5); */
color: rgba(255,255,255,0.8);
@media screen and (max-width: 1000px) {
margin: 20px 0px;
font-size: 25px;
margin-bottom: 10px;
}
`
export const ParagraphDesc = styled.p`
font-size: 24px;
width: 90%;
line-height: 35px;
letter-spacing: 2px;
color: rgb(195,195,195);
font-weight: bold;
font-family: 'Open Sans', sans-serif;
font-weight: 200;
@media screen and (max-width: 1000px) {
width: 100%;
line-height: 35px;
margin-bottom: 25px;
margin-top: 25px;
}
`
export const ImageWrapper = styled.div`
display: flex;
justify-self: flex-start;
height: 600px;
width: 600px;
@media screen and (max-width: 1000px) {
display: none;
/* margin-left: -80px; */
/* justify-content: center; */
/* align-items: center; */
/* height: 200px; */
/* width: 300px; */
/* z-index: 1; */
}
`;
export const ToContact = styled.a`
text-decoration: none;
@media screen and (max-width: 900px) {
margin-bottom: 60px;
z-index: 2;
}
&:hover {
color: black;
}
` |
const { response } = require('express');
const ObjectId = require('mongoose').Types.ObjectId;
const Empresa = require('../models/empresa');
const validarAgencia = async (req, res = response, next) => {
const empresa =req.empresa;
const agencia_id = req.header('x-agencia');
try {
if (!agencia_id) {
return res.status(400).json({
ok: false,
msg: 'La agencia es requerida'
});
}
if (!ObjectId.isValid(agencia_id)) {
return res.status(400).json({
ok: false,
msg: 'La agencia no es válida'
});
}
const agencia = empresa.agencias.id(agencia_id);
if (!agencia) {
return res.status(400).json({
ok: false,
msg: agencia.msg
});
}
req.agencia = agencia;
} catch (error) {
console.log('Error al validar agencia', error);
return res.status(400).json({
ok: false,
msg: 'Favor contacte al administrador ' + error
});
}
next();
}
module.exports = {
validarAgencia
} |
document.querySelector("main#main").remove();
const name = "Richard"
const newHeader = document.createElement('h1');
newHeader.id = 'victory';
newHeader.innerHTML = `${name} is the champion`; |
var obj = {
name: 'John Doe',
greet: function () {
console.log(`Hello ${this.name}`)
}
}
obj.greet()
obj.name = 'Abhishek'
// The call method overrides the name property of the object.
obj.greet.call({ name: 'Jane Doe' })
// The apply method does the same.
obj.greet.apply({ name: 'Jane Doe' })
obj.greet()
// The only difference would be when a function has a parameter involved
// obj.greet.call({ name: 'Jane Doe'}, param, param , param); comma seperated list
// obj.greet.apply({ name: 'Jane Doe'}, [param, param , param]); array of parameters
|
'use strict';
import LivingThing from './LivingThing';
import Eukaryota from './Eukaryota';
import Animal from './Animal';
import Bilateral from './Bilateral';
class Vertebrate extends Bilateral {
}
export default Vertebrate; |
import theme from "./variables";
export default {
drawerListItem: {
alignItems: "center",
borderColor: theme.green,
borderLeftWidth: 5,
flexDirection: "row",
paddingVertical: 25,
paddingHorizontal: 10,
},
drawerListItemEven: {
backgroundColor: "rgba(0, 0, 0, 0.1)",
},
drawerListItemIcon: {
color: theme.green,
marginRight: 10,
},
drawerListItemFocused: {
borderColor: theme.red,
},
drawerListItemIconFocused: {
color: theme.red,
},
};
|
class Student{
constructor(sId,sName){
this.id=sName;
this.name=sId;
this.school='chandaikona M.L high school'
}
}
const student1=new Student('hasan',22);
const student2= new Student('arshad',21 );
console.log(student1,student2); |
import React from "react";
import {View, Text, StyleSheet} from "react-native";
import {NextButton} from "../components/NextButton";
import {useSelector} from "react-redux";
export const IMTScreen = ({navigation}) => {
const toAgeScreen = () => {
navigation.navigate("AgeScreen", {
headerTitle: ''
});
}
const IMT = useSelector(state => state.main.itmIndex);
return (
<View style={styles.container}>
<Text style={styles.title}>
Ваш ИМТ = <Text style={styles.imt}>{IMT.toFixed(1)}</Text>
</Text>
<Text style={styles.text}>
Индекс массы тела (ИМТ) — величина, позволяющая оценить степень соответствия массы человека и его роста
и тем самым косвенно судить о том, является ли масса недостаточной, нормальной или избыточной.
</Text>
{IMT < 25 ?
(<Text style={styles.recommendation}>
У Вас нормальный вес
</Text>) :
(<Text style={styles.recommendation}>
Вам рекомендовано сбросить вес
</Text>)}
<NextButton handler={toAgeScreen} text={'Дальше'}/>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "flex-start",
width: "100%"
},
title: {
marginTop: 100,
marginBottom: 50,
fontSize: 24,
fontWeight: 'bold'
},
text: {
width: '80%',
textAlign: 'center'
},
recommendation: {
width: '80%',
textAlign: 'center',
marginTop: 150,
fontWeight: 'bold',
fontSize: 24
},
imt:{
color: '#d92626'
}
});
|
import { combineReducers } from "redux"
import {
REQUEST_MATCHES,
RECEIVE_MATCHES,
SHOW_ALL_RESULTS,
SHOW_RESULT,
} from "./constants"
function matchesReducer(
state = {
isFetching: false,
matches: [],
},
action,
) {
switch (action.type) {
case REQUEST_MATCHES:
return {
...state,
isFetching: true,
}
case RECEIVE_MATCHES:
return {
...state,
isFetching: false,
matches: action.payload.map(match => {
match.show = false
return match
}),
}
case SHOW_RESULT:
return {
...state,
matches: state.matches.map(
match =>
match.match_id === action.id ? { ...match, show: true } : match,
),
}
case SHOW_ALL_RESULTS:
return {
...state,
matches: state.matches.map(match => ({ ...match, show: true })),
}
default:
return state
}
}
const rootReducer = combineReducers({
matchesReducer,
})
export default rootReducer
|
// import { setTimeout } from 'timers';
(function () {
'use strict';
const ethereumjsUtil = require('ethereumjs-util');
const nodes = require('./js/nodes');
const ethTokens = require('./tokens/ethtokens.json');
const EthereumTx = require('ethereumjs-tx');
angular
.module('app')
.controller('etherWalletController', etherWalletController);
etherWalletController.$inject = ['$scope', '$http'];
function etherWalletController($scope, $http) {
var vm = this;
$scope.myEtherWallet = { tx: {} };
$scope.myEtherWallet.privateKey = null;
$scope.myEtherWallet.show = false;
$scope.nodes = [{
"id":"Myether",
"name":"[ETH]myetherapi.com"
},{
"id":"RopstenInfura",
"name":"[Ropsten]infura.io"
}]
$scope.apiNode = '';
$scope.unlockWallet = function () {
var privateKey = $scope.myEtherWallet.privateKey;
if(!$scope.apiNode) {
toastr.error('请选择节点');
return;
}
if (privateKey) {
var privBuff = new Buffer(privateKey, 'hex');
if (ethereumjsUtil.isValidPrivate(privBuff)) {
var address = ethereumjsUtil.privateToAddress(privBuff);
// address = ethereumjsUtil.addHexPrefix(address);
$scope.myEtherWallet.wallet = new MyWallet(privBuff, address, $scope.apiNode);
$scope.myEtherWallet.show = true;
}
}
}
$scope.genTx = function () {
if ($scope.myEtherWallet.tx) {
var tx = $scope.myEtherWallet.tx;
$scope.myEtherWallet.wallet.genTransaction(tx.toAddress, tx.gasLimit, tx.amount, (error, genTxData) => {
$scope.showTxHash = false;
$scope.txHash = null;
$scope.showSendTransaction = true;
$scope.genTxData = {
rawJson: JSON.stringify(genTxData.rawJson),
signedTx: genTxData.signedTx
};
// $scope.$apply();
})
}
}
$scope.sendTx = function () {
if ($scope.showSendTransaction && $scope.genTxData.signedTx) {
$scope.myEtherWallet.wallet.sendTransaction($scope.genTxData.signedTx, (error, txHash) => {
if(error) {
toastr.error(error.toString());
return;
}
$scope.showTxHash = true;
$scope.txHash = txHash;
$scope.$apply();
toastr.success('send transaction success!');
$scope.myEtherWallet.wallet.setBalance();
});
}
}
class MyWallet {
constructor(privateKey, address, nodeName) {
this.privateKey = privateKey;
this.wallet = null;
this.address = ethereumjsUtil.bufferToHex(address);
this.ethNode = new nodes[nodeName]({ Web3: Web3, $http: $http });
this.explorerTX = this.ethNode.explorerTX;
this.init();
}
init() {
$scope.myEtherWallet.address = this.address;
this.ethNode.getBalance(this.address, (error, balance) => {
$scope.myEtherWallet.balance = balance;
$scope.$apply();
});
$scope.myEtherWallet.tokens = [];
ethTokens.forEach((token) => {
this.addToken(token);
});
}
addToken(token) {
token.balance = 'loading';
token.name = token.symbol;
$scope.myEtherWallet.tokens.push(token);
this.setToken(token);
}
setToken(token) {
this.ethNode.tokenbalance(this.address, token, (error, balance) => {
token.balance = balance;
$scope.$apply();
});
}
setBalance() {
this.ethNode.getBalance(this.address, (error, balance) => {
$scope.myEtherWallet.balance = balance;
$scope.$apply();
});
}
genTransaction(to, gasLimit, amount, cb) {
const privateKey = ethereumjsUtil.toBuffer(this.privateKey);
gasLimit = '0x' + new BigNumber(gasLimit).toString(16);
var amountWei = this.ethNode.web3.toWei(amount, 'ether');
amount = '0x' + new BigNumber(amountWei).toString(16);
const gasPrice = '0x' + this.ethNode.web3.eth.gasPrice.toString(16);
var count = this.ethNode.web3.eth.getTransactionCount(this.address);
var nonce = '0x' + new BigNumber(count).toString(16);
const txParams = {
nonce: nonce,
gasPrice: gasPrice,
gasLimit: gasLimit,
to: to,
value: amount,
data: null,
// EIP 155 chainId - mainnet: 1, ropsten: 3
chainId: this.ethNode.networkId
}
const tx = new EthereumTx(txParams);
tx.sign(privateKey);
const serializedTx = tx.serialize();
var rawTx = '0x' + serializedTx.toString('hex');
cb(null, { rawJson: txParams, signedTx: rawTx });
}
sendTransaction(rawTx, cb) {
this.ethNode.sendRawTransaction(rawTx, cb);
}
}
}
})(); |
import React, { useContext, useState } from 'react'
import { StyleSheet, View } from 'react-native'
import { ThemeContext } from '../context/ThemeContext'
import Container from './Container'
import Icon from './icons/Icon'
import Text from './Text'
const CheckSection = () => {
const [ isChecked, setIsChecked ] = useState(false)
const { isDark } = useContext(ThemeContext)
return (
<Container
style={styles.checkSection(isChecked, isDark)}
disablePress={false}
onPress={() => setIsChecked(!isChecked)}>
<Container style={styles.iconContainer}>
<Icon name="profile" fill="#fff" />
</Container>
<View style={styles.textContainer}>
<Text style={styles.title}>Personal Account</Text>
<Text style={styles.subTitle(isDark)}>**** - **** - 9876</Text>
</View>
<Container style={styles.checkContainer(isChecked, isDark)}>
<Icon
name="check"
stroke={isDark ? isChecked ? '#fff' : '#2D303E' : isChecked ? '#fff' : 'rgba(174, 175, 178, 0)'}
width={16}
/>
</Container>
</Container>
)
}
export default CheckSection
const styles = StyleSheet.create({
checkSection: (isChecked, isDark) => ({
padding: 20,
flexDirection: 'row',
justifyContent: 'space-between',
borderWidth: 1,
borderColor: isDark ? (isChecked ? '#08A0F7' : '#252836') : isChecked ? '#08A0F7' : '#F4F5F9'
}),
iconContainer: {
flex: 1,
backgroundColor: '#FFBF47',
alignItems: 'center',
justifyContent: 'center',
padding: 10,
borderRadius: 13,
marginVertical: 0
},
textContainer: { flex: 10, marginHorizontal: 14 },
title: { fontSize: 14 },
subTitle: (isDark) => ({ fontSize: 12, color: isDark ? 'rgba(255,255,255,0.50)' : 'rgba(0,0,0,0.50)' }),
checkContainer: (isChecked, isDark) => ({
flex: 1,
backgroundColor: isDark
? isChecked ? '#08A0F7' : '#2D303E'
: isChecked ? '#08A0F7' : 'rgba(174, 175, 178, 0.50)',
alignItems: 'center',
justifyContent: 'center',
padding: 10,
borderRadius: 100,
marginVertical: 0,
borderColor: isDark
? isChecked ? '#08A0F7' : 'rgba(255,255,255,0.15)'
: isChecked ? '#08A0F7' : 'rgba(0,0,0,0.30)',
borderWidth: 1
})
})
|
const Joi = require('@hapi/joi');
const { objectId } = require('./custom.validation');
const createInvitation = {
body: Joi.object().keys({
email: Joi.string().required().email(),
role: Joi.string().required().valid('developer', 'admin'),
}),
};
const getUsers = {
query: Joi.object().keys({
sortBy: Joi.string(),
limit: Joi.number().integer(),
page: Joi.number().integer(),
}),
};
const getInvitation = {
params: Joi.object().keys({
invitationId: Joi.string().custom(objectId),
}),
};
module.exports = {
createInvitation,
getUsers,
getInvitation,
};
|
import { createAction, NavigationActions, Storage, delay } from '../utils'
import * as evalutionService from '../services/evalution'
export default {
namespace: 'evalution',
state: {
EvaList: [], //需求的评价
myEvalutionList:[], //我的收到的评价
userEvaList:[], //通过用户CODE查询的用户评价
},
reducers: {
updateState(state, { payload }) {
return { ...state, ...payload }
},
},
effects: {
*addEvalution({ payload, callback }, { call, put }) {
yield call(evalutionService.addEvalution, payload)
if (callback) callback()
},
*findEvaByBcode({ payload }, { call, put }) {
const EvaList = yield call(evalutionService.findEvaByBcode, payload.requireCode)
yield put(createAction('updateState')({ EvaList }))
},
*findMyEvalution({ payload }, { call, put }) {
const myEvalutionList = yield call(evalutionService.findMyEvalution, payload)
yield put(createAction('updateState')({ myEvalutionList }))
},
*findUserEva({ payload }, { call, put }) {
const userEvaList = yield call(evalutionService.findUserEva, payload)
yield put(createAction('updateState')({ userEvaList }))
},
},
subscriptions: {
setup({ dispatch }) {
dispatch({ type: 'loadStorage' })
},
},
}
|
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import {getHomework, sendHomework} from "../../actions/eduActions";
import {Link} from "react-router-dom";
import { reduxForm, Field } from "redux-form";
import {renderError, renderTextAreaField } from "../../utils/renderUtils";
class Solution extends Component {
static propTypes = {
getHomework: PropTypes.func.isRequired,
homework: PropTypes.object,
};
componentDidMount = () => {
this.props.getHomework();
};
getHomework = () => {
const { handleSubmit, error } = this.props;
const homework = this.props.homework;
if (homework) {
return (
<div className="container text-center">
<h3>{homework.description}</h3>
<form onSubmit={handleSubmit}>
<fieldset className="form-group">
<Field placeholder="Your solution here..." name="solution" label="" component={renderTextAreaField}
/>
</fieldset>
<fieldset className="form-group">
{ renderError(error) }
<Link className='m-2 btn btn-outline-secondary' to='/course-my-homework'>Back</Link>
<button type="submit" className="btn btn-primary">Save</button>
</fieldset>
</form>
</div>
);
}
return null;
};
render = () => {
return (
<div>
<h1 className="m-4">Solution</h1>
<hr/>
{this.getHomework()}
</div>
);
}
}
const mapStateToProps = (state) => {
return {
homework: state.edu.homework,
initialValues: {'solution': localStorage.getItem('solution')}
}
};
export default connect(mapStateToProps, { getHomework } )(reduxForm({
form: "update_homework",
onSubmit: sendHomework,
})(Solution)); |
import {startApp} from './main.js'
window.addEventListener('load', () => {startApp()})
|
const categories = [
{
name:"All ",
value:'our-foods',
},
{
name:"BBQs",
value:'bbqs',
},
{
name:"Breads",
value:'breads',
},
{
name:"Burgers",
value:'burgers',
},
{
name:"Chocolates",
value:'chocolates',
},
{
name:"Desserts",
value:'desserts',
},
{
name:"Drinks",
value:'drinks',
},
{
name:"Fried Chicken",
value:'fried-chicken',
},
{
name:"Ice Cream",
value:'ice-cream',
},
{
name:"Pizzas",
value:'pizzas',
},
{
name:"Porks",
value:'porks',
},
{
name:"Sandwiches",
value:'sandwiches',
},
{
name:"Sausages",
value:'sausages',
},
{
name:"Steaks",
value:'steaks',
}
]
export default categories |
/**
* This skill only supports two intents:
*
* - LatestPodcast: get information about the latest episode of a podcast
* - PlayLatestPodcast: play the latest episode of a podcast
*
* The podcasts file holds the dictionary of all podcasts that Alexa should
* know about.
*/
const parser = require('rss-parser');
const podcasts = require('./podcasts.json');
// Taken from: https://twitter.com/rauchg/status/712799807073419264?lang=en
const leftPad = (v, n, c = '0') =>
String(v).length >= n ? '' + v : (String(c).repeat(n) + v).slice(-n);
/**
* Retrieves the latest episode of a podcast
*
* @param {string} rssURL - URL of the RSS feed
* @param {function} callback - callback(err, latestEpisode)
*/
const getLatestEpisode = (rssURL, callback) => {
parser.parseURL(rssURL, (err, parsed) =>
callback(err, parsed && parsed.feed.entries[0])
);
};
/**
* Creates a text response for the LatestPodcast intent
*
* @param {string} podcastName - Name of the podcast
* @param {string} episode - Episode object
*/
const episodeResponse = (podcastName, episode) => {
let pubDate = new Date(episode.pubDate);
pubDate =
leftPad(pubDate.getMonth() + 1, 2) + leftPad(pubDate.getDate() + 1, 2);
const pubDateText = `<say-as interpret-as="date">????${pubDate}</say-as>`;
return `The latest episode from ${podcastName} is titled: ${episode.title}.
The description says: ${episode.contentSnippet
.trim()
.replace(
/[|&;$%@"<>()+,]/g,
''
)}. It was released on ${pubDateText}`.replace(/\n/gm, '');
};
/**
* LatestPodcast intent handler
*
* Emits a ':tell' response
*/
function latestIntent() {
const podcastName = this.event.request.intent.slots.PodcastName.value;
const rssURL = podcasts[podcastName];
if (!rssURL) {
return this.emit(':tell', "I don't know about that podcast");
}
getLatestEpisode(rssURL, (err, episode) => {
if (err) {
console.log(err.message);
return this.emit(':tell', "I'm sorry. Something went wrong.");
}
return this.emit(':tell', episodeResponse(podcastName, episode));
});
}
/**
* PlayLatestPodcast intent handler
*
* Emits a ':tell' resposne and returns a directive
* to start playing audio from a URL
*/
function playIntent() {
const podcastName = this.event.request.intent.slots.PodcastName.value;
const rssURL = podcasts[podcastName];
if (!rssURL) {
return this.emit(':tell', "I don't know about that podcast");
}
getLatestEpisode(rssURL, (err, episode) => {
if (err) {
console.log(err.message);
return this.emit(':tell', "I'm sorry. Something went wrong.");
}
this.response
.speak(`Playing the latest episode of ${podcastName}`)
.audioPlayerPlay(
'REPLACE_ALL',
episode.enclosure.url.replace('http', 'https'), // hack,
episode.enclosure.url.replace('http', 'https'),
null,
0
);
return this.emit(':responseReady');
});
}
/**
* Tells Alexa to stop playing audio
*/
function stopIntent() {
this.response.speak('Bye bye.').audioPlayerStop();
this.emit(':responseReady');
}
/**
* Intent -> Handlers definition
*/
module.exports = {
LatestPodcast: latestIntent,
PlayLatestPodcast: playIntent,
'AMAZON.PauseIntent': stopIntent,
'AMAZON.ResumeIntent': playIntent,
'AMAZON.CancelIntent': stopIntent,
'AMAZON.StopIntent': stopIntent,
SessionEndedRequest: function() {
console.log('Session ended');
},
ExceptionEncountered: function() {
console.log('\n******************* EXCEPTION **********************');
console.log('\n' + JSON.stringify(this.event.request, null, 2));
this.callback(null, null);
},
Unhandled: function() {
this.response.speak(
"Sorry, I could not understand what you've just said."
);
this.emit(':responseReady');
}
};
|
const webpack = require('webpack')
const helpers = require('./helpers')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const AssetsPlugin = require('assets-webpack-plugin')
const TsConfigPathsPlugin = require('awesome-typescript-loader').TsConfigPathsPlugin
const DashboardPlugin = require('webpack-dashboard/plugin');
const HMR = helpers.hasProcessFlag('hot')
const TS_CONFIG = helpers.root('tsconfig.json')
const TS_LOADERS = (HMR ? 'hmr!' : '') + 'awesome-typescript-loader!angular2-template-loader'
const METADATA = {
title: 'Yang2',
baseUrl: '/',
isDevServer: helpers.isWebpackDevServer()
}
module.exports = function (options) {
const IS_PROD = options.env === 'production'
return {
metadata: METADATA,
entry: {
'vendor': './src/vendor.ts',
'main': './src/main.ts'
},
resolve: {
extensions: ['', '.ts', '.js', '.json'],
root: helpers.root('src'),
alias: {app: helpers.root('src/app')},
modulesDirectories: ['node_modules'],
plugins: [ new TsConfigPathsPlugin({tsconfig: TS_CONFIG}) ]
},
resolveLoader: {
modules: ['node_modules', helpers.root('config/web_loaders')]
},
module: {
loaders: [
{
test: /\.ts$/,
loaders: TS_LOADERS
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /\.scss$/,
loaders: [
ExtractTextPlugin.extract({loader: 'style!css?sourceMap!postcss!sass'})
],
// This loader is only for
exclude: [helpers.root('src/app/components')]
},
{
test: /\.scss$/,
loaders: [
'to-string-loader',
'css-loader?sourceMap',
'postcss-loader',
'sass-loader'
]
},
{
test: /\.html$/,
loader: 'raw-loader',
exclude: [helpers.root('src/index.html')]
},
{
test: /\.(jpg|png|gif)$/,
loader: 'file-loader'
}
]
},
plugins: [
new DashboardPlugin(),
new AssetsPlugin({
path: helpers.root('dist'),
filename: 'webpack-assets.json',
prettyPrint: true
}),
new ForkCheckerPlugin(),
new webpack.ContextReplacementPlugin(
/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
helpers.root('src')
),
new CopyWebpackPlugin([
{from: helpers.root('public'), to: ''}
]),
new HtmlWebpackPlugin({
template: 'src/index.ejs',
chunksSortMode: 'dependency'
}),
new ExtractTextPlugin('css/[name].[hash].css')
],
node: {
global: 'window',
crypto: 'empty',
process: true,
module: false,
clearImmediate: false,
setImmediate: false
},
sassLoader: {
includePaths: [helpers.root('src')]
},
postcss: function () {
return [require('postcss-cssnext')]
},
}
}
|
/** @jsx jsx */
import { jsx, Styled } from "theme-ui"
import { useState, useEffect } from "react"
import { motion } from "framer-motion"
import { IoIosRefresh } from "react-icons/io"
import { FaAngleLeft } from "react-icons/fa"
import { Link } from "gatsby"
import Layout from "../../components/layout"
import SEO from "../../components/seo"
import Footer from "../../components/footer"
import Match from "../../components/livescore/match"
const sanityClient = require("@sanity/client")
const client = sanityClient({
projectId: "0jt5x7hu",
dataset: "main",
useCdn: true,
})
const weekdays = [
"Söndag",
"Måndag",
"Tisdag",
"Onsdag",
"Torsdag",
"Fredag",
"Lördag",
]
const months = [
"januari",
"februari",
"mars",
"april",
"maj",
"juni",
"juli",
"augusti",
"september",
"oktober",
"november",
"december",
]
const query = `*[_type == "matchday" && status == "next"]{..., matches[]
{...,
away{team->{"fullName": fullName,"name": name, "id": _id}, goals},
home{team->{"fullName": fullName,"name": name, "id": _id}, goals},
events[]{...,
player->{"fullName": fullName, "name": name,}, assist->{"fullName": fullName, "name": name,}}}
}`
const LivescoreNextPage = () => {
const [matches, setMatches] = useState([])
const [dates, setDates] = useState([])
const [loading, setLoading] = useState(false)
const [refresh, setRefresh] = useState(false)
useEffect(() => {
client.fetch(query).then(matches => {
const start = new Date(matches[0].start)
const end = new Date(matches[0].end)
if (start.getDate() === end.getDate()) {
setDates([
[
weekdays[start.getDay()],
`${start.getDate()}`,
months[start.getMonth()],
],
])
} else {
setDates([
[
weekdays[start.getDay()],
`${start.getDate()}`,
months[start.getMonth()],
],
[weekdays[end.getDay()], `${end.getDate()}`, months[end.getMonth()]],
])
}
setMatches(matches[0].matches)
setLoading(false)
})
}, [refresh])
function hack() {
setLoading(true)
setRefresh(!refresh)
}
return (
<Layout>
<SEO
title="Livescore"
description="Följ Sillyfootball:s omgångar live."
/>
{loading ? (
<div>
<br></br>
</div>
) : (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{
delay: 0.2,
duration: 0.3,
}}
>
{matches.length > 0 &&
dates.map((d, i) => (
<div key={i} sx={{ display: "grid", mt: -4 }}>
<div
sx={{
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
>
{i === 0 && (
<Link to="/livescore/" style={{ textDecoration: "none" }}>
<div sx={{ color: "darkgrey", mt: 2 }}>
<FaAngleLeft size={25} />
</div>
</Link>
)}
<Styled.h2
sx={{
textAlign: "center",
mx: 6,
}}
>
{d[0]} {d[1]} {d[2]}
</Styled.h2>
{i === 0 && <div sx={{ color: "background", mx: 6 }}></div>}
</div>
{/* </div> */}
{matches.map((x, xi) => {
const xdate = new Date(x.start)
const day = xdate.getDate().toString()
if (d[1] === day)
return <Match key={xi} index={xi} match={x} />
return null
})}
</div>
))}
<div sx={{ textAlign: "center", my: 7 }}>
<button
sx={{
appearance: "none",
border: "none",
bg: "primary",
color: "background",
borderRadius: 2,
py: 3,
":active, :after": {
color: "primary",
bg: "background",
opacity: 1,
transition: `0s`,
},
}}
onClick={() => hack()}
>
<IoIosRefresh size={40} />
</button>
</div>
{matches.length > 0 && <Footer />}
</motion.div>
)}
</Layout>
)
}
export default LivescoreNextPage
|
import React, { Suspense, useState } from 'react';
import MyComponent from './Component/Mycomponent';
function App() {
const [currentstate,setstate]=useState({
info:"my first react app",
para:"It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English"
})
const langeventchange=()=>{
setstate({
info:"أول تطبيق رد فعل",
para:"هناك حقيقة مثبتة منذ زمن طويل وهي أن المحتوى المقروء لصفحة ما سيلهي القارئ عن التركيز على الشكل الخارجي للنص أو شكل توضع الفقرات في الصفحة التي يقرأها. الهدف من استخدام لوريم إيبسوم أنه يحتوي على توزيع طبيعي -إلى حد ما- للأحرف ، بدلاً من "
})
}
return (
<Suspense fallback="loading">
<MyComponent data={currentstate.info} data2={currentstate.para} changeHandler={langeventchange} />
</Suspense>
);
}
export default App;
|
// spread : 객체나 배열을 펼칠 수 있음
/*
const slime = {
name: '슬라임'
};
const cuteSlime = {
name: '슬라임',
attribute: 'cute'
};
const purpleCuteSlime = {
name: '슬라임',
attribute: 'cute',
color: 'purple'
};
console.log(slime);
console.log(cuteSlime);
console.log(purpleCuteSlime);
*/
const slime = {
name: '슬라임'
};
const cuteSlime = {
...slime,
attribute: 'cute'
};
const purpleCuteSlime = {
...cuteSlime,
color: 'purple'
};
console.log(slime);
console.log(cuteSlime);
console.log(purpleCuteSlime);
//rest는 반대로 여러개를 함축 가능
const { color, ...rest } = purpleCuteSlime;
console.log(color);
console.log(rest); |
//活动签到
function activitySign() {
//活动id
var taId=$("#taId").val();
//用户名
var tasName=$("#tasName").textbox('getValue');
//手机号码
var tasphone=$("#tasphone").textbox('getValue');
$.ajax({
type : "POST",
dataType : 'json',
url : ctx + '/TbActivitySign/sign?taId=' + taId
+ "&tasName=" + tasName+"&tasphone="+tasphone,
success : function(data) {
if (data["code"] == '100') {
$.messager.alert('提示', data["message"], 'warning');
} else {
$.messager.alert('提示', data["message"], 'warning');
}
}
});
}
$(function(){
$('.addcls')
.linkbutton(
{
text : ' 签 到 ',
plain : true,
iconCls : 'icon-add'
});
});
|
const defaultIfBlockProps = {
selectedCondition: 0,
data: [
{
label: "Nieuw conditioneel blok",
conditions: [],
children: [],
},
],
};
const defaultIfBlockData = {
label: "Nieuw conditioneel blok",
conditions: [],
children: [],
};
const defaultIfConditionData = {
variable: "",
condition: "==",
value: "",
};
export {defaultIfBlockProps, defaultIfBlockData, defaultIfConditionData};
|
/**
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.provide('audioCat.ui.toolbar.item.TimeScoreItem');
goog.require('audioCat.action.ActionType');
goog.require('audioCat.ui.toolbar.item.Item');
goog.require('audioCat.ui.toolbar.item.Item.createIcon');
goog.require('audioCat.ui.visualization.events');
goog.require('goog.dom.classes');
goog.require('goog.events');
/**
* A toolbar item for switching between displaying audio with score or with
* time units.
* @param {!audioCat.utility.DomHelper} domHelper Facilitates DOM interactions.
* @param {!audioCat.state.command.CommandManager} commandManager Manages
* command history. Executes undos and redos.
* @param {!audioCat.state.editMode.EditModeManager} editModeManager Manages the
* current edit mode.
* @param {!audioCat.ui.visualization.TimeDomainScaleManager}
* timeDomainScaleManager Manages the time-domain scale as well as whether
* to display with bars or time units.
* @param {!audioCat.action.ActionManager} actionManager Manages actions.
* @param {!audioCat.ui.tooltip.ToolTip} toolTip Displays tips sometimes after
* user hovers over something.
* @constructor
* @extends {audioCat.ui.toolbar.item.Item}
*/
audioCat.ui.toolbar.item.TimeScoreItem = function(
domHelper,
commandManager,
editModeManager,
timeDomainScaleManager,
actionManager,
toolTip) {
/**
* Manages the scale at which we display the time of audio as well as when we
* change from displaying using bars to using time or vice versa.
* @private {!audioCat.ui.visualization.TimeDomainScaleManager}
*/
this.timeDomainScaleManager_ = timeDomainScaleManager;
/**
* The internals of this item.
* @private {!Element}
*/
this.internals_ = domHelper.createElement('div');
goog.dom.classes.add(this.internals_, goog.getCssName('barTimeItemInternal'));
goog.base(
this, domHelper, editModeManager, actionManager, toolTip, '', undefined,
true,
'Switch whether to display the grid based on time or a 4/4 signature.');
/**
* The element that contains the text noting the signature.
* @private {!Element}
*/
this.timeSignatureTextContainer_ = domHelper.createElement('div');
domHelper.appendChild(this.internals_, this.timeSignatureTextContainer_);
goog.dom.classes.add(
this.timeSignatureTextContainer_,
goog.getCssName('timeSignatureTextContainer'));
var numberOfBeatsContainer = domHelper.createElement('div');
goog.dom.classes.add(
numberOfBeatsContainer, goog.getCssName('numberOfBeatsContainer'));
domHelper.appendChild(
this.timeSignatureTextContainer_, numberOfBeatsContainer);
/**
* Contains the portion of the time signature that is the number of beats.
* @private {!Element}
*/
this.numberOfBeatsContainer_ = numberOfBeatsContainer;
var signatureDividingBarContainer = domHelper.createElement('div');
goog.dom.classes.add(
signatureDividingBarContainer,
goog.getCssName('signatureDividingBarContainer'));
domHelper.appendChild(
this.timeSignatureTextContainer_, signatureDividingBarContainer);
/**
* Contains the dividing bar portion of the time signature.
* @private {!Element}
*/
this.signatureDividingBarContainer_ = signatureDividingBarContainer;
var beatUnitContainer = domHelper.createElement('div');
goog.dom.classes.add(
beatUnitContainer,
goog.getCssName('beatUnitContainer'));
domHelper.appendChild(
this.timeSignatureTextContainer_, beatUnitContainer);
/**
* Contains the beat unit portion of the time signature.
* @private {!Element}
*/
this.beatUnitContainer_ = beatUnitContainer;
this.displayProperTimeSignature_();
/**
* Covers this item with an image that indicates that the time signature is
* disabled.
* @private {!Element}
*/
this.coverImage_ = audioCat.ui.toolbar.item.Item.createIcon(
domHelper, 'images/forbid.svg');
goog.dom.classes.add(
this.coverImage_,
goog.getCssName('barTimeDisplayForbidCover'));
domHelper.appendChild(this.internals_, this.coverImage_);
goog.events.listen(timeDomainScaleManager,
audioCat.ui.visualization.events.SCORE_TIME_SWAPPED,
this.handleScoreTimeSwapped_, false, this);
this.domHelper.listenForPress(this.getDom(), this.handlePress_, false, this);
// Prevent this item from maintaining its active state after being clicked on.
// For instance, the item might not maintain its gradient after being clicked.
this.setClickableOnActive(true);
// Determine the proper aria label.
this.setAriaLabel(this.determineAriaLabel_());
};
goog.inherits(
audioCat.ui.toolbar.item.TimeScoreItem, audioCat.ui.toolbar.item.Item);
/**
* Handles what happens when you click on this button. Specifically, swaps
* whether we are displaying audio with bars or with time units.
* @private
*/
audioCat.ui.toolbar.item.TimeScoreItem.prototype.handlePress_ = function() {
/** @type {!audioCat.action.track.ToggleSignatureTimeGridAction} */ (
this.actionManager.retrieveAction(
audioCat.action.ActionType.TOGGLE_SIGNATURE_TIME_GRID)).doAction();
};
/**
* Displays the proper time signature.
* @private
*/
audioCat.ui.toolbar.item.TimeScoreItem.prototype.displayProperTimeSignature_ =
function() {
// Update the displayed time signature when it is allowed to change.
var signatureTempoManager =
this.timeDomainScaleManager_.getSignatureTempoManager();
var domHelper = this.domHelper;
domHelper.setTextContent(this.numberOfBeatsContainer_,
String(signatureTempoManager.getBeatsInABar()));
domHelper.setTextContent(this.beatUnitContainer_,
String(signatureTempoManager.getBeatUnit()));
};
/**
* Visualizes whether we display audio using bars or time.
* @private
*/
audioCat.ui.toolbar.item.TimeScoreItem.prototype.handleScoreTimeSwapped_ =
function() {
// Changes whether we are active.
this.setActiveState(this.timeDomainScaleManager_.getDisplayAudioUsingBars());
// Set the proper label.
this.setAriaLabel(this.determineAriaLabel_());
};
/**
* Determines the proper aria label at the moment.
* @return {string} The proper label.
* @private
*/
audioCat.ui.toolbar.item.TimeScoreItem.prototype.determineAriaLabel_ =
function() {
// TODO(chizeng): Update the aria time signature if the time signature is
// ever allowed to change.
var label;
if (this.timeDomainScaleManager_.getDisplayAudioUsingBars()) {
label = 'Display with time units.';
} else {
var tempoManager = this.timeDomainScaleManager_.getSignatureTempoManager();
label = 'Display with ' + tempoManager.getBeatsInABar() + ' ' +
tempoManager.getBeatUnit() + ' time signature.';
}
if (!this.getEnabledState()) {
label = 'Disabled ' + label + ' button.';
}
return label;
};
/** @override */
audioCat.ui.toolbar.item.TimeScoreItem.prototype.getInternalDom = function() {
return this.internals_;
};
|
var Jungongjiesuan = new Vue({
el : '#Jungongjiesuan',
data :{
adminId : $("#adminid").val(),
deptId : $("#deptid").val(),
xiangmutext:'',
jiesuan : {},
jiesuanlist : [],
jiesuanzhuangtailist:[],
jiesuanqingkuanglist:[],
xiangmuId:'',
jungongjiesuanId:'',
editFlag : 0, // 0:新增,1:修改
show : false, // 显示列表是否有数据
pageIndex : 1,
pageSize : 10,
pageCount : 0,
recordCount : 0,
inputPageIndexValue : "",
},
created : function() {
var _this = this;
_this.bindJungongjiesuanList();
_this.bindJiesuanzhuangtaiList();
_this.bindJiesuanqingkuangList();
},
methods : {
getjgsj : function(){
this.jiesuan.jiesuanwanchengtime = $("#jgsj").val();
},
bindJiesuanzhuangtaiList:function (){
var _this = this;
layer.open({type:3});
$.post('/jiesuanzhuangtai/find_all',{
text:"",
rdm:Math.random()
},function(ppData){
layer.closeAll("loading");
if(ppData!=null){
if(ppData.result == '1'){
_this.jiesuanzhuangtailist =ppData.resultContent;
}else{
layer.alert(ppData.message);
}
}
},"json");
},
bindJiesuanqingkuangList:function (){
var _this = this;
layer.open({type:3});
$.post('/jiesuanqingkuang/find_all',{
text:"",
rdm:Math.random()
},function(ppData){
layer.closeAll("loading");
if(ppData!=null){
if(ppData.result == '1'){
_this.jiesuanqingkuanglist =ppData.resultContent;
}else{
layer.alert(ppData.message);
}
}
},"json");
},
bindJungongjiesuanList:function (){
var _this = this;
layer.open({type:3});
$.post("/jungongjiesuan/findjiesuanBydeptId",{
xiangmuname :_this.xiangmutext,
deptid : _this.deptId,
pageindex : _this.pageIndex,
pagesize : _this.pageSize,
rdm : Math.random()
},function(ppData){
layer.closeAll("loading");
if (ppData != null){
if(ppData.result == "1"){
var data=ppData.resultContent;
if(data.JiesuanList.length > 0){
_this.show = true;
_this.jiesuanlist=data.JiesuanList;
var PageInfo = data.PageInfo;
_this.pageIndex = PageInfo.pageIndex;
_this.recordCount = PageInfo.recordCount;
_this.pageCount = PageInfo.pageCount;
}else {
_this.show = false;
}
}else{
layer.alert(ppData.message);
}
}
},"json");
},
toAdd : function (ppXiangmuName,ppXiangmuId){
$('#editJungongjiesuanModal').modal();
$("#myModalLabel_jungongjiesuan").html(ppXiangmuName);
this.editFlag = 0;
this.jiesuan = {};
this.xiangmuId=ppXiangmuId;
$("#shifoujizhang_y").prop('checked',false);
$("#shifoujizhang_n").prop('checked',false);
this.jiesuan.shifoujizhang='0';
},
addJiesuan:function () {
var _this = this;
if(_this.deptId!='1'){
_this.jiesuan.jiesuanpifujine=0;
_this.jiesuan.jieyushangjiaojine=0;
}
if(_this.checkInputData()){
layer.open({type:3});
$.post('/jungongjiesuan/add',{
adminId : _this.adminId,
xiangmuId:_this.xiangmuId,
jiesuanzhuangtaiid:$.trim(_this.jiesuan.jiesuanzhuangtaiid),
jiesuanwanchengtime:$.trim(_this.jiesuan.jiesuanwanchengtime),
jiesuanqingkuangid:$.trim(_this.jiesuan.jiesuanqingkuangid),
shifoujizhang:$.trim(_this.jiesuan.shifoujizhang),
jiesuanpifuwenhao:$.trim(_this.jiesuan.jiesuanpifuwenhao),
jiesuanpifujine:$.trim(_this.jiesuan.jiesuanpifujine),
jieyushangjiaojine:$.trim(_this.jiesuan.jieyushangjiaojine),
random : Math.random()
},function(ppData){
if(ppData != null){
layer.closeAll("loading");
if(ppData.result == "1"){
layer.open({
time:1000,
btn:[],
content:"新增成功!",
});
$("#editJungongjiesuanModal").modal("hide");
_this.bindJungongjiesuanList();
}else{
layer.alert(ppData.message);
}
}
},"json");
}
},
perpareToModifyJiesuan :function (ppXiangmuName,ppJungongjiesuanId,ppxiangmuid){
$('#editJungongjiesuanModal').modal();
$("#myModalLabel_jungongjiesuan").html(ppXiangmuName);
this.editFlag = 1;
this.jiesuan = {};
this.jungongjiesuanId=ppJungongjiesuanId;
this.xiangmuId=ppxiangmuid;
this.bindJungongjiesuan();
},
bindJungongjiesuan:function (){
var _this = this;
layer.open({type:3});
$.post('/jungongjiesuan/find_one', {
jungongjiesuanId : _this.jungongjiesuanId,
rdm : Math.random()
},function(ppData) {
layer.closeAll("loading");
if(ppData != null){
if(ppData.result == "1"){
var data = ppData.resultContent;
_this.jiesuan = data;
}else{
layer.alert(ppData.message);
}
}
},"json");
},
modifyJiesuan:function (){
var _this = this;
if(_this.checkInputData()){
layer.open({type:3});
$.post('/jungongjiesuan/modify',{
adminId : _this.adminId,
xiangmuId:_this.xiangmuId,
jungongjiesuanId : _this.jungongjiesuanId,
jiesuanzhuangtaiid:$.trim(_this.jiesuan.jiesuanzhuangtaiid),
jiesuanwanchengtime:$.trim(_this.jiesuan.jiesuanwanchengtime),
jiesuanqingkuangid:$.trim(_this.jiesuan.jiesuanqingkuangid),
shifoujizhang:$.trim(_this.jiesuan.shifoujizhang),
jiesuanpifuwenhao:$.trim(_this.jiesuan.jiesuanpifuwenhao),
jiesuanpifujine:$.trim(_this.jiesuan.jiesuanpifujine),
jieyushangjiaojine:$.trim(_this.jiesuan.jieyushangjiaojine),
random : Math.random()
},function(ppData){
if(ppData != null){
layer.closeAll("loading");
if(ppData.result == "1"){
layer.open({
time:1000,
btn:[],
content:"修改成功!",
});
$("#editJungongjiesuanModal").modal("hide");
_this.bindJungongjiesuanList();
}else{
layer.alert(ppData.message);
}
}
},"json");
}
},
toDelete:function (jungongjiesuanid){
var _this = this;
layer.confirm("确定删除该条竣工结算和决算情况吗?",{
btn : ['是','否']
},function(){
layer.open({type:3});
$.post("/jungongjiesuan/delete", {
jungongjiesuanId : jungongjiesuanid,
random : Math.random()
}, function(ppData) {
if (ppData != null) {
layer.closeAll("loading");
if(ppData.result != "1"){
layer.alert(ppData.message);
}else{
layer.open({
time:1000,
btn:[],
content:"删除成功!",
});
_this.bindJungongjiesuanList();
}
}
},"json");
})
},
//检查输入信息
checkInputData : function() {
var _this = this;
var jiesuanzhuangtaiid = !_this.jiesuan.jiesuanzhuangtaiid ? "" : $.trim(_this.jiesuan.jiesuanzhuangtaiid);
if("" == jiesuanzhuangtaiid&&_this.deptId!="1"){
layer.alert("请选择竣工结算状态!");
return false;
}
var jiesuanqingkuangid = !_this.jiesuan.jiesuanqingkuangid ? "" : $.trim(_this.jiesuan.jiesuanqingkuangid);
if("" == jiesuanqingkuangid&&_this.deptId!="1"){
layer.alert("请选择竣工决算情况!");
return false;
}
var shifoujizhang = !_this.jiesuan.shifoujizhang ? "" : $.trim(_this.jiesuan.shifoujizhang);
if("" == shifoujizhang&&_this.deptId!="1"){
layer.alert("请选择决算是否记账和登记资产!");
return false;
}
var jiesuanpifuwenhao = !_this.jiesuan.jiesuanpifuwenhao ? "" : $.trim(_this.jiesuan.jiesuanpifuwenhao);
if("" == jiesuanpifuwenhao&&_this.deptId=="1"){
layer.alert("请填写两级决算批复文号!");
return false;
}
var jiesuanpifujine = !_this.jiesuan.jiesuanpifujine ? "" : $.trim(_this.jiesuan.jiesuanpifujine);
if("" == jiesuanpifujine&&_this.deptId=="1"&&jiesuanzhuangtaiid=="3"){
layer.alert("请填写决算批复金额!");
return false;
}
if (!_this.checknum(jiesuanpifujine)&&_this.deptId=="1"&&jiesuanzhuangtaiid=="3") {
layer.alert("决算批复金额请填写数字格式!");
return false;
}
var jieyushangjiaojine = !_this.jiesuan.jieyushangjiaojine ? "" : $.trim(_this.jiesuan.jieyushangjiaojine);
if("" == jieyushangjiaojine&&_this.deptId=="1"&&jiesuanzhuangtaiid=="3"){
layer.alert("请填写结余上缴金额!");
return false;
}
if (!_this.checknum(jieyushangjiaojine)&&_this.deptId=="1"&&jiesuanzhuangtaiid=="3") {
layer.alert("结余上缴金额请填写数字格式!");
return false;
}
return true;
},
//检查数字
checknum : function(ppNum) {
var regPos = /^\d+(\.\d+)?$/; //非负浮点数
var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
if (regPos.test(ppNum) || regNeg.test(ppNum)) {
return true;
} else {
return false;
}
},
//跳到首页
SetPageIndex : function(){
this.pageIndex = 1;
},
SetPageEnd : function(){
this.pageIndex = this.pageCount;
},
//上一页
SetPageIndexPrePage : function(){
var PrePage = ((this.pageIndex -1) <= 0) ? 1 : (this.pageIndex -1);
this.pageIndex = PrePage;
},
//下一页
SetPageIndexNextPage : function(){
var NextPage = ((this.pageIndex +1) >= this.pageCount) ? this.pageCount : (this.pageIndex +1);
this.pageIndex = NextPage;
},
//跳转界面
JumpPage : function(){
if(this.inputPageIndexValue <= 1){
this.inputPageIndexValue = 1;
}else if(this.inputPageIndexValue >= this.pageCount){
this.inputPageIndexValue = this.pageCount;
}
this.pageIndex = this.inputPageIndexValue;
this.inputPageIndexValue = '';
},
},
watch :{
//监控分页情况,刷新列表
pageIndex : function(){
this.bindXiadaList();
}
}
}) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.