text
stringlengths 7
3.69M
|
|---|
const View = require("./ttt-view.js") // require appropriate file
const Game = require("./../node_solutions/game.js") // require appropriate file
$(() => {
// Your code here
const game = new Game();
// const $ul = $("<ul class='grid'></ul>")
const $ul = $("ul")
const view = new View(game, $ul);
view.bindEvents();
});
|
$(document).ready(function(){
list_radios();
if (!Modernizr.inputtypes.date) {
$('input[type=date]').datepicker();
$('input[type=date]').css('border-bottom','1px solid lightgray');
$('#ui-datepicker-div').css('background-color','white');
$('#ui-datepicker-div').css('border','1px solid lightgray');
$('#ui-datepicker-div').css('padding','15px');
$('#ui-datepicker-div').css('border-radius','8px');
}
if ( $('[type="date"]').prop('type') != 'date' ) {
$('[type="date"]').datepicker();
}
});
var prefix=34;
function list_radios(){
var lang=$('body').attr('data-lang');
$.getJSON(api_url+'tarifas/list_all?callback=?', {}, function(data){
var list_tarifas=[];
if(data.status=='success') list_tarifas=data.data.rates;
var select=$('#radio');
var optioninicial=$('<option></option>').attr({'value':-1}).text('-'); select.append(optioninicial);
for(var i=0;i<list_tarifas.length;i++){
id=list_tarifas[i].id;
nombres=list_tarifas[i].name;
var option=$('<option></option>').attr({'value':list_tarifas[i].id, 'data-credit-box':list_tarifas[i].credit_box, 'data-credit-wod':list_tarifas[i].credit_wod}).text(list_tarifas[i].name+" ("+list_tarifas[i].price+" €)"); select.append(option);
}
});
}
function enviar() {
if( $('#exoneracioncheck').is(':checked') ){
if($('#password').val()==$('#password_repeat').val()){
var tarifa_id=$('#radio').val();
var datainput = {
email: $('#email').val(),
password: $('#password').val(),
name: $('#nombre').val(),
surname: $('#apellidos').val(),
phone: $('#movil').val(),
direccion: $('#direccion').val(),
nif: $('#nif').val().toUpperCase(),
birthdate: $('#birthdate').val(),
rate_id:tarifa_id
};
$('#enviar').html('<i class="fa fa-cog fa-spin"></i> Enviando');
$.getJSON(api_url+'customers/add?callback=?',datainput,function(data){
if(data.status=='success'){
$('#nif').val('');
$('#nombre').val('');
$('#apellidos').val('');
$('#password').val('');
$('#email').val('');
$('#movil').val('');
$('#birthdate').val('');
$('#direccion').val('');
$('#nuevo_taxista').empty().html('<div class="notice full animated fadeInDown"><div class="icon"><i class="fa fa-smile-o"></i></div><div class="text">¡YA ESTAS REGISTRADO!<br> Podrás acceder a tu cuenta cuando uno de nuestros coaches valide tu registro. Gracias por registrarte en nuestro sistema de reservas!</div></div>');
var content_botonera=$('<div></div>').attr({'class':'download_content'}); $('#nuevo_taxista').append(content_botonera);
var botonera=$('<div></div>').attr({'class':'botonera','style':'width:200px; text-align:center;'}); content_botonera.append(botonera);
var img = $('<img>').attr({'src':base_url+'/static/img/i18n/icono_mini_ppal.png'});
img.attr('style', 'width: 110px; margin-top: -36px; margin-left: auto; margin-right: auto; overflow: auto;');
botonera.append(img);
$("html, body").animate({ scrollTop: 0 }, 600);
}
else{
var message=data.response;
//var warning='Faltan datos';
var warning=data.response;
if (message == 'email_registered') warning = 'El email está en uso';
if (message == 'phone_registered') warning = 'El número de teléfono está en uso';
if (message == 'email_missed') warning = 'Falta el email del usuario';
if (message == 'password_missed') warning = 'Falta la contraseña del usuario';
if (message == 'name_missed') warning = 'Falta el nombre del usuario';
if (message == 'surname_missed') warning = 'Falta el apellido del usuario';
if (message == 'phone_missed') warning = 'Falta el número de teléfono del usuario';
if (message == 'nif_missed') warning = 'Falta el NIF';
if (message == 'rate_id_missed') warning = 'Falta seleccionar una tarifa';
launch_alert(warning,'warning');
}
$('#enviar').html('ENVIAR');
});
}else{
launch_alert('Las contraseñas no coinciden','warning');
}
}else{
launch_alert('Debe aceptar las condiciones de uso','warning');
}
}
|
/*
* @lc app=leetcode id=73 lang=javascript
*
* [73] Set Matrix Zeroes
*/
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var setZeroes = function(matrix) {
const replace = 'a';
for (let y = 0; y < matrix.length; y++) {
for (let x = 0; x < matrix[y].length; x++) {
if (matrix[y][x] === 0) {
let i = 0;
while (i < matrix[y].length) {
matrix[y][i] !== 0 && (matrix[y][i] = replace);
i++;
}
let j = 0;
while (j < matrix.length) {
matrix[j][x] !== 0 && (matrix[j][x] = replace);
j++;
}
}
}
}
for (let y = 0; y < matrix.length; y++) {
for (let x = 0; x < matrix[y].length; x++) {
matrix[y][x] === replace && ( matrix[y][x] = 0 );
}
}
return matrix;
};
|
const { asyncHandler } = require("./asyncHandler");
const { createJWTToken } = require("./jwtToken");
const { hashPassword, passIsCorrect } = require("./bcrypt");
module.exports = {
asyncHandler,
createJWTToken,
hashPassword,
passIsCorrect,
};
|
#!/usr/bin/env node
const fs = require('fs')
const inp = fs.readFileSync(process.argv[2], 'utf8')
const maxN = parseInt(process.argv[3], 10)
let out = ''
process.stdin.setEncoding('utf8')
process.stdin.on('data', chunk => {
out += chunk.trimRight()
if (out.length > 0 && out[out.length - 1].trim()) out += ' '
do {
let n = Math.min(maxN, out.length)
while (inp.indexOf(out.substring(out.length - n)) == inp.lastIndexOf(out.substring(out.length - n))) n--
const ngram = out.substring(out.length - n)
let choices = ''
for (let i = inp.indexOf(ngram); i != -1 && i < inp.length - n; i = inp.indexOf(ngram, i + 1))
choices += inp[i + n]
out += choices[Math.floor(Math.random() * choices.length)]
} while (out[out.length - 1].trim())
process.stdout.write(out)
})
|
var animation_time = {
walkcycle : 10,
attack : 10,
dying : 16
}
var current_map = new CurrentMap();
var GameSprites = {
/**
* What is under the unit when its selected
*
* @type Image
*/
selected_unit_image : new Image(),
// box with building's name
gui_box : new Image(),
// buttons
btn_destroy : new Image(),
btn_clear : new Image(),
btn_ok : new Image(),
// buildings
btn_farm : new Image(),
btn_ktower : new Image(),
btn_kbarracks : new Image(),
btn_woodcutter : new Image(),
btn_kgoldmine : new Image(),
btn_temple : new Image(),
btn_mason : new Image(),
btn_stower : new Image(),
btn_sbarracks : new Image(),
btn_sgoldmine : new Image(),
// units
btn_kwarrior : new Image(),
btn_karcher : new Image(),
btn_kknight : new Image(),
btn_kpaladin : new Image(),
btn_swarrior : new Image(),
btn_sarcher : new Image(),
btn_sknight : new Image(),
btn_smonk : new Image(),
// drawing characters health
life_strip : {
100 : new Image(),
80 : new Image(),
60 : new Image(),
40 : new Image(),
20 : new Image()
},
tilesheet : new Image(),
explosion1 : new Image(),
data : {
gold : [ 7, 11 ],
timber : [7, 12],
stone : [8, 12],
food : [7, 13],
mana : [8, 13],
},
fog : new Image()
}
function inc_ready_sprites(){
GameState.sprites_ready++;
}
(function(){
for (i in GameSprites)
{
if (GameSprites[i] instanceof HTMLImageElement)
{
GameSprites[i].onload = inc_ready_sprites;
}
}
}());
function load_sprites()
{
GameSprites.selected_unit_image.src = config.IMAGES_PATH + 'unit_selected.png';
GameSprites.life_strip[100].src = config.IMAGES_PATH + 'life_strip_100.png';
GameSprites.life_strip[100].onload = inc_ready_sprites;
GameSprites.life_strip[80].src = config.IMAGES_PATH + 'life_strip_80.png';
GameSprites.life_strip[80].onload = inc_ready_sprites;
GameSprites.life_strip[60].src = config.IMAGES_PATH + 'life_strip_60.png';
GameSprites.life_strip[60].onload = inc_ready_sprites;
GameSprites.life_strip[40].src = config.IMAGES_PATH + 'life_strip_40.png';
GameSprites.life_strip[40].onload = inc_ready_sprites;
GameSprites.life_strip[20].src = config.IMAGES_PATH + 'life_strip_20.png';
GameSprites.life_strip[20].onload = inc_ready_sprites;
GameSprites.tilesheet.src = config.IMAGES_PATH + 'knights_tiles.png';
GameSprites.gui_box.src = config.IMAGES_PATH + 'gui_box.png';
GameSprites.btn_destroy.src = config.IMAGES_PATH + 'btn_destroy.png';
GameSprites.btn_clear.src = config.IMAGES_PATH + 'btn_clear.png';
GameSprites.btn_ok.src = config.IMAGES_PATH + 'btn_ok.png';
GameSprites.btn_farm.src = config.IMAGES_PATH + 'btn_farm.png';
GameSprites.btn_ktower.src = config.IMAGES_PATH + 'btn_ktower.png';
GameSprites.btn_kbarracks.src = config.IMAGES_PATH + 'btn_kbarracks.png';
GameSprites.btn_woodcutter.src = config.IMAGES_PATH + 'btn_woodcutter.png';
GameSprites.btn_kgoldmine.src = config.IMAGES_PATH + 'btn_kgoldmine.png';
GameSprites.btn_temple.src = config.IMAGES_PATH + 'btn_temple.png';
GameSprites.btn_mason.src = config.IMAGES_PATH + 'btn_mason.png';
GameSprites.btn_stower.src = config.IMAGES_PATH + 'btn_stower.png';
GameSprites.btn_sbarracks.src = config.IMAGES_PATH + 'btn_sbarracks.png';
GameSprites.btn_sgoldmine.src = config.IMAGES_PATH + 'btn_sgoldmine.png';
// Units
GameSprites.btn_kwarrior.src = config.IMAGES_PATH + 'btn_kwarrior.png';
GameSprites.btn_karcher.src = config.IMAGES_PATH + 'btn_karcher.png';
GameSprites.btn_kknight.src = config.IMAGES_PATH + 'btn_kknight.png';
GameSprites.btn_kpaladin.src = config.IMAGES_PATH + 'btn_kpaladin.png';
GameSprites.explosion1.src = config.IMAGES_PATH + 'explosion1.png'; // 26
GameSprites.btn_swarrior.src = config.IMAGES_PATH + 'btn_swarrior.png';
GameSprites.btn_sarcher.src = config.IMAGES_PATH + 'btn_sarcher.png';
GameSprites.btn_sknight.src = config.IMAGES_PATH + 'btn_sknight.png';
GameSprites.btn_smonk.src = config.IMAGES_PATH + 'btn_smonk.png'; // 30
GameSprites.fog.src = config.IMAGES_PATH + 'fog.png'; // 31
}
|
import axios from 'axios';
import config from '../config'
import router from '../../router/index'
export default {
state: {
tokens: {
access_token: null,
expires_in: null,
refresh_token: null,
token_type: null
},
authenticatedUser: {
id: null,
name: null,
email: null,
picture: null,
created_at: null,
updated_at: null,
}
},
mutations: {
UPDATE_TOKENS(state, tokens){
state.tokens = tokens
},
DESTROY_TOKENS(state){
state.tokens.access_token = null,
state.tokens.expires_in = null,
state.tokens.refresh_token = null,
state.tokens.token_type = null,
state.authenticatedUser.id = null,
state.authenticatedUser.name = null,
state.authenticatedUser.email = null,
state.authenticatedUser.picture = null,
state.authenticatedUser.created_at = null,
state.authenticatedUser.updated_at = null
},
SET_AUTH_USER(state, authUser){
state.authenticatedUser = authUser
},
},
actions: {
login(state, loginDetails){
return new Promise((resolve, reject) => {
let data = {
grant_type: 'password',
client_id: 2,
client_secret: 'BaPLoB7xK3iyMeaErx9jSQo9mx6uSnbKnh5wGGlH',
username: loginDetails.email,
password: loginDetails.password,
remember: loginDetails.remember,
scope: ''
};
axios[config.loginMethod](config.apiUrl + config.loginRequest, data)
.then(response => {
let responseData = response.data;
let now = Date.now();
responseData.expires_in = responseData.expires_in + now;
state.commit('UPDATE_TOKENS', responseData);
resolve(response)
})
.catch(error => {
reject(error)
})
})
},
setAuthenticatedUser({commit, getters}) {
return new Promise((resolve, reject) => {
axios[config.getUserMethod](config.apiUrl + config.getUserRequest, {headers: getters.getHeader})
.then(response => {
let authUser = response.data;
commit('SET_AUTH_USER', authUser);
resolve(response)
})
.catch(error => {
reject(error)
})
})
},
logout(state) {
let redirect = '/';
state.commit('DESTROY_TOKENS');
router.push(redirect);
},
register(state, registerDetails){
return new Promise((resolve, reject) => {
axios[config.registerMethod](config.apiUrl + config.registerRequest, registerDetails)
.then(response => {
resolve(response)
})
.catch(error => {
reject(error)
})
})
},
},
getters: {
getToken(state) {
let token = state.tokens.access_token;
let expiration = state.tokens.expires_in;
if ( !token || !expiration ) {
return null
}
if (Date.now() > parseInt(expiration)) {
/* Arreglar esto! */
state.commit('DESTROY_TOKENS');
return null
} else {
return token
}
},
isAuthenticated(state, getters) {
if (getters.getToken) {
return true
} else {
return false
}
},
getHeader(state, getters) {
let header = {
'Aceept': 'application/json',
'Authorization': 'Bearer ' + getters.getToken
};
return header
},
getAuthenticatedUser(state) {
return state.authenticatedUser
},
},
}
|
import Square from '/js/square.js';
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
context.canvas.height = window.innerHeight;
context.canvas.width = window.innerWidth;
const graph = new OffscreenCanvas(800, 800);
const simulation = new OffscreenCanvas(800, 800);
const simulationCtx = simulation.getContext('2d');
const population = 800;
const arr = [];
let iteration = 0;
// Generation a population
for (let i = 0; i < population; i++) {
arr[i] = new Square(simulationCtx, Math.random() > 0.5);
}
// Auxiliar Function to Draw a Chart
function drawGraph(canvas) {
const ctx = canvas.getContext('2d');
let infect = 0;
for (let i = 0; i < population; i++) {
if (arr[i].infected) infect++;
}
let healt = arr.length - infect;
// Draw a line from the top of canvas (the chart as well)
// to the percentage of non-infected squares
ctx.beginPath();
ctx.moveTo(iteration + 1, 0);
ctx.lineTo(iteration + 1, healt);
ctx.closePath();
ctx.strokeStyle = 'blue';
ctx.stroke();
// Draw a line from the last non-infected all the way to
// the bootom of the Chart
ctx.beginPath();
ctx.moveTo(iteration + 1, healt);
ctx.lineTo(iteration + 1, 800);
ctx.closePath();
ctx.strokeStyle = 'red';
ctx.stroke();
// At the end these two lines represent 100% of population
// and ilustrate well the state of population
// Make the Axis for the chart
ctx.beginPath();
ctx.strokeStyle = 'white';
ctx.moveTo(0, 0);
ctx.lineTo(0, 800);
ctx.moveTo(0, 800);
ctx.lineTo(800, 800);
ctx.closePath();
ctx.stroke();
}
// Magic
function update() {
context.clearRect(0, 0, canvas.width, canvas.height);
if(arr[0].deltaTime > arr[0].time - 1) simulationCtx.clearRect(0, 0, simulation.width, simulation.height);
drawGraph(graph);
context.drawImage(graph, 900, 40);
arr.forEach(square => {
square.update();
square.show();
});
context.drawImage(simulation, 20, 40);
context.rect(20, 40, 800, 800);
context.strokeStyle = 'white';
context.stroke();
iteration++;
if (iteration > 800) iteration = 0;
requestAnimationFrame(update);
}
update();
|
import Phaser from 'phaser';
/*Vector2 = Phaser.Math.Vector2;
const elem2vec = ({xn, yn}) => new Vector2(xn, yn);*/
const isBetween = (b, a, c) =>
(
(b.xn == a.xn) && (b.xn == c.xn) && ((b.yn - a.yn) * (b.yn - c.yn) < 0)
) || (
(b.yn == a.yn) && (b.yn == c.yn) && ((b.xn - a.xn) * (b.xn - c.xn) < 0)
);
class GridController extends Phaser.Events.EventEmitter{
constructor(grid){
super();
this.grid = grid;
this.state = {
selection: null
}
this.handleClick = this.handleClick.bind(this);
this.grid.on("click", this.handleClick);
}
handleClick(elem){
if(!this.state.selection){
this.handleFirstClick(elem);
}else{
this.handleSelectionClick(elem);
}
}
handleFirstClick(elem){
this.state.selection = elem;
elem.smile();
this.grid.disableWhere(it =>
(it.xn != elem.xn && it.yn != elem.yn) ||
it.type != 'heart' ||
it.direction != elem.direction
);
}
async handleSelectionClick(elem){
if(elem === this.state.selection){
elem.calm();
}else{
elem.smile();
await Promise.all([
this.grid.doWhere(
it => isBetween(it, elem, this.state.selection) && it.type == 'heart',
(it, i) => it.rotate({rotation: 1, duration: 250, delay: i * 100})
),
this.grid.replaceElement(elem, {type: 'flower'}),
this.grid.replaceElement(this.state.selection, {type: 'flower'})
]);
if(this.grid.checkWin()){
return this.emit('win');
}
}
this.grid.enableAll();
this.state.selection = null;
}
}
export default GridController;
|
const fs = require("fs");
const path = require("path");
const ServerMock = require("mock-http-server");
const server = new ServerMock({ host: "0.0.0.0", port: 9000 });
// Mock returning player stats
server.on({
method: "GET",
path: '/headtohead.json',
reply: {
status: 200,
headers: { "content-type": "application/json" },
body: fs.readFileSync(path.join(__dirname, 'headtohead.json'), 'utf8')
}
});
server.start(() => {
console.log("mock server started");
});
|
import React, { useState, useContext } from 'react'
import { DataContext } from './DataProvider'
import Togglable from './Togglable'
const CustomUrlInput = () => {
const { url: [url, setUrl] } = useContext(DataContext)
const { status: [status] } = useContext(DataContext)
const { default: [DEFAULT_URI] } = useContext(DataContext)
const [newUrl, setNewUrl] = useState('')
const handleUrlChange = () => {
if (!url || url === '') {
return
}
setUrl(newUrl)
}
const defaultUrl = () => {
setUrl(DEFAULT_URI)
setNewUrl(DEFAULT_URI)
}
return (
<div>
<Togglable buttonText="Use different rules" buttonClass="urlButton" activeClass="urlButtonActive">
<label htmlFor="customUri">
URL:
{' '}
<input value={newUrl} onChange={(event) => setNewUrl(event.target.value)} className="url" id="customUri" placeholder={`e.g. ${url}`} />
</label>
<button type="button" onClick={() => handleUrlChange()} className="entry">Fetch</button>
<button type="button" onClick={() => defaultUrl()} className="entry">Use default rules</button>
</Togglable>
<div className={status.name}>
{ status.text === '' ? <br /> : status.text }
</div>
</div>
)
}
export default CustomUrlInput
|
var orb1, orb2;
function setup(){
createCanvas( window.innerWidth, window.innerHeight );
background(50);
strokeWeight(1);
stroke(255);
noFill();
orb1 = new Orb( width/2, height/2 );
orb2 = new Orb( width/2, height/2 );
}
function draw(){
background(50);
var r = (width < height) ? width/4 : height/4;
stroke(150);
ellipse( width/2, height/2, r*2.8, r*2.8 );
stroke(200);
orb1.update();
orb2.update();
for( var i=orb1.tailLength/10; i<orb1.tailLength/2 ; i+=3 ){
line(
orb1.prev[i].x, orb1.prev[i].y,
orb2.prev[i].x, orb2.prev[i].y
);
}
}
|
$(document).ready(function() {
var update = function() {
document.getElementById("currentDay")
.innerHTML = moment().format('dddd, MMMM Do YYYY, h:mm:ss a');
}
setInterval(update, 1000);
$(".btn").on("click", function () {
var input = $(this).siblings(".form").val();
var hour = $(this).siblings().attr("id");
localStorage.setItem(hour, input);
});
console.log(localStorage.getItem("9"));
var test = localStorage.getItem("9");
$("#nine .form").text($(test));
$("#9").val(localStorage.getItem("nine"));
$("#10").val(localStorage.getItem("ten"));
$("#11").val(localStorage.getItem("eleven"));
$("#12").val(localStorage.getItem("twelve"));
$("#13").val(localStorage.getItem("thirteen"));
$("#14").val(localStorage.getItem("fourteen"));
$("#15").val(localStorage.getItem("fifteen"));
$("#16").val(localStorage.getItem("sixteen"));
$("#17").val(localStorage.getItem("seventeen"));
if ((moment().format("H")) > 9) {
$(nine).css("background-color", "gray");
} else if ((moment().format("H")) < 9) {
$(nine).css("background-color", "rgb(146, 180, 245)");
} else if ((moment().format("H")) == 9) {
$(nine).css("background-color", "red");
} else {
alert('Error');
}
if ((moment().format("H")) > 10) {
$(ten).css("background-color", "gray");
} else if ((moment().format("H")) < 10) {
$(ten).css("background-color", "rgb(146, 180, 245)");
} else if ((moment().format("H")) == 10) {
$(ten).css("background-color", "red");
} else {
alert('Error');
}
if ((moment().format("H")) > 11) {
$(eleven).css("background-color", "gray");
} else if ((moment().format("H")) < 11) {
$(eleven).css("background-color", "rgb(146, 180, 245)");
} else if ((moment().format("H")) == 11) {
$(eleven).css("background-color", "red");
} else {
alert('Error');
}
if ((moment().format("H")) > 12) {
$(twelve).css("background-color", "gray");
} else if ((moment().format("H")) < 12) {
$(twelve).css("background-color", "rgb(146, 180, 245)");
} else if ((moment().format("H")) == 12) {
$(twelve).css("background-color", "red");
} else {
alert('Error');
}
if ((moment().format("H")) > 13) {
$(thirteen).css("background-color", "gray");
} else if ((moment().format("H")) < 13) {
$(thirteen).css("background-color", "rgb(146, 180, 245)");
} else if ((moment().format("H")) == 13) {
$(thirteen).css("background-color", "red");
} else {
alert('Error');
}
if ((moment().format("H")) > 14) {
$(fourteen).css("background-color", "gray");
} else if ((moment().format("H")) < 14) {
$(fourteen).css("background-color", "rgb(146, 180, 245)");
} else if ((moment().format("H")) == 14) {
$(fourteen).css("background-color", "red");
} else {
alert('Error');
}
if ((moment().format("H")) > 15) {
$(fifteen).css("background-color", "gray");
} else if ((moment().format("H")) < 15) {
$(fifteen).css("background-color", "rgb(146, 180, 245)");
} else if ((moment().format("H")) == 15) {
$(fifteen).css("background-color", "red");
} else {
alert('Error');
}
if ((moment().format("H")) > 16) {
$(sixteen).css("background-color", "gray");
} else if ((moment().format("H")) < 16) {
$(sixteen).css("background-color", "rgb(146, 180, 245)");
} else if ((moment().format("H")) == 16) {
$(sixteen).css("background-color", "red");
} else {
alert('Error');
}
if ((moment().format("H")) > 17) {
$(seventeen).css("background-color", "gray");
} else if ((moment().format("H")) < 17) {
$(seventeen).css("background-color", "rgb(146, 180, 245)");
} else if ((moment().format("H")) == 17) {
$(seventeen).css("background-color", "red");
} else {
alert('Error');
}
})
|
export default [
{
path:'/',
redux: [],
component: ()=> import('../layouts/basic'),
children: [
{
path: '/home',
redux: [],
component: ()=> import('../pages/home')
},
{
path: '/space',
redux: [],
component: ()=> import('../pages/space')
},
{
path: '/time',
redux: [],
component: ()=> import('../pages/time')
},
{
path: '/user',
redux: [],
component: ()=> import('../pages/user')
}
]
}
]
|
import React from "react";
import { Box } from "./common";
import { formatSecondsToMinutes } from "../utils";
const Timer = ({ seconds }) => {
const formattedTime = formatSecondsToMinutes(seconds);
return (
<Box
style={{
fontSize: 60,
fontFamily: "serif",
display: "flex",
justifyContent: "center",
}}
>
{formattedTime}
</Box>
);
};
export default Timer;
|
const {
getMovies,
postMovies,
putMovies,
deleteMovies
} = require('../models/movies')
const helper = require('../helper')
module.exports = {
getMovies: async(req, res) => {
const result = await getMovies()
return helper.response(res, 200,null, result)
},
createMovies: async(req, res)=>{
try {
const setData = {
movie : req.body.movie,
genre : req.body.genre,
productionHouseId : req.body.productionHouseId
}
const result = await postMovies(setData)
const message = 'Data berhasil ditambah'
return helper.response(res, 200, message, result)
} catch (error) {
const message = 'Data gagal ditambah'
return helper.response(res, 400, message, error)
}
},
editMovies: async(req, res)=>{
try {
const setData = {
movie : req.body.movie,
genre : req.body.genre,
productionHouseId : req.body.productionHouseId
}
const id = req.params.id
const result = await putMovies(setData, id)
const message = 'Data berhasil diedit'
return helper.response(res, 200, message, result)
} catch (error) {
const message = 'Data gagal diedit'
return helper.response(res, 400, message, error)
}
},
deleteMovies: async(req, res)=>{
try {
const id = req.params.id
const result = await deleteMovies(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)
}
}
}
|
'use strict';
angular.module('banetApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'ngAnimate',
'ppSync'
])
.config(function($routeProvider) {
$routeProvider
.when('/dashboard', {
templateUrl: 'views/dashboard.html',
controller: 'DashboardCtrl'
})
.when('/pinboard', {
templateUrl: 'views/pinboard.html',
controller: 'PinboardCtrl'
})
.when('/pinboard/new', {
templateUrl: 'views/pinboard/new.html',
controller: 'PinboardNewCtrl'
})
.when('/pinboard/show/:id', {
templateUrl: 'views/pinboard/show.html',
controller: 'PinboardShowCtrl'
})
.when('/post', {
templateUrl: 'views/post.html',
controller: 'PostCtrl'
})
.when('/channel/:name', {
templateUrl: 'views/channel.html',
controller: 'ChannelCtrl'
})
.when('/channel/:name/new', {
templateUrl: 'views/channel/:name/new.html',
controller: 'ChannelNameNewCtrl'
})
.otherwise({
redirectTo: '/dashboard'
});
});
|
$('.lessons').click( function(event) {
event.preventDefault();
$('.lessons-menu').removeClass('hidden');
$('.get-help-menu').addClass('hidden');
$('.lessons-menu').html(
'<div class="lessons-menu-box">' +
'<ul class="menu-box-ul">AIARE Level 2 - Rec' +
'<li class="lessons-menu"><a class="menu-link">Introduction</a></li>' +
'<li class="lessons-menu"><a class="menu-link">Chapter 1</a></li>' +
'<li class="lessons-menu"><a class="menu-link">Chapter 2</a></li>' +
'<li class="lessons-menu"><a class="menu-link">Chapter 3</a></li>' +
'</ul>' +
'</div>'
)
});
$('.lessons-menu').click( function(event) {
location.reload();
});
$('.get-help').click( function(event) {
event.preventDefault();
$('.get-help-menu').removeClass('hidden');
$('.lessons-menu').addClass('hidden');
$('.get-help-menu').html(
'<div class="get-help-menu-box">' +
'<ul class="menu-box-ul">Resources' +
'<li class="lessons-menu"><a class="menu-link">Ask Questions About Curriculum</a></li>' +
'<li class="lessons-menu"><a class="menu-link">Report an Issue</a></li>' +
'<li class="lessons-menu"><a class="menu-link">Contact AIARE</a></li>' +
'</ul>' +
'</div>'
)
});
$('.get-help-menu').click( function(event) {
location.reload();
});
|
export class timeQuizGenerator {
// When initially constructed create new task
constructor() {
this.reloadTask();
}
// Generate a random hour and minute to add to the date
generateTimeToChange = () => {
const hour = Math.floor(Math.random() * 23);
const minute = Math.floor(Math.random() * 59);
return [hour, minute];
};
// Function to check for correct answer with time input from HTML input type time.
checkTime = (timeInput) => {
let timeInputSplitted = timeInput.replace("0", "").split(":");
if (
timeInputSplitted[0] === String(this.correctHour) &&
timeInputSplitted[1] === String(this.correctMinute)
) {
return true;
} else {
return false;
}
};
reloadTask = () => {
// Generate random start
this.startHour = String(Math.floor(Math.random() * 23)).padStart(
2,
"0"
);
this.startMinute = String(Math.floor(Math.random() * 59)).padStart(
2,
"0"
);
// Create a new date object to act as base
let startTime = new Date();
startTime.setHours(this.startHour);
startTime.setMinutes(this.startMinute);
startTime.setSeconds = 0;
// Generate random timechange
const timeToChange = this.generateTimeToChange();
const timeToAdjust = timeToChange[0] * 3600 + timeToChange[1] * 60;
// Set global variable to correct time as string, add zero before single value
this.hourToChange = String(timeToChange[0]).padStart(2, "0");
this.minuteToChange = String(timeToChange[1]).padStart(2, "0");
// Add the amount of seconds converting to ms by x 1000
const calculatedNewDate =
new Date().setTime(startTime) + timeToAdjust * 1000;
// Create a new correct Date object
const newCorrectDate = new Date(calculatedNewDate);
// Assign correct values to global variables.
this.correctHour = newCorrectDate.getHours();
this.correctMinute = newCorrectDate.getMinutes();
};
}
|
var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
var expect = require('chai').expect;
var should = require('chai').should;
describe('Serializer', function() {
class MockMap {
constructor(inMap = {}, outMap = {}) {
this.inMap = inMap;
this.outMap = outMap;
}
}
class MockModel {
constructor(map = new MockMap(), values = {}) {
this.__map = map;
for (let key of Object.keys(values))
this[key] = values[key];
}
getMap() {
return this.__map;
}
}
class MockBadModel {
}
describe('serializeModel', function () {
it('should serialize an empty object', function() {
let serializer = require('../src/user_modules/serializer');
let model = new MockModel();
return expect(serializer.serializeModel(model)).to.eventually.be.fulfilled;
});
it('should throw an exception if null is provided', function() {
let serializer = require('../src/user_modules/serializer');
return expect(serializer.serializeModel(null)).to.eventually.be.rejected;
});
it('should throw an exception if undefined is provided', function() {
let serializer = require('../src/user_modules/serializer');
return expect(serializer.serializeModel(undefined)).to.eventually.be.rejected;
});
it('should throw an exception if the provided object is not a SequelizeJS model', function() {
let serializer = require('../src/user_modules/serializer');
let model = new MockBadModel();
return expect(serializer.serializeModel(model)).to.eventually.be.rejected;
});
it('should correctly serialize model with single property', function() {
let serializer = require('../src/user_modules/serializer');
let values = {
'Id': 123321
};
let map = new MockMap({
'Id': 'Id'
}, {
'Id': 'Id'
});
let model = new MockModel(map, values);
let result = serializer.serializeModel(model);
return expect(result).to.eventually.be.fulfilled
.be.deep.equal(values);
});
it('should correctly serialize model with multiple properties', function() {
let serializer = require('../src/user_modules/serializer');
let values = {
'Id': 123321,
'Name': 'Donald'
};
let map = new MockMap({
'Id': 'Id',
'Name': 'Name'
}, {
'Id': 'Id',
'Name': 'Name'
});
let model = new MockModel(map, values);
let result = serializer.serializeModel(model);
return expect(result).to.eventually.be.fulfilled
.be.deep.equal(values);
});
it('should correctly serialize model with multiple properties, even if one does not exist in values', function() {
let serializer = require('../src/user_modules/serializer');
let valuesIn = {
'Id': 123321,
'Name': 'Donald',
};
let valuesOut = {
'Id': 123321,
'Name': 'Donald',
'Age': undefined
};
let map = new MockMap({
'Id': 'Id',
'Name': 'Name',
'Age': 'Age'
}, {
'Id': 'Id',
'Name': 'Name',
'Age': 'Age'
});
let model = new MockModel(map, valuesIn);
let result = serializer.serializeModel(model);
return expect(result).to.eventually.be.fulfilled
.be.deep.equal(valuesOut);
});
it('should correctly serialize model with single property that translates', function() {
let serializer = require('../src/user_modules/serializer');
let valuesIn = {
'Id': 123321
};
let valuesOut = {
'Identification': 123321
};
let map = new MockMap({
'Identification': 'Id'
}, {
'Id': 'Identification'
});
let model = new MockModel(map, valuesIn);
let result = serializer.serializeModel(model);
return expect(result).to.eventually.be.fulfilled
.be.deep.equal(valuesOut);
});
it('should correctly serialize model with multiple properties that translates', function() {
let serializer = require('../src/user_modules/serializer');
let valuesIn = {
'Id': 123321,
'Name': 'Donald'
};
let valuesOut = {
'Identification': 123321,
'FullName': 'Donald'
};
let map = new MockMap({
'Identification': 'Id',
'FullName': 'Name'
}, {
'Id': 'Identification',
'Name': 'FullName'
});
let model = new MockModel(map, valuesIn);
let result = serializer.serializeModel(model);
return expect(result).to.eventually.be.fulfilled
.be.deep.equal(valuesOut);
});
it('should only serialize properties on model that are specified to be serialized', function() {
let serializer = require('../src/user_modules/serializer');
let valuesIn = {
'Id': 123321,
'Name': 'Donald'
};
let valuesOut = {
'Name': 'Donald'
};
let map = new MockMap({
'Name': 'Name'
}, {
'Name': 'Name'
});
let model = new MockModel(map, valuesIn);
let result = serializer.serializeModel(model);
return expect(result).to.eventually.be.fulfilled
.be.deep.equal(valuesOut);
});
it('should only serialize special typed properties on model', function() {
let serializer = require('../src/user_modules/serializer');
let stats = {
'Agility': 12,
'Dogs': 23
};
let valuesIn = {
'Id': 123321,
'Stats': JSON.stringify(stats)
};
let valuesOut = {
'Id': 123321,
'Stats': stats
};
let map = new MockMap({
'Id': 'Id',
}, {
'Id': 'Id',
'Stats': {
Type: 'JSON',
Value: 'Stats'
}
});
let model = new MockModel(map, valuesIn);
let result = serializer.serializeModel(model);
return expect(result).to.eventually.be.fulfilled
.be.deep.equal(valuesOut);
});
});
});
|
var canplay = true;
(function() {
document.onmousemove = handleMouseMove;
function handleMouseMove(event) {
MoiVeuxDuUC();
}
})();
(function() {
document.onclick = handleMouseClic;
function handleMouseClic(event) {
MoiVeuxDuUC();
}
})();
function MoiVeuxDuUC()
{
if (canplay)
{
canplay = false;
var audio = new Audio('https://dl.dropboxusercontent.com/s/j233q4gp20q0o8u/Je%20veux%20du%20UC.mp3');
audio.onended = function(){
canplay = true;
};
audio.play();
}
}
|
import React, { Component } from "react";
import PropTypes from "prop-types";
import Typography from '@material-ui/core/Typography';
class ClassifiedContent extends Component {
state = {
width: window.innerWidth,
};
componentWillMount() {
window.addEventListener('resize', this.handleWindowSizeChange);
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleWindowSizeChange);
}
handleWindowSizeChange = () => {
this.setState({ width: window.innerWidth });
};
render() {
const { data } = this.props;
/*
const body = data.map(obj => (
<Typography
style={{fontSize:16}}
paragraph={true}
>
{obj.content}
</Typography>
));
*/
const body = data.map(obj => (
obj.label === obj.class?
<Typography
style={{fontSize:16, color:'green'}}
paragraph={true}
>
{obj.content}
</Typography>
:
<Typography
style={{fontSize:16, color:'black'}}
paragraph={true}
>
{obj.content}
</Typography>
));
const { width } = this.state;
const widthPercent = (width < 500) ? "100%" : ((500/width)*100)+"%";
return (
<div style={{margin:"0 auto", width: widthPercent}}>
{body}
</div>
);
}
}
ClassifiedContent.propTypes = {
data: PropTypes.array.isRequired,
};
export default ClassifiedContent;
|
(function () {
var $gallery = $('#gallery');
$.getJSON('http://localhost:5000/api/test', function (data) {
var id = 0;
data.forEach(function (entry) {
var city = entry.DestinationId;
var template =
'<li class="gallery-item" data-city="' + city + '">' +
'<div class="gallery-block gallery-id">' + (++id) + '</div>' +
'<div class="gallery-block gallery-name">' + city + '</div>' +
'<div class="gallery-block gallery-wiki">' +
'<img class="gallery-image" src="static/img/beach.png">' +
'<img class="gallery-image" src="static/img/mountain.png">' +
'<img class="gallery-image" src="static/img/island.png">' +
'</div>' +
'<div class="gallery-block gallery-weather>"' + 'Weather' + '</div>';
template += '</li>';
$gallery.append(template);
});
var $li = $gallery.find('li');
$li.each(function () {
var $img = $(this).find('img');
$.getJSON('http://localhost:5000/api/wiki', {city: $(this).data('city')}, function (data) {
for (var i = 0; i < 3; i++) if (data[i]) { $img.eq(i).css({display: 'block'}); }
});
});
});
})($);
|
import React from "react";
import { Route } from "react-router-dom";
import { HomePage } from "./components/HomePage";
import { MapBrowser } from "./components/MapBrowser";
import { Layout } from "./components/Layout";
import {Login} from "./components/Login";
import {Admin} from "./components/Admin";
export const routes = (
<Layout>
<Route exact path="/" component={HomePage} />
<Route path="/browse" component={MapBrowser} />
<Route path="/login" component={Login} />
<Route path="/Admin" component={Admin} />
</Layout>
);
|
/*!
* webkit-dwarf
* Copyright(c) 2013 Daniel Yang <miniflycn@gmail.com>
* MIT Licensed
*/
!function (root) {
/* var */
var
_head = document.getElementsByTagName('head')[0],
_base,
_path = {
'jquery': './components/js/jquery.js'
},
_localBase,
_require,
DOT_RE = /\/\.\//g,
DOUBLE_DOT_RE = /\/[^/]+\/\.\.\//,
DOUBLE_SLASH_RE = /([^:/])\/\//g;
/* Tool */
function _isFunction(f) {
return typeof f === 'function';
}
function _normalize(base, id) {
if (_isUnnormalId(id)) return id;
if (_isRelativePath(id)) return _resolvePath(base, id) + '.js';
return id;
}
function _isUnnormalId(id) {
return (/^https?:|^file:|^\/|\.js$/).test(id);
}
function _isRelativePath(path) {
return (path + '').indexOf('.') === 0;
}
// reference from seajs
function _resolvePath(base, path) {
path = base.substring(0, base.lastIndexOf('/') + 1) + path;
path = path.replace(DOT_RE, '/');
while (path.match(DOUBLE_DOT_RE)) {
path = path.replace(DOUBLE_DOT_RE, '/');
}
return path = path.replace(DOUBLE_SLASH_RE, '$1/');
}
/* Class */
/**
* Cache
* @class
* @static
*/
var Cache = function () {
var map = {};
return {
/**
* get
* @param {String} key
* @returns value
*/
get: function (key) {
return map[key];
},
/**
* set
* @param {String} key
* @param {Object} value
* @returns isSuccess
*/
set: function (key, value) {
if (key in map) return false;
map[key] = value;
return true;
}
};
}();
/**
* Def
* @class
* @static
*/
var Def = function () {
var stack = [];
return {
/**
* push
* @param {Object} o
*/
push: function () {
return stack.push.apply(stack, arguments);
},
/**
* make
* @param {String} src
*/
make: function (src) {
stack.forEach(function (o) {
var
module = _normalize(src, o.m),
deps = o.d,
factory = o.f;
return makeRequire({ base: src })(deps, function () {
var loader = Cache.get(module);
if (!loader) {
loader = new Loader(module, true);
Cache.set(module, loader);
}
return !loader.loaded && loader.set(factory);
}, 0, true);
});
stack.length = 0;
}
};
}();
/**
* Loader
* @class
* @param {String} url
*/
function Loader(url, prevent) {
_isUnnormalId(url) || (url = _path[url]);
!prevent && this.load(url);
this.path = url;
this.succList = [];
this.failList = [];
}
Loader.prototype = {
constructor: Loader,
/**
* load
* @param {String} url
*/
load: function (url) {
var
node = document.createElement('script'),
self = this;
node.addEventListener('load', _onload, false);
node.addEventListener('error', _onerror, false);
node.type = 'text/javascript';
node.async = 'async';
node.src = url;
_head.appendChild(node);
function _onload() {
_onend();
return Def.make(self.path);
}
function _onerror() {
_onend();
_head.removeChild(node);
if (_base && !~url.indexOf(_localBase)) {
return self.load(url.replace(_base, _localBase));
} else {
return self.down();
}
}
function _onend() {
node.removeEventListener('load', _onload, false);
node.removeEventListener('error', _onerror, false);
}
},
/**
* _push
* @private
* @param {Array} list
* @param {Function} cb
*/
_unshift: function (list, cb) {
if (!list.some(function (item) { return item === cb }))
return list.unshift(cb);
},
/**
* succ
* @param {Function} cb
*/
succ: function (cb) {
return this._unshift(this.succList, cb);
},
/**
* fail
* @param {Function} cb
*/
fail: function (cb) {
return this._unshift(this.failList, cb);
},
/**
* done
*/
done: function () {
this.loaded = true;
this.succList.forEach(function (cb) {
return cb();
});
},
/**
* down
*/
down: function () {
this.failList.forEach(function (cb) {
return cb();
});
},
/**
* require
* @returns exports
*/
require: function () {
if (this.factory) {
var module = { exports: {} };
this.factory(makeRequire({ base: this.path }), module.exports, module);
this.exports = module.exports;
this.require = function () {
return this.exports;
};
return this.require();
} else {
return new Error('script has not loaded.');
}
},
/**
* set
* @param {Function} factory
*/
set: function (factory) {
this.factory = factory;
return this.done();
}
}
function _makeModules(modules, r) {
var mods = [];
modules.forEach(function (module) {
mods.push(r(module));
});
return mods;
}
/* returns */
/**
* makeRequire
* @param {Object} opts
* @returns require
*/
function makeRequire(opts) {
var base = opts.base;
function _r(deps, succ, fail, sync) {
var fired, self = this, _deps = deps.slice(0);
if (succ) {
function _checkDeps() {
var res = [];
deps.forEach(function (dep, i) {
var
path = _normalize(base, dep),
loader = Cache.get(path);
if (!loader) {
loader = new Loader(path);
Cache.set(path, loader);
}
if (loader.loaded) {
return;
} else {
res.push(dep);
}
loader.succ(_checkDeps);
fail && loader.fail(fail);
});
deps = res;
// make sure success callback will not trigger multiple times
if (!deps.length && !fired) {
fired = true;
// This is a way to prevent emit too quick for multi module in one file
sync ?
succ() :
setTimeout(function () {
succ.apply(self, _makeModules(_deps, _r));
}, 0);
}
}
_checkDeps();
} else {
var
path = _normalize(base, deps),
loader = Cache.get(path);
if (loader.loaded) {
return loader.require();
} else {
throw new Error('script has not loaded.');
}
}
}
return _r;
}
/**
* define
* define(module, deps, factory)
* define(module, factory)
* define(module, value)
*/
function define(module, deps, factory) {
if (!factory) {
if (_isFunction(deps)) {
factory = deps;
} else {
var tmp = deps;
factory = function (require, exports, module) {
return module.exports = tmp;
}
}
deps = [];
}
Def.push({
m: module,
d: deps,
f: factory
});
}
function opt(opts) {
_base = (opts.base === undefined ? _base : opts.base);
_path = opts.path || _path;
}
/**
* require
* require(deps, succ, [fail])
* require(module)
* @param {Array} deps
* @param {Function} succ
* @param {Function} fail
*/
var require = root.require = function () {
if (_require) return _require.apply(root, arguments);
Def.make(_base || location.href);
if (_base) {
_require = makeRequire({ base: _base });
_localBase = location.href;
} else {
_require = makeRequire({ base: location.href });
}
return _require.apply(root, arguments);
}
require.opt = opt;
require.makeRequire = makeRequire;
root.define = define;
}(window);
|
var totalOsos = 1;
function aumentarOsos(numeroMeses) {
for (var i = 0; i < numeroMeses; i++) {
totalOsos < 10000 ? imprimirFormatoOsos(totalOsos *= 4, 1, i) : imprimirFormatoOsos(totalOsos *= 0.5, 2, i);
}
}
function imprimirFormatoOsos(numeroOsos, tipoDeImpresion, mes) {
console.log(tipoDeImpresion == 1 ? 'Van a existir ' + numeroOsos + ' osos de anteojos después del mes ' + mes :
'Removiendo ' + numeroOsos + ' osos de anteojos de la población.');
tipoDeImpresion != 1 ? imprimirFormatoOsos(numeroOsos, 1, mes) : '';
}
aumentarOsos(11);
|
var ServerUtility = function() {
this.networkIdIndex = 0;
ServerUtility.prototype.getNewNetworkId = function () {
var that = this;
that.set("networkIdIndex", 1 + that.get("networkIdIndex"));
return that.get("networkIdIndex");
}
};
|
function compareStrings(str1, str2) {
if(str1.length > str2.length){
return str1;
} else if (str1.length === str2.length){
var str3 = "Łańcuchy znaków mają taką samą długość";
return str3;
} else{
return str2;
}
}
var string1 = "Uwielbiam JavaScript";
var string2 = "Jestem świetną programistką";
var result = compareStrings(string1, string2);
console.log("Dłuższy łańcuch znaków: " + result);
|
const express = require('express');
const UserController = require('../../controllers/UserController');
const HomeController = require('../../controllers/HomeController');
const rootRouter = (UserModel) => {
const router = express.Router();
const userController = new UserController(UserModel);
const homeController = new HomeController();
router.get('/', userController.index);
router.get('/public/:file', homeController.image);
router.post('/register', userController.register);
router.post('/add-cart', userController.addCart);
router.post('/add-transaction', userController.addTransaction);
router.get('/get-transaction', userController.getTransaction);
router.delete('/remove-cart', userController.removeItemFromCart);
router.delete('/remove-product-cart', userController.removeProductFromCart);
router.post('/modify-cart', userController.modifyProductQuantity);
router.post('/login', userController.login);
router.delete('/logout', userController.logout);
return router;
}
module.exports = rootRouter;
|
var SerialPort = require("serialport");
var app = require('express')();
var http = require('http').Server(app);
var attached = [];
var temperatures = [];
var last_received = [];
var proposed = [];
var count = 0;
var portName = process.argv[2],
portConfig = {
baudRate: 115200,
parser: SerialPort.parsers.readline("\n")
};
var sp;
sp = new SerialPort.SerialPort(portName, portConfig);
app.get('/', function(req, res){
res.sendfile('index.html');
});
var recv = 0;
sp.on("open", function () {
console.log("Listening on Serial");
sp.on('data', function(data) {
recv += 1;
console.log(data)
if(data.substring(0,3) == "GET") {
var id = 0;
console.log("NEW CONNECTECTION REQUESTED");
count += 1;
id = count;
data = data.substring(4);
sp.write("GIVE " + data + " " + id + "\n");
proposed.push(id);
}
else {
var id = data.substring(0, data.indexOf(" "));
var temp = data.substring(data.indexOf(" ") + 1);
var prop = proposed.indexOf(parseInt(id));
if(prop >= 0 && attached.indexOf(parseInt(id)) < 0) {
proposed.slice(prop, 1);
attached.push(parseInt(id));
temperatures.push([]);
last_received.push(0);
console.log("ADDED" + id);
}
var index = attached.indexOf(parseInt(id));
if(index < 0)
return;
last_received[index] = 0;
temperatures[index].push(parseFloat(temp));
}
});
});
function update() {
if(attached.length == 0) {
console.log("No thermostats!");
return;
}
console.log(attached);
console.log(last_received);
for(var i = 0; i < attached.length; i++) {
last_received[i] += 1;
if(last_received[i] > 30) {
attached.splice(i, 1);
temperatures.splice(i, 1);
last_received.splice(i, 1);
i -= 1;
}
}
var avg = 0;
var tts = []
for(var i = 0; i < attached.length; i++) {
if(temperatures[i].length > 0) {
avg += temperatures[i][temperatures[i].length - 1];
tts.push(temperatures[i][temperatures[i].length - 1]);
}
else
tts.push("Err");
}
avg /= attached.length;
if(isNaN(avg)) {
avg = "No data yet";
}
console.log("------");
console.log(attached.length + " thermostats connected");
console.log(tts)
console.log("Average temp: " + avg);
}
setInterval(update, 2000);
app.get('/temps', function(req, res){
res.send(temperatures);
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
|
export default {
email_placeholder: "Email address"
}
|
import * as types from '../actions/actionTypes';
import initialState from './initialState';
import {browserHistory} from 'react-router';
export default function accountReducer(state = initialState.account, action) {
switch(action.type) {
case types.LOGIN_WEBSITE_SUCCESS:
browserHistory.push(`/`)
return action.account;
case types.LOGOUT_SUCCESS:
browserHistory.push(`/`)
return action.account;
default:
return state;
}
}
|
function formatTime(date) {
var year = date.getFullYear()
var month = date.getMonth() + 1
var day = date.getDate()
var hour = date.getHours()
var minute = date.getMinutes()
var second = date.getSeconds()
return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
function formatNumber(n) {
n = n.toString()
return n[1] ? n : '0' + n
}
function formatCalResult(input, result) {
//格式化单个值
if (input == null) {
if (result.toString().search(/\./) > -1) {
var arr = result.toString().split(".");
var n = arr[1].length;
if (n > 4)
n = 4;
return parseFloat(result.toFixed(n));
}
return result;
}
//根据input的小数位数,格式化result
input = input.toString();
var n = 0;
if (input.split(".")[1]) {
n = input.split(".")[1].length;
}
if (n == 0)
n = 2;
return parseFloat(result.toFixed(n));
}
module.exports = {
formatTime: formatTime,
formatCalResult: formatCalResult
}
|
/*global gapi */
import React, { Component } from 'react';
import PostedProperties from './component/PostedProperty/PostedProperty';
import Register from './component/register/Register';
import SignIn from './component/signin/Signin';
import NavBar from './containers/navigation/navigation';
import './App.css';
import 'tachyons';
import NewProperties from './component/NewProperties/NewProperties';
import GoogleSignIn from './containers/GoogleSignin/GoogleAuth';
class App extends Component {
state = {
route: 'signin',
isSignedIn: false,
post: '',
propertyArray: [],
usersArray: [],
authMethod: null
}
addPropertyHandler = (yes) => {
this.setState({post: yes});
}
storePropertyHandler = (properties) => {
this.state.propertyArray.push(properties);
console.log(this.state.propertyArray);
this.addPropertyHandler();
}
onRouteChange = (route) => {
if (route === 'signout') {
this.setState({ isSignedIn: false});
} else if (route === 'home') {
this.setState({isSignedIn: true})
}
this.setState({route: route});
}
loadUsers = (user) => {
this.setState({authMethod: 'password'});
this.state.usersArray.push(user);
console.log(this.state.usersArray, this.state.authMethod);
}
authUserPassword = (login) => {
this.state.usersArray.map((user) => {
if (login.password === user.password && login.email === user.email) {
this.setState({authMethod: 'password'});
this.onRouteChange('home')
} else {
console.log('Failure')
}
})
}
authUserGoogle = (auth) => {
if (auth) {
this.setState({authMethod: 'google'})
this.onRouteChange('home');
} else {
console.log('err');
}
}
signOut = () => {
const auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(() => {
console.log('User signed out.');
this.setState({isSignedIn: false});
this.setState({authMethod: ''})
console.log(this.state.isSignedIn);
this.onRouteChange('signin');
});
}
onGoogleLogout = () => {
console.log('logout');
}
render () {
const { route, propertyArray, isSignedIn, post, authMethod } = this.state;
return (
<div className='App'>
<NavBar onRouteChange={this.onRouteChange} authMethod={authMethod} isSignedIn={isSignedIn} addProperty={this.addPropertyHandler} />
{this.state.authMethod === 'google'
? <input
onClick={this.signOut}
className="nm b ph3 ml2 white pv2 input-reset ba b--black bg-orange grow pointer f6 dib"
type="submit"
value="Logout with Google"/>
: null
}
{route === 'home'
? ( post === 'yes'
? <NewProperties storePropertyHandler={this.storePropertyHandler} />
: (!propertyArray.length
? <div className='tc pa3 ma3 white f4'> No Listed Property. Add a Property Above.</div>
: this.state.propertyArray.map((property) => {
return <PostedProperties
key={property.name}
name={property.name}
detail={property.detail}
realtor={property.realtor}
/>
})
)
)
: ( this.state.route === 'signin'
? <SignIn authUserPassword={this.authUserPassword}><GoogleSignIn authUserGoogle={this.authUserGoogle}/></SignIn>
: <Register loadUsers={this.loadUsers} onRouteChange={this.onRouteChange} />
)
}
</div>
)
}
}
export default App;
|
import React from 'react';
import {DualRing, LoaderWrap} from '../Styled';
const LoaderComponent = () => (
<LoaderWrap>
<DualRing/>
</LoaderWrap>
);
export default LoaderComponent;
|
$(function() {
console.log("Loading page...");
const userInput = $("#user-chat");
userInput.on("keydown", function (event) {
if (event.keyCode === 13) {
const inputValue = $(this).val();
console.log("Player pressed enter. Value was: " + inputValue);
processResponse(inputValue);
$(this).val("");
}
});
// Suppress submission of form. Let keydown function handle everything for the user input.
$("#user-form").on("submit",function(e) {
e.preventDefault();
return false;
})
console.log("Finished loading!");
onLoad();
});
const runners = {
PT_RUNNER: new PeriodicTableRunner()
};
const onLoad = function () {
renderCurrentRunnerName();
generateNewPrompt();
}
let currentPrompt;
let activeRunner = runners.PT_RUNNER;
const renderCurrentRunnerName = function () {
console.log(activeRunner.name);
$("#game-name").text("The current game is " + activeRunner.name);
}
const renderCurrentPrompt = function () {
$("#prompt-target").text("Prompt: " + currentPrompt);
}
const generateNewPrompt = function () {
currentPrompt = activeRunner.generatePrompt(1);
renderCurrentPrompt();
}
const negativeColor = "#e6b2c6";
const positiveColor = "#c2e8ce";
const prefixResultsTableWithObject = function(responseObject) {
//{
// prompt: prompt,
// response: response,
// isResponseCorrect: ptdata[prompt] === response.toLowerCase(),
// correctAnswer: ptdata[prompt]
// }
let backgroundColor = responseObject.isResponseCorrect ? positiveColor : negativeColor;
let tr = $('<tr/>');
tr.append("<td>" + responseObject.prompt + "</td>");
tr.append("<td style='background-color:" + backgroundColor + "'>" + responseObject.response + "</td>");
tr.append("<td>" + responseObject.correctAnswer + "</td>");
$('#results-table').prepend(tr);
}
const processResponse = function(response) {
console.log("Current Prompt: " + currentPrompt + " ; Response: " + response);
let responseObject = activeRunner.resolveResponseAgainstPrompt(currentPrompt, response);
console.log("Response was correct?: " + JSON.stringify(responseObject));
prefixResultsTableWithObject(responseObject);
generateNewPrompt();
}
|
export default () => {
return function * (next) {
this.session.flood = this.session.flood || 0
if (this.data.date > this.session.flood) {
this.floodAction = ((name, action) => {
return this.action(name, action)
.then((msg) => {
this.session.flood = msg.date
return msg
})
})
yield next
}
}
}
|
$( document ).ready(function() {
checkAnimation();
var didScroll;
var lastScrollTop = 0;
var delta = 2;
var navbarHeight = $('nav').outerHeight();
$(window).scroll(function (event) {
didScroll = true;
});
setInterval(function () {
if (didScroll) {
checkAnimation();
didScroll = false;
}
}, 250);
function isElementVisible(elem) {
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top + 300;
return (elemTop <= docViewBottom);
}
// Check if it's time to start the animation.
function checkAnimation() {
var $elem = $('.skills');
// If the animation has already been started
if ($elem.hasClass('start')) {
return;
}
else {
if (isElementVisible($elem)) {
$elem.addClass('start');
jQuery('.skillbar').each(function(){
jQuery(this).find('.skillbar-bar').animate({
width:jQuery(this).attr('data-percent')
},2000);
});
}
}
}
$(".typedcon1").one("mouseenter", function(e){
$(".typed1").typed({
strings: ['A simple classifieds website written in PHP.']
});
})
$(".typedcon2").one("mouseenter", function(e){
$(".typed2").typed({
strings: ['A simple e-commerce website written in JavaScript.']
});
})
$(".typedcon3").one("mouseenter", function(e){
$(".typed3").typed({
strings: ['A web application to find study groups, written in JavaScript.']
});
})
$("#year").text(getCurrentYear());
$("#age").text(getAge(1996, 0, 24));
$("#nav-about").click(function(e) {
e.preventDefault();
$(window).scrollTo(document.getElementById('about'), 800);
});
$("#nav-education").click(function(e) {
e.preventDefault();
$(window).scrollTo(document.getElementById('education'), 800);
});
$("#nav-experience").click(function(e) {
e.preventDefault();
$(window).scrollTo(document.getElementById('experience'), 800);
});
$("#nav-skillset").click(function(e) {
e.preventDefault();
$(window).scrollTo(document.getElementById('skills'), 800);
});
$("#nav-projects").click(function(e) {
e.preventDefault();
$(window).scrollTo(document.getElementById('projects'), 800);
});
$("#nav-contact").click(function(e) {
e.preventDefault();
$(window).scrollTo(document.getElementById('contact'), 800);
});
var cssRule1 =
"color: #034f84;" +
"font-size: 60px;" +
"font-weight: bold;" +
"text-shadow: 1px 1px 5px #034f84;" +
"filter: dropshadow(color=#034f84, offx=1, offy=1);";
console.log("%cHello Again.", cssRule1);
var cssRule2 =
"font-size: 20px;" +
"font-weight: bold;"
console.log("%cI see you like looking under the hood, consider sending me a message or giving me credits for any website idea you may take.", cssRule2)
});
function getAge(year, month, date) {
var birthday = new Date(year, month, date);
var diff = Math.abs(Date.now() - birthday.getTime());
var age = (new Date(diff)).getUTCFullYear() - 1970;
return age;
}
function getCurrentYear() {
var year = (new Date()).getUTCFullYear();
return year;
}
|
$(function () {
//Affichage des menus
$("#sidebar>ul>li>a").click(function () {
var menucourant = $("#champ>div");
menucourant.children().appendTo($("#" + menucourant.attr("class"))); //On enlève le précédent menu
menucourant.removeClass(); //On enlève l'info sur le menu affiché
$("#champ").css('background-color', $(this).parent().css('background-color')); //La couleuuuur
$(this).parent().children("div").appendTo(menucourant); //On met le menu demandé
menucourant.addClass($(this).parent().attr("id")); //On enregistre quel est le menu actuellement affiché
if ($(this).parent().attr("id") != "#menu") {
//$("#champ>span").style.display = "block";
document.getElementById('bouffe').style.display = 'none';
document.getElementById('cocktails').style.display = 'none';
}
return false;
});
//Recherche du compte
function callback (row) {
return row[0].substring(0,row[0].indexOf(';'));
}
$("#main_nom").autocomplete("compte.php", {
max: 0,
minChars: 3,
formatItem: callback,
formatResult: callback,
width: "184px"})
.result(function (event, data, formatted) {
$(this).next().text(formatted.substring(formatted.indexOf(';')+1, formatted.indexOf(',')-1) + " €");
$(this).next().next().attr("src",formatted.substring(formatted.indexOf(',')+1, formatted.indexOf('*')));
});
//Ajouter un sorter pour les dates
$.tablesorter.addParser({
id: "date",
is: function(s) {
return /^\d{2}h\d{2} le \d{2}\/\d{2}$/.test(s);
},
format: function(s) {
return $.tablesorter.formatFloat(s.replace(/^(\d{2})h(\d{2}) le (\d{2})\/(\d{2})$/,"$4$3$1$2"));
},
type: "numeric"
});
//Tri des tableaux
$("table").tablesorter();
//Email et nom automatiques, suppression accents pour nouveau compte
function champsAuto() {
var prenom = no_accent($("#rc_prenom").val());
var nom = no_accent($("#rc_nom").val());
$("#rc_prenom").val(prenom);
$("#rc_nom").val(nom);
$("#rc_email").val(replaceAll(prenom.toLowerCase()," ","") + '.' + replaceAll(nom.toLowerCase()," ","") + '@supelec.fr');
$("#main_nom").val(prenom + " " + nom);
}
$("#rc_prenom").change(champsAuto);
$("#rc_nom").change(champsAuto);
//Création de compte : Gérer les deux champs nom
$("#tache3>a").click(function () {
$("#main_nom").attr("disabled","disabled"); //On désactive le champ de recherche
//On prépare sa réactivation
$("#sidebar>ul>li").not("#tache3").children("a").click(function (event) {
$("#main_nom").removeAttr("disabled");
$(this).unbind(event);
});
});
// Remplace toutes les occurences d'une chaine
function replaceAll(str, search, repl) {
while (str.indexOf(search) != -1)
str = str.replace(search, repl);
return str;
}
function no_accent(str) {
var norm = new Array('À','Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë',
'Ì','Í','Î','Ï', 'Ð','Ñ','Ò','Ó','Ô','Õ','Ö','Ø','Ù','Ú','Û','Ü','Ý',
'Þ','ß', 'à','á','â','ã','ä','å','æ','ç','è','é','ê','ë','ì','í','î',
'ï','ð','ñ', 'ò','ó','ô','õ','ö','ø','ù','ú','û','ü','ý','ý','þ','ÿ','\'');
var spec = new Array('A','A','A','A','A','A','A','C','E','E','E','E',
'I','I','I','I', 'D','N','O','O','O','0','O','O','U','U','U','U','Y',
'b','s', 'a','a','a','a','a','a','a','c','e','e','e','e','i','i','i',
'i','d','n', 'o','o','o','o','o','o','u','u','u','u','y','y','b','y','');
for (var i = 0; i < spec.length; i++)
str = replaceAll(str, norm[i], spec[i]);
return str;
}
// Charge dynamiquement des js au premier clic sur le lien
function chargement_js (type, nom, element) {
var adresse = 'res/js/modif_' + type + '_' + nom + '.js';
if($('head>script[src="' + adresse + '"]').length == 0) {
$(element).unbind('click');
$("head").append('<script type="text/javascript" src="' + adresse + '" />');
$(element).click();
}
return false;
}
// Modification d'une ligne d'un tableau
$("table.modifiable tr>td:first-child").click(function () {
return chargement_js('tableau', $("table.modifiable").attr('id'), this);
});
// Modification d'un compte
$("#charger_compte").click( function () {
//On charge les infos du compte
$.getJSON("donnees.php", { c: $(this).prev().val() },
function(data) {
//On remplit avec les données récupérées
//Parse nom pour prénom/surnom/nom
var prenom, surnom, nom;
var debutPseudo = data.nom.indexOf('"');
if (debutPseudo == -1) {
//Pas de surnom - limite : premier espace
var limite = data.nom.indexOf(' ');
prenom = data.nom.substring(0,limite);
nom = data.nom.substring(limite+1,data.nom.length);
surnom = '';
} else {
prenom = data.nom.substring(0,debutPseudo-1);
var finPseudo = data.nom.indexOf('"',debutPseudo+1);
surnom = data.nom.substring(debutPseudo+1,finPseudo);
nom = data.nom.substring(finPseudo+2,data.nom.length);
}
$("#rc_prenom").val(prenom);
$("#rc_surnom").val(surnom);
$("#rc_nom").val(nom);
$("#rc_id").val(data.id);
$("#rc_depot").val(data.solde);
$("#rc_email").val(data.email);
//Si un trop vieux (=pas de bouton dispo pour sa promo), on le rajoute. Et on enlève ceux rajoutés précédemment
$(".ajoute").remove();
if($("#rc_p" + data.promo).length == 0) {
$("#rc_email").parent().next().append('<input class="ajoute" type="radio" name="promo" value="' + data.promo + '" id="rc_p' + data.promo + '" /> <label class="ajoute" for="rc_p' + data.promo + '">' + data.promo + '</label>')
.children().last().prev().attr("checked","checked");
} else {
$("#rc_p" + data.promo).attr("checked","checked");
}
//On rajoute un bouton si une caution a déjà été donnée : en mettre une nouvelle ?
//Si pas déjà de caution : 0 -> non ; 1 -> oui (càd nouvelle)
//Si déjà une caution : 0 -> non (on l'enlève) ; 1 -> oui (on garde) ; 2 -> nouvelle
if (data.caution == "0" || data.caution == null) {
$("#rc_caution_0").attr("checked","checked")
$("#rc_caution_2").remove();
$("label[for='rc_caution_2']").remove();
} else {
$("#rc_caution_1").attr("checked","checked")
if ($("#rc_caution_2").length == 0) {
$("#rc_caution_1").before('<input type="radio" value="2" id="rc_caution_2" name="caution" /><label for="rc_caution_2">Nouveau chèque</label>');
}
}
$("#rc_coopeman_" + data.coopeman).attr("checked","checked");
$("#rc_ouvert_" + data.ouvert).attr("checked","checked");
});
return false;
});
});
|
/**
* Created by 叶子 on 2017/8/13.
*/
import React, { Component } from 'react';
import { Route, Redirect, Switch } from 'react-router-dom';
import Home from '../components/home/Home';
import Service from '../components/service/Service';
import Detail from '../components/service/Detail';
import Balance from '../components/account/Balance';
import Exchange from '../components/account/Exchange';
import News from '../components/system/News';
import Authentication from '../components/system/Authentication';
import OperationLog from '../components/system/OperationLog';
import SetAccount from '../components/system/SetAccount';
import ChangePwd from '../components/system/ChangePwd';
import ChangePayPwd from '../components/account/ChangePayPwd';
import CarListInfo from '../components/carinfo/carListInfo/CarListInfo'
import FormItemComponent from '../components/carinfo/fromItemComponent/FormItemComponent'
import CarMaintainRecordList from '../components/carinfo/CarMaintainRecord'
import CarMaintainRecordDetail from '../components/carinfo/CarMaintainRecordDetail'
import CarRentalRecord from '../components/carinfo/CarRentalRecord'
import CarRentalRecordDetail from '../components/carinfo/CarRentalRecordDetail'
import AnnualInspectionRecordList from '../components/otherinfo/AnnualInspectionRecordList';
import AnnualInspectionRecord from '../components/otherinfo/AnnualInspectionRecord';
import CarIllegalRecordList from '../components/otherinfo/CarIllegalRecordList';
import CarIllegalRecord from '../components/otherinfo/CarIllegalRecord';
import CarInsuranceFileRecord from '../components/otherinfo/CarInsuranceFileRecord';
import CarInsuranceFileRecordList from '../components/otherinfo/CarInsuranceFileRecordList';
import CarRepairRecordList from '../components/otherinfo/CarRepairRecordList';
import CarRepairRecord from '../components/otherinfo/CarRepairRecord';
import CarInsuranceRecordList from '../components/otherinfo/CarInsuranceRecordList';
import CarInsuranceRecord from '../components/otherinfo/CarInsuranceRecord';
import ContractListInfo from '../components/carinfo/contractListInfo/ContractListInfo'
import ContractDetail from '../components/carinfo/contractDetail/ContractDetail'
import ContractRiskList from '../components/contract_manage/ContractRiskList';
import ContractRiskDetail from '../components/contract_manage/ContractRiskDetail';
// const WysiwygBundle = (props) => (
// <Bundle >
// {(Component) => <Component {...props} />}
// </Bundle>
// );
export default class CRouter extends Component {
requireAuth = (permission, component) => {
const { auth } = this.props;
const { permissions } = auth.data;
// const { auth } = store.getState().httpData;
if (!permissions || !permissions.includes(permission)) return <Redirect to={'404'} />;
return component;
};
render() {
// if(!localStorage.getItem('piccToken')){
// return <Redirect to={'/'} />
// }
return (
<Switch>
<Route exact path="/app/home" component={Home} />
<Route exact path="/app/service" component={Service} />
<Route exact path="/app/service/detail/:id" component={Detail} />
<Route exact path="/app/account/balance" component={Balance} />
<Route exact path="/app/account/exchange" component={Exchange} />
<Route exact path="/app/account/changePayPwd" component={ChangePayPwd} />
<Route exact path="/app/system/news" component={News} />
<Route exact path="/app/system/authentication" component={Authentication} />
<Route exact path="/app/system/operationLog" component={OperationLog} />
<Route exact path="/app/system/setAccount" component={SetAccount} />
<Route exact path="/app/system/changePwd" component={ChangePwd} />
<Route exact path="/app/system/carListInfo" component={CarListInfo}/>
<Route exact path="/app/system/carMaintainList/:id" component={CarMaintainRecordList}/>
<Route exact path="/app/system/carAdd/:id/:params" component={FormItemComponent}/>
<Route exact path="/app/system/maintain/add/:id/:maintainId/:index" component={CarMaintainRecordDetail}/>
<Route exact path="/app/system/rental/record" component={CarRentalRecord}/>
<Route exact path="/app/system/rental/add/:carNumber/:index" component={CarRentalRecordDetail}/>
<Route exact path="/app/car/AnnualInspectionRecord/:carNumber/:carType" component={AnnualInspectionRecord} />
<Route exact path="/app/car/AnnualInspectionRecordList" component={AnnualInspectionRecordList} />
<Route exact path="/app/car/CarIllegalRecordList" component={CarIllegalRecordList} />
<Route exact path="/app/car/CarIllegalRecord/:carNumber/:carType" component={CarIllegalRecord} />
<Route exact path="/app/car/CarInsuranceFileRecord/:carNumber/:carType" component={CarInsuranceFileRecord} />
<Route exact path="/app/car/CarInsuranceFileRecordList" component={CarInsuranceFileRecordList} />
<Route exact path="/app/car/CarRepairRecordList" component={CarRepairRecordList} />
<Route exact path="/app/car/CarRepairRecord/:carNumber/:carType" component={CarRepairRecord} />
<Route exact path="/app/car/CarInsuranceRecordList" component={CarInsuranceRecordList} />
<Route exact path="/app/car/CarInsuranceRecord/:carNumber/:carType" component={CarInsuranceRecord} />
<Route exact path="/app/system/contractListInfo" component={ContractListInfo} />
<Route exact path="/app/system/contractDetail/:id/:source" component={ContractDetail} />
<Route exact path="/app/contract/ContractRiskList" component={ContractRiskList} />
<Route exact path="/app/contract/ContractRiskDetail/:id" component={ContractRiskDetail} />
<Route render={() => <Redirect to="/404" />} />
</Switch>
)
}
}
|
import React from 'react';
import { shallow, mount, render } from 'enzyme';
import sinon from 'sinon';
import BundleImages from '../client/src/components/BundleImages.jsx';
import BundleSelect from '../client/src/components/BundleSelect.jsx';
import Carousel from '../client/src/components/Carousel.jsx';
import HoverGallery from '../client/src/components/HoverGallery.jsx';
import PerksBanner from '../client/src/components/PerksBanner.jsx';
import ProgressBar from '../client/src/components/ProgressBar.jsx';
import TextSection from '../client/src/components/TextSection.jsx';
var testProduct = {
productId: 1,
prices: [1111.11, 2222.22, 3333.33, 4444.44],
images: ['https://i.imgur.com/GzkL3jA.jpg','https://i.imgur.com/Z0BHUC1.jpg', 'https://i.imgur.com/onllnQA.jpg', 'https://i.imgur.com/C1CFsMJ.jpg', 'https://i.imgur.com/En5loGM.jpg', 'https://i.imgur.com/xb6HmNv.jpg', 'https://i.imgur.com/uWLcPsH.jpg', 'https://i.imgur.com/NXLvw3R.jpg', 'https://i.imgur.com/thmV90m.jpg', 'https://i.imgur.com/vz5zc25.jpg', 'https://i.imgur.com/cNpUgq9.jpg', 'https://i.imgur.com/BmV2FQo.jpg', 'https://i.imgur.com/tVtaQgx.jpg', 'https://i.imgur.com/eBH9pj5.jpg'],
short_headers: ['a', 'aa aa', 'aaa aaa aaa', 'aaaa aaaa aaaa aaaa'],
long_headers: ['aaa aaa aaa', 'aaaa aaaa aaaa aaaa', 'aaaaa aaaaa aaaaa aaaaa aaaaa', 'aaaaaa aaaaaa aaaaaa aaaaaa aaaaaa aaaaaa', 'aaaaaaa aaaaaaa aaaaaaa aaaaaaa aaaaaaa aaaaaaa aaaaaaa', 'aaaaaaaa aaaaaaaa aaaaaaaa aaaaaaaa aaaaaaaa aaaaaaaa aaaaaaaa aaaaaaaa', 'aaaaaaaaa aaaaaaaaa aaaaaaaaa aaaaaaaaa aaaaaaaaa aaaaaaaaa aaaaaaaaa aaaaaaaaa aaaaaaaaa', 'aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa', 'aaaaaaaaaaa aaaaaaaaaaa aaaaaaaaaaa aaaaaaaaaaa aaaaaaaaaaa aaaaaaaaaaa aaaaaaaaaaa aaaaaaaaaaa aaaaaaaaaaa aaaaaaaaaaa', 'aaaaaaaaaaaa aaaaaaaaaaaa aaaaaaaaaaaa aaaaaaaaaaaa aaaaaaaaaaaa aaaaaaaaaaaa aaaaaaaaaaaa aaaaaaaaaaaa aaaaaaaaaaaa aaaaaaaaaaaa'],
recc_prod_names: ['a', 'aa aa', 'aaa aaa aaa', 'aaaa aaaa aaaa aaaa'],
captions: ['aaaaa aaaaa aaaaa aaaaa aaaaa. aaaaa aaaaa aaaaa aaaaa aaaaa', 'aaaaa aaaaa aaaaa aaaaa aaaaa. aaaaa aaaaa aaaaa aaaaa aaaaa', 'aaaaa aaaaa aaaaa aaaaa aaaaa. aaaaa aaaaa aaaaa aaaaa aaaaa', 'aaaaa aaaaa aaaaa aaaaa aaaaa. aaaaa aaaaa aaaaa aaaaa aaaaa', 'aaaaa aaaaa aaaaa aaaaa aaaaa. aaaaa aaaaa aaaaa aaaaa aaaaa', 'aaaaa aaaaa aaaaa aaaaa aaaaa. aaaaa aaaaa aaaaa aaaaa aaaaa', 'aaaaa aaaaa aaaaa aaaaa aaaaa. aaaaa aaaaa aaaaa aaaaa aaaaa', 'aaaaa aaaaa aaaaa aaaaa aaaaa. aaaaa aaaaa aaaaa aaaaa aaaaa', 'aaaaa aaaaa aaaaa aaaaa aaaaa. aaaaa aaaaa aaaaa aaaaa aaaaa', 'aaaaa aaaaa aaaaa aaaaa aaaaa. aaaaa aaaaa aaaaa aaaaa aaaaa', 'aaaaa aaaaa aaaaa aaaaa aaaaa. aaaaa aaaaa aaaaa aaaaa aaaaa', 'aaaaa aaaaa aaaaa aaaaa aaaaa. aaaaa aaaaa aaaaa aaaaa aaaaa', 'aaaaa aaaaa aaaaa aaaaa aaaaa. aaaaa aaaaa aaaaa aaaaa aaaaa']
};
var testDisplay = [true, true, true, true];
var testFunc = x => {};
describe('dummy test to make sure jest is working', () => {
test('checks if true is true', () => {
expect(true).toBe(true);
});
});
describe('dummy test to make sure enzyme is working', () => {
test('checks if shallowly rendered html is retrieved using .html()', () => {
const myImage = shallow(<div>test</div>);
expect(myImage.html()).toEqual('<div>test</div>');
});
});
describe('it should render the correct components', () => {
test('should render a component of type BundleImage', () => {
const myImage = shallow(<BundleImages product={testProduct} productsForDisplay={testDisplay} />);
const instance = myImage.instance();
expect(instance).toBeInstanceOf(BundleImages);
});
it("should render a component of type BundleSelect", () => {
shallow(<BundleSelect product={testProduct} productChecked={testFunc} />);
});
test('should render a component of type Carousel', () => {
const myImage = shallow(<Carousel product={testProduct}/>);
const instance = myImage.instance();
expect(instance).toBeInstanceOf(Carousel);
});
it("should render a component of type HoverGallery", () => {
shallow(<HoverGallery product={testProduct} />);
});
it("should render a component of type PerksBanner", () => {
shallow(<PerksBanner product={testProduct} />);
});
it("should render a component of type ProgressBar", () => {
shallow(<ProgressBar progress={0} />);
});
it("should render a component of type TextSection", () => {
shallow(<TextSection product={testProduct} />);
});
});
describe('It should test the carousel buttons', () => {
it('tests foreward then backward buttons', () => {
sinon.spy(Carousel.prototype, 'changeSlide');
const button = shallow(<Carousel product={testProduct} />);
button.find('.buttonNext').simulate('click');
button.find('.buttonPrev').simulate('click');
expect(Carousel.prototype.changeSlide).toHaveProperty('callCount', 2);
button.find('.buttonPrev').simulate('click');
button.find('.buttonNext').simulate('click');
expect(Carousel.prototype.changeSlide).toHaveProperty('callCount', 4);
Carousel.prototype.changeSlide.restore();
});
});
describe('It should test the bundle select checkboxes', () => {
it('tests the 1st checkbox', () => {
const mockCallBack = jest.fn();
const button = shallow(<BundleSelect product={testProduct} productChecked={mockCallBack} />);
var checkbox = () => button.find('#product1');
checkbox().simulate('change', {target: {checked: false}});
expect(mockCallBack.mock.calls.length).toEqual(1);
});
it('tests the 2nd checkbox', () => {
const mockCallBack = jest.fn();
const button = shallow(<BundleSelect product={testProduct} productChecked={mockCallBack} />);
var checkbox = () => button.find('#product2');
checkbox().simulate('change', {target: {checked: false}});
expect(mockCallBack.mock.calls.length).toEqual(1);
});
it('tests the 3rd checkbox', () => {
const mockCallBack = jest.fn();
const button = shallow(<BundleSelect product={testProduct} productChecked={mockCallBack} />);
var checkbox = () => button.find('#product3');
checkbox().simulate('change', {target: {checked: false}});
expect(mockCallBack.mock.calls.length).toEqual(1);
});
});
describe('BundleImage component updates total price accordingly', () => {
var testDisplay = [true, false, false, false];
var testDisplay2 = [true, true, false, false];
test('should call componentWillReceiveProps', () => {
const myImage = shallow(<BundleImages product={testProduct} productsForDisplay={testDisplay} />);
expect(myImage.find('#bundleprice').text().includes('$1111.11')).toBe(true);
myImage.setProps({ productsForDisplay: testDisplay2 });
expect(myImage.find('#bundleprice').text().includes('$3333.33')).toBe(true);
});
});
describe('Carousel lifecycle methods', () => {
it('calls componentDidMount and componentWillUnmount', () => {
sinon.spy(Carousel.prototype, 'componentDidMount');
sinon.spy(Carousel.prototype, 'componentWillUnmount');
const wrapper = mount(<Carousel product={testProduct}/>);
expect(Carousel.prototype.componentDidMount).toHaveProperty('callCount', 1);
wrapper.unmount();
expect(Carousel.prototype.componentWillUnmount).toHaveProperty('callCount', 1);
Carousel.prototype.componentDidMount.restore();
Carousel.prototype.componentWillUnmount.restore();
});
it('updates slide image after 7 seconds', () => {
jest.useFakeTimers()
sinon.spy(Carousel.prototype, 'changeSlide');
const wrapper = mount(<Carousel product={testProduct}/>);
expect(wrapper.find("img").prop("src")).toEqual(testProduct.images[4]);
jest.advanceTimersByTime(8000);
expect(Carousel.prototype.changeSlide).toHaveProperty('callCount', 1);
wrapper.update();
expect(wrapper.find("img").prop("src")).toEqual(testProduct.images[5]);
wrapper.unmount();
});
it('updates slide progress bar after 10 ms', () => {
jest.useFakeTimers()
sinon.spy(Carousel.prototype, 'progressBarInterval');
const wrapper = mount(<Carousel product={testProduct}/>);
jest.advanceTimersByTime(11);
expect(Carousel.prototype.progressBarInterval).toHaveProperty('callCount', 1);
wrapper.unmount();
});
});
|
module.exports = {
dir: {
includes: "_includes",
input: "src",
layouts: "_layouts",
output: "dist"
},
markdownTemplateEngine: "njk"
}
|
import React from 'react';
import './style.css'
const ImageList = (props) => {
const images = props.images.map((image)=> {
return <img key={image.id} src={image.webformatURL} alt="warn" />
})
return(
<div className='img-list'>
{images}
</div>
)
}
export default ImageList
|
var CalendarController = angular.module("CalendarController", []);
CalendarController.controller('CalendarController',
['$scope', '$window', 'CalendarService', 'AuthService', '$location', 'CaveWallAPIService',
function ($scope, $window, calendarService, authService, $location, CaveWallAPIService) {
//'use strict';
function stripEvent(evt) {
var obj =
{
EventEndDate: evt.EventEndDate,
EventID: evt.EventID,
EventIsAllDay: evt.EventIsAllDay,
EventName: evt.EventName,
EventStartDate: evt.EventStartDate,
IsDeleted: evt.IsDeleted,
UserID: evt.UserID,
};
return obj;
}
function setDateField(evt) {
if (evt.EventStartDate != null) {
evt.startHour = evt.EventStartDate.getHours() % 12;
if (evt.startHour == 0)
evt.startHour = 12;
evt.startMinute = evt.EventStartDate.getMinutes();
evt.startAmpm = evt.EventStartDate.getHours() > 11 ? "PM" : "AM";
} else {
evt.startHour = 12;
evt.startMinute = 0;
evt.startAmpm = "PM";
}
if (evt.EventEndDate != null) {
evt.endHour = evt.EventEndDate.getHours() % 12;
if (evt.endHour == 0)
evt.endHour = 12;
evt.endMinute = evt.EventEndDate.getMinutes();
evt.endAmpm = evt.EventEndDate.getHours() > 11 ? "PM" : "AM";
} else {
evt.endHour = 1;
evt.endMinute = 0;
evt.endAmpm = "PM";
}
};
function setDateTimeField(evt) {
var starthour = 0;
if (evt.startAmpm == "AM") {
if (evt.startHour == 12) {
starthour = 0;
} else {
starthour = evt.startHour;
}
} else {
if (evt.startHour == 12) {
starthour = 12;
} else {
starthour = evt.startHour + 12;
}
}
evt.EventStartDate = new Date(evt.EventStartDate.setHours(starthour));
var endhour = 0;
if (evt.endAmpm == "AM") {
if (evt.endHour == 12) {
endhour = 0;
} else {
endhour = evt.endHour;
}
} else {
if (evt.endHour == 12) {
endhour = 12;
} else {
endhour = evt.endHour + 12;
}
}
evt.EventEndDate = new Date(evt.EventEndDate.setHours(endhour));
evt.EventStartDate = new Date(evt.EventStartDate.setMinutes(evt.startMinute));
evt.EventEndDate = new Date(evt.EventEndDate.setMinutes(evt.endMinute));
}
$scope.downloadEvent = function (evt) {
setDateTimeField(evt);
evt = stripEvent(evt);
calendarService.downloadEvent(evt);
};
$scope.fileErrors = null;
$scope.checkfile = function () {
var element = document.getElementById('calendar-json-file');
var file = element.files[0];
if (file != null) {
var name = file.name;
var size = file.size;
var type = file.type;
if (file.size > 100000) {
$scope.fileErrors = "The provided file is too large";
$scope.$apply();
}
else if (file.type != 'application/json' && file.type != "") {
$scope.fileErrors = "The provided file is not a proper event file";
$scope.$apply();
} else {
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function (theFile) {
if (theFile == null || theFile.target == null || theFile.target.result == null) {
$scope.fileErrors = "The provided file is not a proper event file";
$scope.$apply();
} else {
try
{
$scope.fileErrors = null;
$scope.$apply();
var content = JSON.parse(theFile.target.result)
if (content == null) {
$scope.fileErrors = "The provided file is not a proper event file";
$scope.$apply();
} else if (content.EventStartDate == null
|| content.EventEndDate == null
|| content.EventIsAllDay == null
|| content.EventName == null) {
$scope.fileErrors = "The provided file is not a proper event file";
$scope.$apply();
} else {
content.EventID = 0;
content.UserID = 0;
content.IsDeleted = false;
document.getElementById('calendar-json-file').value = null;
calendarService.postEvent(content, function () {
calendarService.getAllEvents(function (evts) {
$("#calendar").fullCalendar('removeEvents');
$("#calendar").fullCalendar('addEventSource', evts);
$("#calendar").fullCalendar('rerenderEvents');
});
});
}
} catch (exc) {
$scope.fileErrors = "The provided file is not a proper event file";
$scope.$apply();
}
}
});
reader.readAsText(file);
}
} else {
$scope.fileErrors = null;
$scope.$apply();
}
};
$scope.eventError = null;
$scope.eventSubmit = function (newEvent) {
$scope.eventError = null;
setDateTimeField(newEvent);
if (newEvent.EventEndDate < newEvent.EventStartDate) {
if (newEvent.EventIsAllDay) {
newEvent.EventEndDate = newEvent.EventStartDate
} else {
$scope.eventError = "The end date must be later than the start date."
}
}
if (newEvent.EventName == null || newEvent.EventName == "") {
$scope.eventError = "You must enter an event name."
}
if ($scope.eventError == null) {
newEvent = stripEvent(newEvent);
if (newEvent.EventID != null) {
calendarService.updateEvent(newEvent, function () {
calendarService.getAllEvents(function (evts) {
$("#calendar").fullCalendar('removeEvents');
$("#calendar").fullCalendar('addEventSource', evts);
$("#calendar").fullCalendar('rerenderEvents');
});
});
} else {
calendarService.postEvent(newEvent, function () {
calendarService.getAllEvents(function (evts) {
$("#calendar").fullCalendar('removeEvents');
$("#calendar").fullCalendar('addEventSource', evts);
$("#calendar").fullCalendar('rerenderEvents');
});
});
}
$scope.newEvent = {};
$('#event-modal').modal('hide');
}
};
$scope.deleteEvent = function (evt) {
evt = stripEvent(evt);
calendarService.deleteEvent(evt, function () {
calendarService.getAllEvents(function (evts) {
$("#calendar").fullCalendar('removeEvents');
$("#calendar").fullCalendar('addEventSource', evts);
$("#calendar").fullCalendar('rerenderEvents');
});
});
$('#event-modal').modal('hide');
};
$scope.eventDiscard = function () {
$scope.newEvent = {};
$('#event-modal').modal('hide');
}
if (authService.getUser() == null) {
$location.path('/login');
}
var me = this; // Use "me" so we don't lose a reference to "this"
this.refreshCalendar = function () {
calendarService.getAllEvents(function (evts) {
// make events array
$("#calendar").fullCalendar({
timezone: 'local',
header: {
left: 'today prev,next',
center: '',
right: 'title'
},
timezone: 'local',
selectable: true,
// http://fullcalendar.io/
events: evts,
eventClick: function (evt) {
$scope.newEvent = evt;
setDateField($scope.newEvent);
$('#event-modal').modal('show');
$scope.$apply();
return false;
},
dayClick: function (dateInfo) {
$scope.newEvent = {
// Fix time zone issue - date is posted in UTC time, which in EST is the day before!
EventStartDate: new Date(dateInfo._d.toUTCString().slice(0, -4)),
EventEndDate: new Date(dateInfo._d.toUTCString().slice(0, -4)),
EventIsAllDay: false,
};
$scope.newEvent.EventStartDate = new Date($scope.newEvent.EventStartDate.setHours(12));
$scope.newEvent.EventEndDate = new Date($scope.newEvent.EventEndDate.setHours(13));
setDateField($scope.newEvent);
$scope.eventError = null;
$scope.$apply();
$('#event-modal').modal('show');
},
loading: function (bool) {
$('#loading').toggle(bool);
},
eventRender: function (evt, element) {
element.find('.fc-time').text($.format.date(evt.EventStartDate, "h:mm a"));
}
});
});
};
this.refreshCalendar();
}]);
|
const express=require("express");
const app=express();
const mongoose=require("mongoose");
const bodyParser=require("body-parser");
const Mark=require("../modules/marks");
app.use(express.static("public"));
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));
mongoose.connect("mongodb://localhost:27017/erpDB",{ useNewUrlParser: true, useUnifiedTopology: true});
app.get("/",function(request,response){
response.render("t-marks");
});
app.post("/",function(request,response){
const regno=request.body.regno;
const da1=request.body.da1;
const da2=request.body.da2;
const midsem=request.body.midsem;
const fat=request.body.fat;
const newmarks=new Mark({
regno:regno,
da1:da1,
da2:da2,
midsem:midsem,
fat:fat
});
newmarks.save();
response.render("t-marks");
})
module.exports=app;
|
import React from "react";
import './ApiSelector.css';
import RoundButton from "./RoundButton";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faBusAlt, faShip, faTrain } from "@fortawesome/free-solid-svg-icons";
import {Databox} from "./";
import { Link, useLocation} from "react-router-dom";
function useQuery() {
return new URLSearchParams(useLocation().search);
}
function selectedApi(query) {
if (!query) {
return []
}
let arr = query.split("+")
return arr
}
function toggleApi(query, api) {
let selected = selectedApi(query)
const index = selected.indexOf(api)
if (index !== -1) {
selected.splice(index, 1)
} else {
selected.push(api)
}
return selected;
}
export default class ApiSelector extends React.Component {
constructor(props) {
super(props);
this.state = {
HSL: false,
Sea: false,
Train: false
}
this.updateInput = this.updateInput.bind(this)
}
updateInput = input => {
console.log(input.target.id);
this.setState(state => ({
[input.target.id]: !state[input.target.id]
}))
}
render() {
return (
<Databox>
<div className={"ApiSelector"}>
<div style={{fontWeight: "600"}}>Valitse näytettävät kulkuneuvot:</div>
<div className={"Buttons"}>
<RoundButton click={this.updateInput} apiName={"Sea"} selected={this.state.Sea}>
<FontAwesomeIcon style={{fontSize: "1.25rem", marginRight: "0.25rem"}} icon={faShip}/> Meriliikenne
</RoundButton>
<RoundButton click={this.updateInput} apiName={"Train"} selected={this.state.Train}>
<FontAwesomeIcon style={{fontSize: "1.25rem", marginRight: "0.25rem"}} icon={faTrain}/> Raideliikenne
</RoundButton>
<RoundButton click={this.updateInput} selected={this.state.HSL}>
<FontAwesomeIcon style={{fontSize: "1.25rem", marginRight: "0.25rem"}} icon={faBusAlt}/> Lähiliikenne
</RoundButton>
</div>
</div>
</Databox>
)
}
}
|
import styled from "styled-components";
export const OrdersFiltersContainer = styled.div`
max-height: 247px;
display: flex;
flex-flow: column;
border: 1px solid grey;
border-right: none;
`;
export const OrdersFilter = styled.div`
width: 100%;
padding: 8px 0;
border-bottom: 1px solid gray;
font-size: 18px;
text-align: center;
text-transform: capitalize;
cursor: pointer;
transition: all 0.3s ease;
&:last-of-type {
border: none;
}
&:hover {
background-color: #d893a2;
color: white;
}
${({ active }) =>
active
? `{background-color: #d893a2;
color: white;}`
: `{background-color: lightgrey}`}
`;
|
var mongoose=require("mongoose");
var cardSchema=new mongoose.Schema({
c_number:{type:String,index:{unique:true}},
c_pin:String,
acc_num:String
});
module.exports=mongoose.model("Card",cardSchema);
|
$("document").ready(function() {
$("#top-dashboardDiv").tabs();
});
|
const mongoose = require("mongoose");
const requireLogin = require("../middlewares/requireLogin");
const Workout = mongoose.model("workouts");
module.exports = app => {
app.get("/api/workouts/:id", requireLogin, async (req, res) => {
const workout = await Workout.findById(req.params.id);
res.send(workout);
});
app.put("/api/workouts/:id", async (req, res) => {
const { exercise, reps, sets, weight } = req.body;
const workout = await Workout.findByIdAndUpdate(req.params.id, req.body.workout);
res.json(workout);
});
app.delete("/api/workouts/:id", async (req, res) => {
const workout = await Workout.findByIdAndRemove(req.params.id);
res.json(workout);
});
app.get("/api/workouts", requireLogin, async (req, res) => {
const workouts = await Workout.find({ _user: req.user.id });
res.send(workouts);
});
app.post("/api/workouts", requireLogin, async (req, res) => {
const { exercise, reps, sets, weight } = req.body;
const workout = new Workout({
exercise,
reps,
sets,
weight,
_user: req.user.id,
date: Date.now()
});
try {
await workout.save();
const user = await req.user.save();
res.send(user);
} catch (err) {
res.status(422).send(err);
}
});
};
|
#!/usr/bin/env node
var sys = require('sys');
var exec = require('child_process').exec;
var program = require('commander');
var coinspot = {
init: function () {
program
.version('0.0.1')
.option('-t, --transaction [txid]', 'Process a transaction')
.parse(process.argv);
if (program.transaction) {
this.getTransaction(program.transaction);
}
},
getTransaction: function (txid) {
exec("bitcoind gettransaction " + txid, this.processTransaction);
},
processTransaction: function (err, stdout, stderr) {
console.log(stdout);
var transaction = JSON.parse(stdout);
console.log(transaction.amount);
}
}
coinspot.init();
|
import React from 'react';
import { Link } from "react-router-dom";
import './error.css';
export default class Error404 extends React.Component {
render() {
return (
<div className="error-page-container error-404">
<div className="error-page-wrap">
<h1>404</h1>
<h2>No encontrado</h2>
<p>El recurso solicitado no ha sido encontrado</p>
<p><Link to="/">Home</Link></p>
</div>
</div>
);
}
}
|
import React from 'react';
import { Box } from '@sparkpost/matchbox';
import { tokens, meta } from '@sparkpost/design-tokens';
import { propData } from './data';
import _ from 'lodash';
function Td(props) {
return (
<Box as="td" py="200" pr="400" fontSize="200" lineHeight="200" {...props} />
);
}
function Th(props) {
return (
<Box
as="th"
textAlign="left"
fontSize="200"
lineHeight="200"
color="gray.900"
fontWeight="400"
pb="200"
{...props}
/>
);
}
function Tr(props) {
return <Box as="tr" {...props} />;
}
function SystemPropsTable(props) {
const data = propData[props.theme];
return (
<Box mb="800" mt="400">
<Box as="table" width="100%">
<thead>
<Tr borderBottom={`2px solid ${tokens.color_gray_200}`}>
<Th width="25%">{_.isArray(data) ? 'Array Index' : 'Key'}</Th>
<Th width="33%">JS Token</Th>
<Th>Value</Th>
</Tr>
</thead>
<tbody>
{_.map(_.keys(data), key => {
const metadata = _.find(meta, ['javascript', data[key]]) || {};
return (
<Tr key={key}>
<Td>{key}</Td>
<Td>{metadata.value ? data[key] : null}</Td>
<Td>{metadata.value ? metadata.value : data[key]}</Td>
</Tr>
);
})}
</tbody>
</Box>
</Box>
);
}
export default SystemPropsTable;
|
//hacemos las importaciones necesarias para que trabajemos con los modulos'
import './styles.css';
import {Todo , TodoList} from './classes'; //aqui ya no se especifica el archivo index por que lo busca por defecto
import { crearTodoHTML } from './js/componentes';
export const todoList = new TodoList();
//Como se mejora una funcion de flecha a continuacion pondre el antes de como sería
todoList.todos.forEach(crearTodoHTML) ;
//todoList.todos.forEach(todo => crearTodoHTML(todo)); aqui todavia seguimos mandando el parametro en la función.
const newTodo = new Todo('aprendiendo dart');
//todoList.todos[0].imp
console.log('todos', todoList.todos);
|
function jsonToTable(json) {
console.log(json);
const keys = Object.keys(json[0]);
console.log(keys);
const table = document.getElementById('prosby');
json.forEach((key) => {
let row = createRow(key);
table.appendChild(row);
});
}
function createRow(json) {
const tr = document.createElement('tr');
const values = Object.keys(json);
values.forEach((value) => {
const td = document.createElement('td');
if (!value.includes("id")) {
td.textContent = json[value];
tr.appendChild(td);
}
});
const acceptButton = document.createElement('button');
acceptButton.textContent = "Zaakceptuj";
acceptButton.classList.add('btn');
acceptButton.classList.add('btn-primary');
acceptButton.setAttribute('id', json.idProsby);
acceptButton.onclick = acceptProsba;
const rejectButton = document.createElement('button');
rejectButton.textContent = "Odrzuć";
rejectButton.classList.add('btn');
rejectButton.classList.add('btn-danger');
rejectButton.setAttribute('id', json.idProsby);
rejectButton.onclick = rejectProsba;
tr.appendChild(acceptButton);
tr.appendChild(rejectButton);
return tr;
}
function acceptProsba(event) {
let prosbaId = event.path[0].getAttribute('id');
fetchProsby().then((prosby) => {
let prosbyArray = prosby.prosby;
prosby.prosby = prosbyArray.filter((prosba) => prosba.idProsby != prosbaId);
let prosba = prosbyArray.filter((prosba) => prosba.idProsby == prosbaId)[0];
fetchZajecia().then((plan) => {
let className;
let oldDate;
let newDate;
plan.events.forEach((zajecia) => {
if (zajecia.id == prosba.idZajec) {
console.log(zajecia);
oldDate = parseDate(zajecia.start);
zajecia.start = prosba.newStart;
zajecia.end = prosba.newEnd;
className = zajecia.title;
newDate = parseDate(zajecia.start);
}
});
fetchOsoby().then((osoby) => {
osobyArray = osoby.osoby;
console.log(osobyArray);
console.log(prosba);
let osoba = osobyArray.filter((osoba) => osoba.id === prosba.idOsoby)[0];
const email = osoba.email;
const replyTo = "plan@wat.edu.pl";
const toName = `${osoba.imie} ${osoba.nazwisko}`;
sendEmail(email, replyTo, className, toName, oldDate, newDate).then((response) => {
savePlan(plan);
saveProsby(prosby);
location.reload();
})
});
});
});
}
function parseDate(stringDate) {
let date = new Date(stringDate);
let parsedDate = `${date.getDate()}.${date.getMonth()}.${date.getFullYear()} ${date.getHours()}:${date.getMinutes()}`
return parsedDate;
}
function sendEmail(toEmail, replyTo, className, toName, oldDate, newDate) {
var template_params = {
"toEmail": toEmail,
"replyTo": replyTo,
"className": className,
"toName": toName,
"oldDate": oldDate,
"newDate": newDate
}
var service_id = "default_service";
var template_id = "template_1APnUedw";
return emailjs.send(service_id, template_id, template_params);
}
function rejectProsba(event) {
let prosbaId = event.path[0].getAttribute('id');
fetchProsby().then((prosby) => {
let prosbyArray = prosby.prosby;
prosby.prosby = prosbyArray.filter((prosba) => prosba.idProsby != prosbaId);
saveProsby(prosby);
location.reload();
});
}
function fetchProsby() {
let url = '../prosby';
return fetch(url).
then((response) => response.json());
}
function fetchZajecia() {
let url = '../plann';
return fetch(url).
then((response) => response.json());
}
function fetchOsoby() {
let url = '../osoby';
return fetch(url).
then((response) => response.json());
}
function saveProsby(prosby) {
let url = '../prosby';
return fetch(url, {
method: 'post',
cache: "no-cache",
pragma: "no-cache",
"cache-control": "no-cache",
headers: {
"Content-Type": "application/json; charset=utf-8"
},
body: JSON.stringify(prosby)
});
}
function savePlan(plan) {
let url = '../plann';
return fetch(url, {
method: 'post',
cache: "no-cache",
pragma: "no-cache",
"cache-control": "no-cache",
headers: {
"Content-Type": "application/json; charset=utf-8"
},
body: JSON.stringify(plan)
});
}
function prepareDataForTable(prosby) {
return fetchLoggedUserData().then((userData) => {
return fetchZajecia().then((response) => {
let plan = response.events;
prosby.forEach((prosba) => {
prosba["title"] = plan[prosba.idZajec - 1].title;
});
prosby = prosby.filter((prosba) => {
let idZajec = prosba.idZajec;
let zajecia = plan.filter((zajecia) => zajecia.id == idZajec)[0];
return zajecia.idWykladowcy === userData.id;
});
return prosby;
}).then((response) => {
return fetchOsoby().then((osoby) => {
let osobyWsz = osoby.osoby;
response.forEach((prosba) => {
prosba.imie = osobyWsz[prosba.idOsoby - 1].imie;
prosba.nazwisko = osobyWsz[prosba.idOsoby - 1].nazwisko;
prosba.grupa = osobyWsz[prosba.idOsoby - 1].grupa;
});
return response;
});
});
});
}
function updateNavbar() {
fetchLoggedUserData().then((userInfo) => {
if (userInfo.role === "WYKLADOWCA") {
document.getElementById('prosbyLink').style.display = "inline-block";
} else {
document.getElementById('prosbyLink').style.display = "none";
}
let id = userInfo.id;
fetchOsoby().then(osoby => {
let osobyArray = osoby.osoby;
const osoba = osobyArray.filter(osoba => osoba.id === id)[0];
const grupa = osoba.grupa;
const userName = `${osoba.imie} ${osoba.nazwisko}`;
document.getElementById('user').textContent = userName;
document.getElementById('grupa').textContent = grupa;
});
});
}
function searchProsby() {
// Declare variables
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("searchPros");
filter = input.value.toUpperCase();
table = document.getElementById("prosby");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 1; i < tr.length; i++) {
let tdArr = [...tr[i].getElementsByTagName("td")];
let shouldBeVisible = false;
tdArr.forEach((td) => {
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
shouldBeVisible = true;
} else {
if (!shouldBeVisible)
tr[i].style.display = "none";
}
}
});
}
}
function fetchLoggedUserData() {
let url = '../user';
return fetch(url).then((response) => response.json());
}
fetchProsby().then((response) => prepareDataForTable(response.prosby).then(jsonToTable))
.catch((error) => {toastr.info('Nie masz zadnych próśb.');});
updateNavbar();
|
import React, { useState, useEffect } from "react";
import DateFnsUtils from "@date-io/date-fns";
import { withRouter } from "react-router-dom";
import {
KeyboardDateTimePicker,
MuiPickersUtilsProvider,
} from "@material-ui/pickers";
import { post } from "axios";
//--------------------------------- What was used from material ui core -------------------------------------
import {
Dialog,
Typography,
Grid,
withStyles,
TextField,
Button,
Switch,
FormGroup,
FormControlLabel,
Checkbox,
} from "@material-ui/core";
//-----------------------------------------------------------------------------------------------------------
const QuestionShuffleSwitch = withStyles((theme) => ({
root: {
width: 42,
height: 26,
padding: 0,
margin: theme.spacing(1),
},
switchBase: {
padding: 1,
"&$checked": {
transform: "translateX(16px)",
color: theme.palette.common.white,
"& + $track": {
backgroundColor: "#52d869",
opacity: 1,
border: "none",
},
},
"&$focusVisible $thumb": {
color: "#52d869",
border: "6px solid #fff",
},
},
thumb: {
width: 24,
height: 24,
},
track: {
borderRadius: 26 / 2,
border: `1px solid ${theme.palette.grey[400]}`,
backgroundColor: theme.palette.grey[50],
opacity: 1,
transition: theme.transitions.create(["background-color", "border"]),
},
checked: {},
focusVisible: {},
}))(({ classes, ...props }) => {
return (
<Switch
focusVisibleClassName={classes.focusVisible}
disableRipple
classes={{
root: classes.root,
switchBase: classes.switchBase,
thumb: classes.thumb,
track: classes.track,
checked: classes.checked,
}}
{...props}
/>
);
});
const MakeQuizForm = ({ onClose, isOpened, onSubmit, classes, match }) => {
// ---------------------------- variables with it's states that we use it in this Dialog -------------------
const [reloadProfile, setReloadProfile] = useState(true);
const [Name, setName] = useState("");
const [Description, setDescription] = useState("");
const [goodStartDate, setGoodStartDate] = useState(false);
const [goodEndDate, setGoodEndDate] = useState(false);
const [questionType, setQuestionType] = useState(false);
const [GradeAppear, setGradeAppear] = useState(false);
const [numberOfQues, setnumberOfQuestions] = useState(0);
const [Duration, setDuration] = useState(0);
const [CurrentDate, setCurrentDate] = useState(new Date());
const [date, setDate] = useState({
start: new Date(),
end: new Date(),
});
const [num, setNum] = useState([]);
//----------------------------------------------------------------------------------------------------------
const handleChange = () => {
setQuestionType((prev) => !prev);
};
const handleChangeAppear = () => {
setGradeAppear((prev) => !prev);
};
const resetStates = () => {
setName("");
setDescription("");
setDate({ start: new Date(), end: new Date() });
setDuration(0);
setnumberOfQuestions(0);
setGoodStartDate(false);
setGoodEndDate(false);
setQuestionType(false);
setGradeAppear(false);
};
// -------------------------------------------------- api Calls ------------------------------------------
const GetNumberOfGroups = async () => {
const Url = `/DoctorManagestudentsGroups/StudentGroups`;
const { data } = await post(Url, null, {
params: { SubjectID: match.params.courseId },
});
setNum(data);
};
//----------------------------------------------------------------------------------------------------------
const handleTotalGradeMethod = (value, CheckTitle) => {
{
setNum((prev) =>
prev.map((choicee) =>
choicee.number !== CheckTitle
? choicee
: { ...choicee, choose: value }
)
);
}
};
useEffect(() => {
GetNumberOfGroups();
}, []);
useEffect(() => {
if (reloadProfile) {
setReloadProfile(false);
}
}, [reloadProfile]);
return (
isOpened && (
<Dialog
open={isOpened}
maxWidth="sm"
fullWidth
PaperProps={{ className: classes.dialogPaper }}
>
<Grid
container
direction="column"
alignItems="stretch"
justify="center"
className={classes.dialog}
>
<Grid item className={classes.titleContainer}>
<Typography
variant="h3"
className={classes.boldText}
align="center"
>
Create Online Quiz
</Typography>
</Grid>
<Grid item>
<Grid container justify="space-around">
<Grid item xs={11}>
<Grid
container
direction="column"
alignItems="stretch"
justify="center"
spacing={3}
>
<Grid item>
<Grid item>
{/* Dialog Quiz Name */}
<TextField
label="Quiz Name"
rows={1}
value={Name}
onChange={(e) => {
setName(e.target.value);
}}
required
variant="outlined"
classes={{
root: classes.textFieldRoot,
}}
InputProps={{
classes: {
notchedOutline: classes.notchedOutline,
},
}}
InputLabelProps={{
classes: {
root: classes.label,
},
}}
style={{ width: "280px" }}
/>
</Grid>
<Grid item>
{/* Dialog Number Of Questions */}
<TextField
label="Number Of Questions"
value={numberOfQues}
type="number"
required
variant="outlined"
onChange={(e) => {
setnumberOfQuestions(Number.parseInt(e.target.value));
}}
classes={{
root: classes.textFieldRoot,
}}
InputProps={{
classes: {
notchedOutline: classes.notchedOutline,
},
inputProps: {
min: 0,
},
}}
InputLabelProps={{
classes: {
root: classes.label,
},
}}
style={{
width: "230px",
marginTop: "-59px",
marginLeft: "320px",
}}
/>
</Grid>
</Grid>
<Grid item style={{ marginTop: "-15px" }}>
<Grid item>
{/* Dialog Duration */}
<TextField
label="Duration (Min)"
required
value={Duration}
type="number"
variant="outlined"
onChange={(e) => {
setDuration(Number.parseInt(e.target.value));
}}
classes={{
root: classes.textFieldRoot,
}}
InputProps={{
classes: {
notchedOutline: classes.notchedOutline,
},
inputProps: {
min: 0,
},
}}
InputLabelProps={{
classes: {
root: classes.label,
},
}}
style={{ width: "230px" }}
/>
</Grid>
<Grid
item
style={{ marginTop: "-60px", marginLeft: "300px" }}
>
<Grid item>
<FormGroup>
<FormControlLabel
labelPlacement="start"
label="Shuffle Questions"
control={
<QuestionShuffleSwitch
checked={questionType}
onChange={handleChange}
/>
}
/>
</FormGroup>
</Grid>
<Grid item>
<FormGroup>
<FormControlLabel
labelPlacement="start"
label="Show Grade"
control={
<QuestionShuffleSwitch
checked={GradeAppear}
onChange={handleChangeAppear}
/>
}
/>
</FormGroup>
</Grid>
</Grid>
</Grid>
<Grid item style={{ marginTop: "20px" }}>
{/* Dialog Description */}
<TextField
label="Description"
rows={2}
multiline
fullWidth
value={Description}
onChange={(e) => {
setDescription(e.target.value);
}}
variant="outlined"
classes={{
root: classes.textFieldRoot,
}}
InputProps={{
classes: {
notchedOutline: classes.notchedOutline,
},
}}
InputLabelProps={{
classes: {
root: classes.label,
},
}}
/>
</Grid>
<Grid item>
<Grid container justify="space-between">
<Grid item xs={5}>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDateTimePicker
required
clearable
autoOk
label="Start Date"
inputVariant="standard"
value={date.start}
onChange={(e) => {
setDate(e.target.value);
}}
onChange={(date) => {
setDate((prev) => ({ ...prev, start: date }));
setCurrentDate(new Date());
}}
onError={(bad) => setGoodStartDate(!bad)}
format="yyyy/MM/dd hh:mm a"
/>
</MuiPickersUtilsProvider>
</Grid>
<Grid item xs={5}>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDateTimePicker
required
clearable
autoOk
label="End Date"
value={date.end}
onChange={(date) => {
setDate((prev) => ({ ...prev, end: date }));
setCurrentDate(new Date());
}}
onError={(bad) => setGoodEndDate(!bad)}
format="yyyy/MM/dd hh:mm a"
/>
</MuiPickersUtilsProvider>
</Grid>
</Grid>
</Grid>
</Grid>
<Grid item style={{ marginTop: "30px", marginLeft: "-200px" }}>
<Grid item style={{ marginLeft: "210px" }}>
<Typography style={{ fontSize: "25px" }}>
Groups :
</Typography>
</Grid>
<Grid item style={{ marginTop: "-40px" }}>
{num.map((choosee, index) => (
<Grid
item
style={
index % 2
? { marginLeft: "500px", marginTop: "-38px" }
: { marginLeft: "350px", marginTop: "5px" }
}
>
<Grid item>
<Typography style={{ fontSize: "25px" }}>
{choosee.number}
</Typography>
</Grid>
<Grid
item
style={{ marginTop: "-41px", marginLeft: "40px" }}
>
<Checkbox
inputProps={{
"aria-label": "uncontrolled-checkbox",
}}
checked={choosee.choose}
classes={{
root: classes.check,
checked: classes.checked,
}}
onChange={(e) => {
handleTotalGradeMethod(
e.target.checked,
choosee.number
);
}}
/>
</Grid>
</Grid>
))}
</Grid>
</Grid>
<Grid container justify="flex-end" spacing={1}>
{/* Close Button */}
<Grid item>
<Grid container justify="flex-end" spacing={1}>
<Grid item>
<Button
variant="outlined"
className={classes.cancelButton}
onClick={() => {
onClose();
resetStates();
}}
>
<Typography
variant="h6"
className={classes.boldText}
color="error"
>
Close
</Typography>
</Button>
</Grid>
</Grid>
</Grid>
{/* Create Button */}
<Grid item>
<Button
variant="outlined"
className={classes.createButton}
disabled={
Name === "" ||
!goodStartDate ||
!goodEndDate ||
date.start < CurrentDate ||
date.end < CurrentDate ||
numberOfQues === 0 ||
Duration === 0 ||
date.start > date.end ||
num?.filter((x) => x.choose == false).length >=
num.length
}
onClick={() => {
resetStates();
localStorage.setItem("numberOfQuestions", numberOfQues);
localStorage.setItem("QuizName", Name);
onSubmit({
Name,
Description,
date,
Duration,
questionType,
GradeAppear,
numberOfQues,
num,
});
}}
>
<Typography
variant="h6"
className={
Name === "" ||
!goodStartDate ||
!goodEndDate ||
date.start < CurrentDate ||
date.end < CurrentDate ||
numberOfQues === 0 ||
Duration === 0 ||
date.start > date.end ||
num?.filter((x) => x.choose == false).length >=
num.length
? classes.createText
: classes.boldText
}
>
Create
</Typography>
</Button>
</Grid>
</Grid>
</Grid>
</Grid>
</Grid>
</Grid>
</Dialog>
)
);
};
// Dialog styles
const styles = (theme) => ({
dialog: {
padding: "10px 0px",
},
multilineColor: {
color: "red",
},
titleContainer: {
marginBottom: "18px",
},
textFieldRoot: {
backgroundColor: "white",
borderRadius: "7px",
},
notchedOutline: {
borderWidth: "1px",
borderColor: `black !important`,
},
label: {
color: "black !important",
fontWeight: "600",
},
dialogPaper: {
minHeight: "auto",
padding: "20px 0px",
},
createButton: {
height: "40px",
width: "130px",
borderRadius: "16px",
border: "2px black solid",
marginTop: "10px",
},
cancelButton: {
height: "40px",
width: "130px",
borderRadius: "16px",
border: "2px red solid",
marginTop: "10px",
},
boldText: {
fontWeight: "600",
},
createText: {
color: "silver",
},
check: {
"&$checked": {
color: "#0e7c61",
},
},
checked: {},
});
export default withStyles(styles)(withRouter(MakeQuizForm));
|
(function(addon) {
if(typeof define === "function" && define.amd) {
define("clique-form.select", ["clique"], function() {
return addon(Clique);
});
}
if(!window.Clique) {
throw new Error("Clique.form.select requires Clique.core");
}
if(window.Clique) {
addon(Clique);
}
})(function(_c) {
var $;
$ = _c.$;
_c.component("formSelect", {
defaults: {
target: ">span:first"
},
boot: function() {
return _c.ready(function(context) {
return _c.$("[data-form-select]", context).each(function() {
var ele, obj;
ele = _c.$(this);
if(!ele.data("clique.data.formSelect")) {
obj = _c.formSelect(ele, _c.utils.options(ele.attr("data-form-select")));
}
});
});
},
init: function() {
var $this;
$this = this;
this.target = this.find(this.options.target);
this.select = this.find("select");
this.select.on("change", function(_this) {
return function() {
var fn, select;
select = _this.select[0];
fn = function() {
try {
this.target.text(select.options[select.selectedIndex].text);
} catch(_error) {}
return fn;
};
return fn();
};
}(this)());
return this.element.data("formSelect", this);
}
});
return _c.formSelect;
});
|
import cn from 'classnames'
export function classname (...args) {
return cn(...args)
}
|
export const ETHER_ADDRESS = '0x0000000000000000000000000000000000000000'
export const EVM_REVERT = 'VM Exception while processing transaction: revert'
export const ether = (n) => {
return new web3.utils.BN(
web3.utils.toWei(n.toString(), 'ether')
)
}
export const tokens = (n) => ether(n)
export const depositEtherEvent = async () => {
const log = result.logs[0]
log.event.should.equal('Deposit')
const events = log.args
events.token.should.equal(ETHER_ADDRESS, 'Ether is incorrect')
events.user.should.equal(user1, 'user address is incorrect')
events.amount.toString().should.equal(amount.toString(), 'amount is incorrect')
events.balance.toString().should.equal(amount.toString(), 'balance is incorrect')
}
export const depositTokenEvent = async () => {
const log = result.logs[0]
log.event.should.equal('Deposit')
const events = log.args
events.token.should.equal(token.address, 'token is incorrect')
events.user.should.equal(user1, 'user address is incorrect')
events.amount.toString().should.equal(amount.toString(), 'amount is incorrect')
events.balance.toString().should.equal(amount.toString(), 'balance is incorrect')
}
|
// Defines the custom CSS for the difficulty slider component
import { withStyles } from '@material-ui/core/styles';
import Slider from '@material-ui/core/Slider';
import ValueLabel from '@material-ui/core/Slider/ValueLabel';
// Custom styles configuration for the Difficulty Slider component
export const DiffSlider = withStyles({
root: {
color: '#34c74f',
height: 8
},
thumb: {
height: 20,
width: 20,
backgroundColor: '#ddd',
border: '0px solid currentColor',
marginTop: -7,
marginLeft: -10,
'&:focus, &:hover, &$active': {
boxShadow: 'inherit'
}
},
active: {},
valueLabel: {
left: 'calc(-50% + 4px)'
},
track: {
height: 6,
borderRadius: 4
},
markLabel: {
fontSize: '0.7em'
}
})(Slider);
// Custom styles for the Difficulty ValueLabel component
export const DiffValueLabel = withStyles({
thumb: {
'&$open': {
'& $offset': {
transform: 'scale(.9) translateY(-5px)'
}
}
},
open: {},
offset: {
zIndex: 1,
lineHeight: 1.2,
top: -46,
left: -10,
transformOrigin: 'bottom center',
transform: 'scale(0)',
position: 'absolute'
},
circle: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
width: 40,
height: 40,
borderRadius: '50% 50% 50% 0',
backgroundColor: 'currentColor',
transform: 'rotate(-45deg)'
},
label: {
transform: 'rotate(45deg)'
}
})(ValueLabel);
|
const router = require("express").Router();
const projectRoutes = require("./projects");
const taskRoutes = require("./tasks");
const usertaskRoutes = require("./usertasks");
const projecttaskRoutes = require("./projecttasks");
const userprojectRoutes = require("./userprojects");
const taskCommentsRoutes = require('./taskComments');
router.use("/projects", projectRoutes);
router.use("/tasks", taskRoutes);
router.use("/usertasks",usertaskRoutes);
router.use("/projecttasks",projecttaskRoutes);
router.use("/userprojects", userprojectRoutes);
router.use('/taskComments', taskCommentsRoutes)
module.exports = router;
|
// stringify.test.js
let assert = require('assert');
let expect = require('chai').expect;
let should = require('chai').should();
const stringify = require ('./stringify.js');
describe.skip("`stringify()`", function () {
// describe("`stringify()`", function () {
it("given an object with properties should return a multi-line string", function(){
let str = stringify({name: "Arthur", swallow: "European"});
let numLines = str.split(/\n/);
expect(numLines).to.have.lengthOf.above(1);
});
it("given a string should return it", function(){
let str = stringify("I don't know! AHHHhhhh...");
expect(str).to.have.string("I don't know! AHHHhhhh...");
});
it("given a number should return a string of that number", function(){
let str = stringify(5);
expect(str).to.have.string("5");
});
it("given an array should return a multi-line string?", function(){
let str = stringify([5, 6]);
let numLines = str.split(/\n/);
expect(numLines).to.have.lengthOf.above(1);
});
// given a function throws an error (worth testing?)
});
|
const path = require('path')
const merge = require('webpack-merge')
const common = require('./webpack.config.js')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const FaviconsWebpackPlugin = require('favicons-webpack-plugin')
module.exports = merge(common, {
mode: 'production',
devtool: 'source-map',
plugins: [
new FaviconsWebpackPlugin({
logo: './app/assets/favicon/matrix.png',
mode: 'webapp',
devMode: 'webapp',
inject: true,
prefix: 'assets/favicons/',
favicons: {
appName: 'skeleton',
appDescription: 'FTD',
developerName: 'FTD Educação',
developerURL: null,
background: '#ddd',
theme_color: '#333',
icons: {
coast: false,
yandex: false,
windows: false
}
}
}),
]
})
|
$(function(){
$(".VImgTitle_link a").eq(0).click(function(){
$("body,html").animate({scrollTop: 0},500);
})
if ((screen.width>750)) {
$(".VImgTitle_link a").eq(1).click(function(){
$("body,html").animate({scrollTop: 14246},500);
})
$(".VImgTitle_link a").eq(2).click(function(){
$("body,html").animate({scrollTop: 21595},500);
})
}else {
// window.onresize=function(){
// var rh1 = $(".Haoban").height();
// var rh2 = $(".BiaoZhun").height();
// var rh3 = $(".artArea").height();
// console.log(rh1);
// console.log(rh2);
// console.log(rh3);
// }
$(".VImgTitle_link a").eq(1).click(function(){
var rh1 = $(".Haoban").height();
var rh2 = $(".BiaoZhun").height();
var rh3 = $(".artArea").height();
$("body,html").animate({scrollTop: (rh1+20)},500);
})
$(".VImgTitle_link a").eq(2).click(function(){
var rh1 = $(".Haoban").height();
var rh2 = $(".BiaoZhun").height();
var rh3 = $(".artArea").height();
$("body,html").animate({scrollTop:(rh2+rh1+20)},500);
})
}
$(".VImgTitle_link a").click(function(){
$(this).addClass("VImgtActive").siblings().removeClass("VImgtActive");
})
})
|
import React, { PropTypes } from 'react'
var Dropdown = React.createClass({
getInitialState() {
return {
isOpen: false
}
},
closeDropdown(event) {
event.preventDefault()
this.setState({ isOpen: false })
},
toggleDropdown(event) {
event.preventDefault()
this.setState({
isOpen: ! this.state.isOpen
})
},
render() {
let { children } = this.props
let { isOpen } = this.state
var renderedChildren = React.Children.map(children, (child) => {
return React.addons.cloneWithProps(child, {
toggleDropdown: this.toggleDropdown,
isOpen: isOpen
})
})
let css = {
position: 'relative'
}
return <div {...this.props} style={css} onMouseLeave={this.closeDropdown}>{renderedChildren}</div>
}
})
var DropdownTitle = React.createClass({
render() {
let { children, toggleDropdown } = this.props
return (
<a href={true} onClick={toggleDropdown}>{children}</a>
)
}
})
var DropdownContent = React.createClass({
propTypes: {
isOpen: PropTypes.bool
},
getDefaultProps() {
return {
isOpen: false
}
},
render() {
let { isOpen, children } = this.props
let css = {
opacity: isOpen ? 1 : 0,
display: isOpen ? 'block' : 'none'
}
return (
<ul className="dropdown-content" style={css}>
{children}
</ul>
)
}
})
export default { Dropdown, DropdownTitle, DropdownContent }
|
import React from "react";
export default function Header() {
return (
<header>
<h1>
<a href="">
<span className="header-logo">TODO</span>
</a>
</h1>
</header>
);
}
|
class Application extends React.Component {
constructor(props){
super(props);
var config = new Config();
config.load_from_local_storage();
var chat_service = new IRCwithIRCloud({
config: config,
update_state: ()=>{this.update_state()},
start_loading: ()=>{this.start_loading()},
end_loading: ()=>{this.end_loading()}
});
this.state = {chat_service: chat_service, config_is_active: false, main_is_active: true, config: config};
}
componentDidMount(){
var state = this.state;
state.chat_service.connect();
this.setState(state);
if(this.to_config_open()){ this.open_config() }
}
to_config_open(){
return !this.state.config.can_connect();
}
select_channel(bid){
var state = this.state;
state.current_bid = bid;
this.setState(state);
}
update_state(){
this.setState(this.state);
}
open_config(){
var state = this.state;
state.main_is_active = false;
state.config_is_active = true;
this.setState(state);
}
open_main(){
var state = this.state;
state.main_is_active = true;
state.config_is_active = false;
this.setState(state);
}
start_loading(){
var state = this.state;
state.loading_status = true;
this.setState(state);
}
end_loading(){
var state = this.state;
state.loading_status = false;
this.setState(state);
}
render(){
return <div>
<SideNavComponent
open_config={()=> this.open_config()}
open_main={()=> this.open_main()}
select_channel={(c)=> this.select_channel(c)}
chat_service={this.state.chat_service}
loading_status={this.state.loading_status}
current_bid={this.state.current_bid}
/>
<ConfigComponent config={this.state.config} status={this.state.config_is_active}/>
<MainComponent
chat_service={this.state.chat_service}
current_bid={this.state.current_bid}
status={this.state.main_is_active}
/>
</div>
}
}
window.Application = Application;
|
import React from 'react';
import PrimeraApp from "../PrimeraApp"
import { shallow } from 'enzyme'
describe('Test in PrimeraApp', () => {
/*
test('should show an message "Hellow im goky"', () => {
const greeting = "Hi! i'm Goku"
const {getByText} = render(<PrimeraApp saludo={greeting}/>)
expect( getByText(greeting)).toBeInTheDocument();
})
*/
test('should show <PrimeraApp/> correctly', () => {
const wrapper = shallow(<PrimeraApp saludo="Hellow!" />)
expect(wrapper).toMatchSnapshot();
})
test('should show the subtitle sneded by props', () => {
const greeting = 'Hello im Goku!'
const subtitle = 'Im subtitle'
const wrapper = shallow(<PrimeraApp saludo={greeting} subtitulo={subtitle} />)
const parragrapthText = wrapper.find('p').text()
})
})
|
import Head from "next/head";
import Link from "next/link";
import { FaGithub, FaLinkedin, FaInstagram } from "react-icons/fa";
//import the packages for interacting with wordpress
import { gql } from "@apollo/client";
import { client } from "../services/index";
export default function Home({ title, tagline, posts }) {
return (
<div className="home__container">
<Head>
<title>React Wordpress Portfolio</title>
<meta
name="description"
content="React based portfolio using wordpress as a headless CMS."
/>
</Head>
<main>
<article className="home__hero">
<div>
<h1 className="home__hero__title">{title}</h1>
<h3 className="home__hero__subtitle">{tagline}</h3>
</div>
<div className="home__button__and__icons">
<Link href="/projects">
<button className="hero__button">View Work</button>
</Link>
<div className="home__icon__group">
<a
href="https://github.com/PatKeenan"
target="_blank"
rel="noopener"
rel="noreferrer"
>
<FaGithub />
</a>
<a
href="https://www.linkedin.com/in/pat-keenan/"
target="_blank"
rel="noopener"
rel="noreferrer"
>
<FaLinkedin />
</a>
<a
href="https://www.instagram.com/patkeenan316/"
target="_blank"
rel="noopener"
rel="noreferrer"
>
<FaInstagram />
</a>
</div>
</div>
</article>
</main>
<footer className="home__footer">
<p>
Built with <span className="accent"> Next.js</span> &
<span className="accent">Wordpress</span>
</p>
</footer>
</div>
);
}
//grab the data from wordpress using static props and apollo
export async function getStaticProps(context) {
const results = await client.query({
query: gql`
query HomePageData {
allSettings {
generalSettingsTitle
generalSettingsDescription
}
}
`,
});
return {
//pass the data returned from wordpress into the props
props: {
title: results.data.allSettings.generalSettingsTitle,
tagline: results.data.allSettings.generalSettingsDescription,
},
// rebuild if project is added to wordpress
revalidate: 1,
};
}
|
const express = require("express");
const { body, validationResult } = require("express-validator");
const UserController = require("../controllers/UserController");
const passport = require("passport");
const User = require("../models/User");
const bcrypt = require("bcrypt");
const { isAdmin, isAuth } = require("../config/auth");
const router = express.Router();
router.get("/user/:username",isAuth, UserController.findByUsername);
router.get("/users", isAuth, UserController.findAll);
router.post("/user/", UserController.create);
router.put("/user/:username",isAuth, UserController.update);
router.delete("/user/:username", isAuth, UserController.deleteUser);
router.get("/admins", isAuth, isAdmin, UserController.getAllAdmins);
router.get("/user", isAuth, UserController.getBook);
router.delete("/user", isAuth, UserController.removeBook);
router.post("/user", isAuth, UserController.addBook);
router.get("/logSucces",(req,res)=>{
res.status(200).send("Loged in succesfully!!");
})
router.post("/login", (req, res, next) => {
passport.authenticate("local", {
successRedirect: "/logSucces",
failureRedirect: "/login",
failureFlash: true,
})(req, res, next);
});
router.post("/register", (req, res) => {
const { username, email, password, role } = req.body;
User.findOne({ email: email }).exec((err, user) => {
console.log(user);
if (user) {
errors.push({ msg: "email already registered" });
res.render("register", { errors, name, email, password, password2 });
} else {
const newUser = new User({
username: username,
email: email,
password: password,
role: role,
});
//hash password
bcrypt.genSalt(10, (err, salt) =>
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
//save pass to hash
newUser.password = hash;
//save user
newUser
.save()
.then((value) => {
res.redirect("/login");
})
.catch((value) => console.log(value));
})
);
}
});
});
router.post("/logout", (req, res) => {
req.logout();
res.status(200).send("You are logged out.");
});
module.exports = router;
|
// server.js
// where your node app starts
const onetime = require('./onetimers')
const conf = require('./conf/config');
const logger = conf.logger;
require('dotenv')
.config();
//OTHER SERVER MODULES MADE BY US
const discordbot = require('./discordbot.js'); //SHUTDOWN UNTIL FURTHER NOTICE
const db = require('./dbfunctions.js');
const warapi = require('./warapi.js');
const socket = require('./socket.js');
// init project
const express = require('express');
const app = express();
var http = require('http')
.Server(app);
var session = require('express-session');
var passport = require('passport');
const shortid = require('shortid');
var SteamStrategy = require('passport-steam').Strategy;
const apikey = process.env.KEY;
//warapi.updateMap();
//warapi.pullStatic();
//warapi.updateStaticTowns();
http.listen(3000, function () {
logger.info('Your app is listening on port 3000')
});
//exports.listener = listener;
app.use(express.static('src'));
socket.import(http);
////STEAM AUTH AREA
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (obj, done) {
done(null, obj);
});
passport.use(new SteamStrategy({
returnURL: conf.fhghq.url + '/auth/steam/return',
realm: conf.fhghq.url,
apiKey: conf.steamApi.key
},
function (identifier, profile, done) {
// asynchronous verification, for effect...
process.nextTick(function () {
profile.identifier = identifier;
return done(null, profile);
});
}
));
app.use(session({
secret: 'your secret',
name: 'name of session id',
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(__dirname + '/../../src'));
app.get('/auth/steam',
passport.authenticate('steam', { failureRedirect: '/' }),
function (req, res) {
res.redirect('/');
});
app.get('/auth/steam/return',
passport.authenticate('steam', { failureRedirect: '/' }),
function (req, res) {
var salt = shortid.generate();
//console.log("User "+req.user._json.steamid+" "+req.user._json.personaname+" has logged on");
//discordbot.auth(req.user._json.steamid,req.user._json.personaname);
if (!db.existscheck(req.user._json.steamid)) {
db.insertuser.run(req.user._json.steamid, salt, req.user._json.personaname, req.user._json.avatarmedium);
} else {
salt = db.getaccount(req.user._json.steamid).salt;
db.updateuser.run(req.user._json.personaname, req.user._json.avatarmedium, req.user._json.steamid);
}
//res.clearCookie('')
res.cookie('steamid', req.user._json.steamid);
res.cookie('salt', salt);
if (req.headers['cookie'] === undefined) {
res.redirect('/');
} else if (!req.headers['cookie'].includes('redir_room')) {
res.redirect('/');
} else {
var cookiestring = req.headers['cookie'];
var id = cookiestring.substring(cookiestring.indexOf(' redir_room') + 12, cookiestring.indexOf(' redir_room') + 21);
res.redirect('/room/' + id);
}
});
app.post('/noauth', function (req, res) {
var idsalt = shortid.generate()
.slice(0, 8);
var salt = shortid.generate();
db.insertuser.run('anonymous' + idsalt, salt, req.query.name, new Date().toString());
res.cookie('steamid', 'anonymous' + idsalt);
res.cookie('salt', salt);
//console.log("Anonymous login",idsalt)
if (req.headers['cookie'] == undefined) {
res.send({ redir: false });
//res.redirect('/');
} else if (!req.headers['cookie'].includes('redir_room')) {
res.send({ redir: false });
//res.redirect('/');
} else {
//console.log("redirecting noauth")
var cookiestring = req.headers['cookie'];
var id = cookiestring.substring(cookiestring.indexOf(' redir_room') + 12, cookiestring.indexOf(' redir_room') + 21);
//console.log("redir room",id)
res.send({
redir: true,
redirId: id
});
//res.redirect('/room/'+id);
}
});
//app.listen(3000);
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/');
}
////STEAM AUTH AREA ENDS
//About
app.get('/about', function (request, response) {
if (db.logincheck(request)) {
response.sendFile(__dirname + '/views/about.html');
} else {
response.redirect('/auth');
}
});
//Profile page
app.get('/', function (request, response) {
if (db.logincheck(request)) {
response.sendFile(__dirname + '/views/index.html');
} else {
response.redirect('/auth');
}
});
//Get users profile from the DB
app.post('/getprofile', function (request, response) {
if (db.logincheck(request)) {
var id = request.query.id;
var account = db.getaccount(id);
//console.log(id)
//console.log(request.query);
var packet = {
name: account.id,
name: account.name,
blueprint: account.blueprint,
avatar: account.avatar
};
//console.log(packet);
response.send(packet);
} else {
response.redirect('/auth');
}
});
//Get info on rooms connected to a profile
app.post('/getuserrooms', function (request, response) {
var rooms = db.getrooms(request.query.id);
response.send(rooms);
});
//Leave a room from profile page
app.post('/leaveroom', function (request, response) {
if (db.logincheck(request)) {
var account = parsecookies(request);
var globalid = request.query.globalid;
var roominfo = db.getroominfo(request.query.globalid);
if (account.id != roominfo.adminid) {
var packet = {
globalid: globalid,
userid: account.id
};
socket.emitleaveroom(packet);
}
db.leaveroom(account.id, globalid);
response.redirect('/');
}
});
//Authorization page
app.get('/auth', function (request, response) {
response.sendFile(__dirname + '/views/auth.html');
});
//Request page for a room - get link
app.get('/request/:id', function (request, response) {
if (db.logincheck(request)) {
response.sendFile(__dirname + '/views/request.html');
} else {
response.redirect('/auth');
}
});
//Request page, part 2 - return user status in the room
app.post('/request2', function (request, response) {
var globalid = request.query.id;
var account = parsecookies(request);
var rank = db.getmembership(account.id, globalid);
var roominfo = db.getroominfo(globalid);
//console.log(roominfo);
if (!roominfo) {
var packet = { rank: 8 };
//console.log(packet);
response.send(packet);
} else {
let settings = JSON.parse(roominfo.settings);
var packet = {
rank: rank,
roomname: settings.name,
secure: settings.secure,
admin: roominfo.adminname,
adminid: roominfo.adminid
};
//console.log(packet);
response.send(packet);
}
});
//Request page, part 3 - submit access request
app.post('/request3', function (request, response) {
var globalid = request.query.globalid;
var account = parsecookies(request);
var rank = db.getmembership(account.id, globalid);
//console.log(rank);
if (rank == 8) {
response.redirect('/');
}
if (rank == 7) {
db.insertrelation.run(account.id + globalid, account.id, globalid, 5, '[0,0]');
var packet = {
globalid: globalid,
userid: account.id
};
socket.emitaccessrequest(packet);
// discordbot.requestaccess(account.id,globalid);
response.redirect('/');
}
});
//Request unsecure page - submit password
app.post('/requestPassword', function (request, response) {
var globalid = request.query.globalid;
var account = parsecookies(request);
//console.log(request.originalUrl);
let check = db.checkpassword(globalid, request.query.password);
if (check) {
db.insertrelation.run(account.id + globalid, account.id, globalid, 3, '[0,0]');
response.send('right');
} else {
response.send('wrong');
}
});
//Creates a room
app.post('/createroom', function (request, response) {
var id = shortid.generate();
var admin = request.query.id;
let settings = request.query.settings;
db.createroom(id, admin, settings);
response.send(id);
});
//Pulls room from a unique link
app.get('/room/:id', function (request, response) {
//console.log(request.headers['cookie'] )
// var order = db.get('orders').find({ id: request.params.id}).value();
if (db.logincheck(request)) {
var account = parsecookies(request);
var rank = db.getmembership(account.id, request.params.id);
if (rank < 4) {
response.sendFile(__dirname + '/views/global.html');
}
if (rank >= 4) {
response.redirect('/request/' + request.params.id);
}
} else {
response.cookie('redir_room', request.params.id);
response.redirect('/auth');
}
});
//pulls room from a unique link, part 2
app.post('/getroom', function (request, response) {
var packet = {};
packet.users = db.getroomusers(request.query.id);
packet.meta = db.getroominfo(request.query.id);
packet.meta.settings = JSON.parse(packet.meta.settings);
packet.dynamic = db.getdynamic();
packet.static = db.getstatic();
packet.private = db.getprivateroominfo(request.query.id);
packet.events = db.getallevents(request.query.id);
packet.stats = { totalplayers: socket.totalplayers };
response.send(packet);
});
app.get('/getcurrentwar', function (request, response) {
var packet = {
totalplayers: socket.totalplayers,
warstats: socket.warstats,
wr: warapi.WR,
currentwar: socket.currentwar
};
response.send(packet);
});
//Pulls room from a unique link
app.get('/getwar/:warnumber', function (request, response) {
let war = db.GetWar(request.params.warnumber);
response.send(war);
});
//Get account data from cookies
function parsecookies(request) {
if (request.headers['cookie'] == undefined) {
return false;
}
if (!request.headers['cookie'].includes('salt')) {
return false;
}
var cookiestring = request.headers['cookie'];
var id = cookiestring.substring(cookiestring.indexOf(' steamid=') + 9, cookiestring.indexOf(' steamid=') + 26)
.replace(';', '');
var salt = cookiestring.substring(cookiestring.indexOf(' salt=') + 6, cookiestring.indexOf(' salt=') + 15)
.replace(';', '');
var result = {
id: id,
salt: salt
};
return result;
}
//onetimers.wipe();
//discordbot.cunt("loaded");
db.cunt('loaded');
warapi.cunt('loaded');
socket.cunt('loaded');
//patch();
function patch() {
warapi.updateMap();
warapi.pullStatic();
warapi.updateStaticTowns();
}
|
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
export default function handler(req, res) {
const url = req.query.TrackURL;
fetch(url).then((response) => {
response.text().then((text) => {
const trackID = text
.split('content="soundcloud://sounds:')[1]
.split('"><meta')[0];
res.status(200).json({ trackID: trackID });
});
});
}
|
"use strict";
exports.DataGridViews = exports.viewFunction = void 0;
var _inferno = require("inferno");
var _vdom = require("@devextreme/vdom");
var _grid_base_views = require("../grid_base/grid_base_views");
var _uiGrid_core = require("../../../../ui/grid_core/ui.grid_core.grid_view");
var _data_grid_props = require("./common/data_grid_props");
var _common = require("../../../../core/utils/common");
var _excluded = ["instance", "showBorders"];
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var VIEW_NAMES = _uiGrid_core.gridViewModule.VIEW_NAMES;
var DATA_GRID_CLASS = "dx-datagrid";
var DATA_GRID_ROLE_NAME = "grid";
var viewFunction = function viewFunction(_ref) {
var showBorders = _ref.props.showBorders,
views = _ref.views;
return (0, _inferno.createComponentVNode)(2, _grid_base_views.GridBaseViews, {
"views": views,
"className": DATA_GRID_CLASS,
"showBorders": showBorders,
"role": DATA_GRID_ROLE_NAME
});
};
exports.viewFunction = viewFunction;
var DataGridPropsType = {
showBorders: _data_grid_props.DataGridProps.showBorders
};
var DataGridViews = /*#__PURE__*/function (_InfernoComponent) {
_inheritsLoose(DataGridViews, _InfernoComponent);
function DataGridViews(props) {
var _this;
_this = _InfernoComponent.call(this, props) || this;
_this.state = {};
_this.update = _this.update.bind(_assertThisInitialized(_this));
return _this;
}
var _proto = DataGridViews.prototype;
_proto.createEffects = function createEffects() {
return [new _vdom.InfernoEffect(this.update, [this.props.instance])];
};
_proto.updateEffects = function updateEffects() {
var _this$_effects$;
(_this$_effects$ = this._effects[0]) === null || _this$_effects$ === void 0 ? void 0 : _this$_effects$.update([this.props.instance]);
};
_proto.update = function update() {
var gridInstance = this.props.instance;
if (!gridInstance) {
return;
}
var dataController = gridInstance.getController("data");
var resizingController = gridInstance.getController("resizing");
(0, _common.deferRender)(function () {
resizingController.resize();
if (dataController.isLoaded()) {
resizingController.fireContentReadyAction();
}
});
};
_proto.render = function render() {
var props = this.props;
return viewFunction({
props: _extends({}, props),
views: this.views,
restAttributes: this.restAttributes
});
};
_createClass(DataGridViews, [{
key: "views",
get: function get() {
var _this2 = this;
if (!this.props.instance) {
return [];
}
var views = VIEW_NAMES.map(function (viewName) {
return _this2.props.instance.getView(viewName);
}).filter(function (view) {
return view;
});
return views.map(function (view) {
return {
name: view.name,
view: view
};
});
}
}, {
key: "restAttributes",
get: function get() {
var _this$props = this.props,
instance = _this$props.instance,
showBorders = _this$props.showBorders,
restProps = _objectWithoutProperties(_this$props, _excluded);
return restProps;
}
}]);
return DataGridViews;
}(_vdom.InfernoComponent);
exports.DataGridViews = DataGridViews;
DataGridViews.defaultProps = _extends({}, DataGridPropsType);
|
import React, { Component } from 'react';
import PartnerIdComponentForm from './PartnerIdComponentForm'
import axios from "axios"
import {Link} from 'react-router-dom';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Navbar from './layout/Navbar';
import { withRouter } from 'react-router-dom';
import { logoutUser } from '../globalState/actions/authentication';
//import { Router, Route, Link } from 'react-router'
class PartnerProfile extends Component {
state = {
_id:null,
email: null,
name: null,
boardOfMembers: null,
vacancies: null,
partners: null,
pastProjects: null,
description: null,
fieldOfWork: null,
}
getPartner = (e) => {
e.preventDefault();
//console.log("in get partner")
const {isAuthenticated, user} = this.props.auth;
this.state._id={user}.user.id;
//console.log(this.state._id)
const partner =this.state._id;
const tokenB= localStorage.getItem('jwtToken');
console.log(tokenB)
//const partner = e.target.elements.id.value;
if(partner){
axios.get(`http://localhost:5000/api/partners/${partner}`, {
Authorization: tokenB
}).then((res) =>{
const _id = partner;
const email = res.data.email;
const name = res.data.name;
const boardOfMembers = res.data.boardOfMembers;
const vacancies = res.data.vacancies;
const partners = res.data.partners;
const pastProjects = res.data.pastProjects;
const description = res.data.description;
const fieldOfWork = res.data.fieldOfWork;
this.setState({_id})
this.setState({email})
this.setState({name})
this.setState({boardOfMembers})
this.setState({vacancies})
this.setState({partners})
this.setState({pastProjects})
this.setState({description})
this.setState({fieldOfWork})
})
} else return;
}
render() {
const {isAuthenticated, user} = this.props.auth;
//console.log({user}.user.id)
this.state._id={user}.user.id;
//this.getPartner;
//console.log(this.state._id)
return (
<div>
{/* <PartnerIdComponentForm getPartner={this.getPartner}/> */}
<center>
{/* { this.getPartner} */}
{ this.state.email ? <p><h4>Email:</h4> {this.state.email}</p>:<p></p>}
{ this.state.name ? <p><h4>Name:</h4> {this.state.name}</p>:<p></p>}
{ this.state.boardOfMembers ? <p><h4>Board Of Members:</h4>{this.state.boardOfMembers}</p>:<p></p> }
{ this.state.vacancies ? <p><h4>Vacancies:</h4><ol>{this.state.vacancies.map(item => <li>{item.title}</li>)}</ol></p>:<p></p> }
{ this.state.partners ? <p><h4>Partners:</h4>{this.state.partners}</p>:<p></p> }
{ this.state.pastProjects ? <p><h4>Past Projects:</h4>{this.state.pastProjects}</p>:<p></p> }
{ this.state.description ? <p><h4>Description:</h4> {this.state.description}</p>:<p></p>}
{ this.state.fieldOfWork ? <p><h4>Field Of Work:</h4> {this.state.fieldOfWork}</p>:<p></p>}
<button onClick={this.getPartner}>View My Profile </button>
</center>
</div>
);
}
}
PartnerProfile.propTypes = {
logoutUser: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired
}
const mapStateToProps = (state) => ({
auth: state.auth
})
/*
EduOrgProfile.propTypes = {
logoutUser: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired
}
const mapStateToProps = (state) => ({
auth: state.auth
})
//export default EduOrgProfile;
export default connect(mapStateToProps)(withRouter(EduOrgProfile));
*/
export default connect(mapStateToProps)(withRouter(PartnerProfile));
//export default PartnerProfile;
|
$(function(){
var yearDate = new Date().getFullYear();
$('#year').html(yearDate);
});
$(window).scroll(function() {
var scrollpos = $(window).scrollTop();
/*if (scrollpos > 200) {
$('.nav-bar').css('background-color', 'rgba(15, 19, 25, 0.90)');
} else {
$('.nav-bar').css('background-color', 'rgba(0, 0, 0, 0.25)');
}*/
$('.fade-in-scroll').each( function(i){
var bottom_of_object = $(this).offset().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
if( bottom_of_window > bottom_of_object ){
$(this).animate({'opacity':'1'},400);
}
});
$('.fade-in-left').each( function(i){
var bottom_of_object = $(this).offset().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
if( bottom_of_window > bottom_of_object ){
$(this).addClass('fadein-left-animate');
}
});
});
$(window).on("load", function(){
$('.main-fullscreen').addClass('fadein-onload');
$('.content-container-2').addClass('fadein-longdelay');
$('#open').click(function() {
$('#mobile-nav-overlay').fadeIn('overlay-show');
$('#open').attr('aria-expanded', 'true');
});
$('#close').click(function() {
$('#mobile-nav-overlay').fadeOut('overlay-show');
$('#close').attr('aria-expanded', 'false');
});
$('#mobile-menu ul li a').click(function() {
$('#mobile-nav-overlay').fadeOut('overlay-show');
$('#close').attr('aria-expanded', 'false');
});
});
/*$(document).ready(function() {
$(window).scroll( function(){
$('.fade-in-scroll').each( function(i){
var bottom_of_object = $(this).offset().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
if( bottom_of_window > bottom_of_object ){
$(this).animate({'opacity':'1'},400);
}
});
$('.fade-in-left').each( function(i){
var bottom_of_object = $(this).offset().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
if( bottom_of_window > bottom_of_object ){
$(this).addClass('fadein-left-animate');
}
});
});
});*/
$(function(){
var email = 'enquiries';
$('#enquiries').html(email);
});
function filterPath(string) {
return string
.replace(/^\//, '')
.replace(/(index|default).[a-zA-Z]{3,4}$/, '')
.replace(/\/$/, '');
}
var locationPath = filterPath(location.pathname);
$('a[href*="#"]').each(function () {
var thisPath = filterPath(this.pathname) || locationPath;
var hash = this.hash;
if ($("#" + hash.replace(/#/, '')).length) {
if (locationPath == thisPath && (location.hostname == this.hostname || !this.hostname) && this.hash.replace(/#/, '')) {
var $target = $(hash), target = this.hash;
if (target) {
$(this).click(function (event) {
event.preventDefault();
$('html, body').animate({scrollTop: $target.offset().top}, 1000, function () {
location.hash = target;
$target.focus();
if ($target.is(":focus")){
return false;
}else{
$target.attr('tabindex','-1');
$target.focus();
};
});
});
}
}
}
});
|
const _ = window._;
const React = window.React;
const ReactDOM = window.ReactDOM;
const Griddle = window.Griddle;
const customColumnProps = {
data: React.PropTypes.object.required,
rowData: React.PropTypes.object.required,
metadata: React.PropTypes.object.required,
};
const CheckboxColumn = React.createClass({
propTypes: customColumnProps,
render() {
const columnName = this.props.metadata.columnName;
const columnValue = this.props.rowData[columnName];
if (columnValue) {
return <div>YES</div>;
} else {
return <div />;
}
},
});
const AttachmentsColumn = React.createClass({
propTypes: customColumnProps,
render() {
const columnName = this.props.metadata.columnName;
const attachments = this.props.rowData[columnName];
const attachmentImages = _.map(attachments, attachment => {
return <img className="artworkPreview" key={attachment.id} src={attachment.url} />;
});
return <div>{attachmentImages}</div>;
},
});
const ArtGallery = React.createClass({
propTypes: {
artists: React.PropTypes.array,
updateOnDisplay: React.PropTypes.func,
},
_toggleOnDisplay(gridRow, event) {
const artistId = gridRow.props.data.artist_id;
this.props.updateOnDisplay(artistId, !gridRow.props.data.on_display);
},
_renderArtistsIfLoaded() {
if (this.props.artists) {
const columnMetadata = [
{
columnName: "name",
displayName: "Artist name",
cssClassName: "artistNameColumn",
visible: true,
order: 0,
},
{
columnName: "on_display",
displayName: "On Display?",
customComponent: CheckboxColumn,
cssClassName: "onDisplayColumn",
visible: true,
order: 1,
},
{
columnName: "attachments",
displayName: "Artwork",
visible: true,
customComponent: AttachmentsColumn,
order: 2,
},
{
columnName: "artist_id",
displayName: "id",
visible: false,
order: 3,
},
];
// Only need the columns due to a bug in griddle https://github.com/GriddleGriddle/Griddle/issues/114
const columns = ["name", "on_display", "attachments"];
return <Griddle onRowClick={this._toggleOnDisplay} results={this.props.artists} showFilter={true} showSettings={true} columnMetadata={columnMetadata} columns={columns} resultsPerPage={10} />;
} else {
return <div> Loading </div>;
}
},
render() {
return (
<ReactBootstrap.Panel>
<h1>Art gallery</h1>
<ReactBootstrap.Grid fluid={true}>
<ReactBootstrap.Row className="show-grid">
<ReactBootstrap.Col xs={0} md={0} lg={2}>
</ReactBootstrap.Col>
<ReactBootstrap.Col xs={12} md={12} lg={8}>
{this._renderArtistsIfLoaded()}
</ReactBootstrap.Col>
</ReactBootstrap.Row>
</ReactBootstrap.Grid>
</ReactBootstrap.Panel>
);
},
});
const ArtGalleryApp = React.createClass({
propTypes: {
// No props here
},
getInitialState() {
return {
artists: null,
};
},
componentDidMount() {
this._loadArtists();
},
_loadArtists() {
$.ajax('/v0/artists').then((response, status, jqXHR) => {
this.setState({
artists: response.artists,
});
});
},
_updateOnDisplay(artistId, isOnDisplay) {
$.ajax('/v0/set_on_display', {
method: 'POST',
data: {
artist_id: artistId,
on_display: isOnDisplay,
},
}).then((response, status, jqXHR) => {
const updatedArtists = response.artist;
const newArtists = _.map(this.state.artists, artist => {
if (artist.artist_id === artistId) {
return _.extend({}, artist, updatedArtists);
} else {
return artist;
}
});
this.setState({
artists: newArtists,
});
});
},
render() {
return (
<ArtGallery artists={this.state.artists} updateOnDisplay={this._updateOnDisplay}/>
);
},
});
var rootNode = document.getElementById('appRoot');
ReactDOM.render(<ArtGalleryApp/>, rootNode);
|
import { FETCH_ISSUES_SUCCESS } from 'actions/issues';
import { emptyState } from 'constants';
export const entities = (state = emptyState.object, { payload, type }) => {
switch (type) {
case FETCH_ISSUES_SUCCESS:
return payload.entities;
default:
return state;
}
};
export default entities;
|
const fs = require("fs");
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const routes = require("./routes/currencyRouter")();
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
const port = 5000;
app.set("view engine", "pug");
app.get("/", function (req, res) {
const listCurrency = JSON.parse(fs.readFileSync("./db/db.json"));
return res.json(listCurrency);
});
app.get("/home", function (req, res) {
return res.render("home");
});
app.get("/add", function (req, res) {
return res.render("add");
});
app.get("/edit", function (req, res) {
return res.render("edit");
});
app.use("/api", routes);
app.listen(port, () => {
console.log(`Server is running on ${port}`);
});
|
import React, { useState } from 'react';
const Pagination = ({
number, totalPosts, leftTransition, rightTransition,
}) => {
const postNumbers = [];
for (let i = 1; i <= totalPosts; i++) {
postNumbers.push(i);
}
return (
<div>
<nav className="pagination-nav">
<ul>
<li className="post-number">
<a>
<span>
0
{number}
</span>
<span>/</span>
<span>
0
{totalPosts}
</span>
</a>
</li>
<li
id="left"
onClick={leftTransition}
>
<a>{'<-'}</a>
</li>
<li
id="right"
onClick={rightTransition}
>
<a>{'->'}</a>
</li>
</ul>
</nav>
</div>
);
};
export default Pagination;
|
app.factory('cities', ['$http', '$q', 'baseServiceUrl',
function($http, $q, baseServiceUrl) {
'use strict';
var citiesApi = baseServiceUrl + '/api/Cities',
deferred = $q.defer();
return {
getCities: function getCities() {
$http.get(citiesApi)
.success(function (data) {
deferred.resolve(data);
})
.error(function (err) {
deferred.reject(err);
});
return deferred.promise;
}
};
}]);
|
import React from "react";
import { useDropzone } from "react-dropzone";
import './ImageUpload.css';
export const ImageUpload = () => {
const [files, setFiles] = React.useState([]);
const { getRootProps, getInputProps } = useDropzone({
accept: "image/*",
onDrop: (acceptedFiles) => {
setFiles(
acceptedFiles.map((file) => Object.assign(file, {
preview: URL.createObjectURL(file)
}))
)
}
})
const images = files.map((file) => (
<div key={file.name}>
<div>
<img src={file.preview} style={{ width: "200px" }} alt="preview" />
</div>
</div>
))
return (
<>
<div id="dragAndDrop" {...getRootProps()}>
<input {...getInputProps()} />
<div style={{ display: "inline-flex" }}>
<p style={{ color: "black" }, { fontStyle: "bold" }}>Upload File </p>
<p> or drag&drop here</p>
</div>
</div>
<div>{images}</div>
</>
);
}
|
import React, { Component } from 'react'
export default class ALL extends Component {
constructor(){
super();
this.state={
data:[]
}
}
componentDidMount(){
console.log('helloContent');
let id = this.props.match.params.id;
let url = 'https://cnodejs.org/api/v1/topics';
fetch(url)
.then((res=>res.json()))
.then((res)=>{
for(var i=0;i<res.data.length;i++){
if(this.props.match.params.id === res.data[i].id){
this.setState({data:res.data[i].content})
}
}
})
}
componentDidUpdate(prevPros){
let id = this.props.match.params.id;
if(id != prevPros.match.params.id){
fetch('https://cnodejs.org/api/v1/topics?')
.then((res=>res.json()))
.then((res)=>{
for(var i=0;i<res.data.length;i++){
if(this.props.match.params.id === res.data[i].id){
this.setState({data:res.data[i].content})
}
}
})
}
}
render() {
return (
<div>
{
<div dangerouslySetInnerHTML={{__html:this.state.data}}></div>
}
</div>
)
}
}
|
import styled from 'styled-components'
export const ChainPage = styled.div`
display: flex;
height: 100%;
overflow: hidden;
`
export const ChartAndRange = styled.div`
display: flex;
flex-direction: column;
flex: 1;
overflow: hidden;
`
export const RangeContainer = styled.div`
height: 64px;
width: 100%;
border-top: 1px solid #d7d7d7;
`
export const ControlsAndBar = styled.div`
display: flex;
`
|
'use strict';
// TODO: namespace.
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str){
return this.slice(0, str.length) == str;
};
}
if (typeof String.prototype.endsWith != 'function') {
String.prototype.endsWith = function (str){
return this.slice(-str.length) == str;
};
}
if (typeof String.prototype.replaceAll !== 'function') {
String.prototype.replaceAll = function (find, replacement){
var v = this, u;
while (true) {
u = v.replace(find, replacement);
if (u === v) return v;
v = u;
}
};
}
Float32Array.prototype.toJSON = function() {
var arr = [];
for (var i=0; i < this.length; i++) arr.push(this[i]);
return arr;
};
Float32Array.fromJSON = function(json) {
return new Float32Array(JSON.parse(json));
};
// Javascript mod on negative numbers keep number negative
if (typeof Number.prototype.mod != 'function') {
Number.prototype.mod = function(n) { return ((this%n)+n)%n; };
}
function clamp(val, minVal, maxVal) {
return (val < minVal) ? minVal : ((val > maxVal) ? maxVal : val);
}
// DOM.
function id(id) {
return document.getElementById(id);
}
// CSRF authenticity token for AJAX requests to Rails
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
// Utility functions for working with the canvas
// Function to get a potentially resized canvas with a given maxWidth and maxHeight
// while retaining the aspect ratio of the original canvas
// The quality of the resized image is probably not great
function getResizedCanvas(canvas, maxWidth, maxHeight)
{
var scale = 1.0;
if (maxWidth && canvas.width > maxWidth) {
scale = Math.min(scale, maxWidth/canvas.width);
}
if (maxHeight && canvas.height > maxHeight) {
scale = Math.min(scale, maxHeight/canvas.height);
}
if (scale != 1.0) {
var newCanvas = document.createElement("canvas");
newCanvas.width = scale*canvas.width;
newCanvas.height = scale*canvas.height;
var ctx = newCanvas.getContext("2d");
ctx.drawImage(canvas, 0, 0, canvas.width, canvas.height, 0, 0, newCanvas.width, newCanvas.height);
return newCanvas;
} else {
return canvas;
}
}
// Copies the image contents of the canvas
function copyCanvas(canvas) {
var c = document.createElement('canvas');
c.width = canvas.width;
c.height = canvas.height;
var ctx = c.getContext('2d');
ctx.drawImage(canvas, 0, 0);
return c;
}
// Trims the canvas to non-transparent pixels?
// Taken from https://gist.github.com/remy/784508
function trimCanvas(c) {
var ctx = c.getContext('2d');
var copy = document.createElement('canvas').getContext('2d');
var pixels = ctx.getImageData(0, 0, c.width, c.height);
var l = pixels.data.length;
var bound = {
top: null,
left: null,
right: null,
bottom: null
};
var i, x, y;
for (i = 0; i < l; i += 4) {
if (pixels.data[i+3] !== 0) {
x = (i / 4) % c.width;
y = ~~((i / 4) / c.width);
if (bound.top === null) {
bound.top = y;
}
if (bound.left === null) {
bound.left = x;
} else if (x < bound.left) {
bound.left = x;
}
if (bound.right === null) {
bound.right = x;
} else if (bound.right < x) {
bound.right = x;
}
if (bound.bottom === null) {
bound.bottom = y;
} else if (bound.bottom < y) {
bound.bottom = y;
}
}
}
var trimHeight = bound.bottom - bound.top + 1;
var trimWidth = bound.right - bound.left + 1;
if (trimHeight > 0 && trimWidth > 0) {
if (trimHeight === c.height && trimWidth === c.width) {
// No need to trim, just return original
return c;
} else {
var trimmed = ctx.getImageData(bound.left, bound.top, trimWidth, trimHeight);
copy.canvas.width = trimWidth;
copy.canvas.height = trimHeight;
copy.putImageData(trimmed, 0, 0);
// open new window with trimmed image:
return copy.canvas;
}
} else {
console.error("Invalid trimmed height or width, returning original canvas");
return c;
}
}
function getTrimmedCanvasDataUrl(canvas,maxWidth,maxHeight) {
var copy = copyCanvas(canvas);
var trimmed = trimCanvas(copy);
var newCanvas = getResizedCanvas(trimmed, maxWidth, maxHeight);
return newCanvas.toDataURL();
}
// UI functions using JQuery
function showLarge(elem) {
var url = elem.attr("src");
elem.addClass("enlarged");
var align = elem.attr("enlarge_align");
if (!align) {
align = "center";
}
$('#large img').show();
$('#large img').attr("src", url);
$('#large img').position({
my: align,
at: align,
of: elem
});
$('#large img').hover(function(){
},function(){
$(this).hide();
elem.removeClass("enlarged");
});
}
function showAlert(message, style, timeout) {
window.setTimeout(function() { hideAlert(); }, timeout || 5000);
$('#alertMessage').html(message);
var alert = $('#alert');
alert.attr('class', 'alert');
alert.addClass(style);
alert.css('font-size', '18pt');
alert.show();
}
function hideAlert() {
$('#alert').hide();
}
|
// Defines the express routes to do GET, POST, PUT, and DELETE requests
// pertaining to questions.
const express = require('express');
const router = express.Router();
// Question Model
const Question = require('../../models/Question');
// @route GET api/questions
// @desc Get all questions
// @access Public
router.get('/', (req, res) => {
Question.find()
.sort({score: -1, date: -1 })
.then(questions => res.json(questions))
});
// @route GET api/questions/findLecture/:lectureID
// @desc Get all questions for a lecture
// @access Public
router.get('/findLecture/:id', (req, res) => {
Question.find(({lectureID: req.params.id}))
.sort({score: -1, date: -1 })
.then(questions => res.json(questions))
});
// @route POST api/questions
// @desc Add a new question
// @access Public
router.post('/', (req, res) => {
const newQuestion = new Question({
content: req.body.content,
score: req.body.score,
lectureID: req.body.lectureID,
googleUserID: req.body.googleUserID,
});
newQuestion.save().then(question => res.json(question)); // save to database
});
// @route PUT api/questions
// @desc Put/upvote a question
// @access Public
router.put('/upvote/:id', (req, res) => {
Question.findById(req.params.id)
.then(question => {
question.score = question.score + 1;
question.upvotes.unshift(req.body.googleID);
question.save().then(()=>res.json(question));
})
.catch(err => res.status(404).json({success:false})); // status used for errors, res.json used for success
});
// @route PUT api/questions
// @desc Put/downvote a question
// @access Public
router.put('/downvote/:id', (req, res) => {
Question.findById(req.params.id)
.then(question => {
question.score = question.score - 1;
question.upvotes = question.upvotes.filter(q => q !== req.body.googleID);
question.save().then(()=>res.json(question));
})
.catch(err => res.status(404).json({success:false})); // status used for errors, res.json used for success
});
// @route DELETE api/questions/:id
// @desc Delete a question
// @access Public
router.delete('/:id', (req, res) => {
Question.findById(req.params.id)
.then(question => question.remove().then(()=>res.json({success: true}))) // then() used with promises
.catch(err => res.status(404).json({success:false})); // status used for errors, res.json used for success
});
module.exports = router;
|
import types from './types';
import { createPluginReducer } from 'rdx/utils/create-reducer';
const initialState = {
amount: '',
fee: '',
fromAddress: '',
memo: '',
toAddress: '',
preSelectedFromAddress: null,
preSelectedToAddress: null,
};
export const sendFundsReducer = createPluginReducer(initialState, {
[types.PRE_SELECT_FROM_ADDRESS](state, action) {
return {
...state,
preSelectedFromAddress: action.payload,
};
},
[types.PRE_SELECT_TO_ADDRESS](state, action) {
return {
...state,
preSelectedToAddress: action.payload,
};
},
[types.SET_AMOUNT](state, action) {
return {
...state,
amount: action.payload,
};
},
[types.SET_FEE](state, action) {
return {
...state,
fee: action.payload,
};
},
[types.SET_FROM_ADDRESS](state, action) {
return {
...state,
fromAddress: action.payload,
};
},
[types.SET_MEMO](state, action) {
return {
...state,
memo: action.payload,
};
},
[types.SET_TO_ADDRESS](state, action) {
return {
...state,
toAddress: action.payload,
};
},
[types.RESET_FIELDS]() {
return initialState;
},
});
|
import axios from 'axios';
export const fetchUsers = () => {
return new Promise( (resolve, reject) => {
axios.get('/api/bot/users/')
.then(result => {
resolve([...result.data.users]);
})
.catch(err => {
reject(err);
})
})
}
export const postMessage = (user_id, message) => {
return new Promise( (resolve, reject) => {
axios.post('/api/bot/messages/', {user_id, message})
.then(result => {
resolve(true);
})
.catch(err => {
reject(err);
})
})
}
|
angular.module("app").factory("ProductService", function ($http, $q) {
var service = {};
service.GetAll = function (skip) {
var promise = $http({
method: 'get',
url: '/Product/GetAll',
params: {skip: skip}
});
return $q.when(promise);
};
service.GetByName = function (item) {
var promise = $http({
method: 'get',
url: '/Product/GetByName',
params: { name: item }
});
return $q.when(promise);
};
service.GetAllNames = function () {
var promise = $http({
method: 'get',
url: '/Product/GetAllNames'
});
return $q.when(promise);
};
service.GetCartByIdClient = function (id) {
var promise = $http({
method: 'get',
url: '/Product/GetCartByIdClient',
params: {
id: id
}
});
return $q.when(promise);
};
service.AgregarAlCarrito = function (item) {
var promise = $http({
method: 'post',
url: '/Product/AgregarAlCarrito',
data: { item: item }
});
return $q.when(promise);
};
service.PublicarProducto = function (file,product) {
var promise = $http({
method: 'post',
url: '/Product/PublicarProducto',
data: { file: file, product: product}
});
return $q.when(promise);
};
service.ConfirmarCarrito = function (item) {
var promise = $http({
method: 'post',
url: '/Product/ConfirmarCarrito'
});
return $q.when(promise);
};
return service;
})
|
app.controller('sregister',['$scope','$http','$localStorage',function($scope,$http,$localStorage){
$scope.names=[{value:"BE"},{value:"B.Tech"},{value:"ME"},{value:"M.Tech"},{value:"MBA"}];
$scope.college=[{value:"K.S.Rangasamy College of Technology"}];
$scope.status=[{value:"active"},{value:"inactive"}];
$scope.registerInfo={
userId:$localStorage.data_value,
regno:undefined,
firstname:undefined,
lastname:undefined,
email:undefined,
department:undefined,
yearofpassing:undefined,
mobile:undefined
}
$scope.studentRegister=function(){
var data={
suserID:$scope.registerInfo.userId,
sregno:$scope.registerInfo.regno,
sfirstname:$scope.registerInfo.firstname,
slastname:$scope.registerInfo.lastname,
semail:$scope.registerInfo.email,
sdepartment:$scope.registerInfo.department,
sdegree:$scope.selectedItemValue,
scollege:$scope.selectedcollegeValue,
sstatus:$scope.selectedstatusValue,
smobile:$scope.registerInfo.mobile,
syear:$scope.registerInfo.yearofpassing
}
$http({
method:'POST',
url:'php/sregister.php',
data:data
}).then(function (response){
console.log(response.data);
alert(response.data);
$scope.demo=JSON.stringify(response);
console.log($scope.demo);
}),function (error){
console.log(error);
}
}
$scope.studentClear=function(){
$scope.registerInfo={
regno:undefined,
firstname:undefined,
lastname:undefined,
email:undefined,
department:undefined,
yearofpassing:undefined,
mobile:undefined,
}
}
}]);
|
/*
contador = 1
while(contador<6){
console.log('Tudo bem?')
contador++
}
do{
console.log('Tudo bem?')
contador++
}while(contador<6)*/
console.log('Vai começar..')
for (var c=1; c<=10;c++){
console.log(c)
}
|
// (Note taking app) taking and saveing a note
const notes = [];
function saveNote(content, id) {
if (content == null || content.length == 0) {
console.log("Content is not defined or it's empty! Please provide a content.");
}
else if (id == null) {
console.log("Id is not defined! Please select an Id and save your note again.");
}
else if (isNaN(id)) {
console.log("Please enter a number for your id");
}
else {
notes.push({content, id});
}
}
saveNote("Pick up groceries", 1);
saveNote("Do laundry", 2);
saveNote("Do shopping", 3);
saveNote("Pick up kid", 4);
console.log(notes);
//Get a note
function getNote(id) {
for (let i = 0; i < notes.length; i++){
if (id == null) {
console.log("Id is not defined! Please select an Id and save your note again.");
}
else if (isNaN(id)) {
console.log("Please enter a number for your id");
}
else if (id == notes[i].id) {
return notes[i];
}
}
return "There is no such note with Id: " + id;
}
let firstNote = getNote(2);
console.log(firstNote);
firstNote = getNote(12);
console.log(firstNote);
//Log out notes
function logOutNotesFormatted() {
for (let note of notes) {
console.log(`The note with id: ${note.id} ,has the following note text: ${note.content}`);
}
};
logOutNotesFormatted();
|
import React, {Component, Fragment} from 'react';
import PropTypes from 'prop-types';
class MyComponent extends Component{
static defaultProps = {
abcd : "Angular",
}
static propTypes = {
abcd : PropTypes.string,
}
state = {
num : 0
}
render(){
return(
<Fragment>
안녕하세요. {this.props.abcd}
<br/>
여기는 state 값이 표현됩니다.
{this.state.num}
<button onClick={()=>{
this.setState({
num:this.state.num + 1
})
}}></button>
</Fragment>
)
}
}
export default MyComponent;
|
module.exports = {
name: 'leave',
description: 'Command to leave a voice channel',
usage: `\`leave\``,
execute(message) {
// Check if user already join the voice channel
if (message.guild.voiceConnection) {
// Empty the queue
if (servers.get(message.guild.id).dispatcher) {
servers.get(message.guild.id).dispatcher.destroy();
}
songQueueGroups.delete(message.guild.id);
message.member.voiceChannel.leave();
} else {
return message.channel.send("You need to be in a voice channel to be able to use this command");
}
},
};
|
/** Global blocks */
export {GlobalStyle} from "./global/globalStyle"
export {GlobalHeader} from "./global/globalHeader"
export {GlobalNavigation} from "./global/globalNavigation"
export {GlobalContent} from "./global/globalContent"
export {GlobalContainer} from './global/globalContainer'
export {GlobalDisplay} from './global/globalDisplay'
export {GlobalGrid} from './global/globalGrid'
export {LeftColumn} from './global/columns/leftColumn'
export {CenterColumn} from './global/columns/centerColumn'
export {RightColumn} from './global/columns/rightColumn'
export {StyledColumnSectionLiner} from './global/columns/styledColumnSectionLiner'
/** Common components */
export {RemoveImgBtnLiner} from './common/button/removeImg/removeImgBtnLiner'
export {StyledRemoveImgNavLink} from './common/button/removeImg/StyledRemoveImgNavLink'
export {RemoveImgSVG} from './common/button/removeImg/RemoveImgSVG'
export {StyledSectionTitleLiner} from './common/section/styledSectionTitleLiner'
export {StyledSectionTitleNavLink} from './common/section/styledSectionTitleNavLink'
export {StyledSectionTitleNumsSpan} from './common/section/styledSectionTitleNumsSpan'
/** Flex classes */
export {
DivFlx,
DivFlxItmCnt,
DivFlxJstBtw,
DivFlxItmCntJstBtw,
DivFlxShr0,
BtnFlx,
BtnFlxItmCnt,
BtnFlxJstBtw,
BtnFlxItmCntJstBtw
} from './common/position/flex/flx'
export {
DivAbs,
DivAbsTop0,
DivAbsRgt0,
DivAbsTop0Rht0
} from './common/position/abs/abs'
/** Common usages */
export {
ImgSz16RndFll
} from './common/img/imgSz'
export {
DivP2, DivPl2, DivPr2, DivPt2, DivPb2, DivPx2, DivPy2,
DivP4, DivPl4, DivPr4, DivPt4, DivPb4, DivPx4, DivPy4
} from './common/padding/padding'
export {DropdownList} from './common/dropdown/dropdownList'
export {DropdownListItem} from './common/dropdown/dropdownListItem'
/** Header */
export {FixedWidthHeaderContainer} from "./header/headerContainer"
export {HeaderBar} from "./header/headerBar"
export {StyledLeftSideItems} from "./header/styledLeftSideItems"
export {StyledLogoLink} from "./header/logo/logoLink"
export {StyledLogoSVG} from "./header/logo/StyledLogoSVG"
export {StyledSearchItemBase} from "./header/search/StyledSeachItem"
export {SearchWrapper} from "./header/search/StyledSeachItem"
export {StyledSearchInput} from "./header/search/StyledSearchInput"
export {StyledSearchInputSVG} from "./header/search/StyledSearchInputSVG"
export {StyledNotificationSVG} from "./header/notification/StyledNotificationSVG"
export {PlayerLayout} from "./header/player/playerLayout"
export {PreviousTrackSVG} from "./header/player/PreviousTrackSVG"
export {PlayTrackSVG} from "./header/player/PlayTrackSVG"
export {NextTrackSVG} from "./header/player/NextTrackSVG"
export {StyledTrackNameItem} from './header/player/styledTrackNameItem'
export {StyledRightSideItems} from "./header/styledRightSideItems"
export {HeaderUserIconLiner} from "./header/user/headerUserIconLiner"
export {HeaderUserIconImg} from "./header/user/headerUserIconImg"
export {StyledHeaderUserName} from "./header/user/StyledHeaderUserName"
export {HeaderUserDropdownSVG} from "./header/user/HeaderUserDropdownSVG"
export {UserDropdownParent} from "./header/dropdown/userDropdownParent"
export {StyledUserDropdown} from "./header/dropdown/userDropdown"
export {UserDropdownLiner} from "./header/dropdown/userDropdownLiner"
export {StyledConnectItem} from './header/dropdown/connect/styledConnectItem'
export {UserDropdownIconLiner} from './header/dropdown/connect/userDropdownIconLiner'
export {StyledUserDropdownName} from './header/dropdown/connect/styledUserDropdownName'
export {StyledUserDropdownMessage} from './header/dropdown/connect/styledUserDropdownMessage'
export {UserDropdownSpacer} from './header/dropdown/userDropdownSpacer'
export {StyledDropdownHelpItem} from './header/dropdown/help/styledDropdownHelpItem'
export {StyledDropdownLogoutItem} from './header/dropdown/logout/styledDropdownLogoutItem'
export {StyledDropdownSettingsItem} from './header/dropdown/settings/styledDropdownSettingsItem'
export {NotificationHeaderControlsLiner} from './header/common/headerControlsLiner'
export {HeaderNotificationAttentionLiner} from './header/notification/HeaderNotificationAttentionLiner'
/** Navigation */
export {NavigationLiner} from './navigation/navigationLiner'
export {NavigationListItem} from './navigation/navigationListItem'
export {NavigationItemLiner} from './navigation/navigationItemLiner'
export {NavigationItemLabel} from './navigation/navigationItemLabel'
export {ProfileNavigationSVG} from './navigation/icon/ProfileNavigationSVG'
export {MessengerNavigationSVG} from './navigation/icon/MessengerNavigationSVG'
export {NewsNavigationSVG} from './navigation/icon/NewsNavigationSVG'
export {CommunityNavigationSVG} from './navigation/icon/CommunityNavigationSVG'
export {GamesNavigationSVG} from './navigation/icon/GamesNavigationSVG'
export {NavigationAttentionLiner} from './navigation/navigationAttentionLiner'
export {NavigationSpacer} from './navigation/navigationSpacer'
/** Navigation advanced */
export {StyledAdvancedNavigation} from './navigation/advanced/styledAdvancedNavigation'
export {StyledAdvancedNavigationItem} from './navigation/advanced/styledAdvancedNavigationItem'
export {StyledOtherButton} from './navigation/advanced/styledOtherButton'
export {StyledOtherLabel} from './navigation/advanced/styledOtherLabel'
export {StyledOtherSVG} from './navigation/advanced/styledOtherSVG'
export {StyledAdvancedDropdownLiner} from './navigation/advanced/dropdown/advancedDropdownLiner'
export {StyledCornerDetail} from './navigation/advanced/dropdown/StyledCornerDetail'
/** Profile Avatar */
export {ProfileAvatarCenterSectionLiner} from './profile/avatar/profileAvatarCenterSectionLiner'
export {StyledAvatarImg} from './profile/avatar/avatarImg'
export {AvatarEditButtonLiner} from './profile/avatar/avatarEditButtonLiner'
export {StyledAvatarEditButton} from './profile/avatar/avatarEditButton'
export {AvatarListItemLiner} from './profile/avatar/list/avatarListItemLiner'
export {AvatarListItemSpan} from './profile/avatar/list/avatalListItemSpan'
export {ArchiveItemSVG} from './profile/avatar/list/ArchiveItemSVG'
export {StatisticsItemSVG} from './profile/avatar/list/StatisticsItemSVG'
export {MemoriesItemSVG} from './profile/avatar/list/MemoriesItemSVG'
export {MoneyTransfersSVG} from './profile/avatar/list/MoneyTransfersSVG'
/** Edit Profile Avatar */
export {EditAvatarListLiner} from './profile/avatar/edit/editAvatarListLiner'
export {StyledAvatarEditList} from './profile/avatar/edit/styledAvatarEditList'
export {AvatarEditListItemLiner} from './profile/avatar/edit/avatarEditListItemLiner'
export {CropAvatarEditListItemSVG} from './profile/avatar/edit/CropAvatarEditListItemSVG'
export {UpdateAvatarEditListItemSVG} from './profile/avatar/edit/UpdateAvatarEditListItemSVG'
export {DecorAvatarEditListItemSVG} from './profile/avatar/edit/DecorAvatarEditListItemSVG'
/** Friends section */
export {ProfileCenterFriendsSectionLiner} from './profile/friends/profileCenterFriendsSectionLiner'
export {StyledFriendsSectionHeader} from './profile/friends/header/styledFriendsSectionHeader'
export {StyledCenterSectionHeaderNavLink} from './profile/styledCenterSectionHeaderNavLink'
export {StyledUpdatesNavLink} from './profile/friends/header/styledUpdatesNavLink'
export {StyledCenterSectionNumSpan} from './profile/styledCenterSectionNumSpan'
/** Friends grid */
export {StyledFriendsGrid} from './profile/friends/grid/styledFriendsGrid'
export {FriendsGridItemLiner} from './profile/friends/grid/friendsGridItemLiner'
export {FriendsGridItemImg} from './profile/friends/grid/friendsGridItemImg'
export {FriendsGridItemLabel} from './profile/friends/grid/friendsGridItemLabel'
/** Music */
export {ProfileMusicCenterSectionLiner} from './profile/music/ProfileMusicCenterSectionLiner'
export {StyledMusicSectionHeader} from './profile/music/header/styledMusicSectionHeader'
/** Right Column */
export {StyledRightColumnSection} from './profile/styledRightColumnSection'
/** Info section */
export {StyledNameItemLiner} from './profile/info/name/styledNameItemLiner'
export {StyledNameItemLabel} from './profile/info/name/styledNameItemLabel'
export {StyledOnlineStatusLabel} from './profile/info/name/styledOnlineStatusLabel'
export {StyledInfoSpacer} from './profile/info/intro/styledInfoSpacer'
export {StyledIntroItemGrid} from './profile/info/intro/styledIntroItemGrid'
export {StyledIntroItemLabel} from './profile/info/intro/styledIntroItemLabel'
export {StyledIntroColOneLiner} from './profile/info/intro/styledIntroColOneLiner'
export {StyledIntroCoTwoLiner} from './profile/info/intro/styledIntroCoTwoLiner'
export {StyledIntroItemNavLink} from './profile/info/intro/styledIntroItemNavLink'
export {StyledInfoDetailsBtn} from './profile/info/details/styledInfoDetailsBtn'
/** Info section Details */
export {StyledDetailsSection} from './profile/info/details/styledDetailsSection'
export {StyledDetailsSectionHeader} from './profile/info/details/styledDetailsSectionHeader'
export {StyledDetailsSectionLiner} from './profile/info/details/styledDetailsSectionLiner'
export {StyledDetailsSectionSpacerLiner} from './profile/info/details/styledDetailsSectionSpacerLiner'
export {StyledDetailsSectionSpacer} from './profile/info/details/styledDetailsSectionSpacer'
export {StyledEditDetailsSectionBtn} from './profile/info/details/styledEditDetailsSectionBtn'
export {StyledEditDetailsSectionNavLink} from './profile/info/details/styledEditDetailsSectionNavLink'
export {StyledIntroItemSpan} from './profile/info/details/styledIntroItemSpan'
/** Profile Statistics Section */
export {StyledStatisticsSection} from './profile/stats/styledStatisticsSection'
export {StyledStatisticsNavLink} from './profile/stats/styledStatisticsNavLink'
export {StyledStatisticsNumsLabel} from './profile/stats/styledStatisticsNumsLabel'
/** Profile Photo Section */
export {StyledPhotoSectionGreedBase} from './profile/photos/styledPhotoSectionGreedBase'
export {StyledPhotoSectionGreed} from './profile/photos/styledPhotoSectionGreed'
export {StyledPhotoSectionImg} from './profile/photos/styledPhotoSectionImg'
export {StyledPhotoSectionImgLiner} from './profile/photos/styledPhotoSectionImgLiner'
export {StyledPhotoSectionImgNavLink} from './profile/photos/styledPhotoSectionImgNavLink'
/** Post Section */
export {StyledPostHeaderLiner} from './common/post/header/styledPostHeaderLiner'
export {StyledPostFooterLiner} from './common/post/footer/styledPostFooterLiner'
export {StyledPostFooterBtn} from './common/post/footer/styledPostFooterBtn'
export {StyledPostFooterRightSideBar} from './common/post/footer/styledPostFooterRightSideBar'
export {LikeSVG} from './common/svg/LikeSVG'
export {CommentSVG} from './common/svg/CommentSVG'
export {RepostSVG} from './common/svg/RepostSVG'
export {ViewsSVG} from './common/svg/ViewsSVG'
export {HorizontalDotsSVG} from './common/svg/HorizontalDotsSVG'
|
let sbtnnormal = document.querySelectorAll('.sbtnn');
let subbtn = document.getElementById('subbtn');
let data = document.getElementById('sum');
let prices = document.getElementById('price');
let input = document.getElementById('input');
let seatselect = [];
let price = 0;
for (let i = 0; i < sbtnnormal.length; i++) {
let list = sbtnnormal[i];
list.onclick = function (){
if(!this.classList.contains("btn-outline-primary")){
this.classList.add("btn-outline-primary");
seatselect.push(this.id);
price += 10;
subbtn.classList.remove("disabled");
} else {
this.classList.remove("btn-outline-primary");
let index = seatselect.indexOf(this.id);
seatselect.splice(index, 1);
if(price >= 10){
price -= 10;
}
if(price < 10){
subbtn.classList.add("disabled");
}
}
data.innerHTML = seatselect;
input.setAttribute('value', seatselect);
prices.innerHTML = price;
};
}
|
import "./RightNavStyles";
import { Ul, StyledLink } from "./RightNavStyles";
import React from "react";
const RightNav = ({ open, toggle }) => {
return (
<Ul open={open} id="sidebar">
<div className="">
<StyledLink to="/our_services" className="nav-link" onClick={toggle}>
Our Services
</StyledLink>
<StyledLink to="/about" className="nav-link" onClick={toggle}>
About Us
</StyledLink>
<StyledLink to="/calculators" className="nav-link" onClick={toggle}>
Calculators
</StyledLink>
<StyledLink to="/contact" className="nav-link" onClick={toggle}>
Contact
</StyledLink>
</div>
</Ul>
);
};
export default RightNav;
|
import Home from './pages/Home';
import ManualAdd from './pages/ManualAdd';
const routes = [
{ path: '/', component: Home },
{ path: '/manual', component: ManualAdd }
];
export default routes;
|
const EventEmitter = require("events");
const lodashget = require("lodash.get");
const Sortable = require("./Util/Sortable");
const debug = require("debug")("Eleventy:EleventyConfig");
// API to expose configuration options in config file
class EleventyConfig {
constructor() {
this.events = new EventEmitter();
this.collections = {};
this.liquidTags = {};
this.liquidFilters = {};
this.nunjucksFilters = {};
this.handlebarsHelpers = {};
this.layoutAliases = {};
// now named `transforms` in API
this.filters = {};
}
on(eventName, callback) {
return this.events.on(eventName, callback);
}
emit(eventName, ...args) {
return this.events.emit(eventName, ...args);
}
// tagCallback: function(liquidEngine) { return { parse: …, render: … }} };
addLiquidTag(name, tagFn) {
if (typeof tagFn !== "function") {
throw new Error(
"EleventyConfig.addLiquidTag expects a callback function to be passed in: addLiquidTag(name, function(liquidEngine) { return { parse: …, render: … } })"
);
}
this.liquidTags[name] = tagFn;
}
addLiquidFilter(name, callback) {
this.liquidFilters[name] = callback;
}
addNunjucksFilter(name, callback) {
this.nunjucksFilters[name] = callback;
}
addHandlebarsHelper(name, callback) {
this.handlebarsHelpers[name] = callback;
}
addFilter(name, callback) {
debug("Adding universal filter %o", name);
this.addLiquidFilter(name, callback);
this.addNunjucksFilter(name, callback);
// these seem more akin to tags but they’re all handlebars has, so
this.addHandlebarsHelper(name, callback);
}
addTransform(name, callback) {
this.filters[name] = callback;
}
addLayoutAlias(from, to) {
this.layoutAliases[from] = to;
}
getCollections() {
return this.collections;
}
addCollection(name, callback) {
if (this.collections[name]) {
throw new Error(
`config.addCollection(${name}) already exists. Try a different name for your collection.`
);
}
this.collections[name] = callback;
}
getMergingConfigObject() {
return {
liquidTags: this.liquidTags,
liquidFilters: this.liquidFilters,
nunjucksFilters: this.nunjucksFilters,
handlebarsHelpers: this.handlebarsHelpers,
filters: this.filters,
layoutAliases: this.layoutAliases
};
}
}
let config = new EleventyConfig();
module.exports = config;
|
import React, { Component, Fragment } from 'react'
import { Container, Table, Card, CardTitle, Row, Col } from 'reactstrap'
import { connect } from 'react-redux'
import { getOrderResult } from '../actions/orderActions'
import PropTypes from 'prop-types'
import { Redirect } from 'react-router-dom'
class OrderResult extends Component {
componentDidMount() {
this.props.getOrderResult()
}
render() {
const { orderResult } = this.props.order
const { isAuthenticated, user } = this.props.authentication
console.log(orderResult)
return (
<Container>
{Object.keys(orderResult).length != 0 ? (<Fragment>
<div style={{ textAlign: 'left', marginBottom: "2rem" }}>
<p>Order Date: {orderResult.date}</p>
<p>Order ID: {orderResult.orderId}</p>
<p>Receipt: <a href={orderResult.receipt_url} target='_blank'>{orderResult.receipt_url}</a></p>
</div>
<div class="table-responsive">
<Table style={{ marginBottom: "5rem" }}>
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
{orderResult.orderItems.map(({ productId, productName, productPrice, productQuantity, productDescription }) => (
<Fragment key={productId}>
<tr>
<td></td>
<td>{productName}</td>
<td>${productPrice}</td>
<td>{productQuantity}</td>
<td>${(productPrice * productQuantity).toFixed(2)}</td>
</tr>
</Fragment>
))}
</tbody>
</Table>
</div>
<Row>
<Col md="6" className="m-auto">
<Card body>
<CardTitle><div style={{ float: "left" }}>Subtotal</div><div style={{ float: "right" }}>${orderResult.subtotal}</div></CardTitle>
<CardTitle><div style={{ float: "left" }}>Taxes</div><div style={{ float: "right" }}>${orderResult.taxes}</div></CardTitle>
<CardTitle><div style={{ float: "left" }}>Tips</div><div style={{ float: "right" }}>${orderResult.tips}</div></CardTitle>
<CardTitle><div style={{ float: "left" }}>Total</div><div style={{ float: "right" }}>${(orderResult.subtotal + orderResult.taxes + orderResult.tips)}</div></CardTitle>
</Card>
</Col>
</Row>
<Row style={{marginTop: '2rem', marginBottom: '2rem'}}>
<Col md="6" className="m-auto">
<Card body>
<strong>Billing Details</strong>
<CardTitle><div style={{ float: "left" }}>City</div><div style={{ float: "right" }}>{orderResult.billing_details.address.city}</div></CardTitle>
<CardTitle><div style={{ float: "left" }}>Country</div><div style={{ float: "right" }}>{orderResult.billing_details.address.country}</div></CardTitle>
<CardTitle><div style={{ float: "left" }}>Line 1</div><div style={{ float: "right" }}>{orderResult.billing_details.address.line1}</div></CardTitle>
<CardTitle><div style={{ float: "left" }}>Postal Code</div><div style={{ float: "right" }}>{orderResult.billing_details.address.postal_code}</div></CardTitle>
</Card>
</Col>
<Col md="6" className="m-auto">
<Card body>
<strong>Shipping Details</strong>
<CardTitle><div style={{ float: "left" }}>City</div><div style={{ float: "right" }}>{orderResult.shipping.address.city}</div></CardTitle>
<CardTitle><div style={{ float: "left" }}>Country</div><div style={{ float: "right" }}>{orderResult.shipping.address.country}</div></CardTitle>
<CardTitle><div style={{ float: "left" }}>Line 1</div><div style={{ float: "right" }}>{orderResult.shipping.address.line1}</div></CardTitle>
<CardTitle><div style={{ float: "left" }}>Postal Code</div><div style={{ float: "right" }}>{orderResult.shipping.address.postal_code}</div></CardTitle>
</Card>
</Col>
</Row>
</Fragment>) : (<div></div>)}
</Container>
)
}
}
OrderResult.propTypes = {
getOrderResult: PropTypes.func.isRequired,
order: PropTypes.object.isRequired,
authentication: PropTypes.object.isRequired
}
const mapStateToProps = (state) => ({
order: state.order,
authentication: state.authentication
})
export default connect(mapStateToProps, { getOrderResult })(OrderResult)
|
/**
*
*/
var payloadSerialOut = document.getElementById('payload-serial-output')
var modemSerialOut = document.getElementById('modem-serial-output')
var payloadPre = document.getElementById('payload-pre');
var modemPre = document.getElementById('modem-pre');
var uploadForm = document.getElementById('upload-form');
var fileInput = document.getElementById('file-input');
var payloadRadio = document.getElementById('payload-radio');
var modemRadio = document.getElementById('modem-radio');
const socket = io()
socket.on('payload-log', log => {
payloadSerialOut.innerHTML += log;
payloadPre.scrollTop = payloadSerialOut.scrollHeight;
});
socket.on('modem-log', log => {
modemSerialOut.innerHTML += log;
modemPre.scrollTop = modemSerialOut.scrollHeight;
});
uploadForm.onsubmit = e => {
e.preventDefault();
var data = new FormData();
data.append('firmware', fileInput.files[0]);
data.append('device', payloadRadio.checked ? 'payload' : 'modem');
fetch('/firmware', {
method: 'POST',
body: data,
})
.then(res => res.json())
.then(data => {
console.log(data);
})
.catch(err => console.log);
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.