text
stringlengths 7
3.69M
|
|---|
/**
* @author Ignacio González Bullón - <nacho.gonzalez.bullon@gmail.com>
* @since 09/01/16.
*/
(function () {
'use strict';
angular.module('corestudioApp.message')
.controller('MessageController', MessageController);
MessageController.$inject = ['Alerts', 'Message'];
function MessageController(Alerts, Message) {
var vm = this;
vm.readMessage = readMessage;
vm.deleteMessage = deleteMessage;
activate();
function activate() {
Message.query({}, function(responseData) {
vm.messages = responseData;
});
}
function readMessage(message) {
Message.update({id: message.id}, function (responseData) {
message.isRead = true;
}, function(response) {
Alerts.addHeaderErrorAlert(response.headers());
});
}
function deleteMessage(message) {
Message.delete({id: message.id}, function (responseData) {
vm.messages.splice(vm.messages.indexOf(message), 1);
}, function (response) {
Alerts.addHeaderErrorAlert(response.headers());
});
}
}
})();
|
/*global define*/
define([
'jquery',
'underscore',
'backbone',
'text!templates/article/article.tpl'
], function ($, _, Backbone, articleTpl) {
'use strict';
return Backbone.View.extend({
tagName: 'div',
// Compile our stats template
template: _.template(articleTpl),
initialize: function() {
this.render();
},
render : function() {
// Récupération du model passé depuis,
// la fonction renderArticle dans views/article/ArticlesView.js
var article = this.options.article;
this.$el.html(this.template({
// Récupération et passage des attributs du model,
// au template article.tpl.
id : article.get('id'),
title : article.get('title'),
text : article.get('text')
}));
return this;
}
});
});
|
/**
* Log tracing functionality, allowing for tracing of the internal functionality of the engine.
* Note that the trace logging only takes place in the debug build of the engine and is stripped
* out in other builds.
*/
class Tracing {
/**
* Set storing the names of enabled trace channels.
*
* @type {Set<string>}
* @private
*/
static _traceChannels = new Set();
/**
* Enable call stack logging for trace calls. Defaults to false.
*
* @type {boolean}
*/
static stack = false;
/**
* Enable or disable a trace channel.
*
* @param {string} channel - Name of the trace channel. Can be:
*
* - {@link TRACEID_RENDER_FRAME}
* - {@link TRACEID_RENDER_FRAME_TIME}
* - {@link TRACEID_RENDER_PASS}
* - {@link TRACEID_RENDER_PASS_DETAIL}
* - {@link TRACEID_RENDER_ACTION}
* - {@link TRACEID_RENDER_TARGET_ALLOC}
* - {@link TRACEID_TEXTURE_ALLOC}
* - {@link TRACEID_SHADER_ALLOC}
* - {@link TRACEID_SHADER_COMPILE}
* - {@link TRACEID_VRAM_TEXTURE}
* - {@link TRACEID_VRAM_VB}
* - {@link TRACEID_VRAM_IB}
* - {@link TRACEID_RENDERPIPELINE_ALLOC}
* - {@link TRACEID_PIPELINELAYOUT_ALLOC}
* - {@link TRACEID_TEXTURES}
* - {@link TRACEID_GPU_TIMINGS}
*
* @param {boolean} enabled - New enabled state for the channel.
*/
static set(channel, enabled = true) {
// #if _DEBUG
if (enabled) {
Tracing._traceChannels.add(channel);
} else {
Tracing._traceChannels.delete(channel);
}
// #endif
}
/**
* Test if the trace channel is enabled.
*
* @param {string} channel - Name of the trace channel.
* @returns {boolean} - True if the trace channel is enabled.
*/
static get(channel) {
return Tracing._traceChannels.has(channel);
}
}
export { Tracing };
|
import React from 'react';
import { Grid, Typography } from '@material-ui/core';
import GameCard from '../../components/GameCard';
const Dashboard = () => {
const games = [{ title: 'Monikimmers' }, { title: 'Wavelength' }]; // will come from API
return (
<Grid>
<Typography variant="h1" align="center">
The Contagions
</Typography>
<Grid container justify="center">
{games.map((game) => (
<GameCard title={game.title} key={game.title} />
))}
</Grid>
</Grid>
);
};
export default Dashboard;
|
import path from 'path';
import express from 'express';
import morgan from 'morgan';
import * as roms from './roms';
const app = express();
const dev = app.get('env') === 'dev';
app.use(morgan(dev ? 'dev' : 'common'));
app.use('/', express.static(path.join(__dirname, 'static')));
app.get('/roms', roms.list);
app.get('/roms/:id', roms.get);
app.get('/files/:name', roms.download);
app.use((error, req, res, next) => { // eslint-disable-line no-unused-vars
console.log(error.stack);
res.sendStatus(500);
});
app.listen(process.env.PORT || 5000);
roms.start();
|
'use strict';
function generateArguments() {
function generateInt(start, end) {
return start + Math.floor((end - start) * Math.random());
}
function generateLetter() {
return String.fromCharCode(generateInt('a'.charCodeAt(0), 'z'.charCodeAt(0) + 1));
}
function generateWord() {
let length = generateInt(1, 5);
let string = '';
for (let i = 0; i < length; ++i) {
string += generateLetter();
}
return string;
}
function generateWords() {
let count = generateInt(5, 10);
let words = new Array(count);
for (let i = 0; i < count; ++i) {
words[i] = generateWord();
}
return words;
}
function generateEmailPattern(words) {
let email = '';
let roll = Math.random();
if (roll < 0.2) {
email += '*';
} else {
roll = Math.random();
if (roll < 0.4) {
email += '*';
} else if (roll < 0.55) {
roll = Math.random();
if (roll < 0.3) {
email += '?';
} else {
email += generateLetter();
}
} else {
email += words[generateInt(0, words.length)];
}
email += '@';
roll = Math.random();
if (roll < 0.4) {
email += '*';
} else if (roll < 0.55) {
roll = Math.random();
if (roll < 0.3) {
email += '?';
} else {
email += generateLetter();
}
} else {
email += words[generateInt(0, words.length)];
}
}
return email;
}
function generateEmail(words) {
let email = generateEmailPattern(words);
while (email.indexOf('*') !== -1) {
email = email.replace('*', generateWord());
}
while (email.indexOf('?') !== -1) {
email = email.replace('?', generateLetter());
}
return email;
}
function generateMessages(words) {
let messages = {};
for (let i = 0; i < 10; ++i) {
messages['msg' + i] = {
from: generateEmail(words),
to: generateEmail(words),
};
}
return messages;
}
function generateRules(words) {
let rules = new Array(10);
for (let i = 0; i < rules.length; ++i) {
rules[i] = {
action: 'act' + i,
from: generateEmailPattern(words),
to: generateEmailPattern(words),
};
}
return rules;
}
let words = generateWords();
return {
messages: generateMessages(words),
rules: generateRules(words),
};
}
function resultsEqual(a, b) {
function actionSequencesEqual(a, b) {
if (a.length != b.length) {
return false;
}
for (let i = 0; i < b.length; ++i) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
for (let k in a) {
if (!(k in b)) {
return false;
}
}
for (let k in b) {
if (!actionSequencesEqual(a[k], b[k])) {
return false;
}
}
return true;
}
let referenceFilter = require('./referenceFilter');
(function runTests() {
console.log('\n\n\n---------------------------');
let args = generateArguments();
console.log(args);
let resultsByFilter = {};
for (let name of require('./filterList')) {
let filter = require('./' + name);
let args2 = JSON.parse(JSON.stringify(args));
resultsByFilter[name] = filter(args2.messages, args2.rules);
}
referenceFilter(args, referenceResults => {
console.log(referenceResults);
for (let name in resultsByFilter) {
let results = resultsByFilter[name];
if (!resultsEqual(results, referenceResults)) {
console.log(`\n\n\n!!!MISMATCH!!! in ${name}:\n`, results);
return;
}
}
setTimeout(runTests, 10000);
});
})();
|
// Global variables
var MouseClickImage;
var MousePointerImage;
var UserUID;
var FirebaseRef;
// onLoad function
$(function() {
// Get the UserUID
var searchArray = window.location.search.split("=");
UserUID = searchArray[1];
// Set up mouse click animation
MouseClickImage = new Image();
MouseClickImage.src = "mouseAnim.gif";
$('#mouseClickDiv').css({
position: "absolute",
marginLeft: 0, marginTop: 0,
top: 50, left: 50
}).appendTo('body');
// Set up mouse pointer image
MousePointerImage = new Image();
MousePointerImage.src = "mousePointer.png";
$('#mousePointerDiv').css({
position: "absolute",
marginLeft: 0, marginTop: 0,
top: 50, left: 50
}).appendTo('body');
// Connect to Firebase
FirebaseRef = new Firebase("https://blazing-fire-4598.firebaseio.com/PageClone/");
// Initial page setup and page change event capture
initialiseRef = FirebaseRef.child('queue').child(UserUID).child('initialise');
initialiseRef.on('value', function(snapshot) {
updateHTMLandFormBaseline(snapshot.val());
});
// Handle scroll events
scrollRef = FirebaseRef.child('queue').child(UserUID).child('scroll');
scrollRef.on('value', function(snapshot) {
var value = snapshot.val();
var yScroll = value.yScroll;
$(window).scrollTop(yScroll);
});
// Handle mouse click events
mouseClickRef = FirebaseRef.child('queue').child(UserUID).child('mouseClick');
mouseClickRef.on('value', function(snapshot) {
mouseLocRef = FirebaseRef.child('queue').child(UserUID).child('mouseLoc');
mouseLocRef.once('value', function(snapshot) {
var value = snapshot.val();
var xValue = value.xMouse - 50;
var yValue = value.yMouse - 50;
$("#mouseClickDiv").css("top", yValue);
$("#mouseClickDiv").css("left", xValue);
$("#mouseClickImage").attr('src', MouseClickImage.src);
});
});
// Handle keyboard events
keyRef = FirebaseRef.child('queue').child(UserUID).child('key');
keyRef.on('value', function(snapshot) {
updateElement(snapshot.val());
});
// Handle element update events
elementRef = FirebaseRef.child('queue').child(UserUID).child('element');
elementRef.on('value', function(snapshot) {
updateElement(snapshot.val());
});
// Handle mouse location events
mouseLocRef = FirebaseRef.child('queue').child(UserUID).child('mouseLoc');
mouseLocRef.on('value', function(snapshot) {
var value = snapshot.val();
var xValue = value.xMouse - 15;
var yValue = value.yMouse;
$("#mousePointerDiv").css("top", yValue);
$("#mousePointerDiv").css("left", xValue);
$("#mousePointerImage").attr('src', MousePointerImage.src);
});
// Handle tidying up the Firebase queue when this page is closed
var disconnectRef = FirebaseRef.child('queue').child(UserUID);
disconnectRef.onDisconnect().remove();
});
// Deal with when we get a new or changed pageload
function updateHTMLandFormBaseline(data) {
// Get the HTML from Firebase
var html = data.html;
// Add in the CSS files
var startPos = html.indexOf("href=");
while (startPos != -1) {
var endPos = html.indexOf(">", startPos);
var cssFile = html.substring(startPos + 6, endPos - 1);
$("<link>").appendTo($('head')).attr({type : 'text/css', rel : 'stylesheet'}).attr('href', cssFile);
startPos = html.indexOf("href=", endPos);
}
// Set up the HTML including the viewport wrapping DIV
var startPos = html.indexOf("HelpRequest") - 9;
html = html.substring(startPos);
var endPos = html.indexOf("</body>");
html = html.substring(0, endPos);
html = "<div id='viewportWrapperDiv'>\n" + html + "</div></body>";
$("#ChangeMe").html(html);
var height = data.viewport.viewportHeight;
var width = data.viewport.viewportWidth;
$("#viewportWrapperDiv").css("width", width);
$("#viewportWrapperDiv").css("height", height);
$("#viewportWrapperDiv").css("border-style", "solid");
$("#viewportWrapperDiv").css("border-color", "red");
// Fill in the form baseline
var formDataArray = jQuery.parseJSON(data.formBaseline);
var tempObject;
for (var formID in formDataArray) {
var elementArray = formDataArray[formID];
for (var elementID in elementArray) {
tempObject = new Object();
tempObject[elementID] = elementArray[elementID];
$("#" + formID).values(tempObject);
}
}
// Update the shown UID to make sure we're seeing exactly the same as the user
$("#HelpRequest").html("Your help session number is " + UserUID + ".");
// Set all the elements in all the forms to disabled and set colour to red
$("form").each(function() {
$("#" + this.name + " :input").attr("disabled", true);
$("#" + this.name + " :input").css('color', 'red');
});
}
// Deal with changes in form elements or key presses
function updateElement(data) {
var tempObject = new Object();
var element = data.element;
var value = data.value;
// Time to introduce a terrible, hopefully temporary, hack...
// This is because it only seems to register successfully for all parts of a set of radio buttons if their IDs are different
// But... If there IDs are different the 'values' function doesn't then set them correctly...
if (element.substr(element.length - 5) == "Radio") {
for(var i = 0; i < element.length; i++) {
if (element.charAt(i) == element.charAt(i).toUpperCase()) {
element = element.substring(0, i);
break;
}
}
}
tempObject[element] = value;
$("#" + data.form).values(tempObject);
}
// Helper function from : http://goo.gl/ZFacl
$.fn.values = function(data) {
var inps = $(this).find(":input").get();
if(typeof data != "object") {
// return all data
data = {};
$.each(inps, function() {
if (this.name && (this.checked
|| /select|textarea/i.test(this.nodeName)
|| /text|hidden|password/i.test(this.type))) {
data[this.name] = $(this).val();
}
});
return data;
} else {
$.each(inps, function() {
// Next 3 lines my patch on the original code to cope with emptying text fields
if ((this.type == "text" || this.type == "textarea") && this.name && (data[this.name] == "")) {
$(this).val("");
}
if (this.name && data[this.name]) {
if(this.type == "checkbox" || this.type == "radio") {
$(this).prop("checked", (data[this.name] == $(this).val()));
} else {
$(this).val(data[this.name]);
}
} else if (this.type == "checkbox") {
$(this).prop("checked", false);
}
});
return $(this);
}
};
|
var fs = require('fs');
var express = require('express');
var app = express();
var multer = require('multer');
var spawn = require('child_process').spawn;
// TODO: add request lock
app.use(multer({
dest: './public/uploads/',
rename: function(fieldname, filename) {
var now = new Date();
return now.toISOString() + '_' +
filename.replace(/\W+/g, '-').toLowerCase();
}
}));
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'jade');
app.get('/', function(req, res) {
res.render('index');
});
app.get('/xlsx_extract_json', function(req, res) {
res.render('xlsx_extract_json');
});
app.get('/diff_json', function(req, res) {
res.render('diff_json');
});
app.get('/find_xlsx_blank', function(req, res) {
res.render('find_xlsx_blank');
});
app.get('/xlsx_patch_json', function(req, res) {
res.render('xlsx_patch_json');
});
app.post('/upload_xlsx_for_extracting_json', function(req, res) {
var xlsx = req.files.xlsx;
if (!xlsx) {
res.send('缺少参数');
return;
}
var workerScript = __dirname + '/tools/xlsx_extract_json/xlsx2json.js';
var xlsxPath = __dirname + '/' + xlsx.path;
var destinationPath = __dirname + '/public/downloads/xlsx_extract_json/';
var worker = spawn('node', [workerScript, xlsxPath, destinationPath]);
worker.stdout.on('data', function(data) {
console.log('' + data);
});
worker.stderr.on('data', function(data) {
console.log('' + data);
res.send('some error happened: ' + data);
});
worker.on('close', function(code) {
console.log('child process exited with code ' + code);
var filesObj = {};
var folders = fs.readdirSync(destinationPath);
folders.forEach(function(folderName) {
var folderStats = fs.statSync(destinationPath + folderName);
if (folderStats.isFile()) {
filesObj[folderName] = [{
name: folderName,
path: '/downloads/xlsx_extract_json/' + folderName
}];
} else if (folderStats.isDirectory()) {
filesObj[folderName] = fs.readdirSync(destinationPath + folderName).map(function(filename) {
return {
name: filename,
path: '/downloads/xlsx_extract_json/' + folderName + '/' + filename
};
});
}
});
res.render('download_extract_json', { folderFiles: filesObj });
});
});
app.post('/upload_json_to_diff', function(req, res) {
var file1 = req.files.file1;
var file2 = req.files.file2;
if (!file1 || !file2) {
res.send('缺少参数');
return;
}
var workerScript = __dirname + '/tools/diff_json/diffJSON.js';
var file1path = __dirname + '/' + file1.path;
var file2path = __dirname + '/' + file2.path;
var destinationPath = __dirname + '/public/downloads/diff_json/diff.json';
var worker = spawn('node', [workerScript, file1path, file2path, destinationPath]);
worker.stdout.on('data', function(data) {
console.log('' + data);
});
worker.stderr.on('data', function(data) {
console.log('' + data);
res.send('some error happened: ' + data);
});
worker.on('close', function(code) {
console.log('child process exited with code ' + code);
res.render('download', { path: '/downloads/diff_json/diff.json' });
});
});
app.post('/upload_xlsx_to_find_blank', function(req, res) {
var xlsx = req.files.xlsx;
var sheet = req.param('sheet');
var origin = req.param('origin');
var target = req.param('target');
if (!xlsx || !origin || !target || !sheet) {
res.send('缺少参数');
return;
}
var workerScript = __dirname + '/tools/xlsx_find_blank/xlsx_find_blank.js';
var xlsxPath = __dirname + '/' + xlsx.path;
var destinationPath = __dirname + '/public/downloads/xlsx_find_blank/untranslated.json';
var worker = spawn('node', [workerScript, xlsxPath, destinationPath, origin, target, sheet]);
worker.stdout.on('data', function(data) {
console.log('' + data);
});
worker.stderr.on('data', function(data) {
console.log('' + data);
res.send('some error happened: ' + data);
});
worker.on('close', function(code) {
console.log('child process exited with code ' + code);
res.render('download', { path: '/downloads/xlsx_find_blank/untranslated.json' });
});
});
app.post('/upload_xlsx_and_json_to_patch', function(req, res) {
var xlsx = req.files.xlsx;
var json = req.files.json;
var sheet = req.param('sheet');
var target = req.param('target');
if (!xlsx || !sheet || !target) {
res.send('缺少参数');
return;
}
var workerScript = __dirname + '/tools/xlsx_patch_json/xlsx_patch_json.js';
var xlsxPath = __dirname + '/' + xlsx.path;
var jsonPath = __dirname + '/' + json.path;
var destinationPath = __dirname + '/public/downloads/xlsx_patch_json/' + xlsx.originalname;
var worker = spawn('node', [workerScript, xlsxPath, jsonPath, destinationPath, sheet, target]);
worker.stdout.on('data', function(data) {
console.log('' + data);
});
worker.stderr.on('data', function(data) {
console.log('' + data);
res.send('some error happened: ' + data);
});
worker.on('close', function(code) {
console.log('child process exited with code ' + code);
res.render('download', { path: '/downloads/xlsx_patch_json/' + xlsx.originalname});
});
});
app.listen(3000, function() {
console.log('listen on 3000...');
});
|
import {System} from "../srcRoot/system.js";
import {DomLevels} from "../srcRoot/domLevels.js";
export class PrivateIcons {
constructor(data={}, container={}, otherParams={}) {
this.doConstruct(data, container, otherParams);
}
doConstruct(data={}, container={}, otherParams={}) {
this.data = data;
if( Object.keys(container).length > 0) {
for(let key of Object.keys(container)) eval('this.' + key + ' = container.' + key + ';');
}
if( Object.keys(otherParams).length > 0) {
for(let key of Object.keys(otherParams)) eval('this.' + key + ' = otherParams.' + key + ';');
}
this.container = container;
this.otherParams = otherParams;
}
execRender(data={}, container={}, otherParams={}) {
this.doConstruct(data, container, otherParams);
let ext = '.json';
let jsonFile = undefinedIs(this.jsonFile);
if(jsonFile.toLowerCase().indexOf(ext) == jsonFile.length - (ext.length)) {
fetch(jsonFile)
.then(response => response.json())
.then(result => this.test = this.iconsIntro(data, container, otherParams, result));
}
}
iconsIntro(data={}, container={}, otherParams={}, jsonData={}) {
let domLevels = new DomLevels();
let cnt = domLevels.createDivElement( this.parentID,
this.ID,
this.tester);
$('#'+this.ID).html(this.createHTMLIcons(this.data, jsonData));
}
createSimpleHTMLIcons(viewFields, fromDB) {
let html = '';
for(let icon of viewFields) {
if(typeof icon.iconFont != 'undefined') {
if(icon.iconFont.length>0 && fromDB[icon.field] == 1) {
html += '<i title="' + icon.title + '" style="color:' + icon.iconColor + ';background-color:' + icon.iconBgColor + ';" class="icon ' + icon.iconFont + '"></i>';
}
}
}
return html;
}
createHTMLIcons(data={}, jsonData={}) {
let system = new System();
let currentRec = data[0];
let aFromDB = system.getArrayFromData(jsonData, data[0]);
let tempData = [];
for(let line of Object.values(jsonData)) {
let iconFont = undefinedIs(line['iconFont']);
if(iconFont.trim().length >0) {
tempData.push({ 'field':line['field'],
'title':line['title'],
'iconFont':line['iconFont'],
'iconColor':line['iconColor'],
'iconBgColor':line['iconBgColor']});
}
}
let index = 1;
let record;
let HTML = '';
while(index<1000) {
record = system.getRecordFromIndex(aFromDB, index); ++index;
if(record==null) {break;}
for(let line of Object.values(tempData)) {
if(line.field == record.fieldName) {
if(record[record.fieldName]==1) {
HTML += '<i title="' + line.title;
HTML += '" style="color:' + line.iconColor + ';background-color:' + line.iconBgColor + ';" ';
HTML += ' class="icon ' + line.iconFont + '" ></i>';
}
}
}
}
return HTML;
}
}
|
/*
* Create a list that holds all of your cards
*/
let counter = 0;
let timer = 0;
let timerId = 0;
const oneStar = '<li><i class="fa fa-star"></i></li>';
const twoStars = '<li><i class="fa fa-star"></i></li><li><i class="fa fa-star"></i></li>';
const threeStars = '<li><i class="fa fa-star"></i></li><li><i class="fa fa-star"></i></li><li><i class="fa fa-star"></i></li>';
$(document).ready(function() {
let cards = $(".card"); //jQuery list of cards
let cardsArray = cards.toArray(); //JS array of cards
for (const card of cards){ //looping over jQuery list of card to perform on click
$(card).on("click", displayCard);
};
$(".restart").click(function(e){ //refresh game
e.preventDefault()
reset();
startTimer();
for (const card of cards){
$(card).remove();
};
shuffledCardsArray = shuffle(cardsArray); //use shuffle function
// take JS array and shuffle- return new array
for (const shuffledCardFromArray of shuffledCardsArray){ //loop thru JS array
$(shuffledCardFromArray).removeClass("open");
$(shuffledCardFromArray).removeClass("show");
$(shuffledCardFromArray).removeClass("match");
$(".deck").append(shuffledCardFromArray);
$(shuffledCardFromArray).on("click", displayCard);
};
});
$("#close").click(function(e){ // if the user clicks on play again
e.preventDefault();
$(".restart").click();
});
$(".restart").click();
});
function displayCard(){ //when a card is clicked, this should happen
$(this).addClass("open");
$(this).addClass("show");
checkScore();
matchMaker();
};
function checkWin(){ //to check to see if a win happens and if it does do this
if ($(".match").length===16){
$("#winnerChickenDinner").modal("show");
stopTimer();
let starryNight = checkScore();
let rating = 0;
if (starryNight === 1){
rating = oneStar;
}else if (starryNight === 2){
rating = twoStars;
}else if (starryNight === 3){
rating = threeStars;
}
$("#winnerChickenDinner .modal-body").html(`<p>Congratulations!</p><p>You won in ${counter} moves and ${timer} seconds! You're rated: <ul class="stars pad"> ${rating} </ul></p>`);
}
};
function stopTimer(){ //stop the timer
clearInterval(timerId);
timerId = 0;
};
function reset(){ //reset the game
counter = 0;
$(".moves").text(counter);
timer = 0;
$(".timer").text(timer);
$(".stars li").remove();
$(".stars").append(threeStars);
};
function incrementCounter(){ //increment the Counter
counter++;
$(".moves").text(counter);
}
function checkScore(){ //Give a player rating on the page
$(".stars li").remove();
if (counter <= 15){
$(".stars").append(threeStars);
return 3;
}else if (counter <= 30){
$(".stars").append(twoStars);
return 2;
}else{
$(".stars").append(oneStar);
return 1;
}
}
function startTimer(){ //start the timer
if (timerId === 0){
timerId = setInterval(function(){
timer++;
$(".timer").text(timer);
}, 1000)
}
};
function matchMaker(){ //determine if a two cards are open and if a match is made
if($(".open").length == 2){
incrementCounter();
let firstIcon = $(".open").first().find("i");
let lastIcon = $(".open").last().find("i");
if(firstIcon.hasClass(lastIcon.attr("class"))){
$(".open").addClass("match");
$(".open").removeClass("show");
$(".open").removeClass("open");
checkWin();
}else {
reHide();
}
}else if ($(".open").length == 1){
console.log("first card");
}else if ($(".open").length > 2){
$(".open").removeClass("show");
$(".open").removeClass("open");
}
};
function reHide(){ //rehide if a match isn't made
const id = setInterval(function(){
$(".open").removeClass("show");
$(".open").removeClass("open");
clearInterval(id);
}, 500)
};
// Shuffle function from http://stackoverflow.com/a/2450976
function shuffle(cardsArray) {
var currentIndex = cardsArray.length, temporaryValue, randomIndex;
while (currentIndex !== 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = cardsArray[currentIndex];
cardsArray[currentIndex] = cardsArray[randomIndex];
cardsArray[randomIndex] = temporaryValue;
}
return cardsArray;
}
|
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import {Container, Content, Header, Form, Input, Item, Button, Label} from 'native-base'
import { StackNavigator, TabNavigator } from 'react-navigation';
import * as firebase from 'firebase';
import HomeScreen from './HomeScreen';
// Initialize Firebase
var config = {
apiKey: "AIzaSyAwNglu4811O9jYhDln0_FPz0HyoOrP5vE",
authDomain: "react-firebase-c9c8a.firebaseapp.com",
databaseURL: "https://react-firebase-c9c8a.firebaseio.com",
projectId: "react-firebase-c9c8a",
storageBucket: "react-firebase-c9c8a.appspot.com",
messagingSenderId: "91068272861"
};
firebase.initializeApp(config);
export default class Login extends React.Component {
static navigationOptions = {
title: 'Login'
};
constructor(props){
super(props)
this.state = ({
email: '',
password: ''
})
}
componentDidMount(){
firebase.auth().onAuthStateChanged((user) => {
if(user != null) {
console.log(user)
}
})
}
signUpUser = (email,password) => {
try {
if(this.state.password.length<6)
{
alert("Please enter atleast 6 characters")
return;
}
firebase.auth().createUserWithEmailAndPassword(email, password).then((user) =>{
alert("You have successfully registered")
return;
})
}
catch(error){
console.log(error.toString())
}
}
loginUser = (email, password) => {
try{
firebase.auth().signInWithEmailAndPassword(email, password).then((user) => {
this.props.navigation.push('Compass')
})
}
catch(error) {
console.log(error.toString())
}
}
async loginWithFacebook(){
const {type,token} = await Expo.Facebook.logInWithReadPermissionsAsync
('875510382633487',{permissions: ['public_profile'] })
if(type == 'success') {
const credential = firebase.auth.FacebookAuthProvider.credential(token)
firebase.auth().signInWithCredential(credential).catch((error) => {
console.log(error);
})
}
}
render() {
const {navigate} = this.props.navigation;
return (
<Container style={styles.container}>
<Form>
<Item floatingLabel>
<Label>Email</Label>
<Input
autoCorrent= {false}
autoCapitalize="none"
onChangeText = {(email) => this.setState({email})}
/>
</Item>
<Item floatingLabel>
<Label>Password</Label>
<Input
secureTextEntry={true}
autoCorrent= {false}
autoCapitalize="none"
onChangeText = {(password) => this.setState({password})}
/>
</Item>
<Button style={{marginTop:10}}
full
rounded
success
onPress={() => this.loginUser(this.state.email,this.state.password)}
>
<Text style={{color:'white'}}> Login </Text>
</Button>
<Button style={{marginTop:10}}
full
rounded
primary
onPress={() => this.signUpUser(this.state.email,this.state.password)}>
<Text style={{color:'white'}}> Sign Up </Text>
</Button>
<Button style={{marginTop:10}}
full
rounded
primary
onPress={() => this.loginWithFacebook() }
>
<Text style={{color:'white'}}> Login With Facebook </Text>
</Button>
</Form>
</Container>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
justifyContent: 'center',
padding:10
},
});
|
import { connect } from 'react-redux'
import * as AppActions from '../actions/AppActions'
import { UserMap } from '../components/Map'
import emojis from '../emojis.json'
const mapStateToProps = (state, ownProps) => {
return {
user: state.app.user,
isSaving: state.app.isSaving,
emojis: emojis,
selectedId: state.app.selected,
isFetching: state.app.isFetchingPins
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
onSave: (uid, pins) => {
dispatch(AppActions.save(uid, pins))
},
selectPin: (data) => {
dispatch(AppActions.selectPin(data))
}
}
}
const MapContainer = connect(
mapStateToProps,
mapDispatchToProps
)(UserMap)
export default MapContainer
|
import {createStackNavigator} from 'react-navigation-stack';
import {createAppContainer} from 'react-navigation';
import WeatherToday from './components/WeatherToday';
const screens = {
WeatherToday:{
screen:WeatherToday
},
}
const WeatherTodayStack = createStackNavigator(screens);
export default createAppContainer(WeatherTodayStack);
|
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classes from './Person.css';
import WithClass from '../../../hoc/WithClass';
class Person extends Component {
constructor(props) {
super(props);
console.log('[Person.js] Inside Constructor', props);
// createRef new to React 16.3
this.inputElement = React.createRef();
}
componentWillMount() {
console.log('[Person.js] Inside componentWillMount()');
}
componentDidMount() {
console.log('[Person.js] Inside componentDidMount()');
// Old would have function here. 16.3 has separatability
// this is actually being executed after the creation of inputElement
// below in the render function
// if (this.props.position === 0) {
// // 16.3 Version
// this.inputElement.current.focus();
// // Old Version
// // this.inputElement.focus();
// }
if (this.props.position === 0) {
this.inputElement.current.focus();
}
}
// 16.3
focus() {
this.inputElement.current.focus();
}
render() {
console.log('[Person.js] Inside render()');
return (
<WithClass classes={classes.Person}>
<p onClick={this.props.click}>I'm {this.props.name} and I am {this.props.age} years old!</p>
<p>{this.props.children}</p>
<input
// 16.3 Version
ref={this.inputElement}
// Old version
// ref={(inp) =>{this.inputElement = inp}}
type="text"
onChange={this.props.changed}
value={this.props.name}/>
</WithClass>
)
}
}
Person.propTypes = {
click: PropTypes.func,
name: PropTypes.string,
age: PropTypes.number,
changed: PropTypes.func
};
export default Person;
|
/**
* Created by gautam on 19/12/16.
*/
import React from 'react';
import { Link, browserHistory } from 'react-router';
import Address from './Address';
import ActivityHeader from './ActivityHeader';
import ActivityFooter from './ActivityFooter';
import TopNotification from './TopNotification';
import $ from 'jquery';
import Base from './base/Base';
import {I, ADDRESS} from '../constants';
import {connect} from 'react-redux';
import {addressSelected, getUserDetails, reFetchUserDetails} from '../actions';
import ajaxObj from '../../data/ajax.json';
class AddressList extends React.Component {
constructor(props) {
super(props)
this.state = {
address: '',
activelkey: '',
notify: {
show: false,
type: 'info',
timeout: 4000,
msg:'',
bottom: 50
}
}
}
render() {
const {notify, activelkey} = this.state,
{userDetails} = this.props,
addressList = userDetails.details ? userDetails.details.addressList : [];
return (
<div>
<ActivityHeader heading = { 'Select your Address' }/>
<TopNotification data={notify}/>
<div className = 'col-md-offset-4 col-md-4 col-xs-12'>
{ Array.isArray(addressList) ? addressList.map( function(address, index) {
return (<Address key = { address.lkey } address = { address } index = { index } active = { activelkey === address.lkey } selectedAddress = { this.selectedAddress }/>)
}, this):'' }
<div className = 'message' style = {{marginTop: 20}}>{Array.isArray(addressList) && addressList.length > 1 ? '*Tap to select your desired address':''}</div>
<div className='add-address col-xs-4'><Link to = '/address/add'>Add New Address</Link></div>
</div>
<ActivityFooter key = { 45 } next = { this.navigateNext } back = { this.navigateBack }/>
</div>
)
}
navigateNext = () => {
if(this.state.activelkey) {
browserHistory.push('booking/confirm');
} else {
this.showNotification(I, ADDRESS);
}
}
navigateBack = () => {
browserHistory.push('/order/details');
}
showNotification = (type, msg, timeout = 4000, bottom = 50) => {
this.setState({notify: {show: true, timeout, type, msg, bottom}})
}
componentDidMount = () => {
const {reFetchDetails} = this.props.userDetails;
if(reFetchDetails) {
this.callGetAddressListIn3Sec();
}
}
callGetAddressListIn3Sec = () => {
Base.showOverlay();
setTimeout(() => { this.getaddresslist() }, 3000);
}
getaddresslist = () => {
this.props.getUserDetails();
this.props.reFetchUserDetails(false);
}
selectedAddress = (address) => {
this.setState({ address, activelkey: address.lkey });
this.props.addressSelected({activelkey: address.lkey});
}
}
function mapStateToProps(state) {
return {
userDetails: state.userDetails
};
}
function mapDispatchToProps(dispatch) {
return {
addressSelected: (options) => {
dispatch(addressSelected(options));
},
getUserDetails: () => {
dispatch(getUserDetails());
},
reFetchUserDetails: (flag) => {
dispatch(reFetchUserDetails(flag));
}
};
}
export default connect(mapStateToProps, mapDispatchToProps)(AddressList);
|
var requirejs = require('requirejs');
var ModuleController = require('../controllers/module');
var TimeseriesController = requirejs('common/modules/single-timeseries');
var View = require('../views/modules/single-timeseries');
var parent = ModuleController.extend(TimeseriesController);
module.exports = parent.extend({
visualisationClass: View,
visualisationOptions: function () {
return _.extend(parent.prototype.visualisationOptions.apply(this, arguments), {
url: this.url
});
}
});
|
// function filterByTerm(inputArr, searchTerm){
// if (!searchTerm) throw Error("searchTerm cannot be empty");
// const regex = new RegExp(searchTerm, "i");
// return inputArr.filter(function(arrElement){
// return arrElement.url.match(regex);
// });
// }
const filterByTerm = require("../src/filterByTerm");
describe("Filter function", ()=>{
test("it should filter by a search term(Link)",()=>{
const input =[
{id:1 , url: "https://www.url1.dev"},
{id:2, url: "https://www.url2.dev"},
{id: 3, url: "https://www.link3.dev"}
];
const output = [{id: 3, url:"https://www.link3.dev"}];
expect(filterByTerm(input, "link")).toEqual(output);
expect(filterByTerm(input, "Link")).toEqual(output);
expect(filterByTerm(input, "uRl")).toEqual([{id:1 , url: "https://www.url1.dev"},
{id:2, url: "https://www.url2.dev"}]);
// expect(filterByTerm(input, "")).
});
});
|
//import $ from 'jquery';
//import howler from 'howler';
import anime from "animejs";
const LANDING = {};
LANDING.intro = document.querySelector('.intro-screen');
LANDING.start = LANDING.intro.querySelector('div#start');
LANDING.path = LANDING.intro.querySelector('path');
const svgAnimation = () => {
console.log('Animation');
anime({
targets: LANDING.intro,
duration: 2000,
easing: 'easeInOutSine',
translateY: '-200vh'
});
anime({
targets: LANDING.path,
duration: 1500,
easing: 'easeInOutSine',
d: LANDING.path.getAttribute('pathdata:id')
});
};
LANDING.start.addEventListener('click',svgAnimation);
|
import {generateUUID, RandomNameGenerator} from "../utils";
import {PortMapping, RestartPolicy, BaseImage, EnvironmentVariable} from "./";
export class Service {
constructor(name) {
this._id = generateUUID();
this._name = name || RandomNameGenerator.getRandomName();
this._baseImage = new BaseImage();
this._ports = [];
this._environment = [];
this._restart = RestartPolicy.NO;
this._active = true;
}
setName(name) {
this._name = name;
}
getName() {
return this._name;
}
setBaseImage(image) {
this._baseImage = new BaseImage(image);
}
/**
* @returns {BaseImage}
*/
getBaseImage() {
return this._baseImage;
}
setRestartPolicy(policy) {
this._restart = RestartPolicy.get(policy);
}
getRestartPolicy() {
return this._restart;
}
addPortMapping(externalPort, internalPort) {
const portMapping = new PortMapping(externalPort, internalPort);
const externalPortAlreadyUsed = this._ports.some(portMapping => portMapping.externalPort === portMapping.getExternalPort());
const internalPortAlreadyUsed = this._ports.some(portMapping => portMapping.internalPort === portMapping.getInternalPort());
if (externalPortAlreadyUsed || internalPortAlreadyUsed) {
// TODO: what to do, when some of the desired ports are already in use?
} else {
this._ports.push(portMapping);
}
}
setPortMappings(portMappings) {
this._ports = portMappings;
}
/**
* @returns {Array<PortMapping>}
*/
getPortMappings() {
return this._ports;
}
addEnvironmentVariable() {
this._environment.push(new EnvironmentVariable(arguments));
}
getEnvironmentVariables() {
return this._environment;
}
/**
* @param key
* @param resolveValue If true, all variables in value are resolved.
* @returns {EnvironmentVariable}
*/
getEnvironmentVariable(key, resolveValue) {
const environmentVariable = this._environment.find(env => env.getKey() === key);
if (environmentVariable && resolveValue === true) {
let value = environmentVariable.getValue();
if (typeof value === 'string' && value.indexOf("$") !== -1) {
value = value.replace(/\$([A-Za-z_]*)/gi, match => {
const envVar = this.getEnvironmentVariable(match.substr(1), true);
return envVar ? envVar.getValue() : match;
});
return EnvironmentVariable.create(key, value);
}
}
return environmentVariable;
}
setEnvironmentVariables(envVars) {
this._environment = envVars;
}
setActive(active) {
this._active = active;
}
isActive() {
return this._active;
}
static fromJSON(json) {
const service = Object.assign(new Service(), json);
service._baseImage = BaseImage.fromJSON(service._baseImage);
service._environment = service._environment.map(EnvironmentVariable.fromJSON);
service._ports = service._ports.map(PortMapping.fromJSON);
return service;
}
}
|
/*
* @Descripttion:
* @version:
* @Author: 唐帆
* @Date: 2020-04-17 13:20:01
* @LastEditors: 唐帆
* @LastEditTime: 2020-04-18 00:38:33
*/
window.addEventListener('load', function () {
// this.alert(1);
// 1 左右按钮随鼠标移入移出隐藏
const arrow_r = document.querySelector('.next');
const arrow_l = document.querySelector('.prev');
const main_area = document.querySelector('.main-area');
const tb_promoa = document.querySelector('.tb-promo');
// const first_img = main_area.children[0].cloneNode(true);
// main_area.appendChild(first_img)
let timer = setInterval(function () {
if (img_index < 3 && direction === 'right') {
img_index++;
arrow_r.click();
} else if (img_index === 3 && direction === 'right') {
direction = 'left';
arrow_l.click();
}
if (img_index > 0 && direction === 'left') {
img_index--;
arrow_l.click();
} else if (img_index === 0 && direction === 'left') {
direction = 'right';
arrow_r.click();
}
}, 3000)
// 鼠标进入则显示
tb_promoa.addEventListener('mouseover', function () {
arrow_r.style.display = 'block';
arrow_l.style.display = 'block';
clearInterval(timer);
timer = null;
});
// 鼠标移出则隐藏
tb_promoa.addEventListener('mouseleave', function () {
arrow_r.style.display = 'none';
arrow_l.style.display = 'none';
timer = setInterval(function () {
if (img_index < 3 && direction === 'right') {
img_index++;
arrow_r.click();
} else if (img_index === 3 && direction === 'right') {
direction = 'left';
arrow_l.click();
}
if (img_index > 0 && direction === 'left') {
img_index--;
arrow_l.click();
} else if (img_index === 0 && direction === 'left') {
direction = 'right';
arrow_r.click();
}
}, 3000)
})
// 2 动态生成小圆圈
const num_of_img = document.querySelector('.main-area').querySelectorAll('li');
const ul_point = document.querySelector('.ul-point');
let needed_number = num_of_img.length;
for (let x = 0; x < needed_number; x++) {
const li = document.createElement('li');
// console.log(x);
li.index = x;
// 绑定事件
li.addEventListener('click', function () {
for (let x of ul_point.children) {
x.className = '';
}
this.className = 'selected';
clickCircle.call(this);
})
ul_point.appendChild(li)
}
// 默认第一个是选中状态
ul_point.children[0].className = 'selected';
// 3 点击小圆,ul 滚动
function clickCircle() {
// console.log(this);
const img_width = main_area.querySelector('img').clientWidth;
// console.log(img_width * this.index);
animate(main_area, -img_width * this.index);
}
const MoveSingleImg = function (type) {
const position_of_imgs = main_area.offsetLeft;
const num_of_img = main_area.querySelectorAll('li');
let needed_number = num_of_img.length - 1;
const img_width = main_area.querySelector('img').clientWidth;
// console.log(position_of_imgs - img_width);
let whether_move = false;
if (type === 'right' && position_of_imgs !== -needed_number * img_width) {
if (position_of_imgs % img_width === 0) {
move_length = position_of_imgs - img_width;
animate(main_area, move_length);
whether_move = true;
}
} else if (type === 'left' && position_of_imgs !== 0) {
if (position_of_imgs % img_width === 0) {
move_length = position_of_imgs + img_width
animate(main_area, move_length);
whether_move = true;
}
}
if (whether_move) {
let index = - move_length / img_width;
const circles = document.querySelector('.ul-point').querySelectorAll('li');
for (let i = 0; i < circles.length; i++) {
circles[i].className = '';
}
circles[index].className = 'selected';
}
}
arrow_r.addEventListener('click', MoveSingleImg.bind(this, 'right'));
arrow_l.addEventListener('click', MoveSingleImg.bind(this, 'left'));
let img_index = 0;
let direction = 'right';
// class DuiLie {
// constructor(x, y) {
// this.arr = [];
// }
// push_my(number) {
// let arr = this.arr;
// arr.push(number);
// this.arr = arr;
// }
// pop_my() {
// if (this.arr.length > 0) {
// let arr = this.arr;
// const a = arr.splice(0, 1)
// return a;
// }
// return false;
// }
// }
// class Son extends DuiLie {
// constructor(x, y) {
// super(x, y)
// }
// }
// const js_duilie = new DuiLie();
// js_duilie.push_my(1);
})
|
$(document).ready(function() {
//FancyBox http://fancybox.net/howto
$(".fancybox").fancybox({
minWidth: '615px',
maxWidth: '615px',
padding: 0,
helpers : {overlay : {css : {'background' : 'rgba(0, 0, 0, 0.85)'}}}
});
//Waypoints http://imakewebthings.com/jquery-waypoints/
$(".block").waypoint(function(direction) {
if (direction === "down") {
$(".class").addClass("active");
} else if (direction === "up") {
$(".class").removeClass("deactive");
};
}, {offset: 100});
//scroll2id http://manos.malihu.gr/page-scroll-to-id
$(".scroll>a").mPageScroll2id({
scrollSpeed: 1100,
offset: 90,
highlightClass:"active"
});
//makes menu slim starting from 2nd section
$(document).on('scroll', function() {
var scroll = $(document).scrollTop();
if (scroll > 150) {
$('.header').addClass('slim');
} else{
$('.header').removeClass('slim');
};
});
//highlights active control
$('.miniatures .item').on('click', function (){
var dataCat = $(this).attr('datacat');
var dataActv = $('.actv').attr('datacat');
var sel = '.' + dataCat;
if (dataCat !== dataActv) {
$('.actv').removeClass('actv');
$(sel).addClass('actv');
};
});
$('.control').on('click', 'li', function() {
var owl = $('.owlCarousel');
var dataCat = $(this).attr('datacat');
var dataGo = $(this).index();
var sel = String ('[datago = ' + String(dataGo) + ']');
var selCat = '.' + dataCat;
var dataActv = $('.actv').attr('datacat');
var idx = $(sel).parent().index();
owl.trigger('owl.goTo', idx);
if (dataCat !== dataActv) {
$('.actv').removeClass('actv');
$(selCat).addClass('actv');
};
});
// wow.js
new WOW().init();
// YANDEX MAPS
var myMap,
myPlacemark;
ymaps.ready(init);
function init () {
myMap = new ymaps.Map('s4', {
center: [55.636544, 37.620663],
zoom: 15
}, {
searchControlProvider: 'yandex#search'
});
myMap.behaviors.disable('scrollZoom');
myPlacemark = new ymaps.Placemark([55.636544, 37.620663],
{
name: 'Варшавское шоссе, д. 95',
description: 'descriptor',
metro:true,
iconContent: '<div class="mark"><div></div>Варшавское шоссе, д. 95</div>'
});
myMap.geoObjects.add(myPlacemark);
}
});
|
$(document).ready(function() {
// prep for api delete
$.ajaxSetup({
headers: { "X-CSRFToken": window.spacescout_admin.csrf_token }
});
/* home tabs */
$('#myTab a').click(function (e) {
e.preventDefault();
$(this).tab('show');
$($(this).attr('href')).children().trigger('exposed', ['Custom', 'Event']);
});
/* deal with tab exposure */
$('#published').on('exposed', function (event) {
loadPublishedSpaces();
});
$('#unpublished').on('exposed', function (event) {
loadUnpublishedSpaces();
});
$('#incomplete').on('exposed', function (event) {
loadIncompleteSpaces();
});
var spacesLoadingCue = function (selector) {
var tpl_src = $('#list-item-loading').html();
window.location.hash = selector.substr(1) + '-spaces';
$(selector).html(Handlebars.compile(tpl_src)());
};
var loadPublishedSpaces = function () {
var selector = '#published';
spacesLoadingCue(selector);
$.ajax({
url: window.spacescout_admin.app_url_root + 'api/v1/space/?published=1',
dataType: 'json',
error: ajaxSpaceError,
success: function (data) {
paintGroupings(selector, data);
}
});
};
var loadUnpublishedSpaces = function () {
var selector = '#unpublished';
spacesLoadingCue(selector);
$.ajax({
url: window.spacescout_admin.app_url_root + 'api/v1/space/?complete=1&published=0',
dataType: 'json',
error: ajaxSpaceError,
success: function (data) {
paintGroupings(selector, data);
}
});
};
var loadIncompleteSpaces = function () {
var selector = '#incomplete';
spacesLoadingCue(selector);
$.ajax({
url: window.spacescout_admin.app_url_root + 'api/v1/space/?complete=0&published=0',
dataType: 'json',
error: ajaxSpaceError,
success: function (data) {
var tpl_src, context, i;
if (data.length) {
tpl_src = $('#incomplete-spaces').html();
context = {
spaces: []
};
$.each(data, function () {
var unfinished = [];
for (i in this.missing_fields) {
unfinished.push({
id: this.id,
field: gettext(this.missing_fields[i].field),
section: this.missing_fields[i].section
});
}
context.spaces.push({
id: this.id,
name: this.name,
unfinished: unfinished,
last_modified: window.spacescout_admin.modifiedTime(new Date(this.last_modified)),
modified_by: (this.hasOwnProperty('modified_by') && this.modified_by && this.modified_by.length) ?
this.modified_by : gettext('unknown'),
manager: this.manager
});
});
} else {
tpl_src = $('#no-spaces').html();
context = {};
}
$(selector).html(Handlebars.compile(tpl_src)(context));
$('.delete-space').click(function (e) {
var t = $(e.target),
id = t.prop('id').match(/space_([0-9]+)/)[1],
name = t.prev().find('span').text();
if (confirm('Really delete space "' + name + '"?')) {
$.ajax({
url: window.spacescout_admin.app_url_root + 'api/v1/space/' + id + '/',
type: 'DELETE',
success: function (data) {
if (t.parent().parent().children().length > 1) {
t.parent().slideUp('fast');
} else {
window.location.reload();
}
},
error: ajaxSpaceError
});
}
});
}
});
};
var paintGroupings = function (selector, data) {
var tpl_src,
context;
if (data.length) {
tpl_src = $('#grouping-groups').html();
context = groupContext(data);
} else {
tpl_src = $('#no-spaces').html();
context = {};
}
$(selector).html(Handlebars.compile(tpl_src)(context));
};
var groupContext = function (data) {
var spaces = [],
groupings = [],
context = {
groupings: []
},
i;
$.each(data, function () {
var group = this.group,
space_data = {
id: this.id,
name: this.name,
description: this.description,
last_modified: window.spacescout_admin.modifiedTime(new Date(this.last_modified)),
modified_by: (this.hasOwnProperty('modified_by') && this.modified_by && this.modified_by.length) ? this.modified_by : gettext('unknown'),
manager: (this.manager.length > 0) ? this.manager : gettext('unknown'),
is_modified: this.is_modified,
is_pending: this.is_pending,
is_published: this.is_published,
is_pending_publication: this.is_pending_publication
};
if (group in spaces) {
spaces[group].push(space_data);
} else {
groupings.push(group);
spaces[group] = [space_data];
}
});
for (i in groupings.sort()) {
context.groupings.push({
name: groupings[i],
spaces: spaces[groupings[i]]
});
}
return context;
};
var ajaxSpaceError = function (xhr) {
var json;
try {
json = $.parseJSON(xhr.responseText);
console.log('space search service error:' + json.error);
} catch (e) {
console.log('Unknown space service error');
}
};
// initialize
switch(decodeURIComponent(window.location.hash.substr(1))) {
case 'unpublished-spaces' :
$('a[href=#unpublished]').tab('show');
loadUnpublishedSpaces();
break;
case 'incomplete-spaces' :
$('a[href=#incomplete]').tab('show');
loadIncompleteSpaces();
break;
default:
loadPublishedSpaces();
break;
}
});
|
import React from 'react'
import Sidebar from '../../components/Sidebar/Sidebar'
import { Container, Grid } from '@material-ui/core'
import useStyles from '../../styles'
export default function Layout(props) {
const classes = useStyles()
return (
<Container className={classes.layout}>
<Grid container>
<Grid item xs={3}>
<Sidebar />
</Grid>
<Grid item xs={9} className={classes.main}>
<Container>
{props.children}
</Container>
</Grid>
</Grid>
</Container>
)
}
|
$('#name').focus(); //focus used to set to first field when webpage loads
$('#other-title').hide();
document.getElementById('mail').placeholder = "Please Insert Email"; //placeholder text set into email
document.getElementById('name').placeholder = "Please Insert Name"; // placeholder text set into name
const paypalP = $("body > div > form > fieldset:nth-child(4) > div:nth-child(5) > p") ; //set js path to a variable
const bitcoinP = $("body > div > form > fieldset:nth-child(4) > div:nth-child(6) > p"); //set js path to a variable
$(paypalP).hide();
$(bitcoinP).hide();
const activities_error_message = ("<label>'Please check at least one activity</label>"); // error message for activities section
//Job role Section$
$('#title').on('change',function() { //on change of title , when other is selected , other title input will display and hide when another selection is made
if ($(this).val()=== 'other') {
$('#other-title').show();
}else{
$('#other-title').hide();
}
});
//T-shirt section
$('#colors-js-puns').hide(); //hide color section
$('#design').on('change', function(){ //when design theme is selceted on js puns it will display from html 3 options
if ($(this).val() ==="js puns") {
$('#colors-js-puns').show();
$('#color').html(`<option value="cornflowerblue">Cornflower Blue (JS Puns shirt only)</option>
<option value="darkslategrey">Dark Slate Grey (JS Puns shirt only)</option>
<option value="gold">Gold (JS Puns shirt only)</option>`);
}else if( // else heart js them is selected , the three options from html will display for that theme in color
$(this).val() ==="heart js"){
$('#colors-js-puns').show();
$('#color').html (`<option value="tomato">Tomato (I ♥ JS shirt only)</option>
<option value="steelblue">Steel Blue (I ♥ JS shirt only)</option>
<option value="dimgrey">Dim Grey (I ♥ JS shirt only)</option> `);
}else{
$('#colors-js-puns').hide(); //anything else will hide the color section completely
}
});
//activity section
let $totalActivityCost= 0; //set the intial total cost amount to 0
let actLabel = $('<label>Total Cost: $0 </label>'); // created label for totalcost and set to a variable
$('.activities').append(actLabel); //append label message to activity section of html
actLabel.hide(); // hide act label (message)
$('.activities').on('click', statCheck) //statchek defined as function statcheck which includes all my checkboxes value
let check1= $("input[name='all']")
let check2= $("input[name='js-frameworks']")
let check3= $("input[name='js-libs']")
let check4= $("input[name='express']")
let check5= $("input[name='node']")
let check6= $("input[name='build-tools']")
let check7= $("input[name='npm']")
function statCheck(){ //StatCheck checks if a box if clicked/unclicked what will occur
$totalActivityCost = 0
if (check1.is(':checked')){ // If check 1 (all) is checked
$totalActivityCost += 200; //Will add or equal to 200
actLabel.show(); //ActLabel (label for Total Cost) will be displayed
} else {
actLabel.hide(); //Act label will hide if nothing is clicked
}
if (check2.is(':checked')){ //if check 2 is checked , check 4 will be disabled
$totalActivityCost += 100 ; // will add or equal 100
check4.prop('disabled', true);
actLabel.show(); //total cost will display
} else {
check4.prop('disabled',false)
}
if (check3.is(':checked')){ //if check 3 is checked , check 5 will be disabled
$totalActivityCost += 100 ; // will add or equal 100 when clicked
check5.prop('disabled', true);
actLabel.show();
} else {
check5.prop('disabled',false)
}
if (check4.is(':checked')){ //if check 4 is checked check 2 will be disabled
$totalActivityCost += 100 ; // will add or equal 100
check2.prop('disabled', true);
actLabel.show();
} else {
check2.prop('disabled',false)
}
if (check5.is(':checked')){ // if check 5 is checked check 3 will be disabled
$totalActivityCost += 100 ; // will add or equal 100
actLabel.show();
check3.prop('disabled', true);
} else {
check3.prop('disabled',false)
}
if (check6.is(':checked')){ //if 6 is checked
$totalActivityCost += 100; // will add or equal 100
actLabel.show(); // display total cost
}
if (check7.is(':checked')){ // if check 7 is clicked
$totalActivityCost += 100; // add or equal 100
actLabel.show();
}
$('.activities label').last().text('Total Cost : $'+$totalActivityCost); //Total Cost string is adding the value of what is clicked to this bottom text in activites
}
// payment section
$('#payment').on('change',function() { //When payment is changed to value
if ($(this).val()=== 'credit card') { // on credit card value
$('.credit-card').show(); // credit card input will display and hide paypal & bitcoin paragraph text
$(paypalP).hide();
$(bitcoinP).hide();
}else if (
$(this).val()=== 'paypal') { // if paypal value is clicked
$('#credit-card').hide(); // credit card input field will hide
$(paypalP).show(); // paypal text will display that is defined from my global
$(bitcoinP).hide(); // bitcoin text will hide
}else if (
$(this).val()=== 'bitcoin') { // if bitcoin text is clicked
$('#credit-card').hide(); //credit card input field will hide
$(paypalP).hide(); //paypal text will hide
$(bitcoinP).show(); //bitcoin text will show
}else {
$('#credit-card').hide(); //if anything else is clicked Everything else will hide
$(paypalP).hide();
$(bitcoinP).hide();
}
});
// Form Validation
function check_name(){ // Created the check name function
let pattern = /^[a-zA-Z]/; // will check regex
let name = $("#name").val();
let errorLabel = $("#name").siblings().eq(1); // target the name label field
if (!pattern.test(name)) { // if pattern text does not match name
errorLabel.text("Name must contain Characters!!").css("color","red"); //error message will display in original name field and set color to error
return true;
}
else {
errorLabel.text("Name:").css("color","black"); //if it is false (text is correct) name will go back to original Name:
return false;
}
}
$("#name").focusout(function () {
check_name();
});
function check_mail() { //check mail will check the text input in email field
let pattern = /^[^@]+@[^@.]+\.[a-z]+$/; //Regex pattern
let email = $('#mail').val();
let errorEmailLabel = $("#mail").siblings().eq(3) //will target the email name label field in html
if (!pattern.test(email)){ // will test pattern if it doesnt match pattern
errorEmailLabel.text("Email must contain an @ and a .").css("color","red");
return true;
}
else{
errorEmailLabel.text("Email:").css("color","black"); //will set text to original Email: if text is correct
return false;
}
}
$("#mail").focusout(function(){
check_mail(); //calls function check_mail
});
const check_activities = () => { //check_activities function
if ($('.activities input:checked').length > 0){ //if the length of input's in activities is greater than 0
$(".activities legend").text("Register for Activities").css("color","black"); //text will remain the same or if it is unclicked
return false;
}else {
$(".activities legend").text("Please select at least one Activity").css("color", "red"); //if no activities are clicked error message will display
return true;
}
}
$(".activities").on('change', function(){
check_activities(); //calls function check_activities
});
function check_credit(){ //Check Credit will check the input for regex
let pattern = /^\d{13,16}$/
let credit = $("#cc-num").val();
let errorCreditLabel = $("#cc-num").siblings().eq(0) //Will target the cc-num label
if (!pattern.test(credit)){ // if pattern does not match regex in pattern
errorCreditLabel.text("Card # must contain 13 - 16 numbers").css("color","red") //error message will display in original field of Card number and turn message red
return true;
} else {
errorCreditLabel.text("Card Number:").css("color","black"); //error message will return to original when it is false (correct text)
return false;
}
}; $("#cc-num").focusout(function(){
check_credit();
});
function check_zip(){ //Check Zip function to check input to match with regex format
let pattern = /^\d{5}$/;
let zip = $("#zip").val();
let errorZipLabel = $("#zip").siblings().eq(0) // targets original Zip name id in html
if (!pattern.test(zip)){ // If Regex pattern is not matching
errorZipLabel.text("Zip must have 5 #'s").css("color","red"); //Error message will be displayed in Original Field of Zip:
return true;
}else {
errorZipLabel.text("Zip Code:").css("color","black"); //Text returns back to original when pattern is correct
return false;
}
}
$("#zip").focusout(function(){
check_zip();
});
function check_cvv(){ //Function to check Cvv and text input written inside
let pattern = /^\d{3}$/;
let cvv = $("#cvv").val();
let errorCvvLabel = $("#cvv").siblings().eq(0); //errorCvvLabel refers to original CVV name input id in html
if (!pattern.test(cvv)){
errorCvvLabel.text("CVV must be 3 #'s").css("color","red"); //Text changes of Cvv name into a error message displayed in red
return true;
}else {
errorCvvLabel.text("CVV:").css("color","black"); //Text changes back to original CVV
return false;
}
}
$("#cvv").focusout(function(){
check_cvv();
});
$('form').submit(function(e){ //submit eventlistener for form
if (check_name() === true || check_mail() === true // if all check functions are true (not correct to regex)
&& check_activities() === true || check_credit() //
=== true || check_zip() === true || check_cvv() === true){
alert ("Please fill form correctly") ; //alert box will display to tell user to fill out the form and the red fields correctly
e.preventDefault(); // preventDefault prevents the form from submitting
return false;
}
else { //else if form is filled correctly to alert Registration Successful
alert("Registration Successful!")
return true;
}
})
|
import React from 'react'
import { shallow } from 'enzyme'
import Movie from './Movie'
describe('Movie Component', () => {
test('renders correctly', () => {
const component = shallow(<Movie
route={{ params: { id: '12345' } }}
navigation={{ navigate: () => {}, goBack: () => {}}}
/>)
expect(component).toMatchSnapshot()
})
})
|
function attachEvents() {
if (localStorage.getItem('token') && localStorage.getItem('token') != undefined) {
logOutButton();
document.getElementById('guest')
.style.display = 'none';
let logOutButtonElement = document.getElementById('log-out');
logOutButtonElement.addEventListener('click', (e) => {
e.preventDefault();
document.getElementById('guest')
.style.display = 'inline';
logOutButtonElement.remove();
localStorage.clear();
})
}
let loadButtonElement = document.querySelector('aside .load');
loadButtonElement.addEventListener('click', loadCatches);
let addButtonElement = document.querySelector('aside .add');
if (localStorage.getItem('token') && localStorage.getItem('token') != undefined) {
addButtonElement.removeAttribute('disabled');
}
addButtonElement.addEventListener('click', createCatch);
console.log(addButtonElement);
async function loadCatches() {
let catchesRequest = await fetch('http://localhost:3030/data/catches')
let catchesList = await catchesRequest.json();
let catchesDivElement = document.getElementById('catches');
Array.from(catchesDivElement.children)
.forEach(c => c.remove());
catchesList.forEach(c => {
catchesDivElement.appendChild(renderCatchHTML(c));
});
}
function renderCatchHTML(c) {
let catchDiv = document.createElement('div');
catchDiv.classList.add('catch');
catchDiv.id = c._id;
catchDiv.setAttribute('ownerId', c._ownerId);
let anglerLabel = document.createElement('label');
anglerLabel.textContent = 'Angler';
let anglerInput = document.createElement('input');
anglerInput.type = 'text';
anglerInput.classList.add('angler');
anglerInput.value = c.angler;
let hr1 = document.createElement('hr');
let weightLabel = document.createElement('label');
weightLabel.textContent = 'Weight';
let weightInput = document.createElement('input');
weightInput.type = 'number';
weightInput.classList.add('weight');
weightInput.value = c.weight;
let hr2 = document.createElement('hr');
let speciesLabel = document.createElement('label');
speciesLabel.textContent = 'Species';
let speciesInput = document.createElement('input');
speciesInput.type = 'text';
speciesInput.classList.add('species');
speciesInput.value = c.species;
let hr3 = document.createElement('hr');
let locationLabel = document.createElement('label');
locationLabel.textContent = 'Location';
let locationInput = document.createElement('input');
locationInput.type = 'text';
locationInput.classList.add('location');
locationInput.value = c.location;
let hr4 = document.createElement('hr');
let baitLabel = document.createElement('label');
baitLabel.textContent = 'Bait';
let baitInput = document.createElement('input');
baitInput.type = 'text';
baitInput.classList.add('bait');
baitInput.value = c.bait;
let hr5 = document.createElement('hr');
let captureTimeLabel = document.createElement('label');
captureTimeLabel.textContent = 'Capture Time';
let captureTimeInput = document.createElement('input');
captureTimeInput.type = 'number';
captureTimeInput.classList.add('captureTime');
captureTimeInput.value = c.captureTime;
let hr6 = document.createElement('hr');
let updateButton = document.createElement('button');
updateButton.classList.add('update');
updateButton.textContent = 'Update';
updateButton.disabled = c._ownerId === localStorage.getItem('userId') ? false : true;
updateButton.addEventListener('click', updateCatch);
let deleteButton = document.createElement('button');
deleteButton.setAttribute('disabled', 'true');
deleteButton.classList.add('delete');
deleteButton.textContent = 'Delete';
deleteButton.disabled = c._ownerId === localStorage.getItem('userId') ? false : true;
deleteButton.addEventListener('click', deleteCatch);
catchDiv.appendChild(anglerLabel);
catchDiv.appendChild(anglerInput);
catchDiv.appendChild(hr1);
catchDiv.appendChild(weightLabel);
catchDiv.appendChild(weightInput);
catchDiv.appendChild(hr2);
catchDiv.appendChild(speciesLabel);
catchDiv.appendChild(speciesInput);
catchDiv.appendChild(hr3);
catchDiv.appendChild(locationLabel);
catchDiv.appendChild(locationInput);
catchDiv.appendChild(hr4);
catchDiv.appendChild(baitLabel);
catchDiv.appendChild(baitInput);
catchDiv.appendChild(hr5);
catchDiv.appendChild(captureTimeLabel);
catchDiv.appendChild(captureTimeInput);
catchDiv.appendChild(hr6);
catchDiv.appendChild(updateButton);
catchDiv.appendChild(deleteButton);
return catchDiv;
}
async function createCatch() {
let angler = document.querySelector('#addForm .angler')
.value;
let weight = Number(document.querySelector('#addForm .weight')
.value);
let species = document.querySelector('#addForm .species')
.value;
let location = document.querySelector('#addForm .location')
.value;
let bait = document.querySelector('#addForm .bait')
.value;
let captureTime = document.querySelector('#addForm .captureTime')
.value;
Array.from(document.querySelectorAll('aside #addForm input'))
.forEach(i => i.value = '');
let newCatch = {
angler,
weight,
species,
location,
bait,
captureTime
}
let createCatchRequest = await fetch('http://localhost:3030/data/catches',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Authorization': localStorage.getItem('token')
},
body: JSON.stringify(newCatch)
});
let createCatchResponse = await createCatchRequest.json();
let catchesDivElement = document.getElementById('catches');
catchesDivElement.appendChild(renderCatchHTML(createCatchResponse));
}
async function updateCatch(e) {
let currentCatch = e.target
.parentElement;
let angler = currentCatch.querySelector('.angler')
.value;
let weight = Number(currentCatch.querySelector('.weight').value);
let species = currentCatch.querySelector('.species')
.value;
let location = currentCatch.querySelector('.location')
.value;
let bait = currentCatch.querySelector('.bait')
.value;
let captureTime = Number(currentCatch.querySelector('.captureTime').value);
let updatedCatch = {
angler,
weight,
species,
location,
bait,
captureTime
}
await fetch(`http://localhost:3030/data/catches/${currentCatch.id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'X-Authorization': localStorage.getItem('token')
},
body: JSON.stringify(updatedCatch)
})
}
async function deleteCatch(e) {
let currentCatch = e.target
.parentElement;
await fetch(`http://localhost:3030/data/catches/${currentCatch.id}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'X-Authorization': localStorage.getItem('token')
}
});
document.getElementById('catches')
.removeChild(currentCatch);
}
function logOutButton() {
let header = document.querySelector('header nav');
let button = document.createElement('div');
button.id = 'log-out';
let anchor = document.createElement('a');
anchor.href = './index.html';
anchor.textContent = 'Logout';
button.appendChild(anchor);
header.appendChild(button);
}
}
attachEvents();
|
const express = require("express");
const router = express.Router();
const path = require("path");
const fs = require("fs");
const data = require("../data/seed.json");
let productData = data;
console.log(productData.products.length);
let nextID = productData.products[productData.products.length-1].id + 1;
//root route
router.get("/", function(req, res){
const landingPagePath = path.join(__dirname, "..", "views" , "landing.ejs");
res.render(landingPagePath);
});
router.get("/products" , function(req, res){
if(req.query.format==="json"){
res.json(productData);
}
const productsPagePath = path.join(__dirname, "..", "views" , "products.ejs");
res.render(productsPagePath, {products:productData.products});
});
router.get("/products/:id" , function(req, res){
const id = req.params.id;
const product = productData.products.find(p => p.id === parseInt(id));
res.json(product);
});
router.post("/products" , function(req, res){
productData.products.push({...req.body, id:nextID})
nextID++;
res.json(productData.products);
});
module.exports = router;
|
var computerGuess = Math.floor(Math.random() * 11);
var x = document.getElementById("userGuess").value;
var answers = document.getElementById("userAttempts")
function gameFunction() {
var x = document.getElementById("userGuess").value;
if (x == computerGuess) {
console.log("You got it.");
document.getElementById("answerText").innerHTML = "You got it! The number was " + computerGuess;
}
else {
console.log("Keep trying - you are almost there");
answers.textContent += x + ", ";
if (x < computerGuess) {
document.getElementById("answerText").innerHTML = "Keep trying! Guess higher :)";
}
else {
document.getElementById("answerText").innerHTML = "Keep trying! Guess lower :P";
}
}
}
|
import React, {Component} from "react";
import "./App.css";
import FriendsList from "./components/FriendsList";
class App extends Component {
render() {
return (
<div className="App">
<div className="header-logo">
<img
className="friends-logo"
src="https://upload.wikimedia.org/wikipedia/commons/b/bc/Friends_logo.svg"
alt="friends logo"
/>
</div>
<FriendsList />
<footer>
<a
href="https://github.com/gsamaniego41/HTTP-AJAX"
target="_blank"
title="GitHub Repo"
>
A Lambda School project by Gabe <i className="fab fa-github" />
</a>
</footer>
</div>
);
}
}
export default App;
|
var ApiServer = require('apiserver')
var apiServer = new ApiServer({ port: 8080 })
// middleware
apiServer.use(/^\/admin\//, ApiServer.httpAuth({
realm: 'ApiServer Example',
encode: true,
credentials: ['admin:apiserver']
}))
apiServer.use(ApiServer.payloadParser())
// modules
apiServer.addModule('1', 'fooModule', {
// only functions exposed
options: {
opt1: 'opt1',
opt2: 'opt2',
opt3: 'opt3'
},
foo: {
get: function (request, response) {
response.serveJSON({
id: request.querystring.id,
verbose: request.querystring.verbose,
method: 'GET',
options: this.options
})
},
post: function (request, response) {
request.resume()
request.once('end', function () {
response.serveJSON({
id: request.querystring.id,
verbose: request.querystring.verbose,
method: 'POST',
payload: request.body // thanks to payloadParser
})
})
}
},
bar: function (request, response) {
response.serveJSON({ foo: 'bar', pow: this._pow(5), method: '*/' + request.method })
},
// never exposed due to the initial underscore
_pow: function (n) {
return n * n
}
})
// custom routing
apiServer.router.addRoutes([
['/foo', '1/fooModule#foo'],
['/foo/:id/:verbose', '1/fooModule#foo'],
['/foo_verbose/:id', '1/fooModule#foo', { 'verbose': true }],
['/bar', '1/fooModule#bar', {}, true] // will keep default routing too
])
// events
apiServer.on('requestStart', function (pathname, time) {
console.info(' ☉ :: start :: %s', pathname)
}).on('requestEnd', function (pathname, time) {
console.info(' ☺ :: end :: %s in %dms', pathname, time)
}).on('error', function (pathname, err) {
console.info(' ☹ :: error :: %s (%s)', pathname, err.message)
}).on('timeout', function (pathname) {
console.info(' ☂ :: timedout :: %s', pathname)
})
apiServer.listen()
|
var express = require('express')
var router = express.Router()
const path = require('path')
router.get('*', function (req, res, next) {
try {
res.sendFile(path.resolve(__dirname, '../public/index.html'))
} catch (e) {
console.log('error sending html file', e)
res.send(e)
}
})
module.exports = router
|
import React from 'react';
import {SafeAreaView} from 'react-navigation';
const Section = ({children, ...props}) => (
<SafeAreaView {...props}>{children}</SafeAreaView>
);
export default Section;
|
import React from 'react';
import {Layout} from "./index";
import {DangerAlert} from "../Alerts";
import {lifecycle} from 'recompose';
import {redirectTo} from "../../functions/redirect";
export const NotFound = lifecycle({
componentDidMount() {
setTimeout(() => redirectTo(this.props.history, '/'), 5000)
}
})(({...rest}) => (
<Layout defaultContainer {...rest}>
<div className={'pt-4 pb-4'}>
<DangerAlert content={`Cette page n'existe pas, vous allez être redirigé vers l'accueil dans 5 secondes`}/>
</div>
</Layout>
));
|
const mongoose = require('mongoose');
// mongoose.set('debug', true);
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.set('useUnifiedTopology', true);
mongoose.connect('mongodb://localhost/elo');
mongoose.Promise = Promise;
module.exports.Player = require('./player');
|
class Comment {
constructor(obj){
this.by = obj.by;
this.id = obj.id;
this.kids = obj.kids;
this.parent = obj.parent;
this.text = obj.text;
this.time = obj.time;
this.type = obj.type;
}
}
export default Comment;
|
var gpstracker = require("gpstracker");
var server = gpstracker.create().listen(8000, function(){
console.log('listening your gps trackers on port', 8000);
});
server.trackers.on("connected", function(tracker){
console.log("tracker connected with imei:", tracker.imei);
tracker.on("help me", function(){
console.log(tracker.imei + " pressed the help button!!".red);
});
tracker.on("position", function(position){
console.log("tracker {" + tracker.imei + "}: lat",
position.lat, "lng", position.lng);
});
tracker.trackEvery(10).seconds();
});
|
import {Input, InputAdornment} from "@material-ui/core";
import {useState} from "react";
import Button from "~/components/atoms/button/Button";
import IconButton from "~/components/atoms/iconButton/IconButton";
import TextField from "~/components/atoms/textfield/Textfield";
import useForm from "~/util/form";
import Configurable from "../Configurable";
import {StyledCurrencyConverter} from "./CurrencyConverter.style";
import CurrencyConverterConfigurator from "./CurrencyConverterConfigurator";
const CurrencyConverter = function (props) {
if (props.liveMode == false) {
return (
<>
<Configurable component={props.component} preview={false} title="Koers berekening" configurator={<CurrencyConverterConfigurator />}>
<Component {...props} />
</Configurable>
</>
);
} else {
return <Component {...props} />;
}
};
const Component = function ({component, ...props}) {
const round = (input) => {
if (input < 1000) return String(input.toFixed(2)).replace(".", ",");
return (
Math.round(input)
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ".") + ",-"
);
};
const data = component.data;
const [reverse, setReverse] = useState(false);
const [form, setForm] = useState({
base: "EUR",
baseValue: 25,
baseSymbol: "€",
currency: props.liveMode == false ? "THB" : data.currencyIso,
currencySymbol: props.liveMode == false ? "฿" : data.currencySymbol,
currencyValue: props.liveMode == false ? "461" : round(25 * data.conversionRate),
rate: props.liveMode == false ? 1 : data.conversionRate,
});
const handleBaseChange = (e) => {
try {
var value = String(e.target.value);
if (isNaN(value)) value = 0;
var converted = value * form.rate;
if (isNaN(converted)) converted = 0;
setForm({...form, currencyValue: round(converted), baseValue: value});
} catch (z) {}
};
const handleCurrencyChange = (e) => {
try {
var value = parseFloat(e.target.value);
if (isNaN(value)) value = 0;
var converted = value / form.rate;
if (isNaN(converted)) converted = 0;
setForm({...form, currencyValue: value, baseValue: round(converted)});
} catch (z) {}
};
const clearBase = () => {
setForm({...form, baseValue: ""});
};
const clearCurrency = () => {
setForm({...form, currencyValue: ""});
};
return (
<StyledCurrencyConverter reverse={reverse}>
<TextField
disabled={props.liveMode == false}
label={form.base}
name="base"
onFocus={clearBase}
onChange={handleBaseChange}
value={form.baseValue}
startAdornment={form.baseSymbol}
/>
<IconButton disabled={props.liveMode == false} onClick={() => setReverse(!reverse)} className="button" icon={["fal", "exchange"]} square />
<TextField
disabled={props.liveMode == false}
label={form.currency}
name="currency"
onFocus={clearCurrency}
onChange={handleCurrencyChange}
value={form.currencyValue}
startAdornment={form.currencySymbol}
/>
</StyledCurrencyConverter>
);
};
export default CurrencyConverter;
|
export {default as PrimaryButton} from './primary';
export {default as SecondaryButton} from './secondary';
|
describe("variations", function() {
describe("by name", function() {
var docSet = jasmine.getDocSetFromFile('test/fixtures/variations.js'),
fadein1 = docSet.getByLongname('anim.fadein(1)')[0],
fadein2 = docSet.getByLongname('anim.fadein(2)')[0];
it('When a symbol has a name with a variation, the doclet has a variation property.', function() {
expect(fadein1.variation).toEqual('1');
expect(fadein2.variation).toEqual('2');
});
it('When a symbol has a name with a variation in the name, the doclet name has no variation in it.', function() {
expect(fadein1.name).toEqual('fadein');
expect(fadein2.name).toEqual('fadein');
});
it('When a symbol has a name with a variation in the name, the doclet longname has the variation in it.', function() {
expect(fadein1.longname).toEqual('anim.fadein(1)');
expect(fadein2.longname).toEqual('anim.fadein(2)');
});
});
describe("by tag", function() {
var docSet = jasmine.getDocSetFromFile('test/fixtures/variations3.js'),
someObject = docSet.getByLongname('someObject')[0],
someObject2 = docSet.getByLongname('someObject(2)')[0],
someObject2method = docSet.getByLongname('someObject(2).someMethod')[0];
it('When a symbol has a variation tag, the longname includes that variation.', function() {
expect(someObject2.longname).toEqual('someObject(2)');
});
it('When a symbol is a member of a variation, the longname includes the variation.', function() {
expect(someObject2method.longname).toEqual('someObject(2).someMethod');
});
});
});
|
import * as types from '../types';
const initialState = {
isLoading: false,
error: null,
successMessage: null,
data: null,
};
const DashboardReducer = (state = initialState, action) => {
switch (action.type) {
case types.DASHBOARD_REQUEST:
return {
...state,
isLoading: true,
error: null,
data: null,
};
case types.DASHBOARD_SUCCESS:
return {
...state,
isLoading: false,
error: null,
data: action.payload.data,
};
case types.DASHBOARD_ERROR:
return {
...state,
error: action.payload.errors,
data: null,
};
default:
return state;
}
};
export default DashboardReducer;
|
cc.Class({
extends: cc.Component,
properties: {
frameWait:{
default:null,
type:cc.SpriteFrame
},
frameAgree:{
default:null,
type:cc.SpriteFrame
},
frameDisagree:{
default:null,
type:cc.SpriteFrame
},
isInit:false,
},
onLoad: function () {
},
onInit: function(){
this.playerNameList = {};
this.playerTypeList = {};
this.playerNodeList = {};
for(var i=0;i<6;i++)
{
this.playerNodeList[i] = this.node.getChildByName("player" + i);
this.playerNameList[i] = this.node.getChildByName("player" + i).getChildByName("name").getComponent("cc.Label");
this.playerTypeList[i] = this.node.getChildByName("player" + i).getChildByName("type").getComponent("cc.Sprite");
}
this.timeNum = this.node.getChildByName("timeNum").getComponent("cc.Label");
this.warning = this.node.getChildByName("warning");
this.btnAgree = this.node.getChildByName("btnAgree");
this.btnDisagree = this.node.getChildByName("btnDisagree");
this.timeCallBack = -1;
this.isInit = true;
},
runTime:function(time){
var self = this;
var curTime = time;
self.timeNum.string = curTime;
self.timeCallBack = function(){
curTime--;
self.timeNum.string = curTime;
if(curTime <= 0)
{
self.unschedule(self.timeCallBack);
self.warning.warning.active = true;
}
};
self.schedule(self.timeCallBack,1);
},
hideTime:function(){
if(this.timeCallBack != -1)
this.unschedule(this.timeCallBack);
this.timeNum.string = "";
},
showFinishLayer:function(){
this.node.active = true;
},
hideFinishLayer:function(){
this.node.active = false;
for(var i=0;i<6;i++)
{
this.playerNameList[i].string = "";
this.playerTypeList[i].spriteFrame = this.frameWait;
this.playerNodeList[i].active = false;
}
this.timeNum.string = "0";
this.btnAgree.active = true;
this.btnDisagree.active = true;
this.warning.active = false;
this.unscheduleAllCallbacks();
},
showPlayer:function(playerCount){
for(var i=0;i<playerCount;i++)
this.playerNodeList[i].active = true;
},
setPlayerName:function(index,name){
this.playerNameList[index].string = name;
},
setPlayerType:function(index,type){
console.log("setPlayerType !!!!==="+index);
console.log("type !!!!==="+type);
if(!this.playerTypeList[index])
return;
if(type == 0)
{
this.playerTypeList[index].spriteFrame = this.frameWait;
}else if(type == 1){
this.playerTypeList[index].spriteFrame = this.frameAgree;
}else if(type == 2){
this.playerTypeList[index].spriteFrame = this.frameDisagree;
}
},
btnClickAgree:function(){
pomelo.request("connector.entryHandler.sendFrame", {"code" : "agreeFinish"},null, function(data) {
console.log("flag is : "+data.flag)
}
);
},
btnClickDisagree:function(){
pomelo.request("connector.entryHandler.sendFrame", {"code" : "refuseFinish"},null, function(data) {
console.log("flag is : "+data.flag)
}
);
},
hideAllBtn:function(){
this.btnAgree.active = false;
this.btnDisagree.active = false;
},
showLayer:function(){
if(this.isInit == false)
this.onInit();
this.node.active = true;
},
hideLayer:function(){
this.node.active = false;
},
});
|
// Copyright (c) 2016-2018, BuckyCloud, Inc. and other BDT contributors.
// The BDT project is supported by the GeekChain Foundation.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the BDT nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"use strict";
const EventEmitter = require('events');
const BDTStack = require('./stack');
const BDTAcceptor = require('./acceptor');
const BDTConnection = require('./connection');
const packageModule = require('./package');
class PeerFinder extends EventEmitter {
constructor() {
super();
this.EVENT = PeerFinder.EVENT;
}
findSN(peerid, fromCache, onStep) {
return Promise.reject('Function PeerFinder.findSN should be overrided.');
}
findPeer(peerid) {
return Promise.reject('Function PeerFinder.findSN should be overrided.');
}
getLocalEPList() {
return [];
}
}
PeerFinder.EVENT = {
SNChanged: 'SNChanged'
}
class SimpleSNFinder extends PeerFinder {
constructor(snPeers) {
super();
this.m_snPeers = snPeers;
}
findSN(peerid, fromCache, onStep) {
if (this.m_snPeers && this.m_snPeers.length) {
return Promise.resolve([packageModule.BDT_ERROR.success, this.m_snPeers]);
} else {
return Promise.Promise.resolve([packageModule.BDT_ERROR.invalidState]);
}
}
}
function newStack(peerid, eplist, mixSocket, peerFinder, remoteFilter, options) {
let stack = new BDTStack(peerid, eplist, mixSocket, peerFinder, remoteFilter, options);
stack.newAcceptor = (acceptorOptions)=>{
return new BDTAcceptor(stack, acceptorOptions);
};
stack.newConnection = (connectionOptions)=>{
return new BDTConnection(stack, connectionOptions);
};
stack.once(BDTStack.EVENT.close, () => {
stack.newAcceptor = null;
stack.newConnection = null;
});
return stack;
}
module.exports = {
newStack: newStack,
Stack: BDTStack,
Connection: BDTConnection,
Acceptor: BDTAcceptor,
ERROR: packageModule.BDT_ERROR,
Package: packageModule.BDTPackage,
PeerFinder,
};
|
import React from 'react';
import './footer.css';
import { Form, Button, Row } from 'react-bootstrap';
import { Link } from 'react-router-dom';
export default function Footer() {
return (
<footer className='main-footer'>
<Row className='ft-main col-11 mx-auto'>
<div className='ft-main-item'>
<h3 className='ft-title'>About</h3>
<ul>
<li>
<Link to='#'>Services</Link>
</li>
<li>
<Link to='#'>Pricing</Link>
</li>
<li>
<Link to='#'>Customers</Link>
</li>
<li>
<Link to='#'>Careers</Link>
</li>
</ul>
</div>
<div className='ft-main-item'>
<h3 className='ft-title'>Resources</h3>
<ul>
<li>
<Link to='#'>Docs</Link>
</li>
<li>
<Link to='#'>Blog</Link>
</li>
<li>
<Link to='#'>Shops</Link>
</li>
<li>
<Link to='#'>Webinars</Link>
</li>
</ul>
</div>
<div className='ft-main-item'>
<h3 className='ft-title'>Contact</h3>
<ul>
<li>
<Link to='#'>Help</Link>
</li>
<li>
<Link to='#'>Sales</Link>
</li>
<li>
<Link to='#'>Advertise</Link>
</li>
</ul>
</div>
<div className='ft-main-item'>
<h3 className='ft-title'>Stay Updated</h3>
<p>Subscribe to our newsletter to get our latest news</p>
<Form.Group className='d-flex flex-column' controlId='formBasicEmail'>
<Form.Control type='email' placeholder='Enter email' name='email' />
<Button className='my-2' variant='info'>
{' '}
Subscribe{' '}
</Button>
</Form.Group>
</div>
</Row>
<hr className='bg-light' />
{/* Footer social */}
<section className='ft-social '>
<ul className='d-flex justify-content-center align-items-center'>
<li>
<Link to='#'>
<i className='fa fa-facebook px-2'></i>
</Link>
</li>
<li>
<Link to='#'>
<i className='fa fa-twitter px-2'></i>
</Link>
</li>
<li>
<Link to='#'>
<i className='fa fa-instagram px-2'></i>
</Link>
</li>
<li>
<Link to='#'>
<i className='fa fa-github px-2'></i>
</Link>
</li>
<li>
<Link to='#'>
<i className='fa fa-linkedin px-2'></i>
</Link>
</li>
</ul>
</section>
{/* Footer legal */}
<section className='ft-legal'>
<ul className='col-11 mx-auto d-flex justify-content-between align-items-center'>
<li>
<Link to='#'>Terms & Conditions</Link>
</li>
<li>
<Link to='#'>
Privacy Policy
</Link>
</li>
<li>© 2021 Copyright ASA</li>
</ul>
</section>
</footer>
);
}
|
/**
* LINKURIOUS CONFIDENTIAL
* Copyright Linkurious SAS 2012 - 2018
*
* - Created on 2015-09-11.
*/
'use strict';
const _ = require('lodash');
const JSDiff = {
/**
* Compute the deep difference between values
*
* @param {*} reference value
* @param {*} compared value
* @param {object} [ignoredPaths]
* @param {string[]} [stack] internal use in recursion
* @returns {string[]} human readable differences
*/
compareValues: function(reference, compared, ignoredPaths, stack) {
if (!ignoredPaths) { ignoredPaths = {}; }
if (!stack) { stack = ['root']; }
let diff = [], i;
const stackPath = stack.join('.');
// ignored path ?
if (ignoredPaths[stack.join('.')]) {
return diff;
}
// strict equality
if (reference === compared) {
return diff;
}
// null vs other
if (compared !== null && reference === null) {
diff.push('"' + stack.join('.') + '": different values (not null, expected null).');
return diff;
}
const referenceType = Array.isArray(reference) ? 'array' : typeof(reference);
const comparedType = Array.isArray(compared) ? 'array' : typeof(compared);
// different type
if (comparedType !== referenceType) {
diff.push(
'"' + stack.join('.') + '": ' +
'different types ("' + comparedType + '", expected "' + referenceType + '").'
);
return diff;
}
// arrays
if (comparedType === 'array') {
if (compared.length !== reference.length) {
diff.push(
'"' + stack.join('.') + '": ' +
'different array lengths (' + compared.length + ', expected ' + reference.length + ').'
);
return diff;
}
for (i = 0; i < compared.length; ++i) {
diff = diff.concat(JSDiff.compareValues(
reference[i],
compared[i],
ignoredPaths,
stack.concat([i + ''])
));
}
return diff;
}
// objects
if (comparedType === 'object') {
const referenceKeys = Object.keys(reference);
const comparedKeys = Object.keys(compared);
// missing keys (ignore keys in ignoredPath)
const deletedKeys = _.filter(_.difference(referenceKeys, comparedKeys), deletedKey => {
// filter ignored paths from deleted keys
return !ignoredPaths[stackPath + '.' + deletedKey];
});
if (deletedKeys.length > 0) {
diff.push(
'"' + stack.join('.') + '": ' +
'missing object properties ("' + deletedKeys.join('", "') + '").'
);
return diff;
}
// some keys added
const addedKeys = _.filter(_.difference(comparedKeys, referenceKeys), addedKey => {
// filter ignored paths from added keys
return !ignoredPaths[stackPath + '.' + addedKey];
});
if (addedKeys.length > 0) {
diff.push(
'"' + stack.join('.') + '": ' +
'added object properties ("' + addedKeys.join('", "') + '").'
);
return diff;
}
// same key values
let key;
for (i = 0; i < referenceKeys.length; ++i) {
key = referenceKeys[i];
diff = diff.concat(JSDiff.compareValues(
reference[key],
compared[key],
ignoredPaths,
stack.concat([key])
));
}
return diff;
}
// neither object nor array
if (reference !== compared) {
diff.push('"' + stack.join('.') + '": values do not match.');
return diff;
}
return diff;
}
};
module.exports = JSDiff;
|
(function(){
function domWalker(el,dir,expr,supnod){
var descend = dir ? 'firstChild' : 'lastChild', skip, txt, i = 0;
dir = dir ? 'nextSibling' : 'previousSibling';
while(el[descend] || el[dir] || el.parentNode) {
if(!skip && el[descend]) {
el = el[descend];
} else if(el[dir]) {
el = el[dir];
skip = 0;
} else {
el = el.parentNode;
skip = 1;
i++;
if(!supnod) {
supnod = el.currentStyle ? el.currentStyle.display :
getComputedStyle(el, null).display;
if(supnod == 'block') break;
else supnod = null;
}
continue;
}
txt = el.nodeValue;
if(i && txt && expr.test(txt)) break;
}
return el || {};
}
function wrapEl(c,q,n) {
var el = c.querySelectorAll(q||'*');
var txt = c.innerText || c.textContent;
var done = n ? ~txt.indexOf('<'+n+'>') : c.querySelector('.hl');
if(!done) for (var i = 0; i < el.length; i++) {
if(q) {
var prt = el[i].parentNode;
var tag = prt.querySelectorAll(q);
var a = el[i].innerHTML.replace(/ /g, String.fromCharCode(160));
if(prt.childNodes.length > 1 && alchar.test(a) && prt.childNodes.length != tag.length){
// omit sequetial tags <i>Proc. 16</i><i>th</i>, omit spaces and comas
a = a.replace(/^([\s,.]+)|^/, '$1'+(el[i-1] === domWalker(el[i],0,alchar).parentNode ? '' : '<'+n+'>'));
a = a.replace(/([\s,]+)$|$/, (el[i+1] === domWalker(el[i],1,alchar).parentNode ? '' : '</'+n+'>')+'$1');
el[i].innerHTML = a;
}
} else {
if(el[i].childNodes.length == 1 && el[i].firstChild.nodeType == 3)
el[i].innerHTML = el[i].innerHTML.replace(dchar, '<span class="hl">$1</span>');
}
}
}
var ctn = document.querySelector('div[contenteditable]');
var dchar = /([^\x09-\x0D\x20-\xFF\u0100-\u017F\u2013-\u2044]+)/g;
var alchar = /[\w\-\xC0-\xFF\u0100-\u017F\u2013()]+/;
var form = document.forms;
for(var i=0; i<form.length; i++) {
form[i].onsubmit = function() {
var ignore = this.ignore && (this.ignore.checked || this.ignore.selectedIndex);
var handle = {
SELECT: 'selectedIndex'
}
if(!ignore) for(var i=0; i<this.length-1; i++) {
var inp = this[i], prohib;
if(!inp[handle[inp.id || inp.nodeName] || 'value']) {
prohib = true;
inp.className = '';
inp.style.background = '#f99';
var redraw = inp.offsetHeight;
inp.className = 'fade-out';
inp.style.background = '';
inp.onfocus = function() {
this.className = '';
}
}
}
if ((!ignore && prohib) || (newabs && !confirm('Sure?'))) return false;
}
}
var newabs = document.forms.newabs;
var abform = document.querySelectorAll('a[href^="#add"]');
for (var i=0; i<abform.length; i++) abform[i].onclick = function() {
var nx = this.nextSibling;
while(nx && nx.nodeType !== 1) nx = nx.nextSibling;
if (nx) nx.style.display = 'block';
this.style.display = 'none';
return false;
}
var tr = document.querySelectorAll('.trlit div[data-ph]');
var cfg = document.querySelectorAll('.trlit input');
for (var i=0; i<cfg.length; i++) cfg[i].onchange = function() {
tr[0].onkeyup();
}
if(tr[1]) tr[0].onkeyup = function() {
tr[1].innerHTML = translit(this.innerHTML,cfg);
}
var panhed = document.querySelectorAll('.panel .h');
for (var i=0; i<panhed.length; i++) {
panhed[i].onclick = function() {
for(var i=0; i<panhed.length; i++) {
var curpan = panhed[i];
var panel = curpan.parentNode;
var cont = panel.querySelector('* ~ div');
var hh = curpan.clientHeight;
var ph = panel.clientHeight;
if(!panel.style.height) {
panel.style.height = ph+'px';
cont.style.display = 'block';
panel.offsetHeight;
}
if(curpan == this) {
panel.style.height = hh+1+cont.offsetHeight+'px';
var hidimg = cont.querySelectorAll('img');
for(var j=0; j<hidimg.length; j++) {
var img = hidimg[j];
var dsrc = img.getAttribute('data-src');
if(dsrc) {
img.src = dsrc;
img.removeAttribute('data-src');
}
}
} else {
panel.style.height = hh+'px';
}
}
}
}
if (newabs) {
if(location.search) {
for(var i=0; i<newabs.length-1; i++) {
newabs[i].onchange = function(){
if(this.name && this.name.indexOf('update'))
this.name = 'update['+this.name+']';
}
}
}
ctn.onkeyup = function() {
autofill();
var prt = window.getSelection().getRangeAt(0).startContainer.parentNode;
if(prt.className == 'hl') {
var bef = prt.innerHTML;
var aft = bef.replace(dchar, '<span class="hl">$1</span>');
if(bef == aft) prt.outerHTML = aft;
}
}
newabs.refs.onpaste = function(e) {
var data = this.value, proc;
var source = {
'PMid' : 'https://www.ncbi.nlm.nih.gov/pubmed/',
'PMCid' : 'https://www.ncbi.nlm.nih.gov/pmc/articles/'
}
if (data && e && e.clipboardData) {
var tmp = document.createElement('div');
tmp.innerHTML = data;
var olddata = tmp.innerText || tmp.textContent;
var newdata = e.clipboardData.getData('text/plain');
olddata = olddata.split(/(?:\r?\n|\r)+/);
newdata = newdata.replace(/(\S)(\r?\n|\r)(\S)/g, '$1 $3');
newdata = newdata.split(/(?:(?:\r?\n|\r) *){2}/);
data = data.split(/(?:\r?\n|\r)+/);
for(var i=0; i<olddata.length; i++) {
for(var j=0; j<newdata.length; j++) {
if(!newdata[j].indexOf(olddata[i])) {
var newref = newdata[j];
for(k in source) newref = newref.replace(k+':', source[k]);
data[i] += encodeURI(newref.substr(olddata[i].length)).replace(/%20/g, " ");
proc = true;
} else if (i == j) console.log(i+' : '+data[i]);
}
}
if(proc) {
this.value = data.join('\n');
this.onchange();
return false;
}
}
}
newabs.section.onchange = function(){
var handle = newabs[0].onchange;
if(handle) handle.call(this);
if(!parseInt(this.value)) {
var prt = this.parentNode;
prt.removeChild(this);
prt.innerHTML += '<input name="section" type="text" placeholder="'+this.value+'">';
prt.lastChild.onchange = handle;
prt.lastChild.focus();
}
}
ctn.onpaste = autofill;
function autofill(){
setTimeout(function(){
wrapEl(ctn,'[style*=italic],em,i','i');
wrapEl(ctn,'[style*=super],sup','sup');
wrapEl(ctn,'[style*=sub],sub','sub');
wrapEl(ctn);
var line = 0;
var data = ctn.innerText || ctn.textContent; // todo: fix firefox
data = data.split(/(?:\r?\n|\r)+/);
//data.unshift(data[3]);
//data.splice(4,1);
for(var i=0; i<data.length; i++) {
var c = data[i].replace(/^\s+|\s+$/g, '');
var x = (c.substring(0,c.indexOf(' '))||c).toLowerCase();
if(!x.indexOf('abstract') || !x.indexOf('keywords') || !x.indexOf('references'))
c = c.substring(x.length+1);
var dummy = document.createElement('div');
dummy.innerHTML = c.replace(/\s+/g, ' ');
if(line != 4) c = dummy.innerHTML;
if(c) {
if(line > 8) {
newabs.refs.value += '\n'+c;
newabs.refs.rows = line-5;
} else if(line > 2) {
if(line == 6 && c.length < 200) {
line--;
newabs[line+3].value += '\n'+c;
newabs.inst.rows = i-4;
} else newabs[line+3].value = c;
} else {
for(var j=0; j<newabs.section.length; j++) {
if(newabs.section[j].innerHTML == c)
newabs.section.value = newabs.section[j].value;
}
if(!!~c.indexOf('doi.org'))
newabs.doi.value = c;
else {
c = c.match(/\d+/g);
if(c && c.length > 4) {
newabs.vol.value = c[1];
newabs.issue.value = c[2];
newabs.page.value = c[3];
newabs.end_page.value = c[4];
}
}}
line++;
}
}
},1)};
}
function translit(cyr,inp) {
var lat = '';
var letter = {
'А':'A','а':'a',
'Б':'B','б':'b',
'В':'V','в':'v',
'Г':'G','г':'g',
'Ґ':'G','ґ':'g',
'Д':'D','д':'d',
'Е':'E','е':'e',
'Э':'E','э':'e',
'Є':'Ye','є':'ye',
'Ё':'Yo','ё':'yo',
'Ж':'Zh','ж':'zh',
'З':'Z','з':'z',
'І':'I','і':'i',
'Ї':'Yi','ї':'yi',
'И':'Y','и':'y',
'Й':'Y','й':'y',
'Ы':'Y','ы':'y',
'К':'K','к':'k',
'Л':'L','л':'l',
'М':'M','м':'m',
'Н':'N','н':'n',
'О':'O','о':'o',
'П':'P','п':'p',
'Р':'R','р':'r',
'С':'S','с':'s',
'Т':'T','т':'t',
'У':'U','у':'u',
'Ф':'F','ф':'f',
'Х':'Kh','х':'kh',
'Ц':'Ts','ц':'ts',
'Ч':'Ch','ч':'ch',
'Ш':'Sh','ш':'sh',
'Щ':'Shch','щ':'shch',
'Ю':'Yu','ю':'yu',
'Я':'Ya','я':'ya',
'Ь':'<!>','ь':'<!>',
'Ъ':'<!>','ъ':'<!>'
};
var alt = { 'И':'I','и':'i' };
var hhh = { 'Г':'H','г':'h' };
var vow = {a:1,o:1,y:1};
var yy = {y:1};
if(inp[0].checked) for (var atr in alt) { letter[atr] = alt[atr]; }
if(inp[1].checked) for (var atr in hhh) { letter[atr] = hhh[atr]; }
for(var i=0; i<cyr.length; i++) {
var ch = cyr.charAt(i);
if(inp[2].checked && vow[letter[cyr.charAt(i-1)]] && ch == 'ї' ||
inp[3].checked && yy[letter[cyr.charAt(i-1)]] && yy[letter[ch]])
ch = 'i';
lat += letter[ch] || ch;
}
return lat;
}
})();
|
import React, {
Component,
} from 'react';
import {
StyleSheet,
View,
Text,
Dimensions,
ScrollView,
} from 'react-native';
import Button from '../button/Button';
import { AppRoutes } from '../../common/config';
const window = Dimensions.get('window');
class SideMenuContent extends Component {
constructor(props) {
super(props);
}
handleNavButtonPress(event, route) {
this.props.navigate(route);
}
renderSideMenuButtons() {
const routes = AppRoutes.getAllRoutes();
const SideMenuButtons = routes.map((route) => {
return (
<View
style={styles.rowContent}
key={route.id}>
<Button
style={[styles.navButton]}
onPress={(e)=>this.handleNavButtonPress(e, {id: route.id})} >
<Text style={styles.navButtonText}>
{route.sidemenu.sideMenuButtonText}
</Text>
</Button>
</View>
);
});
return SideMenuButtons;
}
render() {
return (
<ScrollView
style={[styles.container,{ backgroundColor: this.props.backGndColor }]}
scrollsToTop={false}>
<View style={styles.headerContainer}>
<Text style={styles.headerText}>
Menu Title
</Text>
</View>
<View style={styles.menusContainer}>
{this.renderSideMenuButtons()}
</View>
</ScrollView>
);
}
}
SideMenuContent.propTypes = {
backGndColor: React.PropTypes.string,
};
SideMenuContent.defaultProps = {
backGndColor: '#fff',
};
const styles = StyleSheet.create({
container: {
flex: 1,
width: window.width,
height: window.height,
padding: 5,
},
headerContainer: {
flex: 1,
flexDirection: 'row',
height: 30,
marginTop: 20,
borderBottomWidth: 0.5,
borderBottomColor: '#333333',
},
headerText: {
paddingTop: 5,
paddingBottom: 5,
paddingLeft: 2,
paddingRight: 2
},
menusContainer: {
flex: 1,
height: window.height / 2,
paddingTop: 5,
paddingBottom: 5,
flexDirection: 'column',
},
rowContent: {
height: 50,
flexDirection: 'row',
alignItems: 'center',
}
});
export default SideMenuContent;
|
'use strict';
const cors = require('cors');
function parseValues(originalValues) {
let parsedValues = originalValues;
if (originalValues.includes(',')) {
parsedValues = originalValues.split(',');
}
return parsedValues;
}
module.exports = function corsFactory(config) {
let corsOpts = {};
if (config.enableCORS) {
const origin = parseValues(config.allowedOrigins);
const allowedHeaders = parseValues(config.allowedHeaders);
corsOpts = ({
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
preflightContinue: true,
allowedHeaders,
origin,
});
}
return cors(corsOpts);
};
|
/*
* @Author: wangshengxian
* @Date: 2021-02-01 11:26:01
* @LastEditors: wangshengxian
* @LastEditTime: 2021-02-01 11:40:44
* @Desc: 原生调用js -- 事件管理
*/
import platform from './platform'
import iosBridge from './bridge'
// js事件方法对象
const jsMethodObj = {
// 扫码成功
scanSuccess,
// 支付成功
paySuccess
}
/**
* 原生调用js,js提供扫码成功回调方法给原生调用
* @param {function} callback 回调函数
*/
function scanSuccess(callback) {
if (platform.isIos) {
iosBridge.registerIosBridge('getScanResult', data => {
callback(data)
})
return
}
if (platform.isAndroid) {
// 将vue组件的方法绑定到window上,提供给android调用
window['getScanResult'] = callback.bind(this)
return
}
}
/**
* 原生调用js,js提供支付成功回调方法给原生调用
* @param {function} callback 回调函数
*/
function paySuccess(callback) {
if (platform.isIos) {
iosBridge.registerIosBridge('paymentResult', data => {
callback(data)
})
return
}
if (platform.isAndroid) {
// 将vue组件的方法绑定到window上,提供给android调用
window['paymentResult'] = callback.bind(this)
return
}
}
/**
* 事件监听
* @param {string} fnName 事件名
* @param {function} callback 回调函数
*/
function addEvent(fnName, callback) {
jsMethodObj[fnName] && jsMethodObj[fnName](callback)
}
/**
* js自定义事件对象
*/
export default {
addEvent
}
|
requirejs.config({
paths : {
jquery : "jquery-1.11.1.min",
login : "login",
pub : "public"
}
})
requirejs(["jquery","login","pub"],function($,login,pub){
$(".middle_con").find("i").click(function(){
$(this).addClass("xxk_bt")
.siblings()
.removeClass("xxk_bt")
$(".login_box>div").eq($(this).index()).css("display","block")
.siblings()
.css("display","none")
})
$(".user").delegate(".clear","click",function(){
console.log(1)
console.log($(this).prev())
$(this).prev().val("");
$(this).css("display","none");
})
$("input").focus(function(){
$(".topic").html("");
$(this).next().css("display","block");
})
$("input").blur(function(){
if($(this).val().length==0){
$(this).next().css("display","none");
}
})
$(".clear").click(function(){
console.log(1)
$(this).prev().val("");
})
$(".sub").click(function(){
var lname = $("#user_name").val();
var lpwd = $("#password").val();
//cookie的值
if(document.cookie){
var brr = pub.getCookie2();
for(var key in brr){
console.log(brr[key][0])
var rname = JSON.parse(brr[key][1]).uname;
var rpwd = JSON.parse(brr[key][1]).upwd;
var rphone = JSON.parse(brr[key][1]).uphone;
var rlogined = JSON.parse(brr[key][1]).logined;
if((lname == rname || lname == rphone) && lpwd==rpwd ){
// pub.removeCookie(brr[key]);
console.log(document.cookie)
var json = {
"uname":rname,
"upwd":rpwd,
"uphone":rphone,
"logined":1,
}
pub.setCookie(brr[key][0],JSON.stringify(json));
location.href="index.html";
}else{
$(".topic").html("用户名或密码错误,请重新输入");
}
}
}else{
$(".topic").html("账号不存在");
}
})
})
|
$(document).ready(function () {
var target = document.querySelector('body');
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.addedNodes.length) {
var $el = $(mutation.addedNodes.item(0));
if ($el.hasClass('hc-offcanvas-nav')) {
var $el = $('.header-top .right-buttons-mobile').clone().show().appendTo('.nav-wrapper-0 >.nav-content');
$('.close-burger').show().on('click', function () {
$(this).hide();
Nav.close();
});
}
}
});
});
var config = { attributes: false, childList: true, characterData: false };
observer.observe(target, config);
//observer.disconnect();
var Nav = $('.main-menu').hcOffcanvasNav({
maxWidth: 1024,
position: 'right',
insertClose : false,
labelBack : 'Назад',
});
Nav.on('open', function () {
$('.close-burger').show();
});
//Nav.open();
$('#btn-mobile-search-toggle').click(function () {
$('.endoexpert-header .search-block').toggle();
});
var $pageWrapper = $('.page-wrapper');
var $header = $('.endoexpert-header');
var $bxPanel = $('#bx-panel');
$(document).on('scroll', function () {
var offset = $(document).scrollTop();
if (offset === 0) {
$header.addClass('-top-visible');
} else {
$header.removeClass('-top-visible');
}
var panelHeight = $bxPanel.length ? $bxPanel.height() : 10;
if (offset > panelHeight) {
$header.addClass('-fixed');
$pageWrapper.css('padding-top', $header.height() + 10 + 'px')
} else {
$header.removeClass('-fixed');
$pageWrapper.css('padding-top', '0')
}
});
var $fixedBtn = $('#fixed-block .fixed-btn-2');
if ($fixedBtn.length){
$fixedBtn.click(function () {
if ($(this).hasClass('-up')) {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
}
if ($(this).hasClass('-down')) {
$("html, body").animate({ scrollTop: document.body.scrollHeight }, "slow");
return false;
}
var $swipeBlock = $(this).next();
var top;
if ($(this).offset().top - $(window).scrollTop() + $swipeBlock.height() > $(window).height()) {
top = $(window).height() - ($(this).offset().top - $(window).scrollTop()) - $swipeBlock.height() -120;
} else {
top = - parseInt($swipeBlock.height()/2);
}
$swipeBlock.css('top', top + 'px');
$(this).parent().toggleClass('-active');
var that = this;
$fixedBtn.filter(function () {
if (this !== that) $(this).parent().removeClass('-active');
});
});
$('.i-check-ee').iCheck({
checkboxClass: 'icheckbox_ee',
radioClass: 'iradio_ee'
});
}
var footerSponsorsSlider = new Swiper ('#footer-sponsors-slider', {
navigation: {
nextEl: '#footer-sponsors-slider-next',
prevEl: '#footer-sponsors-slider-prev',
},
spaceBetween: 20,
slidesPerView: 'auto'
});
var footerPartnersSlider = new Swiper ('#footer-partners-slider', {
navigation: {
nextEl: '#footer-partners-slider-next',
prevEl: '#footer-partners-slider-prev',
},
spaceBetween: 20,
slidesPerView: 'auto'
});
var sponsorSliderDelay = $('#sponsors-slider').data('autoplay-delay');
sponsorSliderDelay = sponsorSliderDelay ? {delay: sponsorSliderDelay} : false;
var sponsorSlidesCount = $('#sponsors-slider').find('.swiper-slide').length;
var sponsorSlider = new Swiper ('#sponsors-slider', {
slidesPerView: 4,
slidesPerGroup: 4,
spaceBetween: 10,
loop: true,
loopedSlides: sponsorSlidesCount % 4 ? sponsorSlidesCount : 4,
navigation: {
nextEl: '#sponsors-slider-next',
prevEl: '#sponsors-slider-prev',
},
autoplay: sponsorSliderDelay,
lazy: true,
watchSlidesVisibility: true,
});
var partnersSliderDelay = $('#partners-slider').data('autoplay-delay');
partnersSliderDelay = partnersSliderDelay ? {delay: partnersSliderDelay} : false;
var partnersSlidesCount = $('#partners-slider').find('.swiper-slide').length;
var partnersSlider = new Swiper ('#partners-slider', {
slidesPerView: 4,
spaceBetween: 10,
slidesPerGroup: 4,
loop: true,
loopedSlides: partnersSlidesCount % 4 ? sponsorSlidesCount : 4,
navigation: {
nextEl: '#partners-slider-next',
prevEl: '#partners-slider-prev',
},
autoplay: partnersSliderDelay,
lazy: true,
watchSlidesVisibility: true,
});
var footerMenuSlider = new Swiper ('#footer-menu-slider', {
navigation: {
nextEl: '#footer-menu-slider-next',
prevEl: '#footer-menu-slider-prev',
},
spaceBetween: 2,
slidesPerView: 4,
slidesPerColumn: 3,
slidesPerColumnFill: 'row',
breakpoints: {
1023: {
slidesPerView: 'auto',
slidesPerColumn: 1,
}
}
});
$('.ee-sidebar-block .expand-toggle').click(function () {
$(this).parent().next().slideToggle();
$(this).parent().parent().toggleClass('-collapsed');
});
function toggleEvent() {
var that = this;
$(this).toggleClass('-active');
$.ajax({
url: $(this).data('api-url'),
dataType: 'json',
data: {element_id : $(this).data('element-id')},
success: function (data) {
$(that).toggleClass('-active', data == "1");
},
error: function () {
$(that).removeClass('-active');
}
});
}
$('.js-add-to-favorite').click(toggleEvent);
$('.js-add-to-learn').click(toggleEvent);
$('.js-copy-link').click(function () {
copyToClipboard($(this).data('link') ? $(this).data('link') : window.location.href);
}).tooltipster({
animation: 'fade',
delay: 200,
theme: 'tooltipster-punk',
trigger: 'click',
timer: 2000
});
$('.ee-like-dislike-control i').click(function () {
if ($(this).hasClass('-active')) return false;
var that = this;
var delta = $(this).hasClass('-up') ? 1 : -1;
$(this).addClass('-active').prev().text(parseInt($(this).prev().text())+1);
$.ajax({
url: $(this).parent().data('api-url'),
dataType: 'json',
data: {element_id : $(this).parent().data('element-id'), delta : delta},
success: function (data) {
if (data != "1") {
$(that).removeClass('-active').prev().text(parseInt($(that).prev().text())-1);
}
},
error: function () {
$(that).removeClass('-active').prev().text(parseInt($(that).prev().text())-1);
}
});
});
var $headerWrapper = $('.header-wrapper');
//var headerOffset = $headerWrapper[0].offsetLeft;
var headerWidth = $headerWrapper.outerWidth();
setTimeout(function () {
$('.main-menu .-has-submenu ul').each(function () {
if ($(this).outerWidth() + $(this).parent()[0].offsetLeft > headerWidth) {
$(this).css('left', -($(this).outerWidth() + $(this).parent()[0].offsetLeft - headerWidth));
}
});
}, 1000);
$('.search-block input').focus(function () {
$('.search-block button').show();
$(this).addClass('-focused');
}).blur(function () {
var that = this;
setTimeout(function () {
$('.search-block button').hide();
$(that).removeClass('-focused');
}, 500);
});
$('.ee-link-widget .widget-btn').tooltipster({
trigger : 'click',
content : 'Cкопировано в буфер'
}).click(function () {
var text = $(this).prev().text();
if (!text.trim()) {
text = $(this).prev().find('input').val();
}
copyToClipboard(text);
});
$('.ee-expandable-text .expand-toggle span:last-child').click(function () {
$(this).parent().prev().slideToggle();
if ($(this).hasClass('-expanded')) {
$(this).text($(this).data('expand-text') || 'Развернуть').removeClass('-expanded');
} else {
$(this).attr('data-expand-text', $(this).text());
$(this).text('Свернуть').addClass('-expanded');
}
});
$('.ee-expandable-text-2 .title-toggle').click(function () {
$(this).next().slideToggle();
$(this).toggleClass('-expanded');
});
$('.ee-expandable-text-3').each(function () {
var wrapper = $(this).data('height') ? '<div class="hidden-text" style="max-height: '+$(this).data('height')+'px"></div>' : '<div class="hidden-text"></div>';
$(this).wrapInner(wrapper).append('<span class="expand-toggle">раскрыть</span>');
}).on('click', '.expand-toggle', function () {
$(this).text($(this).text() === 'раскрыть' ? 'свернуть' : 'раскрыть');
$(this).parent().toggleClass('-expanded');
});
$('.ee-expandable-text-4 .expand-toggle span').click(function () {
$(this).parent().prev().slideToggle();
$(this).toggleClass('-expanded');
});
$('.ee-expandable-text-6 .expand-toggle span').click(function () {
$(this).parent().prev().slideToggle();
$(this).toggleClass('-expanded');
});
$('.ee-expandable-text-5__title').click(function () {
$(this).next().slideToggle();
$(this).toggleClass('ee-expandable-text-5__title--active');
});
$('.js-rating-select').each(function () {
$(this).change(function () {
$.post($(this).data('api-url'), {
rating : $(this).val(),
id : $(this).data('publication-id'),
}, function () {
});
}).barrating({
theme: $(this).data('theme') ? $(this).data('theme') : 'fa-stars-gold',
initialRating: $(this).data('current-rating'),
allowEmpty: true,
readonly: !!$(this).data('voted'),
emptyValue: 0
});
});
if ($.tooltipster) {
$('.tooltip').tooltipster({theme: 'tooltipster-shadow'});
}
$('.ee-select-user-status-pics .status-item').click(function () {
$(this).parent().find('.status-item').removeClass('-selected');
$(this).addClass('-selected');
$(this).parent().find('input[type=hidden]').val($(this).data('value'))
});
var $swiper = $('#viewed-pages-slider');
var delay = $swiper.data('autoplay-delay') ? {delay: $swiper.data('autoplay-delay')} : false;
new Swiper ($swiper, {
slidesPerView: 3,
spaceBetween: 20,
navigation: {
nextEl: $swiper.parent().find('.swiper-button-next'),
prevEl: $swiper.parent().find('.swiper-button-prev'),
},
autoplay: delay,
});
$('#fixed-block .random-block .welcome-part .ee-button-7').click(function () {
$('#fixed-block .random-block .ajax-wrapper').load($('#fixed-block .random-block').data('api-url'), function () {
$("#fixed-block .random-block .ajax-wrapper").mCustomScrollbar({
theme: "light-thick",
scrollButtons:{ enable: true }
});
$('#fixed-block .random-block .js-add-to-favorite').click(toggleEvent);
$('#fixed-block .random-block .js-add-to-learn').click(toggleEvent);
$('#fixed-block .random-block .js-go-to-learn').attr('href', $(this).find('.article-title a').attr('href'));
});
$('#fixed-block .random-block .welcome-part').hide();
$('#fixed-block .random-block .main-part').fadeIn();
});
$('#fixed-block .random-block .js-try-again').click(function () {
$("#fixed-block .random-block .ajax-wrapper").mCustomScrollbar('destroy').html('');
$('#fixed-block .random-block .welcome-part .ee-button-7').trigger('click');
});
$('.ee-attach-field').each(function () {
var that = this;
$(this).find('input[type=file]').change(function () {
if (this.files.length) {
$(that).find('.field-file').text(this.files[0].name).css('display', 'inline-block');
$(that).find('.control-delete').css('display', 'inline-block');
$(that).find('.field-title').hide();
}
});
$(this).find('.field-title').click(function () {
$(that).find('input[type=file]').trigger('click');
});
$(this).find('.control-delete').click(function () {
$(this).hide();
$(that).find('.field-file').hide().text('');
$(that).find('input[type=file]').val('');
$(that).find('.field-title').css('display', 'inline-block');
});
});
$('.ee-copy-link-html').click(function () {
copyFormattedToClipboard('<a target="_blank" style="background-color: inherit;font: inherit;" href="'+window.location.href+'">'+$(this).parent().text().trim()+'</a>');
});
$('form').submit(function (e) {
$(this).find('.form-text.-required, .form-select.-required').each(function () {
if (!$(this).val().trim()) {
$(this).addClass('-error');
e.preventDefault();
}
});
$(this).find('input[type=checkbox].-required').each(function () {
if (!$(this).is(':checked')) {
$(this).parent().addClass('-error');
e.preventDefault();
}
});
});
if (typeof IMask === 'function') {
$('.js-phone').each(function () {
IMask(
this,
{
mask: '+000000000000',
}
);
});
$('.js-email').each(function () {
IMask(
this,
{
mask: function (value) {
if(/^[a-zA-Z0-9_\.-]+$/.test(value))
return true;
if(/^[a-zA-Z0-9_\.-]+@$/.test(value))
return true;
if(/^[a-zA-Z0-9_\.-]+@[a-z0-9-]+$/.test(value))
return true;
if(/^[a-zA-Z0-9_\.-]+@[a-zA-Z0-9-]+\.$/.test(value))
return true;
if(/^[a-zA-Z0-9_\.-]+@[a-zA-Z0-9-]+\.[a-zA-Z]{1,4}$/.test(value))
return true;
if(/^[a-zA-Z0-9_\.-]+@[a-zA-Z0-9-]+\.[a-zA-Z]{1,4}\.$/.test(value))
return true;
if(/^[a-zA-Z0-9_\.-]+@[a-zA-Z0-9-]+\.[a-zA-Z]{1,4}\.[a-zA-Z]{1,4}$/.test(value))
return true;
return false;
},
}
);
});
}
if (jQuery().ee_form_file) {
$('.js-form-file').ee_form_file();
}
});
function copyToClipboard(str) {
var el = document.createElement('textarea'); // Create a <textarea> element
el.value = str; // Set its value to the string that you want copied
el.setAttribute('readonly', ''); // Make it readonly to be tamper-proof
el.style.position = 'absolute';
el.style.left = '-9999px'; // Move outside the screen to make it invisible
document.body.appendChild(el); // Append the <textarea> element to the HTML document
var selected =
document.getSelection().rangeCount > 0 // Check if there is any content selected previously
? document.getSelection().getRangeAt(0) // Store selection if found
: false; // Mark as false to know no selection existed before
el.select(); // Select the <textarea> content
document.execCommand('copy'); // Copy - only works as a result of a user action (e.g. click events)
document.body.removeChild(el); // Remove the <textarea> element
if (selected) { // If a selection existed before copying
document.getSelection().removeAllRanges(); // Unselect everything on the HTML document
document.getSelection().addRange(selected); // Restore the original selection
}
}
function copyToClipboardWithTooltip(el, str, message) {
copyToClipboard(str);
$(el).tooltipster('content', message);
$(el).tooltipster('open');
}
function copyFormattedToClipboard (html) {
// Create container for the HTML
// [1]
var container = document.createElement('div')
container.innerHTML = html
// Hide element
// [2]
container.style.position = 'fixed'
container.style.pointerEvents = 'none'
container.style.opacity = 0
// Detect all style sheets of the page
var activeSheets = Array.prototype.slice.call(document.styleSheets)
.filter(function (sheet) {
return !sheet.disabled
})
// Mount the container to the DOM to make `contentWindow` available
// [3]
document.body.appendChild(container)
// Copy to clipboard
// [4]
window.getSelection().removeAllRanges()
var range = document.createRange()
range.selectNode(container)
window.getSelection().addRange(range)
// [5.1]
document.execCommand('copy')
// [5.2]
for (var i = 0; i < activeSheets.length; i++) activeSheets[i].disabled = true
// [5.3]
document.execCommand('copy')
// [5.4]
for (var i = 0; i < activeSheets.length; i++) activeSheets[i].disabled = false
// Remove the container
// [6]
document.body.removeChild(container)
}
window.showPopup = function (options) {
setTimeout(function () {
$.magnificPopup.open({
items: {
src: options.src
},
modal: options.modal,
prependTo: options.prependTo ? options.prependTo : document.body,
mainClass: options.noBg ? 'no-bg' : '',
type: 'inline',
tClose: 'Закрыть (Esc)',
tLoading: 'Загрузка...',
callbacks: {
open: function() {
if (options.onOpen) {
options.onOpen();
}
if (options.noBg) {
$('html').css('overflow', 'initial');
}
},
}
});
}, options.timeout ? options.timeout*1000 : 0);
};
window.showStickyPopup = function (options) {
if (options.modal) {
$(options.src).find('.ee-popup-v4__close').hide();
}
if (options.onClose) {
$(options.src).find('.ee-popup-v4__close').click(options.onClose);
}
$(options.src).fadeIn();
};
window.hideStickyPopup = function (options) {
$(options.src).hide();
};
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
|
import React from 'react'
import { Flex, Box } from 'grid-styled'
import styled from 'styled-components'
import { black, white, gray60 } from './colors'
const PageFlex = styled(Flex)`
width: 100%;
min-height: 100vh;
background-color: rgb(240, 240, 240);
`
export const Page = props => (
<PageFlex flexWrap={'wrap'}>
<Box
width={[1, 3 / 4, 3 / 4, 2 / 3]}
mx={'auto'}
my={[1, 3, 3, 5]}
p={[2, 3, 3, 4]}
>
{props.children}
</Box>
</PageFlex>
)
export const Card = styled(Box)`
background-color: white;
border: 1px solid ${black};
`
Card.defaultProps = {
p: 2
}
export const Break = styled.hr`
width: 100%;
margin: 20px 0;
border: 1px solid ${gray60};
`
|
//用户注册登录信息验证路由
const Router = require('koa-router');
const userController = require('../API/UserController');
const router = new Router({
prefix: '/user'
});
//用户注册
router.post('/regist',userController.Create);
//密码登陆
router.post('/login',userController.Login);
//获取用户信息
router.post('/getuser',userController.GetUser);
module.exports = router;
|
var https = require('https');
var querystring = require('querystring');
var fs = require("fs");
var credentials_file = fs.readFileSync(process.env.HOME + "/.email_credentials", "utf8");
var credentials = require('yaml').eval(credentials_file);
exports.init = function(app) {
app.all("/contact", function contact(req, res) {
// Handle e-mail
if (req.method == "POST" && ! req.param('subject')) {
var sender = req.param('sender');
var name = req.param('name');
var message = req.param('message');
// Set up message
var content = querystring.stringify({
api_user: credentials.user,
api_key: credentials.password,
to: 'mark@tiemonster.info',
toname: 'Mark Cahill',
subject: 'Message from your contact form',
text: message,
from: sender,
fromname: name
});
// Initiate REST request
var request = https.request({
method: "POST",
host: "sendgrid.com",
port: 443,
path: "/api/mail.send.json",
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-length': content.length
}
}, function(response) {
var data = "";
response.on('data', function(chunk) {
data += chunk;
});
response.on('end', function() {
console.log(data);
});
});
// Send request
request.write(content);
request.end();
}
// Show form
var template = req.method == "GET" ? "contact" : "contact_sent";
res.render(template, {
locals: {
title: "Contact me",
request: req
}
});
});
};
|
//-------------------------------------------------------------------------------------------------
// FILLING IN PREFLIGHT INFORMATION IN THE HTML
//-------------------------------------------------------------------------------------------------
// Given the page index for a page (0-based), sets the correct URL to inElement.
// Example: updatePreviewImage( "#preview_image", 0 )
//
// inElement: a jQuery compatible element identifier
// inPage: the (0-based) page number for the page you're interested in
//
function updatePreviewImage(inElement, inPage) {
$(inElement).attr("src", cals_doc_info.docs[0].pages[0].page_img);
}
function shortSysName(name) {
var arr = name.split(" ");
var out;
if (arr[0] === "Microsoft") {
if (arr[2] === "Server") {
out = arr[1] + " " + arr[2] + " " + arr[3];
} else {
out = arr[1] + " " + arr[2];
}
} else {
out = name;
}
return out;
}
// Looks for elements with specific names and replaces their value with the information provided by
// pdfToolbox in the cals_params file or in the XML report file. This function fills elements with
// the following classes:
// - params_document_name
// - params_number_of_pages
// - params_summary_trim_size
// - params_profile_name
// - params_preflighted_when_by
// - params_summary_result
// - params_file_size
// - params_pdf_version
// - params_standards
// - params_document_title
// - params_creator
// - params_producer
// - params_preflight_information
//
// This function uses classes instead of ids because the same value might have to be replaced for
// multiple elements in the DOM
//
function completeFromParams() {
// Document name
$(".params_document_name").html(cals_doc_info.docs[0].file_name);
// Number of pages
$(".params_number_of_pages").html(getNumPages());
// Trim size summary
$(".params_summary_trim_size").html(getTrimSizeSummary());
// Preflight profile name
$(".params_profile_name").html(cals_res_info.profile_name);
// Preflighted when and by
$(".params_preflighted_when_by").html(cals_env_info.date.slice(0, 10) + " <span class='lighter translatable'>at</span> " + cals_env_info.date.slice(11, 16));
// Summary result
$(".params_summary_result").html((getNumberOfErrors() == 0) ? "Success!" : "Errors!").addClass("translatable");
// File size
$(".params_file_size").html(humanFileSize(cals_doc_info.docs[0].file_size, true));
// PDF version
$(".params_pdf_version").html(cals_doc_info.docs[0].pdf_version);
// Standards
var theStandardsText = ($.isArray(cals_doc_info.docs[0].standards) && (cals_doc_info.docs[0].standards.length > 0)) ? cals_doc_info.docs[0].standards.join(", ") : "none";
$(".params_standards").html(theStandardsText);
// Document title
$(".params_document_title").html(cals_doc_info.docs[0].docinfo.Title);
// Creator
$(".params_creator").html(cals_doc_info.docs[0].docinfo.Creator);
// Producer
$(".params_producer").html(cals_doc_info.docs[0].docinfo.Producer);
// Preflight information
var sysName = shortSysName(cals_env_info.os_version_text);
$(".params_preflight_information").html(cals_env_info.tool_name + " " + cals_env_info.tool_variant + " " + cals_env_info.tool_version + " <span class='lighter translatable'>on</span> " + sysName + " <span class='lighter translatable'>by</span> " + cals_env_info.user_name);
}
// Hides either the success or the error image in the report
//
function updateResultImages(inElementSuccess, inElementError) {
if (getNumberOfErrors() == 0) {
$(inElementError).hide();
} else {
$(inElementSuccess).hide();
}
}
// Inserts all hits and fixups in the result section of the report
//
function insertHitsAndFixups(inContainer) {
// Get the information we need to insert
var theHits = getHits();
var theFixups = getFixups();
// If there is content, create it
if ((theHits.length > 0) || (theFixups.length > 0)) {
// Insert all errors, then warnings, then informational items
for (var theErrorIndex = 0; theErrorIndex < theHits.length; theErrorIndex++) {
var theError = theHits[theErrorIndex];
if (theError.severity == "error") {
insertHit(inContainer, "img/hit_error.pdf", theError.rule_name, theError.matches, theError.on_pages, "error");
}
}
for (var theWarningIndex = 0; theWarningIndex < theHits.length; theWarningIndex++) {
var theWarning = theHits[theWarningIndex];
if (theWarning.severity == "warning") {
insertHit(inContainer, "img/hit_warning.pdf", theWarning.rule_name, theWarning.matches, theWarning.on_pages, "warning");
}
}
for (var theInfoIndex = 0; theInfoIndex < theHits.length; theInfoIndex++) {
var theInfo = theHits[theInfoIndex];
if (theInfo.severity == "info") {
insertHit(inContainer, "img/hit_info.pdf", theInfo.rule_name, theInfo.matches, theInfo.on_pages, "info");
}
}
// Insert all fixups
for (var theFixupIndex = 0; theFixupIndex < theFixups.length; theFixupIndex++) {
var theFixup = theFixups[theFixupIndex];
insertFixup(inContainer, "img/hit_fixup.pdf", theFixup.fixup_name, theFixup.succeeded, theFixup.failed);
}
} else {
// Nothing to do, hide this section
$(inContainer).hide();
}
}
// Inserts a single hit item in the result section of the report
//
function insertHit(inContainer, inImageURL, inName, inNumberOfTimes, inPageList, inType) {
// Insert a container for the hit
var theHitContainer = $('<div/>', {
class: 'section_hits_hit ' + inType
}).appendTo($(inContainer));
// Insert an image and a paragraph
var theHitImage = $('<img/>', {
src: inImageURL
}).appendTo(theHitContainer);
// Insert an image and a paragraph
var theHitText = $('<p/>').appendTo(theHitContainer);
// Format the occurrence string as we want
var theOccurrence = addTimes(inNumberOfTimes);
if ((inPageList != undefined) && (inPageList.length > 0)) {
theOccurrence += " " + formatPageList(inPageList);
}
// Calculate the text we want for this item and insert it
theHitText.html(inName + "<span class='lighter smaller'>" + " (" + theOccurrence + ")" + "</span>");
}
// Formats a page list for human consumption
//
function formatPageList(inPageList) {
// Add one to all pages or they'll be wrong (0-based)
for (var theIndex = 0; theIndex < inPageList.length; theIndex++) {
inPageList[theIndex]++;
}
// Our page list must at least have one page or we wouldn't get here... let's format easy cases
// in a special way...
if (inPageList.length == 1) {
return "<span class='translatable'>on</span> <span class='translatable'>page</span> " + inPageList[0];
} else if (inPageList.length < 6) {
return "<span class='translatable'>on</span> <span class='translatable'>pages</span> " + inPageList.join(", ");
} else {
var theShortList = inPageList.slice(0, 5);
var theRemaining = inPageList.length - 5;
return "<span class='translatable'>on</span> <span class='translatable'>pages</span> " +
theShortList.join(", ") + " <span class='translatable'>and</span> " + theRemaining + " <span class='translatable'>more</span>";
}
}
// Inserts a single fixup item in the result section of the report
//
function insertFixup(inContainer, inImageURL, inName, inSucceeded, inFailed) {
// Insert a container for the fixup
var theFixupContainer = $('<div/>', {
class: 'section_hits_fixup'
}).appendTo($(inContainer));
// Insert an image and a paragraph
var theFixupImage = $('<img/>', {
src: inImageURL
}).appendTo(theFixupContainer);
// Insert an image and a paragraph
var theFixupText = $('<p/>').appendTo(theFixupContainer);
// Calculate the text we want for this item and insert it
var theOccurrence = "";
var theSucceededString = addTimes(inSucceeded);
var theFailedString = "<span class='translatable'>failed</span> " + addTimes(inFailed);
if (inSucceeded == 0) {
theOccurrence = theFailedString;
} else {
theOccurrence = (inFailed == 0) ? theSucceededString : theSucceededString + ", " + theFailedString;
}
var theDescription = inName + "<span class='lighter smaller'>" + " (" + theOccurrence + ")</span>";
theFixupText.html(theDescription);
}
// Adds "time" or "times" to a string depending on the number
//
function addTimes(inNumber) {
if (inNumber == 1) {
return inNumber + " <span class='translatable'>time</span>";
} else {
return inNumber + " <span class='translatable'>times</span>";
}
}
// Inserts information about colors
//
function insertColorInformation(inContainer) {
// Get the color information for the whole document
var theColorInformation = xmlGetInkCoverageStatistics(0);
// Loop over the colors and divide it in process colors and spot colors
var theProcessColors = [];
var theSpotColors = [];
for (var theIndex = 0; theIndex < theColorInformation.length; theIndex++) {
// Only handle those that are used
var theColor = theColorInformation[theIndex];
if (theColor.percentage > 0) {
switch (theColor.name) {
case "Cyan":
case "Magenta":
case "Yellow":
case "Black": {
theProcessColors.push(theColor);
break;
}
default: {
theSpotColors.push(theColor);
break;
}
}
}
}
// Add process information
for (var theProcessColorIndex = 0; theProcessColorIndex < theProcessColors.length; theProcessColorIndex++) {
var theColor = theProcessColors[theProcessColorIndex];
insertColorLine(inContainer, "Process color", theColor.name, theColor.percentage, theColor.squareCm);
}
// Add spot color information
for (var theSpotColorIndex = 0; theSpotColorIndex < theSpotColors.length; theSpotColorIndex++) {
var theColor = theSpotColors[theSpotColorIndex];
insertColorLine(inContainer, "Spot color", theColor.name, theColor.percentage, theColor.squareCm);
}
}
// Inserts one line with color information
//
function insertColorLine(inContainer, inKey, inName, inPercentage, inSurface) {
// Insert a container for the color
var theColorContainer = $('<div/>', {
class: 'section_color_key_value'
}).appendTo($(inContainer));
// Insert two text lines for the color
var theKeyText = $('<p/>', {
class: 'section_color_key translatable'
}).appendTo(theColorContainer);
var theValueText = $('<p/>', {
class: 'section_color_value'
}).appendTo(theColorContainer);
// Set the correct text for them
if (sUnitColorCoverage === "sqin") {
var theCoverage = unitConvertCm2ToIn2(inSurface).toFixed(2) + sUnitColorCoverage;
} else if (sUnitColorCoverage === "sqcm") {
var theCoverage = inSurface.toFixed(2) + sUnitColorCoverage;
} else if (sUnitColorCoverage === "sqm") {
var theCoverage = unitConvertCm2ToM2(inSurface).toFixed(2) + sUnitColorCoverage;
}
theKeyText.html(inKey);
theValueText.html(inName + "<span class='lighter smaller'>" + " (" + inPercentage.toFixed(2) + "%, " + theCoverage + ")</span>");
}
function insertPageDimensions() {
var i = 1;
// Initialises an array for each dimension
var cropBox = [];
var trimBox = [];
// Iterates over each page and fills in the dimensions
xmlGetPages().forEach(function () {
if (xmlGetCropBoxWidthForPage(i) === null || xmlGetCropBoxHeightForPage(i) === null) {
console.log('null/cropbox');
} else {
const content = i + ": " + unitConvertFromPoints(xmlGetCropBoxWidthForPage(i), sUnitPageDimensions).toFixed(2) + sUnitPageDimensionsString + " x " + unitConvertFromPoints(xmlGetCropBoxHeightForPage(i), sUnitPageDimensions).toFixed(2) + sUnitPageDimensionsString;
cropBox.push(content);
}
if (xmlGetTrimBoxWidthForPage(i) === null || xmlGetTrimBoxHeightForPage(i) === null) {
console.log('null/trimbox');
} else {
const content = i + ": " + unitConvertFromPoints(xmlGetTrimBoxWidthForPage(i), sUnitPageDimensions).toFixed(2) + sUnitPageDimensionsString + " x " + unitConvertFromPoints(xmlGetTrimBoxHeightForPage(i), sUnitPageDimensions).toFixed(2) + sUnitPageDimensionsString;
trimBox.push(content);
}
i++;
});
// Inserts the UL into the HTML
document.querySelector('.xml_cropbox').appendChild(makeUL(cropBox));
document.querySelector('.xml_trimbox').appendChild(makeUL(trimBox));
}
//-------------------------------------------------------------------------------------------------
// PREFERENCES SUPPORT
//-------------------------------------------------------------------------------------------------
// Called when all resources for the page are ready and loaded
//
$(window).on("load", function () {
// Visibility control
$(".section_hits_fixup").toggle(sShowFixups);
$(".section_hits_hit.info").toggle(sShowInfos);
$(".section_hits_hit.warning").toggle(sShowWarnings);
$(".section_hits_hit.error").toggle(sShowErrors);
$("#section_more_information").toggle(sShowMoreInformation);
$("#section_colors").toggle(sShowColorInformation);
$("#section_pagedimensions").toggle(sShowPageDimensions);
$("#nohits").toggle(sShowNoHits);
$("#section_missing_fonts").toggle(sShowMissingFonts);
$("#oi").toggle(sShowOutputIntent);
if (document.getElementById("xmlFonts").innerHTML == "") {
$('.section_missing_fonts').toggle(false);
}
// Colors
if (getNumberOfErrors() == 0) {
$("#section_summary").css("background-color", sColorSummaryBackground_success);
} else {
$("#section_summary").css("background-color", sColorSummaryBackground_error);
}
/*
//$( "#" + inId ).toggle( inVisible );
/*
// Ajust visibility of elements
reportSetVisibilityForElementWithId( "infobox", sShowInfoBox );
reportSetVisibilityForElementWithId( "details", sShowDetails );
reportSetVisibilityForElementWithId( "details_hits", sShowDetailsHits );
reportSetVisibilityForElementWithId( "details_docinfo", sShowDetailsDocumentInfo );
reportSetVisibilityForElementWithId( "details_environment", sShowDetailsEnvironment );
// Visibility settings for errors, warnings, infos and fixes are controlled in the actual
// Javascript code that adds these items to the report
// Change colors as necessary
$( "span.red" ).css( "color", sColorAccent );
$( "div.hrule" ).css( "background-color", sColorAccent );
$( "#tool_name" ).css( "color", sColorAccent );
$( "#tool_variant" ).css( "color", sColorSecondaryAccent );
$( "span.severity_label" ).css( "color", sColorSecondaryAccent );
$( "span.fixup_label" ).css( "color", sColorAccent );
$( "span.docinfo_label" ).css( "color", sColorAccent );
$( "span.environment_label" ).css( "color", sColorAccent );
$( "div.ov_hit_box" ).css( "border-color", sColorAccent );
$( "#infobox" ).css( "border-color", sColorAccent );
$( "#header" ).css( "border-color", sColorAccent );
$( "#overview_preview" ).css( "background-color", sColorThumbnailBackground );
$( ".step_header" ).css( "border-color", sColorAccent );
*/
});
|
import { Scene } from 'phaser';
import styles from '../utils/styles';
const characterPositions = [
[200, 340],
[520, 300],
[840, 380],
[360, 620],
[680, 620],
];
export default class CrewScene extends Scene {
constructor() {
super({ key: 'crew', active: false });
this.tokens = [];
}
preload() {
this.load.image('character-1', 'assets/character-1.png');
this.load.image('character-2', 'assets/character-2.png');
this.load.image('character-3', 'assets/character-3.png');
this.load.image('character-4', 'assets/character-4.png');
this.load.image('character-5', 'assets/character-5.png');
}
buyToken() {
this.owner.purchaseToken().then(response => {
this.showPurchasedToken(response.token, response.transactionHash);
}).catch(error => {
console.error(error);
});
}
showPurchasedToken(token, transactionHash) {
this.owner.tokenService.unsubscribe();
this.scene.stop('crew');
this.scene.start('receipt', { owner: this.owner, token: token, transactionHash: transactionHash });
}
showTokenDetails(token) {
this.owner.tokenService.unsubscribe();
this.scene.stop('crew');
this.scene.start('unit', { owner: this.owner, token: token });
}
drawToken(token, index) {
let character = token.imageId;
let characterPosition = characterPositions[index];
let characterImage = this.physics.add.image(characterPosition[0], characterPosition[1], `character-${character}`);
characterImage.setScale(1.2);
characterImage.setOrigin(0,0);
let velocityX = Math.random() * (100 - (-100)) + (-100);
let velocityY = Math.random() * (300 - (-300)) + (-300);
characterImage.setVelocity(velocityX, velocityY);
characterImage.setBounce(1, 1);
characterImage.setGravityY(200);
characterImage.setCollideWorldBounds(true);
characterImage.setInteractive({ useHandCursor: true });
characterImage.on('pointerup', () => {
this.showTokenDetails(token);
});
this.characters.push(characterImage);
}
configureTokens() {
let totalTokens = this.tokens.length;
this.characters.forEach(image => {
image.destroy();
});
this.characters = [];
this.tokens.forEach((token, i) => {
this.drawToken(token, i);
});
var title = '...'
if (totalTokens === 1) {
title = 'You have 1 guy!';
} else if (totalTokens < 5) {
title = 'You have ' + totalTokens + ' guys!';
} else {
title = 'You have a full crew!';
}
this.title.text = title;
if (totalTokens < 5) {
this.moreButton.setInteractive({ useHandCursor: true });
this.moreButton.alpha = 1;
} else {
this.moreButton.alpha = 0.3;
this.moreButton.removeInteractive();
}
}
handleTransfer(event) {
const { from, to, tokenId } = event.returnValues;
const address = this.owner.tokenService.defaultAccount;
if (to == address) {
const existingToken = this.tokens.find(token => { return token.id == tokenId });
if (!existingToken) {
this.owner.tokenService.getImageId(tokenId).then(imageId => {
this.tokens.push({ id: tokenId, imageId: imageId });
this.configureTokens();
});
}
} else if (from == address) {
this.tokens = this.tokens.filter(token => { return token.id != tokenId });
this.configureTokens();
} else {
console.error('Received unexpected event', event);
}
}
create(config) {
this.owner = config.owner;
this.tokenService = config.tokenService;
this.tokens = config.tokens;
this.characters = [];
this.make.text({
x: 0,
y: 1200,
origin: { x: 0, y: 1 },
padding: 20,
text: "These are the crypto characters you own from our smart contract. Each character is represented by a unique token which determines its appearance.\n\nYou can buy up to five characters using a credit card. To purchase, use this test number: 4242 4242 4242 4242. Use any expiration date and cvv.",
style: styles.explanation
});
this.physics.world.setBounds(0, 168, 1100, 500);
this.title = this.sys.make.text({
x: 600,
y: 0,
origin: { x: 0.5, y: 0 },
padding: 20,
style: styles.title
});
this.moreButton = this.sys.make.text({
x: 600,
y: 950,
padding: 20,
origin: { x: 0.5, y: 1 },
style: styles.primaryButton,
alpha: 0,
text: 'Buy Character: $1.00'
});
this.moreButton.on('pointerup', () => {
this.buyToken();
});
this.logOutButton = this.sys.make.text({
x: 1180,
y: 20,
padding: 20,
origin: { x: 1, y: 0 },
style: styles.secondaryButton,
text: 'Sign Out'
});
this.logOutButton.setInteractive({ useHandCursor: true });
this.logOutButton.on('pointerup', () => {
this.owner.logOut();
});
this.configureTokens();
this.owner.tokenService.subscribe((event) => {
this.handleTransfer(event);
});
}
};
|
import { useState } from "react";
import {Link, useHistory} from "react-router-dom";
import axios from "axios";
import IsCookie from "./IsCookie"
axios.defaults.baseURL="http://18.219.215.9:8081";
function Login(){
const history=useHistory();
const OnLogin=async (e)=>{
e.preventDefault();
const {userName,password}=loginInfo;
await axios.post('/login',{
username:userName,
password:password
}).then(
response=>{
const dataRequest=response.data;
document.cookie=dataRequest[`Bearer-Token`]
alert("로그인 성공!")
history.push("/");
IsCookie();
}
).catch((e)=>{
console.log(e);
alert("아이디와 비밀번호를 다시 입력해 주세요");
return;
})
}
const OnLoginEx=(e)=>{
console.log(e);
const {userName,password}=loginInfo;
if(userName===''){
alert("userName을 넣어주세요!");
return;
}
if(password===''){
alert("password을 넣어주세요!");
return;
}
OnLogin(e);
}
const [loginInfo,setLoginInfo]=useState({
userName:'',
password:''
})
const LoginInfoChange=(e)=>{
const {name,value}=e.target;
setLoginInfo(
{
...loginInfo,
[name]:value
}
)
}
return(
<form onSubmit={OnLoginEx}>
<h1>로그인 연습</h1>
<input placeholder="userName" name='userName' onChange={(e)=>LoginInfoChange(e)}></input>
<input placeholder="password" name='password'onChange={(e)=>LoginInfoChange(e)} ></input>
<button onClick={OnLoginEx}>Login</button>
<Link to="/Join">Join</Link>
</form>
);
}
export default Login;
|
import models from "../../../models";
export default function (req, res, next) {
return models.menu_item
.findAll({
where: {
menus_id: req.params.menus_id,
is_active: 1
}
})
.then(menu_items => {
res.send(menu_items)
})
.catch(err => {
next(err);
});
}
|
import loadPolyfills from "./polyfills.js";
loadPolyfills();
/* 1. Array.map()
const arr = [10, 20, 30, 40, 50, 60];
const arr2 = arr.map((e) => e * 2);
const arr3 = arr.map2((e) => e * 2);
console.log(arr);
console.log(arr2);
console.log(arr3);
*/
/* 2. Array.filter
const arr = [10, 20, 30, 40, 50, 60, 70, 80, 90];
const arr2 = arr.filter((e) => e % 20 === 0);
const arr3 = arr.filter2((e) => e % 20 === 0);
console.log(arr);
console.log(arr2);
console.log(arr3);
*/
/* Array Deep Copy
let arr = [10,20,30,40,50,[100,110,120,130,140,[200,210,220,230,240]]];
let arr2 = arr.map2(e => e);
console.log(arr);
console.log(arr2);
arr[0] = 1000;
arr[5][0] = 2000;
arr[5][5][0] = 3000;
console.log(arr);
console.log(arr2);
let arr = [10,20,30,40,50,[100,110,120,130,140,[200,210,220,230,240]]];
let arr2 = arr.deepCloneArray();
console.log(arr);
console.log(arr2);
arr[0] = 1000;
arr[5][0] = 2000;
arr[5][5][0] = 3000;
console.log(arr);
console.log(arr2);
*/
/* 4. Deep Clone
*/
let emp = {
fname: "Jasmeet",
lname: "Singh",
address: {
lines: {
line1: "abcd",
line2: "efgh",
},
city: "wxyz",
state: "Maharashtra",
country: "India",
},
contact: ["9876543210", "6123457890", "8123456790"],
};
let emp4 = Object.deepClone(emp);
emp.address.state = "Uttar Pradesh";
console.log(emp);
console.log(emp4);
// emp.address.state = "Uttar Pradesh";
// console.log(emp);
// console.log(emp3);
|
/* global $ */
'use strict';
//**********/
//STEP 0: INITIALIZATION
//*********/
$(document).ready(function() {
render();
handleQuizStart();
handleAnswerSubmitted();
handleResetButton();
handleCurrentScore();
});
/********************************************************
Step 1: Define objects & database
********************************************************/
const QUESTIONS = [
{question: 'What position did he play?',
answers: ['Point guard', 'Center', 'Power Forward', 'Shooting guard', 'Small Forward'],
correctAnswer: 'Shooting guard'},
{question: 'Jordan made a NBA comeback in 2001. Which team did he play for?',
answers: ['Chicago Bulls', 'Washington Wizards', 'Boston Celtics', 'Phoenix Suns', 'Los Angeles Lakers'],
correctAnswer: 'Washington Wizards'},
{question: 'In 2010, Michael became majority owner of which NBA team?',
answers: ['Oklahoma City Thunder', 'Houston Rockets', 'Philadelphia 76ers', 'Charlotte Bobcats', 'Chicago Bulls'],
correctAnswer: 'Charlotte Bobcats'},
{question: 'Which of the following NBA players did NOT appear in the film Space Jam?',
answers: ['Larry Bird', 'Shawn Bradley', 'Charles Barkley', 'Muggsy Bogues', 'Kobe Bryant'],
correctAnswer: 'Kobe Bryant'},
{question: 'How many NBA Championships did Michael have?',
answers: ['6', '10', '4', '8', '3'],
correctAnswer: '6'}];
const STORE = {
currentQuestionIndex: null,
userAnswer: [],
userCorrectAnswers: [],
userIncorrectAnswers: [],
currentView: 'start',
currentScore: 0,
};
/***********************/
//TEMPLATE GENERATORS//
/**********************/
const introTemplate = function() {
return `<h1 id='js-quiz-header'>His Airness, Michael Jordan:<br> How much do you know?</h1>
<img id='js-jordan-dunk' src='jordandunk.jpg' class='js-splash-page-dunk alt='Michael Jordan dunking the basketball from free throw line'>
<input type='submit' class='js-the-button' id='startButton' value='Start Quiz'>`;
};
const correctAnswerTemplate = function() {
return `
<p class='js-feedback'>Correct!</p>
`;
};
const wrongAnswerTemplate = function() {
return `
<p class='js-feedback'><p>Sorry, that is incorrect.</p>
`;
};
const resultsTemplate = function() {
return `
<div class='js-outro'>
<p>You scored ${handleFinalScore()}</p><br>
<p>Reset quiz to play again</p><br>
<input type='submit' id='js-reset-quiz' value='Reset Quiz'></div>
`;
};
const questionTemplate = function() {
return `<div class='js-questions' 'js-question-item-${STORE.currentQuestionIndex}>${QUESTIONS[STORE.currentQuestionIndex].question}</div<br>
<div class='js-answer-choices'>
<form id='js-answerSelected'>
<input type='radio' name='answers' id='js-choice1' value='${QUESTIONS[STORE.currentQuestionIndex].answers[0]}'>
<label for='js-choice1'>${QUESTIONS[STORE.currentQuestionIndex].answers[0]}</label><br/>
<input type='radio' name='answers' value='${QUESTIONS[STORE.currentQuestionIndex].answers[1]}'>
<label for='js-choice2' id='js-choice2'>${QUESTIONS[STORE.currentQuestionIndex].answers[1]}</label><br/>
<input type='radio' name='answers' value='${QUESTIONS[STORE.currentQuestionIndex].answers[2]}'>
<label for='js-choice3' id='js-choice3'>${QUESTIONS[STORE.currentQuestionIndex].answers[2]}</label><br/>
<input type='radio' name='answers' value='${QUESTIONS[STORE.currentQuestionIndex].answers[3]}'>
<label for='js-choice4' id='js-choice4'>${QUESTIONS[STORE.currentQuestionIndex].answers[3]}</label><br/>
<input type='radio' name='answers' value='${QUESTIONS[STORE.currentQuestionIndex].answers[4]}'>
<label for='js-choice5' id='js-choice5'>${QUESTIONS[STORE.currentQuestionIndex].answers[4]}</label><br/>
<input type='submit' id='js-answersSubmit' class='js-the-button' value='Enter'>
<input type='submit' id='js-reset-quiz' value='Reset Quiz'>
</div>Question ${STORE.currentQuestionIndex+1} of ${QUESTIONS.length}</div>
<div>Current score: ${handleCurrentScore()}</div>
</form>
`;
};
/**********/
//STEP 1: RENDER
//**********/
function render() {
if (STORE.currentView === 'start') {
$('.intro').show();
$('.intro').append(introTemplate);
$('.questions').hide();
$('.feedback').hide();
$('.score').hide();
$('.outro').hide();
}
else if ((STORE.currentView === 'questions') && (STORE.userCorrectAnswers[STORE.currentQuestionIndex])) {
$('.questions').show();
$('.questions').append(questionTemplate);
$('.intro').hide();
$('.feedback').show();
$('.answer-incorrect').hide();
// $('.feedback').html(correctAnswerTemplate);
$('.outro').hide();
}
else if ((STORE.currentView === 'questions') && (STORE.userIncorrectAnswers[STORE.currentQuestionIndex])) {
$('.intro').hide();
$('.questions').show();
$('.feedback').show();
$('.answer-correct').show();
// $('.feedback').html(wrongAnswerTemplate);
$('.outro').hide();
}
else if (STORE.currentView === 'questions') {
$('.intro').hide();
$('.questions').show();
$('.questions').html(questionTemplate);
$('.score').hide();
$('.outro').hide();
}
else {
$('.outro').show();
$('.outro').html(resultsTemplate);
$('.intro').hide();
$('.questions').hide();
$('.feedback').hide();
}
}
/**********/
//STEP 2: EVENT LISTENERS(USER INPUT)
/*********/
function handleQuizStart() {
changeView('start');
$('.js-quiz-container').on('click', '#startButton', function(e) {
e.preventDefault();
changeView('questions');
STORE.currentQuestionIndex = 0;
handleCurrentScore();
render();
});
}
function handleResetButton() {
$('.js-quiz-container').on('click', '#js-reset-quiz', function(e) {
e.preventDefault();
STORE['userAnswer'] = [];
STORE['userCorrectAnswers'] = [];
STORE['userIncorrectAnswers'] = [];
STORE['currentScore'] = 0;
handleQuizStart();
render();
});
}
function handleAnswerSubmitted() {
$('.js-quiz-container').on('click', '#js-answersSubmit', function(e) {
e.preventDefault();
if (STORE.currentQuestionIndex === (QUESTIONS.length-1)) {
const lastAnswer = $('input[name=answers]:checked').val();
STORE.userAnswer.push(lastAnswer);
checkAnswer(lastAnswer);
handleResults();
render();
}
else {
const answer = $('input[name=answers]:checked').val();
STORE.userAnswer.push(answer);
checkAnswer(answer);
STORE.currentQuestionIndex++;
render();
}
});
}
function handleCorrectAnswer() {
$('.answer-correct').show();
}
function handleWrongtAnswer() {
$('.answer-incorrect').show();
}
/***************/
//STEP 3: Helper Functions
/**************/
function checkAnswer(answer) {
if (STORE.userAnswer[STORE.currentQuestionIndex] === QUESTIONS[STORE.currentQuestionIndex].correctAnswer) {
STORE.userCorrectAnswers.push(answer);
render();
} else {
STORE.userIncorrectAnswers.push(answer);
render();
}
}
function changeView(view) {
STORE.currentView = view;
}
function handleResults() {
changeView('results');
handleResetButton();
render();
}
function handleCurrentScore() {
//handling empty arrays if user has either no incorrect answers or no correct answers
if (STORE.currentView === 'results' && STORE.userCorrectAnswers === []) {
STORE.userCorrectAnswers = 0;
}
else if (STORE.currentView === 'results' && STORE.userIncorrectAnswers === []) {
STORE.userIncorrectAnswers = 0;
}
const score = STORE.userCorrectAnswers.length;
return score;
}
function handleFinalScore() {
const finalScore = STORE.userAnswers.length/STORE.userCorrectAnswers.length*100;
if (finalScore === Infinity) {
return 100;
} else {
return finalScore;
}
}
|
/**
* take html string and get rid of all html tags and special symbols, leaving only simple text
* @param html
*/
export function removeHTMLtags (html) {
return html
.replace(/<[^>]+>/gm, '')
.replace(/(\\n|\n| )/gm, ' ')
}
|
import React from "react";
import PropTypes from "prop-types";
import Parent from "./p";
import ChildOne from "./c1";
import ChildTwo from "./c2";
import ChildThree from "./c3";
export default class Container extends React.Component {
constructor(props) {
super(props);
this.state = { value: "" };
}
static childContextTypes = {
value: PropTypes.string,
changeValue: PropTypes.func
};
changeValue = value => {
this.setState({ value });
};
getChildContext() {
return {
value: this.state.value,
changeValue: this.changeValue
};
}
render() {
return (
<div>
<Parent>
<ChildOne />
</Parent>
<Parent>
<ChildTwo />
</Parent>
<ChildThree />
</div>
);
}
}
|
class FlexDate extends Date {
inc(delta_ms) {
this.setTime(this.getTime() + delta_ms.valueOf())
}
format() {
return String(this).substring(0,15)
}
}
|
// TODO: module docs
'use strict';
// TODO: docs
exports.createParser = require('jsdoc/src/parser').createParser;
// TODO: docs
var Parser = exports.Parser = function() {
var astBuilder;
var visitor;
var runtime = require('jsdoc/util/runtime');
if ( !runtime.isRhino() ) {
throw new Error('You must run JSDoc on Mozilla Rhino to use the Rhino parser.');
}
astBuilder = new ( require(runtime.getModulePath('jsdoc/src/astbuilder')) ).AstBuilder();
visitor = new ( require(runtime.getModulePath('jsdoc/src/visitor')) ).Visitor(this);
Parser.super_.call(this, astBuilder, visitor);
};
require('util').inherits(Parser, require('jsdoc/src/parser').Parser);
// TODO: update docs
/**
* Adds a node visitor to use in parsing
*/
Parser.prototype.addNodeVisitor = function(visitor) {
this._visitor.addRhinoNodeVisitor(visitor);
};
// TODO: docs
/**
* Get the node visitors used in parsing
*/
Parser.prototype.getNodeVisitors = function() {
return this._visitor.getRhinoNodeVisitors();
};
|
import {
FETCH_NOTIFICATION_LOGS_LOADING,
FETCH_NOTIFICATION_LOGS,
FETCH_NOTIFICATION_LOGS_ERROR,
UPDATE_LAST_NOTIFIED
} from './notificationLogs.actionType'
import { dateDisplayFormater } from '../../helpers/date.helper'
import { database } from '../../firebase/firebase'
import PushNotification from '../../helpers/notification.helper'
// export const fetchNotificationLogs = (payload) => {
// return dispatch => {
// dispatch(fetchNotificationLogsLoading())
// database().ref(`/smarthome/logs`).on('value', (snap) => {
// let data = snap.val()
// dispatch(fetchNotificationLogsSuccess(data))
// }, (err) => { dispatch(fetchNotificationLogsError()) })
// }
// }
export const watchNotification = (lastNotified) => {
/* istanbul ignore next */
return dispatch => {
/* istanbul ignore next */
dispatch(fetchNotificationLogsLoading())
/* istanbul ignore next */
database().ref(`/smarthome/logs`).on('value', (snaphot) => {
/* istanbul ignore next */
let val = snaphot.val()
/* istanbul ignore next */
if(val) {
val = Object.values(snaphot.val()).reverse()
/* istanbul ignore next */
if(val[0].createdAt > lastNotified) {
lastNotified = val[0].createdAt
/* istanbul ignore next */
let notificationMessage = {
id: lastNotified,
largeIcon: "ic_launcher",
smallIcon: "ic_launcher",
autoCancel: true,
bigText: `${ val[0].description }`,
subText: `${ dateDisplayFormater(val[0].createdAt) }`,
vibrate: true,
vibration: 300,
title: "Fortress - Smart Home Security",
message: `${ val[0].title }`,
}
/* istanbul ignore next */
PushNotification.localNotification(notificationMessage);
/* istanbul ignore next */
dispatch(updateLastNotified(val[0].createdAt))
}
} else {
/* istanbul ignore next */
val = []
}
dispatch(fetchNotificationLogsSuccess(val))
}, (err) => { dispatch(fetchNotificationLogsError()) })
}
}
export const notificationsDelete = (payload) => {
database().ref(`/smarthome/logs/${payload}`).set(null)
}
export const fetchNotificationLogsSuccess = (payload) => {
/* istanbul ignore next */
return {
type: FETCH_NOTIFICATION_LOGS,
payload: payload
}
}
const fetchNotificationLogsLoading = () => ({
type: FETCH_NOTIFICATION_LOGS_LOADING,
})
const fetchNotificationLogsError = () => ({
type: FETCH_NOTIFICATION_LOGS_ERROR
})
export const updateLastNotified = (payload) => {
/* istanbul ignore next */
return {
type: UPDATE_LAST_NOTIFIED,
payload: payload
}
}
|
var m = require('mithril');
var View = require('./View');
var Credits = require("./Credits");
var { about, bio, interviews, credits } = require('../content');
module.exports = {
view: ({ attrs: { battery, icon, offset } }) => {
return m( View, { title: 'Just an Idea', battery, icon, offset },
m('.about-mobile',
m('.about-mobile__section', m.trust( about ) ),
m('.about-mobile__section',
m( 'h1', 'interviews' ),
interviews.map( ({ title, name, profession }) => m('.about-mobile__credit',
m('em', title ),
m( 'span', 'with ', name ),
m('span', profession )
))
),
credits.map( ({ role, name, url }) => m('.about-mobile__credit',
m('h1', role ),
url
? m( 'a', { href: url, target: '_blank'}, name )
: m( 'span', name )
))
// m('h1', 'Stroma Cairns'),
// m.trust( bio ),
// m('a', { href: 'http://stromacairns.co.uk/', target: '_blank'}, 'stromacairns.co.uk'),
// m('a', { href: 'http://bewe.me/', target: '_blank' }, 'Website by Ben West' )
// m('.about-mobile__credits',
// m( Credits, { interviews } )
// )
)
)
}
}
|
import Enzyme, { configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import {
FETCH_USER_DATA,
FETCH_USER_DATA_LOADING,
FETCH_USER_DATA_ERROR
} from '../store/userData/userData.actionType';
import {
searchUser
} from '../store/userData/userData.actions';
let result;
let mockResult;
let mockPayload = {}
let mockUsers = {
123456: {
email: '123456@email.com',
username: '123456',
pin: '123456',
deviceId: '123456'
},
654321: {
email: '654321@email.com',
username: '654321',
pin: '654321',
deviceId: '654321'
},
testerDeveloper123Testing: {
email: 'testerDeveloper123Testing@email.com',
username: 'testerDeveloper123Testing',
pin: '654321',
deviceId: 'testerDeveloper123Testing'
}
}
describe('Action searchUser Test', () => {
it('searchUser Success Test', () => {
let expectedActions = [
{type: "FETCH_USER_DATA_LOADING"},
{type: "FETCH_USER_DATA"},
];
result = searchUser(mockUsers);
let index = 0
result((action) => {
expect(action).toEqual(expectedActions[index]);
index++
})
})
})
|
import ActionTypes from './ActionTypes';
import Accounts from './Accounts';
import AppStates from './AppStates';
import JobStatus from './JobStatus';
import UserTypes from './UserTypes';
export {
ActionTypes,
Accounts,
AppStates,
JobStatus,
UserTypes,
};
|
import React from 'react';
import DatePicker from "react-datepicker";
import '../../main.scss';
import './Profile.scss';
import "react-datepicker/dist/react-datepicker.css";
import {getProfile, setProfile, togglePage} from "../../actions";
import {connect} from "react-redux";
export class Profile extends React.Component {
constructor(props) {
super(props);
// this.state = ({
// 'name': '',
// 'surname': '',
// 'country': '',
// 'city': '',
// 'phone': '',
// 'company': '',
// 'position': '',
// 'birthDate': '',
// 'user_avatar': ''
// })
this.state = ({...props.profile});
}
handleProfile = ev => {
ev.preventDefault();
const formData = new FormData(ev.currentTarget);
this.props.setProfile(formData);
};
handleChange = ev => this.setState({ [ev.target.name]: ev.target.value });
handleBirth = date => this.setState({ birthDate: date });
goToLessons = () => {
console.log("switching");
};
// componentDidMount() {
// this.props.getProfile();
// }
// componentWillReceiveProps(nextProps, nextContext) {
// this.setState({...nextProps.profile});
// }
dateInput = ({onClick}) => (
<input className="profile__date--input" onClick={onClick}>
</input>
);
render() {
console.log(this.state);
const { name, surname, country, city, phone, company, position, birthDate, user_avatar } = this.state;
return (
<div className="profile">
<h1>Personal Account</h1>
<h2 id="profileError" className="profile__error--server" hidden>Wrong!</h2>
<form className="profile__form" onSubmit={this.handleProfile} name="loginForm" encType="multipart/form-data">
<div className="profile__flexible">
<div>
<div className="profile__item">
<label htmlFor="name">Name: </label><input className="profile__item" type="text" name="name" placeholder="name" value={name} onChange={this.handleChange} />
</div>
<h4 className="profile__error" id="nameError" hidden />
<div className="profile__item">
<label htmlFor="surname">Surname: </label><input className="profile__item" type="text" name="surname" placeholder="surname" value={surname} onChange={this.handleChange} />
</div>
<h4 className="profile__error" id="surnameError" hidden />
<div className="profile__item">
<label htmlFor="country">Country: </label><input className="profile__item" type="text" name="country" placeholder="country" value={country} onChange={this.handleChange} />
</div>
<h4 className="profile__error" id="countryError" hidden />
<div className="profile__item">
<label htmlFor="city">City: </label><input className="profile__item" type="text" name="city" placeholder="city" value={city} onChange={this.handleChange} />
</div>
<h4 className="profile__error" id="cityError" hidden />
<div className="profile__item">
<label htmlFor="phone">Phone: </label><input className="profile__item" type="text" name="phone" placeholder="phone" value={phone} onChange={this.handleChange} />
</div>
<h4 className="profile__error" id="phoneError" hidden />
<div className="profile__item">
<label htmlFor="company">Company: </label><input className="profile__item" type="text" name="company" placeholder="company" value={company} onChange={this.handleChange} />
</div>
<h4 className="profile__error" id="companyError" hidden />
<div className="profile__item">
<label htmlFor="position">Position: </label><input className="profile__item" type="text" name="position" placeholder="position" value={position} onChange={this.handleChange} />
</div>
<h4 className="profile__error" id="positionError" hidden />
</div>
<div className="profile__blocked">
<label htmlFor="birth_date">Date of Birth: </label>
<DatePicker
placeholderText="select..."
dateFormat="yyyy-MM-dd"
name='birth_date'
selected={birthDate}
customInput={this.dateInput(this)}
onChange={date => this.handleBirth(date) }/>
<label>Set avatar: </label>
<input type="file" name="user_avatar" id="user_avatar" onChange={this.handleChange} />
<label className="avatar" htmlFor="user_avatar">choose... </label>
{user_avatar !== '' ? <img className='profile__avatar' src={ user_avatar }/> : ''}
</div>
</div>
<button className="btnAction" type="submit" id="btnProfile">Confirm</button>
</form>
</div>
);
}
}
const mapStateToProps = state => {
return {
profile: state.profile
}
};
const mapDispatchToProps = dispatch => ({
togglePage: () => dispatch(togglePage()),
// getProfile: () => dispatch(getProfile()),
setProfile: (formData, profile) => dispatch(setProfile(formData, profile))
});
const ProfileContainer = connect(mapStateToProps, mapDispatchToProps)(Profile);
export default ProfileContainer;
|
import Navbar from "./Navbar";
import Sidebar from "./Sidebar";
import Footer from "./Footer";
import CartButtons from "./CartButtons";
import Hero from "./Hero";
import Contact from "./Contact";
import FeaturedProducts from "./FeaturedProducts";
import PageHero from "./PageHero";
import Services from "./Services";
import Error from "./Error";
import Loading from "./Loading";
import ProductImages from "./ProductImages";
import Stars from "./Stars";
import AddToCart from "./AddToCart";
import AmountButtons from "./AmountButtons";
import Filters from "./Filters";
import Sort from "./Sort";
import ProductList from "./ProductList";
import GridView from "./GridView";
import ListView from "./ListView";
import CartContent from "./CartContent";
import CartColumns from "./CartColumns";
import CartItem from "./CartItem";
import CartTotals from "./CartTotals";
export {
AddToCart,
AmountButtons,
CartButtons,
CartContent,
CartColumns,
CartItem,
CartTotals,
Contact,
Error,
FeaturedProducts,
Filters,
Footer,
GridView,
Hero,
ListView,
Loading,
Navbar,
PageHero,
ProductImages,
ProductList,
Services,
Sidebar,
Sort,
Stars,
};
|
import React, { Component } from 'react';
import classnames from 'classnames';
import { connect } from 'react-redux';
import {
Card,
CardBody,
CardHeader,
Col,
FormGroup,
Label,
Button
} from 'reactstrap';
import axios from 'axios';
class ChangePasswordAdmin extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
oldPassword: '',
newPassword: '',
newPassword1: '',
messageSucc:'',
messageErr:''
};
}
onChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
}
onSubmit = (e) => {
e.preventDefault();
}
clearMsg=()=>{
this.refs.oldPassword.innerHTML = '';
this.refs.newPassword.innerHTML = '';
this.refs.newPassword1.innerHTML = '';
}
_changePassword = () => {
this.clearMsg();
if(this.state.oldPassword === ''||
this.state.newPassword === ''){
if(this.state.oldPassword === "")this.refs.oldPassword.innerHTML = 'Vui lòng không bỏ trống';
if(this.state.newPassword === '')this.refs.newPassword.innerHTML = 'Vui lòng không bỏ trống';
return false;
}if(this.state.newPassword!==this.state.newPassword1){
this.refs.newPassword1.innerHTML = 'Mật khẩu không khớp';
return false;
}
this.setState({
isLoading: false
})
const user = {uid: this.props.auth.user.user_id, password: this.state.oldPassword, newPassword: this.state.newPassword1}
axios.put(`/api/auth/changePassword`,user).then(res => {
this.setState({
isLoading: false,
messageSucc: res.data.message,
messageErr:"",
oldPassword: '',
newPassword: '',
newPassword1: '',
})
}).catch(err => {
this.setState({messageErr:err.response.data.message, messageSucc:""});
});
}
render() {
return (
<div className="addProduct">
<div className="row">
<div className="col-md-8">
<Col xs="12" sm="12">
<Card>
<CardHeader>
<strong>Thay đổi mật khẩu</strong>
</CardHeader>
<CardBody>
<FormGroup>
{this.state.messageSucc===""?"":<div style={{width:'100%'}} className="alert alert-success" role="alert">{this.state.messageSucc}</div>}
{this.state.messageErr===""?"":<div style={{width:'100%'}} className="alert alert-danger" role="alert">{this.state.messageErr}</div>}
<Col xs="6">
<Label htmlFor="company">Mật khẩu cũ</Label>
<input ref=''
type="password"
className={classnames('form-control form-control-lg')}
name="oldPassword"
value={this.state.oldPassword}
onChange={this.onChange}
/>
<div style={{display:'block'}} ref='oldPassword' className="invalid-feedback"></div>
</Col>
</FormGroup>
<FormGroup>
<Col xs="6">
<Label htmlFor="company">Mật khẩu mới</Label>
<input ref=''
type="password"
className={classnames('form-control form-control-lg')}
name="newPassword"
value={this.state.newPassword}
onChange={this.onChange}
/>
<div style={{display:'block'}} ref='newPassword' className="invalid-feedback"></div>
</Col>
</FormGroup>
<FormGroup>
<Col xs="6">
<Label htmlFor="company">Nhập lại mật khẩu mới</Label>
<input ref=''
type="password"
className={classnames('form-control form-control-lg')}
name="newPassword1"
value={this.state.newPassword1}
onChange={this.onChange}
/>
<div style={{display:'block'}} ref='newPassword1' className="invalid-feedback"></div>
</Col>
</FormGroup>
<div style={{marginTop:20}}>
<FormGroup row className="my-0">
<Col col="3" sm="2" md="2" className="mb-3 mb-xl-0">
<Button style={{marginLeft:15}} block color="primary" onClick={this._changePassword}>Lưu</Button>
</Col>
</FormGroup>
</div>
</CardBody>
</Card>
</Col>
</div>
</div>
</div>
);
}
}
const mapStateToProps = state => ({
auth: state.auth,
errors: state.errors
});
export default connect(mapStateToProps, { })(ChangePasswordAdmin);
|
import React, { useEffect, useState } from 'react'
const Home= ()=> {
const [data , setData] = useState([])
useEffect(()=>
{
fetch("/allpost" ,{
headers:{
"Authorization":"Bearer "+localStorage.getItem("jwt")
}
}).then(res=>res.json()).then(result=>{
console.log(result)
setData(result.posts)
})
},[])
return (
<>
<div className="container mt-2" >
{
data.slice().reverse().map(item=>{
return(
<div className="card mb-4" style={{maxWidth:"700px" , margin:"auto" , backgroundColor:"rgba(255, 217, 0, 0.884)"}} >
{/* <img className="card-img-top " style={{width: "6%" , height:"1rem"}}} alt="not found"/> */}
{/* <p className="circle" style={{backgroundColor:"red",width:"15px"}}>{item.postedBy.name}</p> */}
<p className="card-title ml-4 m-4 text-uppercase" >{item.postedBy.name}</p>
<img className="card-img-top" style={{width: "100%" , height:"30rem"}} src={item.photo} alt="not found"/>
<div className="card-body">
<p className="card-text font-weight-bold ">{item.title}</p><hr style={{backgroundColor:"white"}}></hr>
<p className="card-text">{item.body}</p>
<a href={item.photo} className="btn btn-dark pl-4 pr-4" >Register</a>
</div>
</div>
)
})
}
</div>
</>
)
}
export default Home
|
import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { margin } from 'styled-system';
import { pick } from '@styled-system/props';
import { createPropTypes } from '@styled-system/prop-types';
import { visuallyHidden } from '../../styles/helpers';
import { deprecate } from '../../helpers/propTypes';
import { ScreenReaderOnly } from '../ScreenReaderOnly';
import { toggle, input, StyledIndicator, StyledOutline } from './styles';
const StyledToggle = styled('label')`
${toggle}
${margin}
`;
const StyledInput = styled('input')`
${visuallyHidden}
${input}
`;
function Toggle(props) {
const {
id,
value,
checked,
defaultChecked,
disabled,
onChange,
onFocus,
onBlur,
label,
required,
'aria-describedby': ariaDescribedBy,
'data-id': dataId,
...rest
} = props;
const systemProps = pick(rest);
return (
<StyledToggle htmlFor={id} disabled={disabled} {...systemProps}>
{label && <ScreenReaderOnly>{label}</ScreenReaderOnly>}
<StyledInput
id={id}
value={value}
defaultChecked={defaultChecked}
checked={checked}
disabled={disabled}
onChange={onChange}
onFocus={onFocus}
onBlur={onBlur}
required={required}
type="checkbox"
aria-describedby={ariaDescribedBy}
data-id={dataId}
/>
<StyledOutline checked={checked} />
<StyledIndicator checked={checked} />
</StyledToggle>
);
}
Toggle.displayName = 'Toggle';
Toggle.propTypes = {
'aria-describedby': PropTypes.string,
'data-id': PropTypes.string,
checked: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]),
defaultChecked: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]),
compact: deprecate(PropTypes.bool, 'Compact prop has been removed'),
disabled: PropTypes.bool,
id: PropTypes.string.isRequired,
label: PropTypes.string,
onChange: PropTypes.func,
onFocus: PropTypes.func,
onBlur: PropTypes.func,
required: PropTypes.bool,
value: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]),
...createPropTypes(margin.propNames),
};
export default Toggle;
|
import React from 'react';
import UserInfo from '../userInfo/UserInfo';
import './user-list.css';
import UserSearch from '../search/UserSearch';
class UserList extends React.Component {
render() {
return (
<div className="user-list">
<UserSearch {...this.props}/>
{
this.props.userList && this.props.userList.length > 0 ? (
this.props.userList.map(element => {
return (
<UserInfo user={element} {...this.props} key={element.id}/>
)
})
): ''
}
</div>
)
}
}
export default UserList;
|
var
expect = require('chai').expect,
sinon = require('sinon'),
lodown = require('../index'),
customers = require('./fixtures/customers.json');
describe('lodown', function() {
describe('each', function() {
it('should iterate an Array, applying action to each element, index of the element, and the collection', function() {
var action = sinon.spy();
lodown.each(customers, action);
expect(action.callCount).to.equal(customers.length);
customers.forEach(function(customer, index){
expect(action.calledWith(customer, index, customers)).to.be.true;
});
});
it('should iterate an Object, applying action for each value, key of value, and Object', function() {
var action = sinon.spy();
var customer = customers[0];
lodown.each(customer, action);
expect(action.callCount).to.equal(Object.keys(customer).length);
for(var key in customer) {
expect(action.calledWith(customer[key], key, customer)).to.be.true;
}
});
});
});
|
const utils = require('loopback-datasource-juggler/lib/utils')
const loopback = require('loopback')
const chai = require('chai')
const { expect } = chai
chai.use(require('chai-datetime'))
chai.use(require('dirty-chai'))
chai.use(require('sinon-chai'))
require('mocha-sinon')
// Create a new loopback app.
const app = loopback()
// Set up promise support for loopback in non-ES6 runtime environment.
global.Promise = require('bluebird')
// import our mixin.
require('../lib')(app)
// Connect to db
const dbConnector = loopback.memory()
const Item = loopback.PersistedModel.extend('item', {
name: String,
status: String,
readonly: Boolean,
readonlyRecalculated: Boolean,
promised: String,
}, {
mixins: {
Calculated: {
properties: {
created: 'calculateCreated',
readonly: {
callback: 'calculateReadonly',
recalculateOnUpdate: true,
},
promised: 'calculatePromised',
},
},
},
})
Item.calculateReadonly = function calculateReadonly(item) {
return item.status === 'archived'
}
Item.calculateCreated = function calculateCreated() {
return new Date()
}
Item.calculatePromised = function calculatePromised(item, cb) {
cb = cb || utils.createPromiseCallback()
process.nextTick(function() {
cb(null, 'As promised I get back to you!')
})
return cb.promise
}
// Attach model to db
Item.attachTo(dbConnector)
app.model(Item)
app.use(loopback.rest())
app.set('legacyExplorer', false)
beforeEach(function() {
this.sinon.spy(Item, 'calculateReadonly')
this.sinon.spy(Item, 'calculateCreated')
this.sinon.spy(Item, 'calculatePromised')
this.clock = this.sinon.useFakeTimers()
})
describe('Creating new items', function() {
describe('findOrCreate', function() {
beforeEach(function() {
return Item.findOrCreate({
name: 'Item 3',
status: 'new',
})
.then(item => (this.res = item[0]))
})
describe('basic', function() {
it('should call the defined callback once', function() {
expect(Item.calculateCreated).to.have.been.calledOnce()
})
it('should set property to the callbacks return value', function() {
expect(new Date(this.res.created)).to.equalDate(new Date('1970-01-01'))
})
})
describe('promise', function() {
it('should call the defined callback once', function() {
expect(Item.calculatePromised).to.have.been.calledOnce()
})
it('should set property to the callbacks return value', function() {
expect(this.res.promised).to.equal('As promised I get back to you!')
})
})
describe('recalculateOnUpdate', function() {
it('should call the defined callback once', function() {
expect(Item.calculateReadonly).to.have.been.calledOnce()
})
it('should set property to the callbacks return value', function() {
expect(this.res.readonly).to.equal(false)
})
})
})
describe('upsert', function() {
beforeEach(function() {
return Item.upsert({
name: 'Item 3',
status: 'new',
})
.then(item => (this.res = item))
})
describe('basic', function() {
it('should call the defined callback once', function() {
expect(Item.calculateCreated).to.have.been.calledOnce()
})
it('should set property to the callbacks return value', function() {
expect(new Date(this.res.created)).to.equalDate(new Date('1970-01-01'))
})
})
describe('promise', function() {
it('should call the defined callback once', function() {
expect(Item.calculatePromised).to.have.been.calledOnce()
})
it('should set property to the callbacks return value', function() {
expect(this.res.promised).to.equal('As promised I get back to you!')
})
})
describe('recalculateOnUpdate', function() {
it('should call the defined callback once', function() {
expect(Item.calculateReadonly).to.have.been.calledOnce()
})
it('should set property to the callbacks return value', function() {
expect(this.res.readonly).to.equal(false)
})
})
})
describe('save', function() {
beforeEach(function() {
const item = new Item({
name: 'Item',
status: 'new',
})
return item.save()
.then(updatedItem => (this.res = updatedItem))
})
describe('basic', function() {
it('should call the defined callback once', function() {
expect(Item.calculateCreated).to.have.been.calledOnce()
})
it('should set property to the callbacks return value', function() {
expect(new Date(this.res.created)).to.equalDate(new Date('1970-01-01'))
})
})
describe('promise', function() {
it('should call the defined callback once', function() {
expect(Item.calculatePromised).to.have.been.calledOnce()
})
it('should set property to the callbacks return value', function() {
expect(this.res.promised).to.equal('As promised I get back to you!')
})
})
describe('recalculateOnUpdate', function() {
it('should call the defined callback once', function() {
expect(Item.calculateReadonly).to.have.been.calledOnce()
})
it('should set property to the callbacks return value', function() {
expect(this.res.readonly).to.equal(false)
})
})
})
})
describe('Updating existing items', function() {
describe('save', function() {
beforeEach(function() {
const item = new Item({
name: 'Item',
status: 'new',
})
return item.save()
.then(updatedItem => {
updatedItem.status = 'archived'
return updatedItem.save()
})
.then(updatedItem => (this.res = updatedItem))
})
describe('basic', function() {
it('should call the defined callback once', function() {
expect(Item.calculateCreated).to.have.been.calledOnce()
})
it('should set property to the callbacks return value', function() {
expect(new Date(this.res.created)).to.equalDate(new Date('1970-01-01'))
})
})
describe('promise', function() {
it('should call the defined callback once', function() {
expect(Item.calculatePromised).to.have.been.calledOnce()
})
it('should set property to the callbacks return value', function() {
expect(this.res.promised).to.equal('As promised I get back to you!')
})
})
describe('recalculateOnUpdate', function() {
it('should call the defined callback twice', function() {
expect(Item.calculateReadonly).to.have.been.calledTwice()
})
it('should set property to the callbacks return value', function() {
expect(this.res.readonly).to.equal(true)
})
})
})
describe('upsert', function() {
beforeEach(function() {
const item = new Item({
name: 'Item',
status: 'new',
})
return item.save()
.then(updatedItem => {
updatedItem.status = 'archived'
return Item.upsert(updatedItem)
})
.then(updatedItem => (this.res = updatedItem))
})
describe('basic', function() {
it('should call the defined callback once', function() {
expect(Item.calculateCreated).to.have.been.calledOnce()
})
it('should set property to the callbacks return value', function() {
expect(new Date(this.res.created)).to.equalDate(new Date('1970-01-01'))
})
})
describe('promise', function() {
it('should call the defined callback once', function() {
expect(Item.calculatePromised).to.have.been.calledOnce()
})
it('should set property to the callbacks return value', function() {
expect(this.res.promised).to.equal('As promised I get back to you!')
})
})
describe('recalculateOnUpdate', function() {
it('should call the defined callback twice', function() {
expect(Item.calculateReadonly).to.have.been.calledTwice()
})
it('should set property to the callbacks return value', function() {
expect(this.res.readonly).to.equal(true)
})
})
})
describe('updateAttributes', function() {
beforeEach(function() {
const item = new Item({
name: 'Item',
status: 'new',
})
return item.save()
.then(updatedItem => updatedItem.updateAttribute('status', 'archived'))
.then(updatedItem => (this.res = updatedItem))
})
describe('basic', function() {
it('should call the defined callback once', function() {
expect(Item.calculateCreated).to.have.been.calledOnce()
})
it('should set property to the callbacks return value', function() {
expect(new Date(this.res.created)).to.equalDate(new Date('1970-01-01'))
})
})
describe('promise', function() {
it('should call the defined callback once', function() {
expect(Item.calculatePromised).to.have.been.calledOnce()
})
it('should set property to the callbacks return value', function() {
expect(this.res.promised).to.equal('As promised I get back to you!')
})
})
describe('recalculateOnUpdate', function() {
it('should call the defined callback twice', function() {
expect(Item.calculateReadonly).to.have.been.calledTwice()
})
it('should set property to the callbacks return value', function() {
expect(this.res.readonly).to.equal(true)
})
})
})
})
|
/*!
* Copyright (c) 2018 Digital Bazaar, Inc. All rights reserved.
*/
'use strict';
const ControllerProofPurpose = require('./ControllerProofPurpose');
module.exports = class AssertionProofPurpose extends ControllerProofPurpose {
constructor({
term = 'assertionMethod', controller,
date, maxTimestampDelta = Infinity} = {}) {
super({term, controller, date, maxTimestampDelta});
}
};
|
import { Navbar } from "../Common/Navbar/Navbar";
import { EventElements } from "./EventElements";
import { Container, Modal } from 'react-bootstrap';
import React, { Fragment } from "react";
import axios from 'axios';
import { FormCreateEditEvent } from './FormCreateEditEvent';
import './Events.css';
import Pagination from '../Common/Pagination/Pagination';
const URLEvents = 'http://localhost:3000/events';
export const Events = () => {
const [events, setEvents] = React.useState([]);
const [searchedEvents, setSearchedEvents] = React.useState([]);
const [eventToEdit, setEventToEdit] = React.useState({});
const [showEA, setShowEA] = React.useState(false);
const [title, setTitle] = React.useState("");
const [type, setType] = React.useState("");
const [currentPage, setCurrentPage] = React.useState(1);
const [postsPerPage] = React.useState(2);
const indexOfLastPost = currentPage * postsPerPage;
const indexOfFirstPost = indexOfLastPost - postsPerPage;
const currentPost = searchedEvents.slice(indexOfFirstPost, indexOfLastPost);
const paginate = (pageNumber) => setCurrentPage(pageNumber);
React.useEffect(() => {
getEvents();
}, [])
const getEvents = async () => {
const response = await axios.get(URLEvents);
setEvents(response.data);
setSearchedEvents(response.data);
}
const search = (e) => {
const searchedWord = e.target.value;
if (!searchedWord.length > 0) {
setSearchedEvents(events);
} else {
let searched = searchedEvents.filter(event => event.name.toLowerCase().includes(searchedWord.toLowerCase()));
setSearchedEvents(searched);
}
}
const handleShowEA = (type, event = {}) => {
setTitle(type + " Event");
setShowEA(true);
if (event) {
setEventToEdit(event);
}
}
const handleCloseEA = () => {
setShowEA(false);
}
return (
<div className="contentPage">
<Navbar></Navbar>
<div className="eventsPage">
<p id="title">Events</p>
<div id="btn-input">
<input id="searchInput" onChange={(e) => { search(e) }}></input>
<button id='btnAdd1' onClick={() => { handleShowEA("Add"); setType("add"); }} >Add new</button>
</div>
<div id="btnEvents">
{/* <button className="btnTypeEvents" >Ongoing</button>
<button className='btnTypeEvents' >Future</button>
<button className='btnTypeEvents' >Past</button> */}
</div>
<div className="eventsList">
{
currentPost && currentPost.map((event, index) => {
return (
<div key={index}>
<Container>
<EventElements nameEvent={event.name} descriptionEvent={event.description} dateEvent={event.date} timeEvent={event.time} locationEvent={event.location} />
</Container>
</div>
)
})
}
</div>
<Pagination
postsPerPage={postsPerPage}
totalPosts={searchedEvents.length}
paginate={paginate}
/>
</div>
<Fragment>
<Modal show={showEA} onHide={handleCloseEA} animation={false}>
<Modal.Header closeButton>
<Modal.Title id="lblTitle">{title}</Modal.Title>
</Modal.Header>
<Modal.Body>
<FormCreateEditEvent formType={type} handleCloseEA={handleCloseEA}></FormCreateEditEvent>
</Modal.Body>
<Modal.Footer>
</Modal.Footer>
</Modal>
</Fragment>
</div>
);
}
|
import Axios from "axios";
import { LOADING, LOADED, ERROR, UNASKED, aF } from ".";
const DIRECT_OBJECT = `ITEMS`;
const LOADING_ITEMS = `LOADING_` + DIRECT_OBJECT;
const LOADED_ITEMS = `LOADED_` + DIRECT_OBJECT;
const ERROR_ITEMS = `ERROR_` + DIRECT_OBJECT;
const ADD_ITEM = `ADD_ITEM`;
const DELETE_ITEM = `DELETE_ITEM`;
export const getItems = () => async dispatch => {
try {
dispatch(aF(LOADING_ITEMS));
const allItems = await Axios.get(`/api/items`);
dispatch(aF(LOADED_ITEMS, allItems.data));
} catch (e) {
dispatch(aF(ERROR_ITEMS, e));
}
};
const initialState = { status: UNASKED, collection: [] };
const allItems = (state = initialState, action) => {
switch (action.type) {
case LOADING_ITEMS:
return { ...state, status: LOADING };
case LOADED_ITEMS:
return { ...state, status: LOADED, collection: action.payload };
case ADD_ITEM:
return {
...state,
status: LOADING,
collection: [...state.collection, action.payload],
};
case DELETE_ITEM:
return {
...state,
status: LOADING,
collection: action.payload,
};
case ERROR_ITEMS:
return { ...state, status: ERROR };
default:
return state;
}
};
export default allItems;
|
/* Slider */
var slideIndex = 1;
showSlides(slideIndex);
// Next/previous controls
function plusSlides(n) {
showSlides(slideIndex += n);
}
// Montrer l'image en fonction de la dot choisi
function currentSlide(n) {
showSlides(slideIndex = n);
}
// Slider
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("dot");
if (n > slides.length) {
slideIndex = 1
}
if (n < 1) {
slideIndex = slides.length
}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex - 1].style.display = "block";
dots[slideIndex - 1].className += " active";
}
// Scrol top
$(function(){
$('body').append("<div id='scrolltop'><i class='fas fa-caret-square-up fa-3x'></i></div>");
$('#scrolltop').css ({
'position': 'fixed',
'width': '35px',
'height': '35px',
'bottom': '50px',
'right': '50px',
'display': 'none'
});
$(window).scroll(function(){
if ($(window).scrollTop()<350) {
$('#scrolltop').fadeOut();
} else {
$('#scrolltop').fadeIn();
}
});
$('#scrolltop').click(function(){
$('html, body').animate({scrollTop:'0'}, 'slow');
});
});
// slider
// Présentation des films de Buster keaton (index.html)
var slideIndexx = 0;
showSlidess();
function showSlidess() {
var i;
var slides = document.getElementsByClassName("miniSlides1");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndexx++;
if (slideIndexx > slides.length) {
slideIndexx = 1
}
slides[slideIndexx - 1].style.display = "block";
setTimeout(showSlidess, 5000); // Change image every 2 seconds
}
// Présentation des films de Harold Lloyd (index.html)
showSlidesss();
function showSlidesss() {
var i;
var slides = document.getElementsByClassName("miniSlides2");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndexx++;
if (slideIndexx > slides.length) {
slideIndexx = 1
}
slides[slideIndexx - 1].style.display = "block";
setTimeout(showSlidesss, 5000); // Change image every 2 seconds
}
// QUIZ //
// les questions
var Lequiz = [{
question: "En quelle année Buster Keaton se lance dans le cinéma ?",
reponse: {
a: '1915',
b: '1917',
c: '1922'
},
correctAnswer: 'b'
},
{
question: "Il obtient son premier grand rôle, dans :",
reponse: {
a: 'La maison démontable',
b: 'Frigo déménageur',
c: 'Frigo à l’Electric Hotel'
},
correctAnswer: 'a'
},
{
question: "Quel était son surnom ?",
reponse: {
a: 'L’homme qui ne rit jamais',
b: 'Le clown triste',
c: 'L’artiste burlesque'
},
correctAnswer: 'a'
},
{
question: "A partir de quand sa carrière décline ?",
reponse: {
a: 'Les années 20',
b: 'Les années 30',
c: 'Les années 40'
},
correctAnswer: 'b'
},
{
question: "quoi le reconnait-on ?",
reponse: {
a: 'Son costume 3 pièces',
b: 'Son canotier et ses lunettes',
c: 'Son cigare'
},
correctAnswer: 'b'
},
{
question: "En quelle année est-il né ?",
reponse: {
a: '1893',
b: '1898',
c: '1900'
},
correctAnswer: 'a'
},
{
question: "En quelle année est-il au sommet de sa carrière ?",
reponse: {
a: '1921',
b: '1923',
c: '1929'
},
correctAnswer: 'b'
},
{
question: "Quel est son film le plus célèbre ?",
reponse: {
a: 'Monte la haut',
b: 'Monte là-dessus',
c: 'Descend par là'
},
correctAnswer: 'b'
}
];
var quizContainer = document.getElementById('quiz');
var resultsContainer = document.getElementById('results');
var submitButton = document.getElementById('submit');
generateQuiz(Lequiz, quizContainer, resultsContainer, submitButton); //création du quiz
function generateQuiz(questions, quizContainer, resultsContainer, submitButton) {
function showQuestions(questions, quizContainer) {
// stock les élèments et les réponse choisi
var output = [];
var reponse;
// Pour chaque question
for (var i = 0; i < questions.length; i++) {
// premier reset de la liste
reponse = [];
// Pour chaque réponse possible
for (letter in questions[i].reponse) {
// ajout des radios
reponse.push(
'<label>' +
'<input type="radio" name="question' + i + '" value="' + letter + '">' +
letter + ': ' +
questions[i].reponse[letter] +
'</label>'
);
}
// ajout des questions et des réponses dans le output
output.push(
'<div class="question">' + questions[i].question + '</div>' +
'<div class="reponse">' + reponse.join('') + '</div>'
);
}
// combine le tout dans une seul string d'html et le met dans le html
quizContainer.innerHTML = output.join('');
}
function showResults(questions, quizContainer, resultsContainer) {
// récupère les reponsé des tableaux
var answerContainers = quizContainer.querySelectorAll('.reponse');
// garde un aperçu des réponse de l'utilisateur
var userAnswer = '';
var numCorrect = 0;
// pour chaque questions
for (var i = 0; i < questions.length; i++) {
// trouver la réponse sélectionner
userAnswer = (answerContainers[i].querySelector('input[name=question' + i + ']:checked') || {}).value;
// si la réponse est correct
if (userAnswer === questions[i].correctAnswer) {
// inrémentation au conteur de bonne réponse
numCorrect++;
// color en verre
answerContainers[i].style.color = 'lightgreen';
}
// si réponse incorrect ou non cocher
else {
// color en rouge
answerContainers[i].style.color = 'red';
}
}
// montre le nombre de bonne réponse
resultsContainer.innerHTML = numCorrect + ' out of ' + questions.length;
}
// montre les questions
showQuestions(questions, quizContainer);
// montre les réponse lors du click sur le bouton
submitButton.onclick = function() {
showResults(questions, quizContainer, resultsContainer);
}
}
|
import { KeyBlueButton, InvisibleButton } from "buttons";
import "style/Tutorial.less";
import { FormattedMessage as T, injectIntl, defineMessages } from "react-intl";
const messages = defineMessages({
step0Title: {
id: "tutorial.step.0.title",
defaultMessage: "What is the Decred Blockchain?",
},
step0TextBoldp1: {
id: "tutorial.step.0.text.bold.p1",
defaultMessage: "The blockchain is the heart of Decred, "
},
step0Textp1: {
id: "tutorial.step.0.text.p1",
defaultMessage: " where all activity that takes place is stored. It is like a global, decentralised spreadsheet or ledger that records all the activity that happens when Decred funds are transferred keeping track of how many tokens are sent, and what the balance of every account is.",
},
step0Textp2: {
id: "tutorial.step.0.text.p2",
defaultMessage: "The blockchain is used to confirm that new transactions are valid and that no fraud is taking place.",
},
step0Textp3: {
id: "tutorial.step.0.text.p3",
defaultMessage: "Decred uses an innovative hybrid proof-of-work (PoW) proof-of-stake (PoS) for validating the transactions, keeping the network secure and making decisions on the consensus rules.",
},
step0Textp4: {
id: "tutorial.step.0.text.p4",
defaultMessage: "In return for participation, miners (PoW) and stakers (PoS) are rewarded with newly generated Decred tokens.",
},
step1Title: {
id: "tutorial.step.1.title",
defaultMessage: "What is a Wallet?",
},
step1TextBoldp1: {
id: "tutorial.step.1.text.bold.p1",
defaultMessage: "Wallet is the tool for interacting with the blockchain and using the currency.",
},
step1Textp1: {
id: "tutorial.step.1.text.p1",
defaultMessage: "It can be used to send and receive Decred funds, and acts as a personal ledger of transactions.",
},
step1Textp2: {
id: "tutorial.step.1.text.p2",
defaultMessage: "Decrediton Wallet can also be used for participating in staking (PoS) and project governance by time-locking your funds in return for tickets.",
},
step2Title: {
id: "tutorial.step.2.title",
defaultMessage: "Key to Your Wallet",
},
step2Textp1: {
id: "tutorial.step.2.text.p1",
defaultMessage: "Wallets are determinstically generated by a wallet seed. The mnemonic",
},
step2TextBoldp1: {
id: "tutorial.step.2.text.bold.p1",
defaultMessage: "seed is a list of 33 words",
},
step2Textp12: {
id: "tutorial.step.2.text.p12",
defaultMessage: " that can be easily written down on a piece of paper for backup.",
},
step2Textp2: {
id: "tutorial.step.2.text.p2",
defaultMessage: "The seed works as a master key that stores all of the information needed to re-create the wallet at any time.",
},
step2Textp3: {
id: "tutorial.step.2.text.p3",
defaultMessage: "If the wallet encryption passphrase is forgotten or the wallet is destroyed (e.g. computer breaks), the seed can be used to recover the wallet. Same seed can also be used to export your wallet to other Decred wallet clients.",
},
step2Textp4: {
id: "tutorial.step.2.text.p4",
defaultMessage: "Failure to keep your seed key private can result in the theft of your entire wallet. Under no circumstanes should it ever be revealed to someone else.",
},
step3Title: {
id: "tutorial.step.3.title",
defaultMessage: "Staking and Governance",
},
step3Textp1: {
id: "tutorial.step.3.text.p1",
defaultMessage: "Participation in staking (PoS) requires only existing Decred funds."
},
step3TextLightp1: {
id: "tutorial.step.3.text.light.p1",
defaultMessage: "(Unlike Proof-of-Work (PoW) mining that requires computing resources and electricity)."
},
step3Textp2: {
id: "tutorial.step.3.text.p2",
defaultMessage: "Funds can be time-locked in return for tickets on the network. Tickets are chosen at random to vote on the validity of blocks. By average a ticket gets voted in 28 days"
},
step3TextLightp2: {
id: "tutorial.step.3.text.light.p2",
defaultMessage: "(possible maximum time period is 142 days)."
},
step3Textp22: {
id: "tutorial.step.3.text.p22",
defaultMessage: "A succesful vote returns the stakeholder a part of the Block Reward plus the original cost of the ticket. In case of missing the vote"
},
step3TextLightp22: {
id: "tutorial.step.3.text.pLight22",
defaultMessage: "(0.5% probability)"
},
step3Textp23: {
id: "tutorial.step.3.text.p23",
defaultMessage: ", the original cost of the ticket is safely returned to the user without the reward.",
},
step3Textp3: {
id: "tutorial.step.3.text.p3",
defaultMessage: "Changes are inevitable for all digital currencies, whether deciding on development matters or resolving unexpected problems. Decred’s innovative governance system is built into the blockchain. This allows for seamless adaption to changes while keeping the existing blockchain ecosystem safe. The same tickets are also used as voting power when deciding on consensus changes.",
},
step3Textp4: {
id: "tutorial.step.3.text.p4",
defaultMessage: "Staking encourages long term investment in Decred by giving the stakeholders decision-making power in projects governance as well rewarding them for participation."
},
step4Title: {
id: "tutorial.step.4.title",
defaultMessage: "Safety Tips",
},
step4TextBoldp1: {
id: "tutorial.step.4.text.bold.p1",
defaultMessage: "Only You are responsible for your security.",
},
step4Textp2: {
id: "tutorial.step.4.text.p2",
defaultMessage: "Always keep your seed key and password safe. If you lose your seed key or password, nobody else can recover it.",
},
step4Textp3: {
id: "tutorial.step.4.text.p3",
defaultMessage: "Make a backup of your seed key and password. Do not store it on your computer, instead write it down or print it out on a piece of paper or save it to a USB drive.",
},
step4Textp4: {
id: "tutorial.step.4.text.p4",
defaultMessage: "Do not store your seed key in a cloud storage or a password service. If your account gets compromised, so may your funds.",
},
step4Textp5: {
id: "tutorial.step.4.text.p5",
defaultMessage: "Do not enter your seed key to any phising website. Nobody can reverse, cancel or refund transactions if your wallet has been compromised.",
},
step4Textp6: {
id: "tutorial.step.4.text.p6",
defaultMessage: "When something doesn’t seem right or you don’t understand it ask questions and do research. Avoid making a decision based on fear.",
},
});
const TutorialPage = ({ intl, tutorialStep, onNextTutorialStep, onGoToStep, finishTutorial }) => {
return (
<div className="tutorial">
<div className={"tutorial-side step-" + tutorialStep}>
<div className={"tutorial-side-image step-" + tutorialStep}>
</div>
</div>
<div className="tutorial-main">
<div className="tutorial-main-header">
{{
0: intl.formatMessage(messages.step0Title),
1: intl.formatMessage(messages.step1Title),
2: intl.formatMessage(messages.step2Title),
3: intl.formatMessage(messages.step3Title),
4: intl.formatMessage(messages.step4Title),
}[tutorialStep]}
</div>
<div className="tutorial-main-text">
{{
0:
<Aux>
<div className="column">
<p><span className="bold">{intl.formatMessage(messages.step0TextBoldp1)} </span>{intl.formatMessage(messages.step0Textp1)}</p>
<p>{intl.formatMessage(messages.step0Textp2)}</p>
</div>
<div className="column">
<p>{intl.formatMessage(messages.step0Textp3)}</p>
<p>{intl.formatMessage(messages.step0Textp4)}</p>
</div>
</Aux>,
1:
<Aux>
<div className="column">
<p><span className="bold">{intl.formatMessage(messages.step1TextBoldp1)} </span>{intl.formatMessage(messages.step1Textp1)}</p>
<p>{intl.formatMessage(messages.step1Textp2)}</p>
</div>
</Aux>,
2:
<Aux>
<div className="column">
<p>{intl.formatMessage(messages.step2Textp1)}<span className="bold">{intl.formatMessage(messages.step2TextBoldp1)} </span>{intl.formatMessage(messages.step2Textp12)}</p>
<p>{intl.formatMessage(messages.step0Textp2)}</p>
<p>{intl.formatMessage(messages.step2Textp3)}</p>
</div>
<div className="column">
<p><span className="bold">{intl.formatMessage(messages.step2Textp4)}</span></p>
</div>
</Aux>,
3:
<Aux>
<div className="column">
<p><span className="bold">{intl.formatMessage(messages.step3Textp1)} </span>{intl.formatMessage(messages.step3TextLightp1)}</p>
<p><span className="bold">{intl.formatMessage(messages.step3Textp2)} </span>{intl.formatMessage(messages.step3TextLightp2)}<span className="bold">{intl.formatMessage(messages.step3Textp22)} </span>{intl.formatMessage(messages.step3TextLightp22)}<span className="bold">{intl.formatMessage(messages.step3Textp23)}</span></p>
</div>
<div className="column">
<p>{intl.formatMessage(messages.step3Textp3)}</p>
<p>{intl.formatMessage(messages.step3Textp4)}</p>
</div>
</Aux>,
4:
<Aux>
<div className="column">
<p><span className="bold">{intl.formatMessage(messages.step4TextBoldp1)} </span></p>
<p>{intl.formatMessage(messages.step4Textp2)}</p>
<p>{intl.formatMessage(messages.step4Textp3)}</p>
<p>{intl.formatMessage(messages.step4Textp4)}</p>
</div>
<div className="column">
<p>{intl.formatMessage(messages.step4Textp5)}</p>
<p><span className="bold">{intl.formatMessage(messages.step4Textp6)}</span></p>
</div>
</Aux>
}[tutorialStep]}
</div>
<div className="tutorial-main-toolbar">
<KeyBlueButton className="next-button" onClick={tutorialStep < 4 ? onNextTutorialStep : finishTutorial} >
<T id="tutorial.nextBtn" m={"Next"}/>
</KeyBlueButton>
<div className="tutorial-main-toolbar-step-indicators">
<div className={tutorialStep == 0 ? "current" : tutorialStep > 0 ? "checked" : ""} onClick={tutorialStep !== 0 ? ()=>onGoToStep(0) : null}></div>
<div className={tutorialStep == 1 ? "current" : tutorialStep > 1 ? "checked" : tutorialStep < 1 ? "unchecked" : ""} onClick={tutorialStep !== 1 ? ()=>onGoToStep(1) : null}></div>
<div className={tutorialStep == 2 ? "current" : tutorialStep > 2 ? "checked" : tutorialStep < 2 ? "unchecked" : ""} onClick={tutorialStep !== 2 ? ()=>onGoToStep(2) : null}></div>
<div className={tutorialStep == 3 ? "current" : tutorialStep > 3 ? "checked" : tutorialStep < 3 ? "unchecked" : ""} onClick={tutorialStep !== 3 ? ()=>onGoToStep(3) : null}></div>
<div className={tutorialStep == 4 ? "current" : tutorialStep > 4 ? "checked" : tutorialStep < 4 ? "unchecked" : ""} onClick={tutorialStep !== 4 ? ()=>onGoToStep(4) : null}></div>
</div>
{tutorialStep < 4 &&
<InvisibleButton className="skip-button" onClick={finishTutorial}>
<T id="tutorial.skipBtn" m={"Skip"}/>
</InvisibleButton>
}
</div>
</div>
</div>
);
};
export default injectIntl(TutorialPage);
|
import React from 'react';
import './stats.css';
const Stats = (props) =>
<section className="stat-container">
<img className="star-bloc" src={props.stats.bgImage} alt='' />
<div className="main-bloc">
<div className="text-bloc">
<h2 className="title" >{props.stats.title}</h2>
<p>{props.stats.about}</p>
</div>
<div className="card-bloc">
{props.stats.cards.map((card,i)=> (
<div key={i} className="card">
<img src={card.icon} alt='' />
<h3>{card.title}</h3>
<p>{card.content}</p>
</div>
))}
</div>
</div>
</section>
export default Stats
|
if(typeof(JS_LIB_LOADED)=='boolean')
{
// test to make sure rdf base class is loaded
if(typeof(JS_RDF_LOADED)!='boolean')
include(JS_LIB_PATH+'rdf/rdf.js');
// test to make sure file class is loaded
if (typeof(JS_FILE_LOADED)!='boolean')
include(JS_LIB_PATH+'io/file.js');
var JS_RDFFILE_FLAG_SYNC = 1; // load RDF source synchronously
var JS_RDFFILE_FLAG_DONT_CREATE = 2; // don't create RDF file (RDFFile only)
var JS_RDFFILE_FILE = "rdfFile.js";
function RDFFile(aPath, aFlags, aNameSpace, aID)
{
this.created = false;
if(aPath)
this._file_init(aPath, aFlags, aNameSpace, aID);
}
RDFFile.prototype = new RDF;
RDFFile.prototype._file_init = function (aPath, aFlags, aNameSpace, aID) {
aFlags = aFlags || JS_RDFFILE_FLAG_SYNC; // default to synchronous loading
if(aNameSpace == null) {
aNameSpace = "http://jslib.mozdev.org/rdf#";
}
if(aID == null) {
aID = "JSLIB";
}
// Ensure we have a base RDF file to work with
var rdf_file = new File(aPath);
if (!rdf_file.exists() && !(aFlags & JS_RDFFILE_FLAG_DONT_CREATE)) {
if (rdf_file.open("w") != JS_LIB_OK) {
return;
}
var filestr =
'<?xml version="1.0" ?>\n' +
'<RDF:RDF\n' +
' xmlns:'+ aID +'="'+ aNameSpace +'"\n' +
' xmlns:RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#">\n' +
'</RDF:RDF>\n';
jslibPrint("here4!\n");
if (rdf_file.write(filestr) != JS_LIB_OK) {
rdf_file.close();
return;
}
this.created = true;
}
rdf_file.close();
// Get a reference to the available datasources
var serv = Components.classes["@mozilla.org/network/io-service;1"].
getService(Components.interfaces.nsIIOService);
if (!serv) {
throw Components.results.ERR_FAILURE;
}
var uri = serv.newFileURI(rdf_file.nsIFile);
this._rdf_init(uri.spec, aFlags);
};
jslibDebug('*** load: '+JS_RDFFILE_FILE+' OK');
} // END BLOCK JS_LIB_LOADED CHECK
// If jslib base library is not loaded, dump this error.
else
{
dump("JS_RDFFILE library not loaded:\n" +
" \tTo load use: chrome://jslib/content/jslib.js\n" +
" \tThen: include('chrome://jslib/content/rdf/rdfFile.js');\n\n");
}
|
import $ from 'jquery'
/*=========================================
= State Landing Page =
=========================================*/
/**
* When the user hovers over the map, highlight the name of the state in the list. Likewise, when the user hovers over the state name in the list, highlight the state on the map.
*/
const StatesLanding = () => {
if ($('.statesLanding-mainContent').length) {
// Hover on list
$('.stateLink').hover(
function() {
let stateID = $(this).data('state')
highlightState(stateID, 'highlight')
},
function() {
let stateID = $(this).data('state')
highlightState(stateID, 'unhighlight')
}
)
// Hover on map
$('#map path, #map g, #map polygon')
.not($('.nolink'))
.hover(
function() {
let stateID = $(this).attr('id')
highlightList(stateID, 'highlight')
highlightState(stateID, 'highlight')
},
function() {
let stateID = $(this).attr('id')
highlightList(stateID, 'unhighlight')
highlightState(stateID, 'unhighlight')
}
)
// Inactive States
$('#map path.nolink, #map g.nolink').hover(
function(e) {
let x = e.clientX + 20 + 'px',
y = e.clientY + 20 + 'px'
let stateID = $(this).attr('id')
let state = stateID.replace(/-/g, ' ')
state = state.toUpperCase()
$('.statesLanding-map').append(
"<div class='tooltip' style='top: " +
y +
'; left: ' +
x +
"'><span>" +
state +
'</span><br /> No data available.</div>'
)
},
function() {
$('.statesLanding-map .tooltip').remove()
}
)
// Click on map and go to state page
$('#map path, #map g, #map polygon')
.not($('.nolink'))
.click(function() {
let stateID = $(this).attr('id')
location.href = '/states/' + stateID
})
}
}
function highlightState(stateID, action) {
let state = $('path#' + stateID + ', #' + stateID + ' path')
if (action == 'highlight') {
state.addClass('active')
} else {
state.removeClass('active')
}
}
function highlightList(stateID, action) {
let stateLink = $("a[data-state='" + stateID + "']")
if (action == 'highlight') {
stateLink.addClass('active')
} else {
stateLink.removeClass('active')
}
}
export default StatesLanding
|
const BaseModel = require('./BaseModel')
const _ = require('lodash')
class UserModel extends BaseModel {
constructor() {
super()
this.TableName = 'TT_User'
}
// 主键查询
async getUserById(inparam) {
let query = { key: { userId: inparam.userId }, project: ['userName', 'userId', 'createAt'] }
let res = await this.getItem(query)
return res.Item
}
// 索引查询
async queryUser(inparam) {
// 索引查询
// let query = {
// IndexName: 'userNameIndex',
// KeyConditionExpression: 'userName=:userName',
// ExpressionAttributeValues: {
// ':userName': inparam.userName
// }
// }
// 不指定索引 默认主分区查询
// let query = {
// KeyConditionExpression: 'userId=:userId',
// ExpressionAttributeValues: {
// ':userId': inparam.userId
// }
// }
// 查询分页示例
/**
* 注:测试发现 加了ScanIndexForward:false 降序返回的时候,临界值的时候也会返回LastEvaluatedKey
*
*/
let query = {
IndexName: 'groupNameIndex',
KeyConditionExpression: '#groupName=:groupName',
// ScanIndexForward: false, // 降序返回
Limit: 50, // 查询数量
ExpressionAttributeNames: {
'#groupName': 'groupName'
},
ExpressionAttributeValues: {
':groupName': inparam.groupName
}
}
if (inparam.LastEvaluatedKey) {
query.ExclusiveStartKey = inparam.LastEvaluatedKey
}
let res = await this.query(query)
console.log(res)
return
return res.Items
}
// 扫描查询
async scanUser(inparam) {
let scan = {
ProjectionExpression: 'userId,userName',
FilterExpression: 'sex = :sex',
Limit: 54,
ExpressionAttributeValues: {
':sex': inparam.sex
}
}
let res = await this.scan(scan)
console.log(res)
return
return res.Items
}
// 分页查询
async page() {
// ScanIndexForward: false, // 降序返回
// Limit:20, // 查询数量
}
// 插入数据
async putData(inparam) {
let itemData = {
userId: inparam.userId,
userName: inparam.userName,
createAt: inparam.createAt || Date.now()
}
let res = await this.putItem(itemData)
return res
}
// 更新数据
async updateData(inparam) {
// 构造更新数据
let updateItem = {
key: { userId: inparam.userId },
updateItem: { userName: inparam.userName }
}
// 调用数据库操作
let res = await this.updateItem(updateItem)
return res
}
// 删除数据
async deleteData(inparam) {
let deleteItem = {
key: { userId: inparam.userId }
}
let res = await this.deleteItem(deleteItem)
return res
}
// 批量写入数据 一次性最多能操作25个
async batchWriteUser(inparam) {
let putData = []
for (let item of inparam) {
putData.push({ action: 'put', data: item })
}
let batchArr = _.chunk(putData, 25)
for (let chunk of batchArr) {
await this.batchWrite(chunk)
}
}
}
// 测试示例
async function run() {
try {
// let res = await new UserModel().getUserById({ userId: '11' })
// let res = await new UserModel().queryUser({ userName: 'test50' })
// let res = await new UserModel().queryUser({ userId: '50' })
// let res = await new UserModel().queryUser({ groupName: 1 })
let res = await new UserModel().scanUser({ sex: 1 })
// let res = await new UserModel().putData({ userId: '1111', userName: 'test02' })
// let res = await new UserModel().updateData({ userId: '3', userName: 'test03' })
// let res = await new UserModel().deleteData({ userId: '0' })
// let data = [
// { action: 'update', tableName: 'TT_User', data: { userId: '0' }, updateItem: { userName: 'test0', groupName: 0 } },
// { action: 'put', tableName: 'TT_User', data: { userId: '200', userName: `test200`, createAt: Date.now(), updateAt: Date.now(), groupName: _.sample([0, 1]), sex: _.sample([0, 1]) } }
// { action: 'delete', tableName: 'TT_User', data: { userId: '200' } },
// ]
// let res = await new BaseModel().transcatWrite(data)
// let batchGetData = [
// { tableName: 'TT_User', key: { userId: '11' } ,project:['userId','userName']},
// { tableName: 'TT_User', key: { userId: '22' } ,project:['userId','userName']},
// { tableName: 'TT_Token', key: { userId: '11' } ,project:['aa','bb']}
// ]
// let res = await new BaseModel().batchGet(batchGetData)
// let transcatData = [
// { tableName: 'TT_User', key: { userId: '11' } ,project:['userId','userName']},
// { tableName: 'TT_User', key: { userId: '22' } ,project:['userId','userName']},
// { tableName: 'TT_Token', key: { userId: '11' } ,project:['aa','bb']}
// ]
// let res = await new BaseModel().transcatGet(transcatData)
// let data = [
// { action: 'put', tableName: 'TT_User', data: { userId: '200', userName: `test200`, createAt: Date.now(), updateAt: Date.now(), groupName: _.sample([0, 1]), sex: _.sample([0, 1]) } },
// { action: 'put', tableName: 'TT_Token', data: { id: '111111111', token: `dsfedcswfefe`, createAt: Date.now(), updateAt: Date.now() } },
// { action: 'delete', tableName: 'TT_User', data: { userId: '200' } },
// ]
// let res = await new BaseModel().batchWrite(data)
// let batchData = []
// for (let i = 0; i < 100; i++) {
// batchData.push({ userId: i.toString(), userName: `test${i}`, createAt: Date.now(), updateAt: Date.now(),groupName:_.sample([0,1]),sex:_.sample([0,1]) })
// }
// let res = await new UserModel().batchWriteUser(batchData)
console.log(1, res)
} catch (err) {
console.log(2, err)
return err
}
}
run()
|
import React from 'react';
import {View, Text, TextInput, TouchableOpacity, StyleSheet} from 'react-native';
import Heading from '../../../components/Heading';
import NumberPad from '../../../components/NumberPad';
export default class KeyPad extends React.Component {
render(){
return(
<View style={styles.container}>
<Heading />
<NumberPad />
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'rgb(71, 80, 92)'
},
})
|
var logueado = 0;
var idFacebook;
var idCliente;
var nombreCliente;
var emailCliente;
var telefonoCliente;
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);
js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function statusChangeCallback(response) {
if (response.status === 'connected') {
response.authResponse.accessToken;
logueado = 1;
$("#loginFacebook").hide();
$("#logoutFacebook").show();
FB.api('/me', {
fields: "id,about,age_range,picture,bio,birthday,context,email,first_name,gender,hometown,link,location,middle_name,name,timezone,website,work"
}, function(response) {
loguearFacebook(response);
idFacebook=response.id;
$("#nombreCliente").val(response.name);
$("#emailCliente").val(response.email);
$("#profileFullName").html(response.name);
$("#profilePicture").html("<img src='https://graph.facebook.com/" + response.id + "/picture?type=large' width='46' height='46'/>");
$("#profileFullNameX").html(response.name);
$("#profilePictureX").html("<img src='https://graph.facebook.com/" + response.id + "/picture?type=large' width='500' height='500'/>");
setTimeout(function(){
$("#modalLoginFacebook").modal("hide");
},500);
});
} else if (response.status === 'not_authorized') {
logueado = 0;
$("#loginFacebook").hide();
$("#logoutFacebook").show();
$("#nombreCliente").val("");
$("#emailCliente").val("");
$("#profileFullName").html("");
$("#profilePicture").html("");
$("#profileFullNameX").html("");
$("#profilePictureX").html("");
} else {
$("#loginFacebook").show();
$("#logoutFacebook").hide();
$("#nombreCliente").val("");
$("#emailCliente").val("");
$("#profileFullName").html("");
$("#profilePicture").html("");
$("#profileFullNameX").html("");
$("#profilePictureX").html("");
logueado = 0;
}
}
window.fbAsyncInit = function() {
FB.init({
appId: '1752586204975951',
cookie: true, // enable cookies to allow the server to access the session
xfbml: true, // parse social plugins on this page
version: 'v2.5' // use graph api version 2.5
});
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
function loguearFacebook(objetoFacebook){
$.ajax({
type: "POST",
url: "archivos/phps/logueoFacebook.php",
data: {
info: objetoFacebook
},
dataType: 'json'
}).done(function(respuesta) {
idCliente=respuesta;
llamarFavoritos(respuesta)
});
}
|
/**
* Module dependencies.
*/
var express = require('express'),
stylus = require('stylus'),
nib = require('nib');
var app = module.exports = express.createServer();
// stylus compiler
function compile(str, path) {
return stylus(str)
.set('filename', path)
.set('compress', false)
.use(nib());
}
// Configuration
app.configure(function(){
app.set('title', 'Droid Patterns');
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(stylus.middleware({ src: __dirname + '/public', compile: compile }));
app.use(app.router);
app.use(express.static( __dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
// Home
app.get('/', function(req, res){
res.render('index', {
title: 'Droid Patterns'
});
});
var photos = [
{ photo_id: '001', title: 'Twitter - Timeline', description: 'list of tweets', url: 'http://www.flickr.com/photos/takenbyhim/5511070544/'},
{ photo_id: '002', title: 'Gowalla - Dashboard', description: 'available features', url: 'http://www.flickr.com/photos/takenbyhim/5520051620/'},
{ photo_id: '003', title: 'Google Maps - Map', description: 'map view', url: 'http://www.flickr.com/photos/takenbyhim/5266338249/'},
];
var patterns = [
{ pattern_id: '001', title: 'Action Bar', description: 'Action Bar Pattern', url: 'http://www.flickr.com/photos/takenbyhim/sets/72157625486558361/'},
{ pattern_id: '002', title: 'Dashboard', description: 'Dashboard Pattern', url: 'http://www.flickr.com/photos/takenbyhim/sets/72157625910087928/'},
{ pattern_id: '003', title: 'Quick Action', description: 'Quick Action Pattern', url: 'http://www.flickr.com/photos/takenbyhim/sets/72157625910134946/'},
];
// list photos from specific pattern
app.get('/pattern/:pattern_id', function(req, res) {
res.render('photos', {
title: 'Pattern Name',
photos: photos
})
});
var apps = [
{ app_id: '001', title: 'Twitter', description: 'Twitter for Android', url: 'http://www.flickr.com/photos/takenbyhim/sets/72157626227506962/'},
{ app_id: '002', title: 'Gowalla', description: 'Gowalla for Android', url: 'http://www.flickr.com/photos/takenbyhim/sets/72157626095009021/'},
{ app_id: '003', title: 'Google Maps', description: 'Google Maps for Android', url: 'http://www.flickr.com/photos/takenbyhim/sets/72157625510610688/'},
];
// list photos from specific app
app.get('/app/:app_id', function(req, res) {
res.render('photos', {
title: 'App Name',
photos: photos
})
});
// Only listen on $ node app.js
if (!module.parent) {
app.listen(3000);
console.log("Express server listening on port %d", app.address().port);
}
|
'use strict';
const Parser = require('rss-parser');
const parser = new Parser();
parser.parseURL('https://sosnicaraguareporte.com/')
.then((feed) => {
console.log(feed.title);
feed.items.forEach(item => {
console.log(item.title + ':' + item.link)
});
});
|
import React from "react";
import { Link } from "gatsby";
import styled from "styled-components";
import colors from "../constants/colors";
const CloseIcon = () => (
<svg
fill={colors.white}
height="24"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" />
<path d="M0 0h24v24H0z" fill="none" />
</svg>
);
const Banner = styled.div`
display: flex;
align-items: center;
color: ${colors.white};
> p {
flex: 1;
}
`;
const BannerLink = styled(Link)`
color: ${colors.white};
:visited {
color: ${colors.white5};
}
`;
const CloseButton = styled.button`
background: none;
border: none;
:focus {
outline: none;
}
`;
class CookieBanner extends React.Component {
state = {
hideCookieBanner: true
};
componentDidMount() {
this.setState({
hideCookieBanner: localStorage.getItem("hideCookieBanner")
});
}
hideCookieBanner = () => {
localStorage.setItem("hideCookieBanner", true);
this.setState({
hideCookieBanner: true
});
};
render() {
return this.state.hideCookieBanner ? null : (
<Banner>
<p>
Um unsere Webseite für Sie optimal zu gestalten und fortlaufend
verbessern zu können, verwenden wir Cookies. Durch die weitere Nutzung
der Webseite stimmen Sie der Verwendung von Cookies zu. Weitere
Informationen zu Cookies erhalten Sie in unserer{" "}
<BannerLink to="datenschutz">Datenschutzerklärung</BannerLink>
</p>
<CloseButton
onClick={this.hideCookieBanner}
aria-label="Cookies akzeptieren"
>
<CloseIcon />
</CloseButton>
</Banner>
);
}
}
export default CookieBanner;
|
"use strict";
/* packages
========================================================================== */
var express = require("express");
var app = express();
var cors = require("cors");
var bodyParser = require("body-parser");
const { Logtail } = require("@logtail/node");
var Sentry = require('@sentry/node');
var fs = require("fs");
var mongoose = require("mongoose");
/* sentry
========================================================================== */
Sentry.init({ dsn: DEFAULT_SENTRY_DSN, environment: DEFAULT_ENV });
app.use(Sentry.Handlers.requestHandler());
/* controllers
========================================================================== */
var api = require("./app/api.js");
var databaseInit = require("./app/databaseInit.js");
/* cors configuration
========================================================================== */
var corsOpts = {
origin: DEFAULT_CORS_ORIGIN
};
app.options("/file/:id", cors(corsOpts)); // enable pre-flight request
/* app configuration
========================================================================== */
app.use(bodyParser.json());
/* log and files
========================================================================== */
app.locals.logger = new Logtail(DEFAULT_LOGGER_KEY);
if (!fs.existsSync("./files")) {
fs.mkdirSync("./files");
}
/* database connection
========================================================================== */
mongoose.connect(DEFAULT_DATABASE_URI, {
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true
}, function(err) {
if (err) {
app.locals.logger.error("Initialization: Error connecting to database '3dpreviewer'", {meta: {err: err.message}});
console.error("- ERROR connecting to database '3dpreviewer'\n " + err.message);
} else {
console.log("> Connected to database '3dpreviewer'");
databaseInit.deleteOldRecords(app);
databaseInit.loadDefaultDB(app);
}
});
/* API
========================================================================== */
app.get('/file', cors(corsOpts), api.getAll);
app.post('/file', cors(corsOpts), api.upload);
app.get('/file/:id', cors(corsOpts), api.getById);
app.delete('/file/:id', cors(corsOpts), api.deleteById);
app.get('/health', cors(), api.checkStatus);
/* app connection
========================================================================== */
app.use(Sentry.Handlers.errorHandler());
app.use((err, req, res, next) => { res.sendStatus(500); });
app.listen(process.env.PORT || DEFAULT_PORT, function () {
console.log("> 3D Previewer server running on http://localhost:" + (process.env.PORT || DEFAULT_PORT));
});
|
import '../src/App.css';
// import 'bootstrap/dist/css/bootstrap.min.css';
import React, { useState, useEffect } from 'react';
import SolarSystem from './components/SolarSystem';
import InfoDisplay from './components/InfoDisplay';
import Stars from './images/stars.png';
import TextData, {
mercuryData,
venusData,
earthData,
marsData,
jupiterData,
saturnData,
uranusData,
neptuneData,
} from './Textdata';
import Signup from './components/Signup';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import { AuthProvider } from './contexts/AuthContext';
import Dashboard from './components/Dashboard';
import Login from './components/Login';
import PrivateRoute from './components/PrivateRoute';
import ForgotPassword from './components/ForgotPassword';
import UpdateProfile from './components/UpdateProfile';
import MobileNavLinks from './components/MobileNavLinks';
import HamburgerMenu from './components/HamburgerMenu';
import RightSide from './components/RightSide';
import firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/auth';
import { useAuthState } from 'react-firebase-hooks/auth';
import { useCollectionData } from 'react-firebase-hooks/firestore';
function App() {
const [selected, setSelected] = useState(marsData);
const [showSettings, setShowSettings] = useState(false);
const [showNames, setShowNames] = useState(false);
return (
<>
{/* <div className='App' style={{ backgroundImage: `${Stars}` }}></div> */}
<BrowserRouter>
<AuthProvider>
<Route path='/'>
<div className='container2'>
<div className='empty-container'></div>
<RightSide
selectedPlanet={selected}
handleSelected={setSelected}
/>
<SolarSystem
showSettings={showSettings}
handleShowSettings={setShowSettings}
showNames={showNames}
handleShowNames={setShowNames}
/>
</div>
</Route>
<PrivateRoute exact path='/dashboard' component={Dashboard} />
<PrivateRoute path='/update-profile' component={UpdateProfile} />
<Route path='/signup' component={Signup} />
<Route path='/login' component={Login} />
<Route path='/forgot-password' component={ForgotPassword} />
<Route path='/mobile-nav-links' exact component={MobileNavLinks} />
</AuthProvider>
</BrowserRouter>
</>
);
}
export default App;
|
//////////////////////////////////////////////////////////
var texto="";
var email="";
var emailNovo="";
var senhaAntiga;
function efetuarAlteracoes(form)
{
var nome = $("#nome");
var tel = $("#tel");
email = $("#email");
emailNovo = $("#emailNovo");
var regExTel = /^(?:\+\d{2}\s?)??\(?\d{2}?\)?\s?\d{4,5}-?\d{4}$/;
var regExEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
var validaEmail = regExEmail.test(email.val());
var validaEmailNovo = regExEmail.test(emailNovo.val());
var validaTel = regExTel.test(tel.val());
if(validaSenha() && validaEmail && validaTel && nome.val() != "")
{
verificarEmailAntigo(form);
}
else
abrirModal("Verifique se os campos estão preenchidos corretamente!");
}
/////////////////////////////////////////////////////////////
var s = "";
verificarEmailAntigo = function(form)
{
$.ajax({
url : "http://localhost:3000/Acesso/"+ email.val()
}).done(function(dados){
$.each(dados, function(key, val){
s += val.senha;
return false;
})
console.log(s);
if(s != "")
{
senhaAntiga = s;
s="";
verificarEmailNovo();
}
else
abrirModal("Email antigo não consta no registro");
});
}
function verificarEmailNovo()
{
$.ajax({
url : "http://localhost:3000/Acesso/"+ emailNovo.val()
}).done(function(dados){
$.each(dados, function(key, val){
s += val.senha;
return false;
})
console.log(s);
if(s != "" && email.val() != emailNovo.val())
{
s="";
abrirModal("Email novo já consta no registro de outra conta");
}
else
{
if(senhaAntiga == $("#senha1").val())
alterar($("#formularioAlt"));
else
abrirModal("Senha não compatível com o email antigo fornecido");
}
});
}
/////////////////////////////////////////////////////////////
function validaSenha()
{
var senhaNova = $("#senha").val();
var senhaAntiga = $("#senha1").val();
var senhaConfirma = $("#senha2").val();
if(senhaNova === "" || senhaAntiga === "" ||senhaConfirma ==="")
{
senhaAntiga===""?$("#senhaNova").focus():$("#senhaConfirma").focus();
return false;
}
else if(senhaNova !== senhaConfirma)
{
$("#senha").focus();
return false;
}
return true;
}
//////////////////////////////////////////////////////////////////////
alterar = function(form){
$.post( "http://localhost:3000/UsuarioAlterar", form.serialize() ).done(function(data){
if (!data.erro) {
window.location.href = "AlteracaoEfetuada.html";
}
alert(data.mensagem);
});
window.location.href = "AlteracaoEfetuada.html";
};
/////////////////////////////////////////////////////////////////////////
var modal = document.getElementById("modalAviso");
var span = document.getElementsByClassName("close")[0];
abrirModal = function(texto){
$("#h5ModalAviso").html(texto);
modal.style.display = "block";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
};
span.onclick = function(){
modal.style.display = "none";
}
|
angular.module('Techtalk')
.factory('socket', function ($rootScope, config) {
if (typeof (io) != "undefined") {
var socket = io.connect(config.Urls.URLService, { reconnection: false });
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
}
};
}
return;
})
.directive('serverError', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
element.on('keydown', function () {
ctrl.$setValidity('server', true)
});
}
}
})
.directive('ngEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if (event.which === 13) {
scope.$apply(function () {
scope.$eval(attrs.ngEnter);
});
var $id = $("." + attrs.ngScrollBottomText);
$id.scrollTop($id[0].scrollHeight + 250);
event.preventDefault();
}
});
};
})
.directive("ngScrollBottom", function () {
return {
link: function (scope, element, attr) {
var $id = $("." + attr.ngScrollBottom);
$(element).on("click", function () {
$id.scrollTop($id[0].scrollHeight + 250);
$('.msg-field').focus();
});
}
}
});
|
var searchData=
[
['hploss',['HPLoss',['../classHPLoss.html',1,'']]]
];
|
import {BLOG_LIST_REQUEST, BLOG_LIST_FAIL, BLOG_LIST_SUCCESS, BLOG_CREATE_FAIL, BLOG_CREATE_REQUEST, BLOG_CREATE_SUCCESS, BLOG_GET_REQUEST, BLOG_GET_SUCCESS, BLOG_GET_FAIL} from '../constants/blogConstants'
export const blogListReducer = (state={blogs: []}, action) => {
switch(action.type){
case BLOG_LIST_REQUEST:
return {loading: true, blogs: []}
case BLOG_LIST_SUCCESS:
return {loading: false, blogs: action.payload}
case BLOG_LIST_FAIL:
return {loading: false, error: action.payload}
default:
return state
}
}
export const blogGetById = (state={blog:{}}, action) => {
switch(action.type){
case BLOG_GET_REQUEST:
return {loading: true, blog: {}}
case BLOG_GET_SUCCESS:
return {loading: false, blog: action.payload}
case BLOG_GET_FAIL:
return {loading: false, error: action.payload}
default:
return state
}
}
export const blogCreateReducer = (state={}, action) => {
switch(action.type){
case BLOG_CREATE_REQUEST:
return {loading: true}
case BLOG_CREATE_SUCCESS:
return {loading: false, blog: action.payload}
case BLOG_CREATE_FAIL:
return {loading: false, error: action.payload}
default:
return state
}
}
|
// Dependencies
const express = require('express');
const router = express.Router();
const path = require('path');
const exphbs = require("express-handlebars");
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
// Require our Articles and Comments Models
const Articles = require("./models/Articles.js");
const Comments = require("./models/Comments.js");
// Scraping Tools
var cheerio = require('cheerio');
var request = require('request');
// Scrape Route
app.get("/scrape", function(req, res) {
// Make a request call to grab the HTML body from the site of your choice
request("https://www.theatlantic.com/latest/", function(error, response, html) {
var $ = cheerio.load(html);
var result = {};
// Look for the specified clas
$("li.article").each(function(i, element) {
// grab the link
result.link = $(element).children().attr("href");
// Grabbing the title requires going for the child of the child with class .hed
result.title = $(element).children().children(".hed").text();
//Use the Articles Model to add each new article
var newArt = new Articles(result);
//Add the new Article to the DB. This will give it a unique ID. Using array would have only given the array the ID, not the entry
newArt.save(function(error, doc){
if (error) {
console.log(error);
}
else {
console.log(doc);
}
});
// Go back to the home page...or should we redirect to /articles after the scrape
res.redirect('/')
});
});
//Route to get all of the scraped articles
app.get("/articles", function (req, res) {
Articles.Find({}, function (error, doc) {
if (error) {
console.log(error);
}
else {
res.json(doc); //Send as JSON for front end to populate
}
});
});
// Get the articles by article ID and populate with the comments
app.get("/articles/:id", function(req, res) {
// Using the id passed in the id parameter, prepare a query that finds the matching one in our db
Article.findOne({ "_id": req.params.id })
.populate("Comments")
.exec(function(error, doc) {
if (error) {
console.log(error);
}
else {
res.json(doc);
}
});
});
app.post("/articles/:id", function(req, res) {
// Create a new comment and pass the req.body to the entry
var newComment = new Comments(req.body);
// And save the comment to the db
newCommment.save(function(error, doc) {
// Log any errors
if (error) {
console.log(error);
}
// Otherwise
else {
// Use the article id to find and update it's note
Articles.findOneAndUpdate({ "_id": req.params.id }, { "Comments": doc._id })
// Execute the above query
.exec(function(err, doc) {
// Log any errors
if (err) {
console.log(err);
}
else {
// Or send the document to the browser
res.send(doc);
}
});
}
});
});
// Export Router to server.js
module.exports = router;
|
import axios from 'axios';
const baseUrl = "/api/persons/";
const getAll = () => {
return axios.get(baseUrl);
}
const addNewPhone = (newObject) => {
return axios.post(baseUrl,newObject);
}
const updatePhone = (id,newObject) => {
return axios.put(baseUrl.concat(id),newObject);
}
const deletePhone = (id) => {
return axios.delete(baseUrl.concat(id));
}
export default {getAll,addNewPhone,deletePhone,updatePhone}
|
import * as types from '../constants'
const initialState = {
programs: [],
selectedProgram: null,
courses: [],
masterCourses: [],
currentCourse: null,
courseInfo: null,
hp: 0,
hpGradeMultiply: 0,
years: [],
selectedYear: null,
readyToCalculate: false,
index: 0,
specialisations: [],
}
export default function programsReducer (state = initialState, action) {
switch (action.type) {
case types.INCREASE_INDEX:
return {
...state,
index: state.index +1,
}
case types.SET_READY_TO_CALCULATE:
return {
...state,
readyToCalculate: true,
}
case types.ADD_PROGRAMS:
return {
...state,
programs: [...state.programs, ...action.payload],
}
case types.ADD_YEARS:
return {
...state,
years: [...state.years, ...action.payload],
}
case types.SELECT_PROGRAM:
return {
...state,
selectedProgram: action.payload,
}
case types.SELECT_YEAR:
return {
...state,
selectedYear: action.payload,
}
case types.GET_COURSES:
return {
...state,
courses: [...action.payload],
}
case types.GET_SPECIALISATIONS:
return {
...state,
specialisations: [...action.payload],
}
case types.SET_CURRENT_COURSE:
return {
...state,
currentCourse: action.payload,
}
case types.SET_COURSE_INFO:
return {
...state,
courseInfo: action.payload,
}
case types.ADD_HP:
return {
...state,
hp: state.hp + action.payload,
}
case types.ADD_HP_GRADE_MULTIPLY:
return {
...state,
hpGradeMultiply: state.hpGradeMultiply + action.payload,
}
case types.ADD_MASTER_COURSE:
return {
...state,
masterCourses: [...state.masterCourses, action.payload],
}
case types.ADD_TO_SPECIALISATIONS:
let temp = state.specialisations
let course = action.course
console.log(course);
for(let i = 0; i< action.specialisations.length; i++){
let index = getIndex(temp, action.specialisations[i], course)
if(index > -1){
temp[index] = {
...temp[index],
courses: [...temp[index].courses, course]
}
}
}
return {
...state,
specialisations: temp,
}
default:
return state
}
}
const getIndex = function(array, object, course){
let index = -1
for(let i = 0; i<array.length; i++){
if(array[i].title == object){
return i
}
}
return index
}
|
import React, {useRef} from 'react';
import { Dropdown } from 'semantic-ui-react';
import DateTimePicker from '../../DateTimePicker/DateTimePicker';
import './StatisticDevicePage.scss';
import StatisticDeviceTable from './StatisticDeviceTable/StatisticDeviceTable';
// import RoleBasedRender from '../RoleBasedRender/RoleBasedRender';
const mockInfo = [
{ object: '06.10.2019 14:30 — 15:00', readiness: 50 },
{ object: '06.10.2019 14:30 — 15:00', readiness: 40 },
{ object: '06.10.2019 14:30 — 15:00', readiness: 30 },
{ object: '06.10.2019 14:30 — 15:00', readiness: 20 },
];
const dateFilterOptions = [
{
key: '1 января 2019 - 1 сентября 2019',
text: '1 января 2019 - 1 сентября 2019',
value: '1 января 2019 - 1 сентября 2019',
},
{
key: '1 сентября 2019 - 1 октября 2019',
text: '1 сентября 2019 - 1 октября 2019',
value: '1 сентября 2019 - 1 октября 2019',
},
];
function StatisticDevicePage({ history, match }) {
const handleRowClick = event => history.push(`${ match.path }/1`);
const handleSubmit = event => console.log('Clicked Download');
const resetChanges = event => console.log('Clicked Cancel');
return (
<div>
<div className="statisticHeader">
<h1>Статистика <span>Прибор учёта 1</span></h1>
</div>
<div className='flex-row'>
{/* <Dropdown
defaultValue='1 января 2019 - 1 сентября 2019'
fluid
className="app-dropdown-button date-range-selector dropdown-margin"
selection
icon='angle down'
options={ dateFilterOptions }
/> */}
<DateTimePicker />
</div>
<div className='flex-row'>
<div>
<div className="regular-text">Поотребление</div>
<div className="balance-value">500000 кВт·ч</div>
</div>
<div className="method-calc">
<div className="regular-text">Способ определения объёма потребления</div>
<div className="balance-value">Приём</div>
</div>
</div>
<StatisticDeviceTable
objects={ mockInfo }
onRowClick={ handleRowClick }
/>
</div>
);
}
export default StatisticDevicePage;
|
//UTILIZAR AQUI OS TOKENS DE SUA CONTA PESSOAL DO PARSE
Parse.initialize();
$(document).ready(function() {
mostra_categorias();
//adiciona uma categoria, verificando se ela já não existe
$("#add_cat").click(function() {
if(confirm("Tem certeza que deseja adicionar essa categoria?")){
var categoria = Parse.Object.extend("categoria");
var categoria = new categoria();
var cat = document.getElementById('categoria').value;
var existe = false;
if (document.getElementById(cat)){
existe = true;
}
//verifica se a categoria não é nula ou se já não existe
if(cat != "" && !existe){
categoria.save({categoria: cat}, {
success: function(object) {
$("#errorUploading").addClass("alert alert-success");
$("#errorUploading").html("Categoria salva com sucesso!<i class=\"glyphicon glyphicon-remove remove_alert\"></i>");
},
error: function(model, error) {
$("#errorUploading").addClass("alert alert-danger");
$("#errorUploading").html("Houve um erro ao salvar a categoria. Tente novamente.<i class=\"glyphicon glyphicon-remove remove_alert\"></i>");
}
});
}else{
$("#errorUploading").addClass("alert alert-danger");
if(cat == ""){
$("#errorUploading").html("Formulário vazio!<i class=\"glyphicon glyphicon-remove remove_alert\"></i>");
}
if(existe){
$("#errorUploading").html("Essa categoria já existe!<i class=\"glyphicon glyphicon-remove remove_alert\"></i>");
}
}
}
mostra_categorias();
});
//deleta uma categoria ao clicar no X vermelho. Deleta também todos os cards dessa categoria
$(document).on("click", ".remove_categoria", function() {
var categoria = Parse.Object.extend("categoria");
var query_cat = new Parse.Query(categoria);
var cat = $(this).prop("title");
var object_id = $(this).attr('id');
if(confirm("Você quer mesmo deletar esta categoria? Todos os cards desta categoria também serão deletados.")){
query_cat.get(object_id, {
success: function(result) {
// The object was retrieved successfully.
result.destroy({
success: function(result) {
// The object was deleted from the Parse Cloud.
var card = Parse.Object.extend("card");
var query_card = new Parse.Query(card);
query_card.equalTo("categoria",cat);
query_card.find({
success: function(results) {
alert("Categoria deletada. Todos os cards dessa categoria também foram deletados.");
for (var i = results.length - 1; i >= 0; i--) {
var object = results[i];
object.destroy();
}
},
error: function(error) {
alert("Erro de busca: " + error.code + " " + error.message);
}
});
$("."+object_id).remove();
},
error: function(result, error) {
// The delete failed.
// error is a Parse.Error with an error code and message.
alert("Erro de exclusão: " + error.code + " " + error.message);
}
});
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
alert("Erro de busca: " + error.code + " " + error.message);
}
});
}
mostra_categorias();
});
//remove as mensagens de falha ou sucesso ao salvar um card/categoria
$(document).on("click", ".remove_alert", function() {
$("#errorUploading").removeClass("alert alert-danger");
$("#errorUploading").removeClass("alert alert-success");
$("#errorUploading").html("");
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.