text
stringlengths 7
3.69M
|
|---|
// Sets the date at the bottom of the jumbotron
$('#currentDay').text(moment().format('dddd, MMMM Do'))
// Creates an array to store the time-blocks for access later
let timeBlocks = []
// Creates an array to store events from localStorage
let currentEvents = JSON.parse(localStorage.getItem('currentEvents')) || []
// Creates section elements for timeblocks between 9AM and 5PM
for(let i = 0; i <= 8; i++) {
// Creates new section element, then adds classes
let block = $('<section>')
block.addClass("row time-block")
// Decides whether to use "AM" of "PM"
let timeCode = ''
if(i < 3) {
timeCode = "AM"
} else {
timeCode = "PM"
}
// Sets inner HTML for the block
block.html(`
<div class="col-sm-1 hour">${(((i + 8) % 12) + 1)}${timeCode}</div>
<textArea class="col-sm-10"></textArea>
<div class="col-sm-1 saveBtn">
<i class="fa fa-save save"></i>
</div>
`)
// Checks if the current time-block is in the past, present, or future and adds a class accordingly
if(i + 9 < moment().hour()) {
block.addClass('past')
} else if(i + 9 > moment().hour()) {
block.addClass('future')
} else {
block.addClass('present')
}
// Gives textArea the proper event if one has been saved previously
if(currentEvents[i] !== undefined) {
block.children("textArea").val(currentEvents[i])
}
// Adds block to timeBlocks array, then appends block to schedule container
timeBlocks.push(block[0])
$('#schedule').append(block)
}
// Listens for a click on the save icon in a saveBtn element
$("*").click(event => {
// Checks to ensure we have clicked the correct icon
if($(event.target).hasClass('save')) {
// Gets the text and stores it in newEvent
let newEvent = $(event.target).parent().parent().children("textArea").val()
// Gets index of the currently clicked block within the timeBlocks array
let index = jQuery.inArray($(event.target).parent().parent()[0], timeBlocks)
// Sets the correspondingly indexed element of currentEvents to have the newEvent text
currentEvents[index] = newEvent
// Sets the local storage to have the updated currentEvents array
localStorage.setItem('currentEvents', JSON.stringify(currentEvents))
}
})
|
var sound = require('./piezo/shutdown-sound.js');
var exec = require('child_process').exec;
var p;
process.on('exit', function(){
p.kill();
});
var wpi = require('wiring-pi');
wpi.wiringPiSetupPhys();
//which pin connect to button hit
var shutdownBtn = 40;
wpi.pinMode(40, wpi.INPUT);
while(true){
if(wpi.digitalRead(40) == 1){
sound.play();
p = exec('sudo shutdown');
process.exit();
}
}
|
import toArray from 'object/toArray';
import setDefault from 'object/setDefault';
console.log('setDefault', setDefault);
export default {
toArray,
setDefault
};
export {
toArray,
setDefault
};
|
module.exports = function(babel) {
var t = babel.types;
let globalScope = null;
const visitor = {
Program({scope}) {
globalScope = scope;
},
CallExpression(path) {
const {node} = path;
if (isFsReadFileSync(node.callee)) {
const filenameNode = node.arguments[0];
if (t.isCallExpression(filenameNode) && isRequireResolve(filenameNode.callee)) {
const moduleNode = filenameNode.arguments[0];
if (t.isStringLiteral(moduleNode)) {
path.replaceWith(
t.callExpression(t.identifier('require'), [
t.stringLiteral(`raw-loader!${moduleNode.value}`),
]),
);
}
}
}
},
};
function isFsReadFileSync(node) {
return (
t.isMemberExpression(node) &&
t.isIdentifier(node.object) &&
node.object.name === 'fs' &&
t.isIdentifier(node.property) &&
node.property.name === 'readFileSync'
);
}
function isRequireResolve(node) {
return (
t.isMemberExpression(node) &&
t.isIdentifier(node.object) &&
node.object.name === 'require' &&
t.isIdentifier(node.property) &&
node.property.name === 'resolve'
);
}
return {
visitor,
};
};
|
import Product from "./Models/Product.js"
import Value from "./Models/Value.js"
import { EventEmitter } from "./Utils/EventEmitter.js"
import { isValidProp } from "./Utils/isValidProp.js"
class AppState extends EventEmitter {
/** @type {Product[]} */
products = [
new Product({
id: 'carhart', name: 'jacket 3', price: 70, description: 'warm jacket', imgUrl: "https://encrypted-tbn3.gstatic.com/shopping?q=tbn:ANd9GcQLp0jaXA3-JTImJbBNJz-OlF-FI08zf4_fRJcQSY_fd-ugJ-oKkPWghOomc_VWYIzHS5mWVnLbOUE&usqp=CAc", quantity: 50
}),
new Product({
id: 'icepick', name: 'icepick 101', price: 25, description: 'cool tool to climb up ice sculptures', imgUrl: "https://images-na.ssl-images-amazon.com/images/I/31QiwKre0wL._AC_SY450_.jpg", quantity: 45
}),
new Product({
id: 'tire chains', name: 'tire chains 204', price: 100, description: 'to help your car not make you stranded', imgUrl: "https://images-na.ssl-images-amazon.com/images/I/31QiwKre0wL._AC_SY450_.jpg", quantity: 67
})
]
/** @type {Product[]} */
cart = []
}
export const ProxyState = new Proxy(new AppState(), {
get(target, prop) {
isValidProp(target, prop)
return target[prop]
},
set(target, prop, value) {
isValidProp(target, prop)
target[prop] = value
target.emit(prop, value)
return true
}
})
|
var G_EDITOR_OBJECT_EVENT_MOVE_SKIPPER = 0;
var G_EDITOR_OBJECT_EVENT_RESIZE_SKIPPER = 0;
var G_EDITOR_OBJECT_EVENT_ROTATE_SKIPPER = 0;
var G_EDITOR_TRANSLATE_MOVE = false;
var G_EDITOR_INFO = {
id: '',
title: '',
mode: DOCUMENT_EDITMODE_NONE,
orientation: '',
ratio: ''
};
// ruler 표시
function _onEditorCustomMouseMove(editorpos, objpos) {
editorRulerMove(editorpos[0], editorpos[1]);
}
function _onEditorCustomMouseOut() {
editorRulerHide();
}
function _onEditorBoxResize(e) {
var editorBoxWidth = $(this).width();
var editorBoxHeight = $(this).height();
var editorAreaWidth, editorAreaHeight;
var editorBlankWidth, editorBlankHeight;
editorAreaWidth = editorBoxWidth;
editorAreaHeight = editorBoxHeight;
do {
var ratio, ratioXY, ratioX, ratioY;
var scrollX, scrollY, t;
ratio = G_EDITOR_INFO['ratio'];
if (ratio == '') break;
ratioXY = ratio.split(':');
if (ratioXY.length != 2) break;
ratioX = parseFloat(ratioXY[0]);
ratioY = parseFloat(ratioXY[1]);
if (isNaN(ratioX) || isNaN(ratioY)) break;
if (G_EDITOR_INFO['orientation'] == ORIENTATION_LANDSCAPE) {
scrollX = G_MAIN_SCROLLBAR_SIZE;
scrollY = 0;
} else {
scrollX = 0;
scrollY = G_MAIN_SCROLLBAR_SIZE;
}
t = ratioY / ratioX;
editorAreaWidth = Math.round((editorBoxHeight - scrollX) / t) + scrollY;
editorAreaHeight = Math.round((editorBoxHeight));
if (editorAreaWidth > editorBoxWidth) {
t = ratioX / ratioY;
editorAreaWidth = Math.round((editorBoxWidth));
editorAreaHeight = Math.round((editorBoxWidth - scrollY) / t) + scrollX;
}
} while (false);
editorBlankWidth = editorBoxWidth - editorAreaWidth;
editorBlankHeight = editorBoxHeight - editorAreaHeight;
$('section .editor-blank-x').width(editorBlankWidth);
$('section .editor-blank-y').height(editorBlankHeight);
$('section .editor-area').width(editorAreaWidth);
$('section .editor-area').height(editorAreaHeight);
e.preventDefault();
e.stopPropagation();
$('.editor-area .object').trigger(EVT_EDITORRESIZE);
}
function editorInit() {
$('section .editor-box').on(EVT_RESIZE, _onEditorBoxResize);
controlInit();
// 편집기에서 객체 선택시 Control영역에 스타일등 표시
$(document).on(EVENT(EVT_SELECT, EVT_UNSELECT), '.editor-area .object', function (e) {
controlSetObject();
editorUpdateStatus();
});
$(document).on(EVT_DOCUMENT_UPDATE, function (e) {
editorUpdateStatus();
});
// 객체 이동/크기변경시 Control영역에 해당값 바로반영
// SKIPPER : 이벤트를 5번받으면 한번만 적용
$(document).on(EVENT(EVT_MOVE, EVT_MOVING), '.editor-area .object.selected', function (e) {
var layoutKeys = ['left', 'top', 'bottom', 'right'];
var styleKeys = ['transform-translate-x', 'transform-translate-y'];
var obj = $(this);
G_EDITOR_OBJECT_EVENT_MOVE_SKIPPER = INC_MOD(G_EDITOR_OBJECT_EVENT_MOVE_SKIPPER, 5);
if (G_EDITOR_OBJECT_EVENT_MOVE_SKIPPER != 0 && e.type == EVT_MOVING) return;
$.each(layoutKeys, function (idx, item) { controlLayoutSetData(item); });
$.each(styleKeys, function (idx, item) { controlStyleSetData(item); });
});
$(document).on(EVENT(EVT_RESIZE, EVT_RESIZING), '.editor-area .object.selected', function (e) {
var keys = ['left', 'top', 'bottom', 'right', 'width', 'height'], obj = $(this);
G_EDITOR_OBJECT_EVENT_RESIZE_SKIPPER = INC_MOD(G_EDITOR_OBJECT_EVENT_RESIZE_SKIPPER, 5);
if (G_EDITOR_OBJECT_EVENT_RESIZE_SKIPPER != 0 && e.type == EVT_RESIZING) return;
$.each(keys, function (idx, item) { controlLayoutSetData(item); });
});
$(document).on(EVENT(EVT_ROTATE, EVT_ROTATING), '.editor-area .object.selected', function (e) {
var keys = ['transform-rotate'], obj = $(this);
G_EDITOR_OBJECT_EVENT_ROTATE_SKIPPER = INC_MOD(G_EDITOR_OBJECT_EVENT_ROTATE_SKIPPER, 5);
if (G_EDITOR_OBJECT_EVENT_ROTATE_SKIPPER != 0 && e.type == EVT_ROTATING) return;
$.each(keys, function (idx, item) { controlStyleSetData(item); });
});
$(document).on(EVT_STYLECHANGE, '.editor-area .object.selected', function (e) {
var keys = ['background-image'], obj = $(this);
$.each(keys, function (idx, item) { controlStyleSetData(item); });
});
$('footer .status').on(EVT_MOUSECLICK, '> *', function (e) {
var uid = $(this).attr('data-uid');
var type = $(this).attr('data-type');
if (type == 'body') {
$('.editor-area').IEditor('unselect');
} else {
$('.editor-area').IEditor('select', $('.editor .object[data-uid="'+uid+'"]'));
}
});
}
function editorOpen(options) {
G_EDITOR_INFO['id'] = options.id;
G_EDITOR_INFO['title'] = options.title;
G_EDITOR_INFO['orientation'] = options.orientation;
G_EDITOR_INFO['mode'] = options.mode;
G_EDITOR_INFO['ratio'] = options.ratio;
$('section .editor-box').trigger(EVT_RESIZE);
docEditorInfoApply();
if ($('.editor-area *').length > 0) {
$('.editor-area').IEditor('destroy');
}
$('.editor-area').IEditor({
orientation: G_EDITOR_INFO['orientation'],
style: options.css,
data: options.data
//onCustomMouseMove: _onEditorCustomMouseMove,
//onCustomMouseOut: _onEditorCustomMouseOut
});
$('.editor-area').on(EVT_DRAWEND, function (e) {
toolSet(EDITOR_TOOL_SELECT);
e.preventDefault();
e.stopPropagation();
});
}
function editorUpdate(options) {
G_EDITOR_INFO['id'] = options.id;
G_EDITOR_INFO['title'] = options.title;
G_EDITOR_INFO['orientation'] = options.orientation;
G_EDITOR_INFO['mode'] = options.mode;
G_EDITOR_INFO['ratio'] = options.ratio;
$('section .editor-box').trigger(EVT_RESIZE);
docEditorInfoApply();
}
function editorClose() {
$('.editor-area').IEditor('destroy');
G_EDITOR_INFO['id'] = '';
G_EDITOR_INFO['title'] = '';
G_EDITOR_INFO['orientation'] = '';
G_EDITOR_INFO['mode'] = DOCUMENT_EDITMODE_NONE;
G_EDITOR_INFO['ratio'] = '';
$('section .editor-box').trigger(EVT_RESIZE);
docEditorInfoApply();
}
function editorGetData(parent) {
var datas = [];
$(parent).find(' > .object').each(function (idx, obj) {
var objData = {};
objData.id = $(obj).IObject('id');
objData.type = $(obj).IObject('getType');
objData.css = $(obj).IObject('css');
objData.data = $(obj).IObject('getData');
objData.lockMove = $(obj).IObject('getLockMove');
objData.lockResize = $(obj).IObject('getLockResize');
if (objData.type == OBJECT_TYPE_BOX) {
objData.items = editorGetData(obj);
}
datas.push(objData);
});
return datas;
}
function editorSetData(parent, data) {
var editor = $('.editor-area').data('inews-IEditor');
$.each(data, function (idx, objData) {
var obj = $('<div></div>').appendTo($(parent));
$(obj).IObject({
id: objData.id,
type: objData.type,
editor: editor,
style: objData.css,
data: objData.data
});
/* obj.IObject('id', objData.id);
$.each(objData.css, function (key, val) {
if (val.length > 1) {
obj.IObject('css', key, val[0], val[1]);
} else {
obj.IObject('css', key, val[0]);
}
});
$.each(objData.data, function (key, val) {
obj.IObject('setData', key, val);
});
*/
if (objData.type == OBJECT_TYPE_BOX) {
editorSetData(obj, objData.items);
}
obj.trigger(EVT_REDRAW);
});
}
function editorRulerMove(x, y) {
var rulerX = $('.editor-ruler-x .editor-ruler-arrow');
var rulerY = $('.editor-ruler-y .editor-ruler-arrow');
rulerX.css({
'visibility': 'visible',
'margin-left': x
});
rulerY.css({
'visibility': 'visible',
'margin-top': y
});
}
function editorRulerHide() {
var rulerX = $('.editor-ruler-x .editor-ruler-arrow');
var rulerY = $('.editor-ruler-y .editor-ruler-arrow');
rulerX.css({
'visibility': 'hidden',
'margin-left': 0
});
rulerY.css({
'visibility': 'hidden',
'margin-top': 0
});
}
function editorSetTranslateMove(val) {
G_EDITOR_TRANSLATE_MOVE = val;
}
function editorGetTranslateMove() {
return G_EDITOR_TRANSLATE_MOVE;
}
function editorUpdateStatus() {
var selected = $('.editor-area .object.selected');
var status = $('footer .status');
status.empty();
if (selected.length == 1) {
$.each($(selected).IObject('getPath'), function (i, obj) {
var span = $('<span></span>');
if (i == 0) span.addClass('light');
span.addClass('link');
span.attr('data-uid', obj.uid);
span.attr('data-type', obj.type);
span.html(SPRINTF('%s%s', obj.type, ((obj.id) ? '#'+obj.id : '')));
span.prependTo(status);
if (obj.type != 'body') $('<span></span>').html('>').prependTo(status);
});
}
}
|
import { distanceFindHandler } from './distanceFind';
export const closestCountry = (country1, countries) => {
let countryCode = country1;
const input = countryCode;
const inputCountry = countries.find(country => country.alpha3Code === input);
const boaders = inputCountry?.borders ? inputCountry.borders : [];
//Serched through the internet and found the largerst distence between two countries and assigned that as min distance
let minDistance = 19994;
let nearCountry = null;
countries.filter(country => !boaders.includes(country.alpha3Code)).forEach(country => {
const distance = distanceFindHandler(country.alpha3Code, input, countries);
if (distance && minDistance > distance) {
minDistance = distance;
nearCountry = country.name;
}
});
return nearCountry;
}
|
(function() {
if (typeof TFE === "undefined") {
window.TFE = {};
};
var Piece = TFE.Piece = function() {
this.combinable = true;
var rand = Math.random();
if (rand < .9) {
this.val = 2;
} else {
this.val = 4;
}
};
Piece.prototype.doubleVal = function(){
this.val = (this.val * 2);
this.combinable = false;
};
})();
|
// The comparison matrix
function ComparisonMatrix(items) {
var self = this;
self.items = items;
self.matrix = {};
self.explicitCount = 0;
_.each(self.items, function (item) {
self.matrix[item] = {};
self.matrix[item][item] = "=";
});
self.opposite = function (value) {
return value == "=" ? "=" : value == "<" ? ">" : "<";
};
self.get = function (a, b) {
if (self.matrix[a][b]) {
return self.matrix[a][b];
} else {
throw { items: [a, b] };
}
};
self.set = function (a, b, value) {
self.explicitCount++;
self.updateSingle(a, b, value);
self.updateSingle(b, a, self.opposite(value));
};
self.updateSingle = function (a, b, value) {
self.matrix[a][b] = value;
self.updateTransitive(a, b);
};
self.updateTransitive = function (a, b) {
if (self.matrix[a][b] == "=") {
// ((Cij = “=”) ⋀ (Cjk is known)) ⇒ Cik = Cjk
_.each(_.keys(self.matrix[b]), function (c) {
if (!self.matrix[a][c]) {
self.updateSingle(a, c, self.matrix[b][c]);
}
});
} else {
// (Cij ∈ { “<”, “>”}) ⋀ (Cjk ∈ {Cij, “=”}) ⇒ Cik = Cij
_.each(_.keys(self.matrix[b]), function (c) {
if (
!self.matrix[a][c] &&
(self.matrix[a][b] == self.matrix[b][c] || self.matrix[b][c] == "=")
) {
self.updateSingle(a, c, self.matrix[a][b]);
}
});
}
};
}
// This is the very simplest form of quick sort.
// Unknown comparison interrupt is done inside the matrix.get() method
function quickSort(x, matrix) {
var array = x;
function qsortPart(low, high) {
var i = low;
var j = high;
var x = array[Math.floor((low + high) / 2)];
do {
while (matrix.get(array[i], x) == ">") i++;
while (matrix.get(array[j], x) == "<") j--;
if (i <= j) {
var temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
} while (i <= j);
if (low < j) {
qsortPart(low, j);
}
if (i < high) {
qsortPart(i, high);
}
}
qsortPart(0, array.length - 1);
}
$(function () {
//on load
$("#error").hide();
var arrLang = {
en: {
"menu-home": "Home",
"menu-create": "Create a list",
"menu-contact": "Contact",
"create-a-list": "Create a list",
"input-header": "Type a list of items to be sorted",
"place-holder": "Enter each item on a new line",
error: "Minimum number of items = 2",
"trim-button": "Trim list before sorting",
"sort-now-button": "Sort NOW",
"discard-header": "Discard this one?",
"discard-button": "Discard?",
"keep-in-list-button": "Keep?",
"2left": "You only have 2 items left",
"submit-to-sort": "Sort",
"ask-header": "Which do you choose?",
"results-header": "Your prioritised list",
"explicit-count": "Total number of comparisons needed: ",
"start-over-fresh-button": "start over",
"start-over-same-button": "start over with same list",
"download-list": "Download List",
info: "A cuorum project",
contact: "info at cuorum dot org",
},
es: {
"menu-home": "Inicio",
"menu-create": "Crear una lista",
"menu-contact": "Contacto",
"create-a-list": "Crear una lista",
"input-header": "Escribe una lista de cosas para ordenar",
"place-holder": "Separar cada ítem con un salto de línea",
error: "Número mínimo de ítems = 2",
"trim-button": "Descartar ítems de la lista",
"sort-now-button": "Ordenar YA",
"discard-header": "Descartar o conserver este ítem?",
"discard-button": "Descartar",
"keep-in-list-button": "Conservar",
"2left": "Solo quedan 2 opciones",
"submit-to-sort": "Ordenar",
"ask-header": "Cuál eliges?",
"results-header": "Tu lista priorizada",
"explicit-count": "Numero de comparaciones: ",
"start-over-fresh-button": "Volver a empezar",
"start-over-same-button": "reempezar de nuevo (la misma lista)",
"download-list": "Descargar lista",
info: "Un proyecto de cuorum",
contact: "info arroba cuorum punto org",
},
cat: {
"menu-home": "Inici",
"menu-create": "Crear una llista",
"menu-contact": "Contacte",
"create-a-list": "Crear una llista",
"input-header": "Escriu una llista de coses per ordenar",
"place-holder": "Separar cada ítem amb un salt de línia.",
error: "Número mínim d'ítems = 2",
"trim-button": "Descartar ítems de la llista",
"discard-header": "Descartar o conserver aquest item?",
"discard-button": "Descartar",
"sort-now-button": "Ordenar JA",
"keep-in-list-button": "Conservar",
"2left": "Només quedan dues opciones",
"submit-to-sort": "Ordenar",
"ask-header": "Quin esculls?",
"results-header": "La teva llista prioritzada",
"explicit-count": "Nombre de comparacions requerits: ",
"start-over-fresh-button": "Tornar a començar",
"start-over-same-button": "comença de nou (la mateixa llista)",
"download-list": "Descarregar lista",
info: "Un projecte de cuorum",
contact: "info arroba cuorum punt org",
},
};
var lang = localStorage.getItem("lang");
// lang === null ? (lang = "en") : (lang = lang);
switch (lang) {
case "es":
$("#es").addClass("current-lang");
$("#en").removeClass("current-lang");
$("#cat").removeClass("current-lang");
break;
case "en":
$("#es").removeClass("current-lang");
$("#en").addClass("current-lang");
$("#cat").removeClass("current-lang");
break;
case "cat":
$("#es").removeClass("current-lang");
$("#en").removeClass("current-lang");
$("#cat").addClass("current-lang");
break;
default:
break;
}
console.log("language at load:", lang);
$(".lang").each(function (index, element) {
var lang = localStorage.getItem("lang");
lang === null ? (lang = "en") : (lang = lang);
console.log("lang in function", lang);
console.log("value of this", this);
console.log("value of index", index);
console.log("value of element", element);
if ($(element).is("textarea")) {
$(element).attr("placeholder", arrLang[lang][$(element).attr("key")]);
} else {
$(element).text(arrLang[lang][$(element).attr("key")]);
}
});
var matrix;
var lines;
var count = 0;
//////STRAIGHT TO SORT //////
$("#sort-now-button").click(function () {
var lines = [];
var items = [];
var count = 0;
//show each item in list
$.each($("#input-items").val().split(/\n/), function (i, line) {
if (line) {
items.push(line);
} else if (line == /\n/ || line == "") {
null;
// lines.push("");
}
});
items = [...new Set(items)];
if (items.length === 0) {
$("#input").hide();
$("#error").show();
// $("#textarea").attr("placeholder", "You cannot submit an empty list");
// $(this).text("You cannot submit an empty list");
var delay = 2000;
// var url = 'https://itsolutionstuff.com'
setTimeout(function () {
window.location.replace("list.html").reload();
}, delay);
// window.location.replace("list.html").reload();
}
// need error message
else {
$("#input").hide();
$("#to-be-discarded").hide();
$("#discard-page").hide();
$("#ask").show();
$("#results").hide();
console.log("OK");
localStorage.setItem("items", [...items]);
console.log("items in sort now", items);
$("results").hide();
matrix = new ComparisonMatrix(items);
tryQuickSort();
localStorage.setItem("items", [...items]);
console.log("items in sort now", items);
}
});
///DISCARD DIV ///
$("#discard-button").click(function () {
var lines = [];
var items = [];
var count = 0;
//show each item in list
$.each($("#input-items").val().split(/\n/), function (i, line) {
if (line) {
lines.push(line);
} else if (line == /\n/ || line == "") {
null;
// lines.push("");
}
});
lines = [...new Set(lines)];
console.log(lines.length);
$("#results").hide();
if (lines.length === 2) {
items = [...new Set(lines)];
localStorage.setItem("items", [...items]);
console.log("items length:", items.length);
$("#input").hide();
$("#to-be-discarded").hide();
$("#discard-page").hide();
$("#ask").show();
$("results").hide();
matrix = new ComparisonMatrix(items);
tryQuickSort();
localStorage.setItem("items", [...items]);
console.log("items in sort now", items);
} else if (lines.length === 1) {
items = [...new Set(lines)];
localStorage.setItem("items", [...items]);
console.log("items length =1");
$("#input").hide();
$("#to-be-discarded").hide();
$("#discard-page").hide();
$("#ask").hide();
$("results").hide();
matrix = new ComparisonMatrix(items);
tryQuickSort();
// localStorage.setItem("items", [...items]);
// console.log("items in sort now", items);
} else if (lines.length === 0) {
$("#input").hide();
$("#error").show();
// $("#textarea").attr("placeholder", "You cannot submit an empty list");
// $(this).text("You cannot submit an empty list");
var delay = 2000;
// var url = 'https://itsolutionstuff.com'
setTimeout(function () {
window.location.replace("list.html").reload();
}, delay);
// window.location.replace("list.html").reload();
} else {
localStorage.setItem("lines", [...lines]);
$("#input").hide();
$("#to-be-discarded").show();
$("#discard-page").show();
$("#ask").hide();
$("#to-be-discarded").html(lines[count]);
$("#keep-in-list-button").show();
$("#discard-from-list-button").show();
function nextQuestion() {
count++;
$("#to-be-discarded").html(lines[count]);
items = lines.filter((x) => x !== "*");
console.log("items", items);
localStorage.setItem("items", [...items]);
items.length === 2 ? $("#twoLeft").show() : null;
if (count === lines.length || items.length === 2) {
$("#discard-header").hide();
$("#to-be-discarded").hide();
$("#keep-in-list-button").hide();
$("#discard-from-list-button").hide();
$("#submit").show();
}
}
}
$("#discard-from-list-button").click(() => {
var newlines = lines.splice(count, 1, "*");
items.push(newlines[0]);
nextQuestion();
});
$("#keep-in-list-button").click(() => {
nextQuestion();
});
});
///ASK DIV (sorting)///
$("#submit").click(function (e) {
e.preventDefault();
var items = localStorage.getItem("items").split(",");
console.log(items);
$("results").hide();
matrix = new ComparisonMatrix(items);
tryQuickSort();
});
function tryQuickSort() {
items = localStorage.getItem("items").split(",");
console.log(items);
try {
quickSort(items, matrix);
showResults();
} catch (e) {
askUser(e.items[0], e.items[1]);
}
}
function askUser(a, b) {
$("#input").hide();
$("#discard-page").hide();
$("#ask").show();
$("results").hide();
$("#ask_a").text(a);
$("#ask_b").text(b);
}
$(".ask_answer").click(function (e) {
e.preventDefault();
var a = $("#ask_a").text();
var b = $("#ask_b").text();
var result = $(this).data("result");
matrix.set(a, b, result);
tryQuickSort();
});
///RESULTS DIV///
function showResults() {
$("#input").hide();
$("#ask").hide();
$("#results").show();
$("#results_list").html();
$("#explicit_count").text(matrix.explicitCount);
$("#explicit_count").show();
_(items).each(function (item) {
$("<li />").appendTo($("#results_list")).text(item);
});
}
$("#start_over_clean").click(function (e) {
window.location.replace("list.html").reload();
lines = [];
items = [];
});
$(".translate").click(function () {
var lang = $(this).attr("id");
localStorage.setItem("lang", lang);
switch (lang) {
case "es":
$("#es").addClass("current-lang");
$("#en").removeClass("current-lang");
$("#cat").removeClass("current-lang");
break;
case "en":
$("#es").removeClass("current-lang");
$("#en").addClass("current-lang");
$("#cat").removeClass("current-lang");
break;
case "cat":
$("#es").removeClass("current-lang");
$("#en").removeClass("current-lang");
$("#cat").addClass("current-lang");
break;
default:
break;
}
console.log("language changed");
console.log("language:", lang);
$(".lang").each(function (index, element) {
var lang = localStorage.getItem("lang");
console.log("lang", lang);
if ($(this).is("textarea")) {
$(this).attr("placeholder", arrLang[lang][$(this).attr("key")]);
} else {
$(this).text(arrLang[lang][$(this).attr("key")]);
}
});
});
});
// var set_lang = function (dictionary) {
// $("[data-translate]").each(function(){
// if($(this).is( "input" )){
// $(this).attr('placeholder',dictionary[$(this).data("translate")] )
// } else{
// $(this).text(dictionary[$(this).data("translate")])
// }
// })
// };
|
import TreeMapBase from './tree_map.base';
import { Tracker } from '../components/tracker';
import { expand } from '../core/helpers';
import { parseScalar as _parseScalar } from '../core/utils';
var DATA_KEY_BASE = '__treemap_data_';
var dataKeyModifier = 0;
var proto = TreeMapBase.prototype;
import './api';
import './hover';
import './tooltip';
proto._eventsMap.onClick = {
name: 'click'
};
var getDataKey = function getDataKey() {
var dataKey = DATA_KEY_BASE + dataKeyModifier++;
return dataKey;
};
expand(proto, '_initCore', function () {
var that = this;
var dataKey = getDataKey();
var getProxy = function getProxy(index) {
return that._nodes[index].proxy;
};
that._tracker = new Tracker({
widget: that,
root: that._renderer.root,
getNode: function getNode(id) {
var proxy = getProxy(id);
var interactWithGroup = _parseScalar(that._getOption('interactWithGroup', true));
return interactWithGroup && proxy.isLeaf() && proxy.getParent().isActive() ? proxy.getParent() : proxy;
},
getData: function getData(e) {
var target = e.target;
return (target.tagName === 'tspan' ? target.parentNode : target)[dataKey];
},
getProxy: getProxy,
click: function click(e) {
that._eventTrigger('click', e);
}
});
that._handlers.setTrackerData = function (node, element) {
element.data(dataKey, node._id);
};
});
expand(proto, '_disposeCore', function () {
this._tracker.dispose();
});
|
import React from 'react';
import { makeStyles, useTheme } from '@material-ui/core/styles';
import Drawer from '@material-ui/core/Drawer';
import List from '@material-ui/core/List';
import Divider from '@material-ui/core/Divider';
import IconButton from '@material-ui/core/IconButton';
import ChevronLeftIcon from '@material-ui/icons/ChevronLeft';
import ChevronRightIcon from '@material-ui/icons/ChevronRight';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import DashboardIcon from '@material-ui/icons/Dashboard';
import TodayIcon from '@material-ui/icons/Today';
import AssessmentIcon from '@material-ui/icons/Assessment';
import LiveHelpIcon from '@material-ui/icons/LiveHelp';
import InfoIcon from '@material-ui/icons/Info';
import Typography from '../../../Components/Typography';
const drawerWidth = 240;
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
},
appBar: {
transition: theme.transitions.create(['margin', 'width'], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
},
appBarShift: {
width: `calc(100% - ${drawerWidth}px)`,
marginLeft: drawerWidth,
transition: theme.transitions.create(['margin', 'width'], {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen,
}),
},
drawer: {
width: drawerWidth,
flexShrink: 0,
},
drawerPaper: {
width: drawerWidth,
},
drawerHeader: {
display: 'flex',
alignItems: 'center',
padding: theme.spacing(0, 1),
// necessary for content to be below app bar
...theme.mixins.toolbar,
justifyContent: 'flex-end',
},
content: {
flexGrow: 1,
padding: theme.spacing(3),
transition: theme.transitions.create('margin', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
marginLeft: -drawerWidth,
},
contentShift: {
transition: theme.transitions.create('margin', {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen,
}),
marginLeft: 0,
},
darawerFooter: {
position: 'absolute',
bottom: 0,
padding: theme.spacing(3),
},
}));
const Sidebar = (props) => {
const classes = useStyles();
const theme = useTheme();
const sidebarData = [
{ icon: <DashboardIcon />, name: 'Dashboard' },
{ icon: <TodayIcon />, name: 'Reminder' },
{ icon: <AssessmentIcon />, name: 'Reports' },
];
const sidebarInfoData = [
{ icon: <LiveHelpIcon />, name: 'Help' },
{ icon: <InfoIcon />, name: 'Info' },
];
return (
<Drawer
className={classes.drawer}
variant='persistent'
anchor='left'
open={props.open}
classes={{
paper: classes.drawerPaper,
}}
>
<div className={classes.drawerHeader}>
<IconButton onClick={props.handleDrawerClose}>
{theme.direction === 'ltr' ? (
<ChevronLeftIcon />
) : (
<ChevronRightIcon />
)}
</IconButton>
</div>
<Divider />
<div className={classes.darawerContent}>
<List>
{sidebarData.map((data, index) => (
<ListItem button key={index}>
<ListItemIcon>{data.icon}</ListItemIcon>
<ListItemText primary={data.name} />
</ListItem>
))}
</List>
<Divider />
<List>
{sidebarInfoData.map((data, index) => (
<ListItem button key={index}>
<ListItemIcon>{data.icon}</ListItemIcon>
<ListItemText primary={data.name} />
</ListItem>
))}
</List>
</div>
<Divider style={{ width: '100%' }} />
<div className={classes.darawerFooter}>
<Typography>V 1.0.1</Typography>
</div>
</Drawer>
);
};
export default Sidebar;
|
import React, { Component } from 'react';
import TreeViewFilterContainer from '../../containers/TreeViewFilterContainer';
import { Grid, Row, Col } from 'react-flexbox-grid';
import {Tabs, Tab} from 'material-ui/Tabs';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import NavigationFullscreenExit from 'material-ui/svg-icons/navigation/fullscreen-exit';
import Report from '../modules/Report'
import axios from 'axios';
import { complementaryColor, selectedColor, interactionProfileName, galaxyViewName, overviewName } from '../../utilities/constants';
import Overview from '../modules/Overview';
import GalaxyView from '../modules/GalaxyView';
import ProfileView from '../modules/ProfileView';
import ReportChipContainer from '../modules/ReportChipContainer';
import PropTypes from 'prop-types';
const styles = {
root: {
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'space-around',
},
floatingButton: {
position: 'absolute',
right: 30,
bottom: 30,
zIndex: 100
}
};
/**
* This component combines the ReportChipContainer, Overview, Galaxy View, Interaction Profile and Report View.
*/
class MainView extends Component {
constructor(props) {
super(props);
this.state = {
col: 4,
isGalaxyFullscreen: false,
isOverviewFullscreen: false,
isProfileFullscreen: false,
tableData: [],
tableTitle: '',
tableDrugs: [],
open: false,
width: 0,
height: 0,
currentReport: ''
}
this.toggleFullscreenOverview = this.toggleFullscreenOverview.bind(this);
this.toggleFullscreenGalaxy = this.toggleFullscreenGalaxy.bind(this);
this.toggleFullscreenProfile = this.toggleFullscreenProfile.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleOpen = this.handleOpen.bind(this);
this.handleClose = this.handleClose.bind(this);
this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
}
/**
* Set initial window dimensions and create window resize listener to automatically update them.
*/
componentDidMount() {
this.updateWindowDimensions();
window.addEventListener('resize', this.updateWindowDimensions);
}
/**
* Remove window resize listener on unmount.
*/
componentWillUnmount() {
window.removeEventListener('resize', this.updateWindowDimensions);
}
/**
* Update window dimensions using current measurements.
*/
updateWindowDimensions() {
this.setState({width: window.innerWidth, height: window.innerHeight});
}
/**
* If the tour is started while in fullscreen mode, exit fullscreen mode.
*/
componentWillReceiveProps(nextProps) {
if(nextProps.tourRunning !== this.props.tourRunning && nextProps.tourRunning === true) {
this.setState({col: 4, isGalaxyFullscreen: false, isOverviewFullscreen: false, isProfileFullscreen: false});
}
}
/**
* Open the reports view.
*
* @param {object} report contains information about type of report (drug/adr) and the drugs involved in the report
*/
handleOpen(report) {
// This part was commented out to avoid a waiting period before opening the report view for the drug/interaction that was last
// opened in the report view
// if (this.state.currentReport !== '' && this.state.currentReport.type === report.type &&
// _.isEqual(this.state.currentReport.drugs, report.drugs)
// ) {
// this.setState({
// open: true,
// });
// } else {
const title = report.type === 'drug' ? _.startCase(report.drugs[0]) : report.drugs.map((drug) => (_.startCase(drug))).join(" - ");
this.setState({
currentReport: report,
tableData: [],
open: true,
tableTitle: 'Reports for ' + title,
})
if (report.type === 'drug') {
axios.get('/csv/reports?drug=' + report.drugs[0])
.then(response => {
this.setState({
tableData: response.data,
tableDrugs: [report.drugs[0]],
});
if(this.props.currentSelector === '.galaxyReports') {
this.props.nextTourStep();
}
});
}
if (report.type === 'adr') {
axios.get('/csv/reports?drug1=' + report.drugs[0] + '&drug2=' + report.drugs[1])
.then(response => {
this.setState({
tableData: response.data,
tableDrugs: report.drugs,
});
});
}
// }
}
/**
* Close the reports view. If the tour is at the reports step, advance the tour.
*/
handleClose() {
this.setState({
open: false,
});
if(this.props.currentSelector === '.report') {
this.props.nextTourStep();
}
}
/**
* Fullscreen the Overview.
*/
toggleFullscreenOverview() {
this.setState((prevState, props) => {
return {
col: 12,
isOverviewFullscreen: true,
isProfileFullscreen: false,
isGalaxyFullscreen: false
}
})
}
/**
* Fullscreen the Galaxy View.
*/
toggleFullscreenGalaxy() {
this.setState((prevState, props) => {
return {
col: 12,
isOverviewFullscreen: false,
isGalaxyFullscreen: true,
isProfileFullscreen: false
}
})
}
/**
* Fullscreen the Interaction Profile View.
*/
toggleFullscreenProfile() {
this.setState((prevState, props) => {
return {
col: 12,
isOverviewFullscreen: false,
isGalaxyFullscreen: false,
isProfileFullscreen: true
}
})
}
/**
* Return the current tab based on which view is fullscreened.
*/
getTabsIndex() {
if (this.state.isOverviewFullscreen) {
return 0;
} else if (this.state.isGalaxyFullscreen) {
return 1;
} else if (this.state.isProfileFullscreen) {
return 2;
} else {
return 0;
}
}
/**
* Handle changing the tab index.
*
* @param {number} value new tab index
*/
handleChange(value) {
this.setState({
value: value,
});
}
render() {
let profileTitle = interactionProfileName;
if (this.props.selectedDrug != '') {
profileTitle += `: ${_.capitalize(this.props.selectedDrug)}`;
} else if (this.props.selectedRule != '') {
const drugsString = this.props.selectedRule.split(' --- ').map(drug => _.capitalize(drug)).join(' - ');
profileTitle += `: ${drugsString}`;
}
return (
<div>
<Grid fluid style={{ marginTop: 10, height: this.state.col === 12 ? 'calc(100% - 70px - 72px - 48px - 50px)' : 'calc(100% - 70px - 72px - 50px)'}}>
<FloatingActionButton
onClick={() => {this.setState({ col: 4, isOverviewFullscreen: false, isGalaxyFullscreen: false, isProfileFullscreen: false })}}
backgroundColor={complementaryColor}
style={{
position: 'absolute',
right: 20,
bottom: 70,
zIndex: 100,
display: this.state.col === 12 ? 'block' : 'none'
}}
>
<NavigationFullscreenExit />
</FloatingActionButton>
<ReportChipContainer
selectedRule={this.props.selectedRule}
deleteNode={this.props.deleteNode}
selectedDrug={this.props.selectedDrug}
clearSearchTerm={this.props.clearSearchTerm}
clearRule={this.props.clearRule}
links={this.props.links}
scoreRange={this.props.scoreRange}
handleOpen={this.handleOpen}
currentDrugs={this.props.currentDrugs}/>
<Row>
<Col xs={12} md={12}>
<Tabs style={{marginBottom: 0,
display: this.state.col === 4 ? 'none' : 'block'}}
inkBarStyle={{background: selectedColor, height: '4px', marginTop: '-4px'}}
value={this.getTabsIndex()}
onChange={this.handleChange}>
<Tab label={overviewName} style={{background: complementaryColor}} onActive={this.toggleFullscreenOverview} value={0}/>
<Tab label={<div style={{display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', width: '100%'}}><div style={{width: 48}}/>{galaxyViewName} <div style={{alignSelf: 'flex-end'}}><TreeViewFilterContainer /></div></div>} style={{background: complementaryColor}} onActive={this.toggleFullscreenGalaxy} value={1}/>
<Tab label={profileTitle} style={{background: complementaryColor}} onActive={this.toggleFullscreenProfile} value={2}/>
</Tabs>
</Col>
<Col xs={12} md={this.state.col} style={{
display: (this.state.col === 12 && (this.state.isProfileFullscreen || this.state.isGalaxyFullscreen)) ? 'none' : 'block',
}}
>
<Overview
col={this.state.col}
toggleFullscreenOverview={this.toggleFullscreenOverview}
onClickNode={this.props.onClickNode}
onClickEdge={this.props.onClickEdge}
currentSelector={this.props.currentSelector}
nodes={this.props.nodes}
links={this.props.links}
width={this.state.width}
height={this.state.height}
selectedDrug={this.props.selectedDrug}
isFetching={this.props.isFetching}
filter={this.props.filter}
minScore={this.props.minScore}
maxScore={this.props.maxScore}
isUpdating={this.props.isUpdating}
scoreRange={this.props.scoreRange}
nextTourStep={this.props.nextTourStep}
isOverviewFullscreen={this.state.isOverviewFullscreen}
status={this.props.status}
getStatus={this.props.getStatus}/>
</Col>
<Col xs={12} md={this.state.col} style={{
display: (this.state.col === 12 && (this.state.isProfileFullscreen || this.state.isOverviewFullscreen)) ? 'none' : 'block',
}}>
<GalaxyView
col={this.state.col}
toggleFullscreenGalaxy={this.toggleFullscreenGalaxy}
currentDrugs={this.props.currentDrugs}
filter={this.props.filter}
minScore={this.props.minScore}
maxScore={this.props.maxScore}
width={this.state.width}
height={this.state.height}
onClickNode={this.props.showDetailNode}
onClickEdge={this.props.onClickEdge}
onDeleteNode={this.props.deleteNode}
onClearDrug={this.props.clearSearchTerm}
handleOpen={this.handleOpen}
scoreRange={this.props.scoreRange}
dmeRange={this.props.dmeRange}
isGalaxyFullscreen={this.state.isGalaxyFullscreen}
selectedDrug={this.props.selectedDrug}/>
</Col>
<Col xs={12} md={this.state.col} style={{
display: (this.state.col === 12 && (this.state.isGalaxyFullscreen || this.state.isOverviewFullscreen)) ? 'none' : 'block',
}}>
<ProfileView
col={this.state.col}
toggleFullscreenProfile={this.toggleFullscreenProfile}
selectedDrug={this.props.selectedDrug}
selectedRule={this.props.selectedRule}
scoreRange={this.props.scoreRange}
filter={this.props.filter}
minScore={this.props.minScore}
maxScore={this.props.maxScore}
isProfileFullscreen={this.state.isProfileFullscreen}
profileTitle={profileTitle}/>
</Col>
</Row>
</Grid>
<Report
tableTitle={this.state.tableTitle}
open={this.state.open}
handleClose={this.handleClose}
tableData={this.state.tableData}
drugs={this.state.tableDrugs}
currentSelector={this.props.currentSelector}
nextTourStep={this.props.nextTourStep}
windowWidth={this.state.width} />
</div>
)
}
}
MainView.propTypes = {
/**
* Indicates whether the data is still being fetched for the nodes and links.
*/
isFetching: PropTypes.bool.isRequired,
/**
* Array of links representing all interaction between pairs of drugs in the visualization.
*/
links: PropTypes.array.isRequired,
/**
* Array of nodes representing all drugs in the visualization.
*/
nodes: PropTypes.array.isRequired,
/**
* Array of drugs currently in the Galaxy View.
*/
currentDrugs: PropTypes.array.isRequired,
/**
* Name of the currently selected drug.
*/
selectedDrug: PropTypes.string.isRequired,
/**
* Name of the currently selected rule (of format: drug_1 --- drug_2).
*/
selectedRule: PropTypes.string.isRequired,
/**
* Can be 'all', 'known', or 'unkown'. Corresponds to filtering interactions by known/unknown.
*/
filter: PropTypes.string.isRequired,
/**
* Minimum score for filtering interactions.
*/
minScore: PropTypes.number.isRequired,
/**
* Maximum score for filtering interactions.
*/
maxScore: PropTypes.number.isRequired,
/**
* Array of score boundaries, indicating how to color nodes/edges based on score.
*/
scoreRange: PropTypes.array.isRequired,
/**
* Array of severe ADR count boundaries, indicating how to color galaxy view headers.
*/
dmeRange: PropTypes.array.isRequired,
/**
* Contains information about the status of the last MARAS analysis ran.
*/
status: PropTypes.object.isRequired,
/**
* Callback used when a node is clicked. Takes the node as a parameter.
*/
onClickNode: PropTypes.func.isRequired,
/**
* Callback used when an edge is clicked. Takes the edge as a parameter.
*/
onClickEdge: PropTypes.func.isRequired,
/**
* Callback used when a node is clicked (Galaxy View). Takes the node as a parameter.
*/
showDetailNode: PropTypes.func.isRequired,
/**
* Callback used when a drug is removed from the galaxy view. Takes the drug name as a parameter.
*/
deleteNode: PropTypes.func.isRequired,
/**
* Used to indicate that the visualization is updating as a new filter has been applied. Takes a boolean indicating whether updating is in progress.
*/
isUpdating: PropTypes.func.isRequired,
/**
* Remove the currently selected rule from the Interaction Profile.
*/
clearRule: PropTypes.func.isRequired,
/**
* Remove the currently selected drug from the Interaction Profile.
*/
clearSearchTerm: PropTypes.func.isRequired,
/**
* Used to get updated information about the status of the last MARAS analysis ran.
*/
getStatus: PropTypes.func.isRequired
};
export default MainView;
|
import produce from 'immer';
import {
createAgreementAction,
getPostAction,
getPostsAction,
} from './actions';
import {
genericReducer,
namedEntityParams,
namedListParams,
} from '../../dataProvider/routineUtils';
export const initialState = {
posts: namedListParams('posts'),
post: namedEntityParams('post'),
agreement: namedEntityParams('agreement'),
};
const homeReducer = (state = initialState, action) =>
produce(state, draft => {
switch (action.type) {
case getPostAction.REQUEST:
case getPostAction.SUCCESS:
case getPostAction.FAILURE:
genericReducer(state, draft, action, initialState.post.name);
break;
case getPostsAction.REQUEST:
case getPostsAction.SUCCESS:
case getPostsAction.FAILURE:
genericReducer(state, draft, action, initialState.posts.name);
break;
case createAgreementAction.REQUEST:
case createAgreementAction.SUCCESS:
case createAgreementAction.FAILURE:
genericReducer(state, draft, action, initialState.agreement.name);
break;
default:
break;
}
});
export default homeReducer;
|
import Head from "~/components/atoms/head/Head";
import WithAuthentication from "~/Authentication/withAuthentication";
import CmsPage from "~/components/templates/cmsPage/CmsPage";
import StyledDashboard from "./index.style";
import Title from "~/components/atoms/title/Title";
const Dashboard = function () {
return (
<>
<Head title="Dashboard - TravelOcto" />
<CmsPage title="Dashboard">
<StyledDashboard>
<Title component="h1" variant="h1">
Welkom
</Title>
</StyledDashboard>
</CmsPage>
</>
);
};
export default WithAuthentication(Dashboard);
|
import React, { Component } from 'react'
export default class Counter extends Component {
constructor(props){
super(props)
this.state = {
count: 0
}
}
incrementChanges= () =>{
// if (incrementNumber){
// this.setState(prevState =>{
// return { count: prevState.count + incrementNumber }
// }
// )
// }else{
this.setState(prevState =>{
return { count: prevState.count + 1 }
}
)
// }
}
render() {
return (
<div>
{this.props.render(this.state.count, this.incrementChanges)}
</div>
)
}
}
|
import React from 'react'
const Oppmuntring = (props) => {
return (
<div className="oppmuntring">
<h1>Kom igjen {props.navn}</h1>
<p>{props.emne} er ikke så vanskelig som du tror.</p>
<p>Du må bare øve</p>
</div>
)
}
export default Oppmuntring
|
import Queue from './Queue'
import Request from './Request'
import utils from './utils'
function Frisbee (options) {
var queue = new Queue()
options = options || {}
var maxItems = options.maxItems || 5
var xhrOptions = utils.getXhrOptions(options)
var meta = utils.getMeta(options)
var getRequestData = typeof options.getRequestData === 'function'
? options.getRequestData
: utils.getRequestData
var send = function (quantity) {
var data = queue.dequeue(quantity)
var xhr = new Request(xhrOptions)
var requestData = getRequestData(data, meta)
if (requestData) {
xhr.send(requestData)
}
}
this.add = function (item) {
queue.enqueue(item)
if (queue.length === maxItems) {
send(maxItems)
}
}
this.sendAll = function () {
var queueLength = queue.length
if (!queueLength) {
return
}
send(queueLength)
}
}
export default Frisbee
|
/**
* Created by user on 01.04.15.
*/
'use strict';
angular.module('crm')
.controller('EditClientModalCtrl',function($scope, $timeout, $filter, data, close, $rootScope,
ClientSetup, DataStorage, Notification, DataProcessing) {
$scope.fields1 = {};
$scope.fields3 = {};
$scope.fields4 = {};
$scope.saved = false;
$scope.clientInfo = 'ActiveElement';
$scope.apiTabClass = false;
$scope.clientDetails = false;
$scope.modalTitle = data.modalTitle;
$scope.fieldOptions1 = ClientSetup.clientEditFormFields();
$scope.fieldOptions3 = ClientSetup.clientEditApiFormFields();
$scope.fieldOptions4 = ClientSetup.clientEditDetailsFormFields();
if (data.clientObj) {
var countrySelectValue = $filter('filter')($scope.fieldOptions4.countrySelectOptions.data, {id: data.clientObj.CountryId}, true)[0];
data.clientObj.IsActive ? $scope.fieldOptions1.activeRLOptions.data[0].checked = 'checked' : $scope.fieldOptions1.activeRLOptions.data[1].checked = 'checked';
data.clientObj.Address1 ? $scope.fields1.address1TxtValue = data.clientObj.Address1 : false;
data.clientObj.Address2 ? $scope.fields1.address2TxtValue = data.clientObj.Address2 : false;
data.clientObj.State ? $scope.fields1.stateTxtValue = data.clientObj.State : false;
data.clientObj.ZipCode ? $scope.fields1.zipTxtValue = parseInt(data.clientObj.ZipCode) : false;
data.clientObj.Phone ? $scope.fields1.phoneTxtValue = parseInt(data.clientObj.Phone) : false;
data.clientObj.LastName ? $scope.fields1.lastnameTxtValue = data.clientObj.LastName : false;
data.clientObj.FirstName ? $scope.fields1.firstnameTxtValue = data.clientObj.FirstName : false;
data.clientObj.Email ? $scope.fields1.emailTxtValue = data.clientObj.Email.replace(/ /g,'') : false;
data.clientObj.CompanyName ? $scope.fields1.companynameTxtValue = data.clientObj.CompanyName : false;
data.clientObj.City ? $scope.fields1.cityTxtValue = data.clientObj.City : false;
data.clientObj.PrimaryContact ? $scope.fields1.primaryContactTxtValue = data.clientObj.PrimaryContact : false;
data.clientObj.ApiUsername ? $scope.fields3.loginTxtValue = data.clientObj.ApiUsername : false;
data.clientObj.ApiPassword ? $scope.fields3.passwordTxtValue = data.clientObj.ApiPassword : false;
// fields 4
data.clientObj.CountryId || data.clientObj.CountryId==0 ? $scope.fields4.countrySelectValue = countrySelectValue : false;
data.clientObj.ReferralSource ? $scope.fields4.referralSourceTxtValue = data.clientObj.ReferralSource : false;
data.clientObj.DateEntered ? $scope.fields4.dateCreatedNoEditTxtValue = DataProcessing.toDateFormat(data.clientObj.DateEntered * 1000) : false;
data.clientObj.DateModified ? $scope.fields4.dateEditedNoEditTxtValue = DataProcessing.toDateFormat(data.clientObj.DateModified * 1000) : false;
data.clientObj.ExpirationDate ? $scope.fields4.expirationDateValue = DataProcessing.toDateFormat(data.clientObj.ExpirationDate * 1000) : false;
data.clientObj.Terms ? $scope.fields4.termsTxtValue = data.clientObj.Terms : false;
data.clientObj.PaymentMethod ? $scope.fields4.paymentMethodTxtValue = data.clientObj.PaymentMethod : false;
data.clientObj.AccountNumber ? $scope.fields4.accountNumberTxtValue = parseInt(data.clientObj.AccountNumber) : false;
data.clientObj.RoutingNumber ? $scope.fields4.routingNumberTxtValue = parseInt(data.clientObj.RoutingNumber) : false;
data.clientObj.AccountManager ? $scope.fields4.accountManagerTxtValue = data.clientObj.AccountManager : false;
data.clientObj.LicenseFee ? $scope.fields4.licenseFeeTxtValue = data.clientObj.LicenseFee : false;
data.clientObj.TransactionFee ? $scope.fields4.transactionFeeTxtValue = data.clientObj.TransactionFee : false;
data.clientObj.SiteSetupFee ? $scope.fields4.siteSetupFeeTxtValue = data.clientObj.SiteSetupFee : false;
data.clientObj.ProgrammingFee ? $scope.fields4.programmingFeeTxtValue = data.clientObj.ProgrammingFee : false;
data.clientObj.ClickFee ? $scope.fields4.clickFeeTxtValue = data.clientObj.ClickFee : false;
data.clientObj.FraudFee ? $scope.fields4.fraudFeeTxtValue = data.clientObj.FraudFee : false;
data.clientObj.BandwidthFee ? $scope.fields4.bandwidthFeeTxtValue = data.clientObj.BandwidthFee : false;
data.clientObj.OtherFee1 ? $scope.fields4.otherFee1TxtValue = data.clientObj.OtherFee1 : false;
data.clientObj.OtherFee2 ? $scope.fields4.otherFee2TxtValue = data.clientObj.OtherFee2 : false;
data.clientObj.PrimaryName ? $scope.fields4.primaryNameTxtValue = data.clientObj.PrimaryName : false;
data.clientObj.PrimaryEmail ? $scope.fields4.primaryEmailTxtValue = data.clientObj.PrimaryEmail : false;
data.clientObj.PrimaryPhone ? $scope.fields4.primaryPhoneTxtValue = data.clientObj.PrimaryPhone : false;
data.clientObj.TechnicalName ? $scope.fields4.technicalNameTxtValue = data.clientObj.TechnicalName : false;
data.clientObj.TechnicalEmail ? $scope.fields4.technicalEmailTxtValue = data.clientObj.TechnicalEmail : false;
data.clientObj.TechnicalPhone ? $scope.fields4.technicalPhoneTxtValue = data.clientObj.TechnicalPhone : false;
data.clientObj.BillingName ? $scope.fields4.billingNameTxtValue = data.clientObj.BillingName : false;
data.clientObj.BillingEmail ? $scope.fields4.billingEmailTxtValue = data.clientObj.BillingEmail : false;
data.clientObj.BillingPhone ? $scope.fields4.billingPhoneTxtValue = data.clientObj.BillingPhone : false;
data.clientObj.AdminName ? $scope.fields4.adminNameTxtValue = data.clientObj.AdminName : false;
data.clientObj.AdminEmail ? $scope.fields4.adminEmailTxtValue = data.clientObj.AdminEmail : false;
data.clientObj.AdminPhone ? $scope.fields4.adminPhoneTxtValue = data.clientObj.AdminPhone : false;
data.clientObj.OpsName ? $scope.fields4.opsNameTxtValue = data.clientObj.OpsName : false;
data.clientObj.OpsEmail ? $scope.fields4.opsEmailTxtValue = data.clientObj.OpsEmail : false;
data.clientObj.OpsPhone ? $scope.fields4.opsPhoneTxtValue = data.clientObj.OpsPhone : false;
$scope.fields4.crmCheckboxValue = [];
data.clientObj.cbcrm ? $scope.fields4.crmCheckboxValue.push({"id":1,"name":"CRM", "value": true}) : false;
data.clientObj.cbdeclines ? $scope.fields4.crmCheckboxValue.push({"id":7,"name":"Declines", "value": true}) : false;
data.clientObj.cbemails ? $scope.fields4.crmCheckboxValue.push({"id":4,"name":"Emails", "value": true}) : false;
data.clientObj.cbexports ? $scope.fields4.crmCheckboxValue.push({"id":5,"name":"Exports", "value": true}) : false;
data.clientObj.cbmid ? $scope.fields4.crmCheckboxValue.push({"id":6,"name":"Multi MID", "value": true}) : false;
data.clientObj.cbnegdb ? $scope.fields4.crmCheckboxValue.push({"id":9,"name":"Neg Database", "value": true}) : false;
data.clientObj.cbreports ? $scope.fields4.crmCheckboxValue.push({"id":3,"name":"Reports", "value": true}) : false;
data.clientObj.cbbilling ? $scope.fields4.crmCheckboxValue.push({"id":2,"name":"Billing", "value": true}) : false;
data.clientObj.cbchargebacks ? $scope.fields4.crmCheckboxValue.push({"id":8,"name":"Chargebacks", "value": true}) : false;
}
$scope.save = function(result) {
$scope.$broadcast('show-errors-check-validity');
// TAB 1 Information
if ($scope.clientInfo){
if ($scope.editClientForm.$invalid)
return false;
var saveObj = ClientSetup.makeInfoSaveObject(data.clientObj.ClientID, $scope.fields1);
$scope.saving = true;
DataStorage.anyApiMethod('/clients/edit').post(saveObj, function(results){
if (results.Status === 0) {
Notification.success({message: $rootScope.t('modals.administration.client.editclient.saved-notification')});
close(false);
} else {
$scope.saving = false;
}
});
}
// TAB 2 API
if ($scope.apiTab){
if ($scope.apiForm.$invalid)
return false;
var saveObj = ClientSetup.makeApiSaveObject(data.clientObj.ClientID, $scope.fields3);
$scope.saving = true;
DataStorage.anyApiMethod('/clients/apicredentials').post(saveObj, function(results){
if (results.Status === 0) {
Notification.success({message: $rootScope.t('modals.administration.client.editclient.saved-notification')});
close(false);
} else {
$scope.saving = false;
}
});
}
// TAB 3 Details
if ($scope.clientDetails){
if ($scope.detailsForm.$invalid)
return false;
var saveObj = ClientSetup.makeDetailsSaveObject(data.clientObj.ClientID, $scope.fields4);
$scope.saving = true;
DataStorage.anyApiMethod('/clients/details').post(saveObj, function(results){
if (results.Status === 0) {
Notification.success({message: $rootScope.t('modals.administration.client.editclient.saved-notification')});
close(false);
} else {
$scope.saving = false;
}
});
}
};
$scope.changeTab = function (elem) {
switch (true) {
case elem === 'clientInfo':
$scope.clientInfo = 'ActiveElementColor';
$scope.apiTab = false;
$scope.clientDetails = false;
$scope.$broadcast('show-errors-reset');
return false;
break;
case elem === 'apiTab':
$scope.apiTab = 'ActiveElementColor';
$scope.clientInfo = false;
$scope.clientDetails = false;
$scope.$broadcast('show-errors-reset');
return false;
break;
case elem === 'clientDetails':
$scope.clientDetails = 'ActiveElementColor';
$scope.apiTab = false;
$scope.clientInfo = false;
$scope.$broadcast('show-errors-reset');
return false;
break;
default:
return false;
break;
}
};
$scope.changeTab('clientInfo')
$scope.close = function() {
close(false, 500); // close, but give 500ms for bootstrap to animate
};
});
|
var exports = module.exports = {}
// Generate digit for bank code.
function randomNumber()
{
min = 0,
max = 9;
return (Math.floor(Math.random() * (max - min + 1)) + min).toString();
}
// Three consecutive digits should not be incremental (e.g. 1236 is invalid)
function checkPINCodeThreeIncremental(tempArray)
{
var index = 0;
for (index = 0; index < tempArray.length - 2; index++) {
if ((tempArray[index + 1] == parseInt(tempArray[index]) + 1) && (tempArray[index + 2] == parseInt(tempArray[index + 1]) + 1))
{
return false;
}
}
return true;
}
//Two consecutive digits should not be the same (e.g. 1156 is invalid)
function checkPINCodeTwoConsecutive(tempArray)
{
var index = 0;
for (index = 0; index < tempArray.length; index++) {
if ((tempArray[index + 1] == tempArray[index]))
{
return false;
}
}
return true;
}
function conditionForPINCode (pinArray)
{
var tempArray = pinArray.split("");
var validation = true;
if(!checkPINCodeThreeIncremental(tempArray) || !checkPINCodeTwoConsecutive(tempArray))
{
validation = false;
}
return validation;
};
exports.PINCodeGenerator = function() {
var i = 0;
var pinArray = "";
var validated = false;
var duplicatedList = [];
//1,000
while(i < 4){
pinArray += randomNumber();
i++;
if(i === 4)
{
validated = conditionForPINCode(pinArray);
if(!validated && duplicatedList.indexOf(pinArray) > -1){
i = 0;
pinArray = "";
}else{
duplicatedList.push(pinArray);
}
}
}
return pinArray;
};
/*
1. The library should export a function that returns a batch of 1,000 PIN codes in random order
2. Each PIN code in the batch should be unique
Each PIN should be:
3.1 4 digits long
3.2 Two consecutive digits should not be the same (e.g. 1156 is invalid)
3.3 Three consecutive digits should not be incremental (e.g. 1236 is invalid)
3.4 The library should have automated tests.
*/
|
import style from '../style.css';
import style_1 from '../index.html';
|
const express = require("express");
const app = express();
// import routes
const authRoutes = require("./routes/auth");
// route middlewares
app.use(express.json()); // for body parser
app.use("/eSamudaay", authRoutes);
app.listen(3000, () => console.log("server is running..."));
|
import React from 'react';
import Api from '../api/api'
import {connect} from 'react-redux';
import {UPDATE_TEAMLIST} from '../data/store'
class Ranking extends React.Component {
constructor(props) {
super(props);
this.state = {
updated: null,
error: null
};
}
componentWillMount() {
// Tap tap API server
Api.teamlist((json) => {
this.props.updateTeamlist(json);
this.setState({
updated: Date()
});
}, (mes) => {
this.setState({
error: mes
});
})
}
clearError() {
this.setState({
error: null
});
}
render() {
const {teaminfo, teamlist} = this.props;
var ranking = teamlist.map((team, index) => {
return (
<tr className={teaminfo.id == team.id ? 'active' : ''} key={team.id}>
<td>{index + 1}</td>
<td>{team.name}</td>
<td>{team.points}</td>
</tr>
);
});
var errorMessage;
if (this.state.error) {
errorMessage = (
<div className="ui floating negative message">
<i className="close icon" onClick={this.clearError.bind(this)}></i>
<div className="header">
Error
</div>
<p>{this.state.error[0]}</p>
</div>
);
}
return (
<div className="ui container">
<div>Last updated: <span>{this.state.updated}</span></div>
<table className="ui striped very compact table">
<thead>
<tr>
<th className="two wide">Rank</th>
<th className="twelve wide">Team</th>
<th className="two wide">Points</th>
</tr>
</thead>
<tbody>
{ranking}
</tbody>
</table>
<div className="ui divider">
</div>
{errorMessage}
</div>
);
}
};
export default connect(
(state) => ({
teaminfo: state.teamInfo,
teamlist: state.teamList
}),
(dispatch) => ({updateTeamlist: (data) => dispatch({type: UPDATE_TEAMLIST, data: data})})
)(Ranking);
|
var http = require("http");
http.createServer(function (request, response) {
response.writeHead(200, {
"Access-Control-Allow-Origin": "http://127.0.0.1:8088",
"Access-Control-Allow-Methods": "GET, POST, PUT",
"Access-Control-Allow-Headers": "X-Test-Cors",
"Access-Control-Max-Age": "180",
"Access-Control-Allow-Credentials": "true",
"Content-Type": "text/html;charset=utf-8"
});
response.write("<html><body><h1>cors跨域</h1></body></html>");
response.end();
}).listen(8087);
console.log("server listening on port:8087");
|
import React from 'react'
import { shallow } from 'enzyme'
import Carousel from './carousel'
describe('Carousel Component', () => {
const data = ["1", "2", "3"]
test('renders correctly', () => {
const component = shallow(<Carousel data={data} width={400} />)
expect(component).toMatchSnapshot()
})
})
|
// npm requirement
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({extended: true});
app.use(bodyParser.json());
app.use(urlencodedParser);
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/test';
var htmlDir = "/public/views";
// Connect to the db
var bucket;
var db = MongoClient.connect(url, function (err, db) {
if (!err) {
console.log("Connected to Mongo");
bucket = db.collection('restaurants');
} else {
console.error("Ooops ! You are not connected to mongo server, Please log");
process.exit(1);
}
});
/* GET home page. */
app.get('/', function (req, res) {
var html ='<style>body {font-family: Georgia, "Times New Roman",Times, serif;color: purple;background-color: #DACFCF }h1 {font-family: Helvetica, Geneva, Arial,SunSans-Regular, sans-serif }</style>'+
'<p><center><h2>CRUD NodeJS Express MongoDB</h2></center></p>' +
'<br /><br /><br /><br /> ' +
'<center>' +
'<a href="/connect"><button type="button" class="btn btn-primary"><span class="glyphicon glyphicon-off" aria-hidden="true"></span>Connected to Mongo</button></a>' +
'<a href="/find"><button type="button" class="btn btn-primary"><span class="glyphicon glyphicon-off" aria-hidden="true"></span>Find document</button></a>' +
'<a href="/create"><button type="button" class="btn btn-primary"><span class="glyphicon glyphicon-off" aria-hidden="true"></span>Insert document</button></a>' +
'<a href="/delete"><button type="button" class="btn btn-primary"><span class="glyphicon glyphicon-off" aria-hidden="true"></span>Delete document</button></a>' +
'<p><img src="http://cdn.meme.am/instances/59664439.jpg" alt="connected" style="width:304px;height:228px;"></p>';
'</center>';
res.send(html);
});
// home page
app.get('/connect', function (req, res) {
var html = '<style>body {font-family: Georgia, "Times New Roman",Times, serif;color: purple;background-color: #DACFCF }h1 {font-family: Helvetica, Geneva, Arial,SunSans-Regular, sans-serif }</style>'+
'<center><h2>Connected : Mongo version 2.6.10 </h2>' +
'<br/><br/><br/><br/><br/>' +
'<p><img src="http://www.mememaker.net/static/images/memes/4062664.jpg" alt="connected" style="width:304px;height:228px;"></p>' +
'<a href="http://0.0.0.0:3000/"><button type="button" class="btn btn-primary">Home</button></a></center>';
if (!db) {
res.send(html);
} else {
res.send("Ooops ! You are not connected to mongo server, Please log");
}
});
// find document
app.get('/find', function (req, res) {
res.sendfile(__dirname + '/' + htmlDir + '/findDocument.html');
});
app.get('/findMany', function (req, res) {
bucket.find({}).toArray(function (err, result) {
if (err) {
console.log(err);
} else if (result.length) {
console.log('Found:', result);
res.send(JSON.stringify(result));
} else {
console.log('search character not found');
}
});
//res.send(html);
});
// find document with a specific character
app.get('/findOne/:critere/:id', function (req, res) {
if (req.params.critere === 'idR') {
bucket.find({"restaurant_id": req.params.id}).toArray(function (err, result) {
if (err) {
console.log(err);
} else if (result.length) {
res.send(result);
} else {
console.log('search character not found');
}
});
} else if (req.params.critere === 'cuisine') {
bucket.find({"cuisine": req.params.id}).toArray(function (err, result) {
if (err) {
console.log(err);
} else if (result.length) {
res.send(result);
} else {
console.log('search character not found');
}
});
} else if (req.params.critere === 'borough') {
bucket.find({"borough": req.params.id}).toArray(function (err, result) {
if (err) {
console.log(err);
} else if (result.length) {
res.send(result);
} else {
console.log('search character not found');
}
});
}
});
app.get('/create', function (req, res) {
res.sendfile(__dirname + '/' + htmlDir + '/insertDocument.html');
});
app.get('/insert/:id&:building&:coord1&:coord2&:street&:zipcode&:borough&:cuisine&:date&:grade&:score&:name', function (req, res) {
bucket.insertOne({
"address": {
"street": req.params.street,
"zipcode": req.params.zipcode,
"building": req.params.building,
"coord": [req.params.coord1, req.params.coord2]
},
"borough": req.params.borough,
"cuisine": req.params.cuisine,
"grades": [
{
"date": new Date(req.params.date),
"grade": req.params.grade,
"score": req.params.score
}
],
"name": req.params.name,
"restaurant_id": req.params.id
}, function (err, result) {
if (err) {
alert(err);
} else {
res.send("le restaurant a été inseré avec succès ");
}
});
});
app.get('/delete', function (req, res) {
res.sendfile(__dirname + '/' + htmlDir + '/deleteDocument.html');
});
// delete
app.get('/delete/:id', function (req, res) {
bucket.remove({'restaurant_id': req.params.id}, 1, function (err, result) {
if (err) {
res.send(err);
} else {
res.send("le restaurant a été supprimé avec succès " + result);
}
});
});
app.get('/deleteOne/:id', urlencodedParser, function (req, res, next) {
bucket.remove({"restaurant_id": req.params.id});
res.redirect('http://localhost:3000/find')
});
// TODO Complete update document
app.get('/update/:id', function (req, res) {
var html = '<form method="post" action="/updatedDocument">' +
'<div>' + req.params.id +
': <input type="text" name="something" placeholder="something"></div>' +
'<input type="hidden" name="id" value="' + req.params.id + '">' +
'<div><input type="submit" value="go"></div>' +
'</form>';
res.send(html);
});
app.post('/updated', urlencodedParser, function (req, res) {
var html = '<p>edited and updated ' + req.body.id + ' : ' + req.body.something + ' in db</p>';
res.send(html);
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port)
});
|
const candidatesService = require('../services/candidates');
const trie = require('../services/trie-search');
function get(req, res) {
candidatesService.get(req.body, (error, result) => {
if (error) {
res.sendStatus(500);
throw error;
}
return res.status(200).send(result);
});
}
function getById(req, res) {
candidatesService.getById(req.query.id, (error, result) => {
if (error) {
res.sendStatus(500);
throw error;
}
return res.status(200).send(result);
});
}
function insert(req, res) {
candidatesService.insert(req.body, req.user.id, (error) => {
if (error) {
res.sendStatus(500);
throw error;
}
return res.status(201).send();
});
}
function validate(req, res) {
candidatesService.validate(req.query.email, (error, result) => {
if (error) {
res.sendStatus(500);
throw error;
}
return res.status(result).send();
});
}
function update(req, res) {
candidatesService.update(req.query.id, req.body, req.user.id, (error) => {
if (error) {
res.sendStatus(500);
throw error;
}
return res.status(200).send();
});
}
function search(req, res) {
candidatesService.search(req.query, req.body, (error, result) => {
if (error) {
res.sendStatus(500);
throw error;
}
return res.status(200).send(result);
});
}
function report(req, res) {
candidatesService.report(req.query, (error, result) => {
if (error) {
res.sendStatus(500);
throw error;
}
res.setHeader('Content-Type', 'application/octet-stream');
res.setHeader('Content-Disposition', 'attachment; filename= report.xlsx');
res.end(result, 'binary');
});
}
function trieSearch(req, res) {
const params = req.query.candidate.split(' ');
if (params.lenght > 2) {
return res.status(404).send();
}
trie.search(params.join(' '), (error, answer) => {
if (error) {
res.sendStatus(500);
throw error;
}
if (answer.length) {
return res.status(200).send(answer);
}
return res.status(200).send([]);
});
}
function getHistory(req, res) {
candidatesService.getHistory(req, (error, result) => {
if (error) {
res.sendStatus(500);
throw error;
}
return res.status(200).send(result);
});
}
module.exports = {
get,
getById,
getHistory,
insert,
validate,
update,
search,
report,
trieSearch,
};
|
export {LoginFormContainer} from './login-form.container'
export {LOGIN_FORM_FIELD_KEY} from './login-form.constants'
|
const { Movie , validateMovie} =require('../model/movie');
const {Genre } = require('../model/genre');
const express = require('express');
const router = express.Router();
router.get('/', async (req, res) => {
const movie = await Movie.find();
if(!movie) return res.status(404).send("movie was not in record.");
res.send(movie);
});
router.get('/:id', async (req, res) => {
const movie = await Movie.findById(req.params.id);
if(!movie) return res.status(404).send("movie was not in record for given id");
res.send(movie);
});
router.post('/', async (req, res) => {
const { error } = validateMovie(req.body);
if(error) return res.status(400).send(error.details[0].message);
const genre = await Genre.findById(req.body.genreId);
if(!genre) return res.status(400).send("Invalid genre");
let movie = new Movie({
title : req.body.title,
genre :{
_id : genre._id,
name : genre.name
},
numberInStock: req.body.numberInStock,
dailyRentalRate : req.body.dailyRentalRate
});
await movie.save();
res.send(movie);
});
router.put('/:id', async (req, res) => {
const genre = await Genre.findById(req.body.genreId);
if(!genre) return res.status(400).send("Invalid genre");
const movie = await Movie.findByIdAndUpdate(req.params.id,{
title : req.body.title,
genre :{
_id : genre._id,
name : genre.name
},
numberInStock: req.body.numberInStock,
dailyRentalRate : req.body.dailyRentalRate
}, {new: true});
if(!movie) return res.status(400).send("Invalid Id");
res.send(movie);
});
router.delete('/:id', async (req, res) =>{
const movie = await Movie.findByIdAndRemove(req.params.id);
if(!movie) return res.status(400).send("Invalid Id");
res.send(movie);
});
module.exports =router;
|
import React, { useEffect, useState, useRef, useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useHistory } from 'react-router-dom'
import styled from 'styled-components'
import { ent_act } from "../reducers/root_reducer"
import { getSongUrl } from '../actions/actions'
import { PlayIcon, PauseIcon, PrevIcon, NextIcon } from './active_svgs'
const convertSecsToMins = seconds => {
let mins = Math.floor(seconds / 60).toString();
let secs = Math.floor(seconds % 60);
secs = (secs < 10 ? '0' + secs.toString() : secs.toString());
return `${mins}:${secs}`
}
const ProgressBar = styled.div`
display: flex;
align-items: center;
width: 100%;
height: 2px;
min-height: 30px;
position:absolute;
top:-15px;
z-index:10;
overflow-x:hidden;
cursor: pointer;
.track-elapsed {
height: 2px;
background-color: #ad0f37;
}
.track-remaining {
height: 2px;
background-color: grey;
}
.thumb-container {
height: 100%;
width:0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
z-index:5;
}
.thumb {
/* display: none; */
border-radius: 50%;
background-color: #ad0f37;
width: 10px;
height: 10px;
}
`
const PlayerDiv = styled.div`
height:60px;
min-height:60px;
position: relative;
`
const SwipeDiv = styled.div`
display:flex;
align-items:center;
height:100%;
cursor: pointer;
.control {
display:flex;
align-items:center;
margin:0 6px;
cursor: pointer;
>* {
margin:0 6px;
}
.play-button {
height: 32px;
width: 32px;
}
.skip-button {
height: 24px;
width: 24px;
margin:0 6px;
}
}
.song-info {
margin-left:19px;
height:100%;
width:100%;
font-size:.9em;
overflow:hidden;
white-space: nowrap;
display: flex;
flex-direction: column;
justify-content: center;
div {
display:flex;
flex-direction: column;
justify-content:center;
align-items:flex-start;
}
div:nth-of-type(1) {
color: #777777;
}
&:hover {
color: #ad0f37;
}
}
.time-info {
font-size:.7em;
}
.noselect{
user-select: none;
-webkit-user-select: none;
-moz-user-select: none;
}
`
export default function AudioPlayer({ winWidth }) {
const dispatch = useDispatch();
const [duration, setDuration] = useState(null);
const [progress, setProgress] = useState(0);
const [down, setDown] = useState(false);
const [songInfo, setSongInfo] = useState(null);
const [start, setStart] = useState(null)
const [curSongId, setCurSongId] = useState(null)
const songUrl = useSelector(state => state.player.songUrl);
const playlistD = useSelector(state => state.entities.playlistD);
const songD = useSelector(state => state.entities.songD);
const track = useSelector(state => state.player.track);
const playing = useSelector(state => state.player.playing);
const aud = useRef()
const playerdiv = useRef(null)
const history = useHistory();
useEffect(() => {
window.aud = aud.current;
aud.current.addEventListener('loadedmetadata', handleLoadedMeta);
document.addEventListener('keydown', handleSpace)
return () => {
aud.current.removeEventListener('loadedmetadata', handleLoadedMeta)
document.removeEventListener('keydown', handleSpace)
}
}, [])
useEffect(() => {
playerdiv.current.addEventListener("touchend", handleSwipeEnd);
return () => {
playerdiv.current.removeEventListener("touchend", handleSwipeEnd);
};
}, [start]);
useEffect(() => {
let title = '';
let artist = '';
if (track
&& track[1] < playlistD[track[0]].length // when last song of pl is deleted, while it's being played
// won't allow this case to enter if statement
) {
let song;
if (track[0] == 'search_results') {
song = playlistD[track[0]][track[1]];
} else {
song = songD[playlistD[track[0]][track[1]][0]];
}
if (!song) {
song = { title: "", artist: '' }
}
artist = song.artist;
title = song.title;
setSongInfo(song)
}
if ('mediaSession' in navigator) {
navigator.mediaSession.metadata = new MediaMetadata({ title, artist });
navigator.mediaSession.setActionHandler('previoustrack', skip(-1));
navigator.mediaSession.setActionHandler('nexttrack', skip(1));
navigator.mediaSession.setActionHandler('play', onPlayClick);
navigator.mediaSession.setActionHandler('pause', onPlayClick);
}
}, [track, playlistD]) // remount when new track or when playlist is modified (eg when new song added)
useEffect(() => {
if (!track || !playing) return;
let song_id = track[0] == 'search_results' ?
song_id = playlistD[track[0]][track[1]].id
:
playlistD[track[0]][track[1]][0];
if (curSongId != song_id) {
dispatch(getSongUrl(song_id));
setCurSongId(song_id);
} else {
aud.current.play();
}
}, [track, playing])
const skip = (dir) => () => {
if (!track) return
const newtr = [...track];
newtr[1] += dir;
if (!playlistD[newtr[0]][newtr[1]]) return;
dispatch({ type: ent_act.LOAD_TRACK, track: newtr });
dispatch({ type: ent_act.SET_PLAY })
};
function handleLoadedMeta(e) {
let sec;
// webkit audio doubles song duration with silent second half
if (window.webkitAudioContext) { sec = e.target.duration / 2; }
else { sec = e.target.duration; }
setDuration([sec, convertSecsToMins(sec)])
}
function handleSpace(e) {
if (e.target.type && e.target.type.slice(0, 4) === 'text') return;
if (e.key === " ") {
e.preventDefault()
e.stopPropagation()
onPlayClick()
}
}
function handleTimeUpdate(e) {
const prog = e.target.currentTime / duration[0];
if (window.webkitAudioContext && prog >= 1) { skip(1)(); } //for webkit
if (!down) { setProgress(prog); }
}
const handleMouseUp = (e) => {
e.stopPropagation()
const prog = e.clientX / winWidth;
setProgress(prog);
aud.current.currentTime = prog * duration[0];
setDown(false);
document.removeEventListener('mousemove', updateDrag);
document.removeEventListener('mouseup', handleMouseUp);
};
const handleTouchEnd = (e) => {
e.stopPropagation()
const prog = e.changedTouches[0].clientX / winWidth;
setProgress(prog);
aud.current.currentTime = prog * duration[0];
setDown(false);
document.removeEventListener('touchmove', updateDrag);
document.removeEventListener('touchend', handleTouchEnd);
};
const updateDrag = (e) => {
let prog;
if (!e.clientX) { prog = e.touches[0].clientX / winWidth; }
else { prog = e.clientX / winWidth; }
setProgress(prog);
};
const ProgressBarHandler = {
onMouseDown: (e) => {
if (!e.clientX) return;
e.stopPropagation()
if (!duration) return;
setProgress(e.clientX / winWidth);
setDown(true);
document.addEventListener('mouseup', handleMouseUp);
document.addEventListener('mousemove', updateDrag);
},
onTouchStart: (e) => {
e.stopPropagation()
if (!duration) return;
setProgress(e.touches[0].clientX / winWidth);
setDown(true);
document.addEventListener('touchend', handleTouchEnd);
document.addEventListener('touchmove', updateDrag);
},
}
const handleSwipeStart = e => {
setStart(e.touches[0].clientX)
}
const handleSwipeEnd = e => {
const dir = e.changedTouches[0].clientX - start;
setStart(null)
if (Math.abs(dir) < 100) {
const pl_id = track[0]
if (pl_id) history.push(`/playlist_D/${pl_id}`)
else history.push('')
} else if (dir > 0) skip(-1)()
else skip(1)()
}
function handleTitleClick(e) {
const pl_id = track[0]
if (pl_id === 'search_results') {
history.push('/upload');
} else if (pl_id === 'songs_playlist') {
history.push('');
} else {
history.push(`/playlist_D/${pl_id}`);
}
}
function onPlayClick() {
if (!aud.current.paused) {
aud.current.pause();
dispatch({ type: ent_act.SET_PAUSE })
} else if (!aud.current.emptied) {
dispatch({ type: ent_act.SET_PLAY });
}
}
return <>
<PlayerDiv >
<ProgressBar {...ProgressBarHandler}>
<div className='track-elapsed' style={{ width: `${progress * 100}%` }} />
<div className='thumb-container' >
<div className='thumb' />
</div>
<div className='track-remaining' style={{ width: `${100 - progress * 100}%` }} />
</ProgressBar>
<SwipeDiv ref={playerdiv} onTouchStart={handleSwipeStart} onMouseDown={handleTitleClick}>
<div className='control'
onTouchStart={(e) => {
e.stopPropagation()
}}
onMouseDown={(e) => {
e.stopPropagation()
}}
>
{winWidth > 500 && <PrevIcon {...{ scale: 1, size: "24px", onClick: skip(-1) }} />}
<div className='play-button'
onClick={onPlayClick}
onTouchStart={(e) => {
e.stopPropagation()
}}
>
{playing ?
<PauseIcon {...{ scale: 1, size: "32px" }} /> :
<PlayIcon {...{ scale: 1, size: "32px" }} />
}
</div>
{winWidth > 500 && <NextIcon {...{ scale: 1, size: "24px", onClick: skip(1) }} />}
</div>
{duration &&
<div className='time-info'>
{`${convertSecsToMins(progress * duration[0])}`}/{duration[1]}
</div>
}
<div className='song-info noselect'>
<div>{songInfo && songInfo.artist}</div>
<div>{songInfo && songInfo.title}</div>
</div>
</SwipeDiv>
</PlayerDiv>
<audio
// controls
id='audio'
ref={aud}
crossOrigin="anonymous"
autoPlay
src={songUrl}
onEnded={skip(1)}
onTimeUpdate={handleTimeUpdate}
/>
</>
}
|
$(function(){
// メッセージ宣言
const MSG_CONTACT_COUNT_ERR = '500文字以内で入力してください。';
// SPメニュー
$('.js-toggle-sp--menu').on('click',function(){
$(this).toggleClass('active');
$('.js-toggle-sp--menu-target').toggleClass('active');
});
// コメントカウント(お問い合わせ画面)
$('.js-comment-input').keyup(function () {
// 入力値の文字列長を取得
let count = $(this).val().length;
// 文字列長を画面に出力
$('.js-comment--count').text(count);
// DOMを取得
let textarea = $('.js-comment-input');
let err_msg = $('.js-err_comment');
let btn = $('.btn');
// var form_g = $(this).closest('.form-group');
if (count > 500){
textarea.addClass('err__block');
err_msg.addClass('err__comment');
err_msg.text(MSG_CONTACT_COUNT_ERR);
btn.prop("disabled", true);
btn.addClass('inactive');
} else {
textarea.removeClass('err__block');
err_msg.removeClass('err__comment');
err_msg.text("");
btn.prop("disabled", false);
btn.removeClass('inactive');
}
});
// カレンダー表示
$('.datepicker').datepicker({
showOtherMonths: true, //他の月を表示
selectOtherMonths: true //他の月を選択可能
});
// アコーディオンメニュー
$('.toggle_switch').on('click', function () {
$(this).toggleClass('open');
$(this).next('.toggle_contents').slideToggle();
});
//処理完了時のメッセージ表示
let $jsShowMsg = $('#js-msg');
let msg = $jsShowMsg.text();
if (msg.replace(/^[\s ]+|[\s ]+$/g, "").length) {
$jsShowMsg.slideToggle('slow');
setTimeout(function () { $jsShowMsg.slideToggle('slow'); }, 5000);
}
$(function () {
$('#openModal').click(function () {
$('#modalArea').fadeIn();
});
$('#closeModal , #modalBg').click(function () {
$('#modalArea').fadeOut();
});
});
});
|
// ECMA 7 - includes() shim
// TC39 2014-11 'contains' renamed to 'includes'
if (!Array.prototype.includes ||
// Firefox v. 35 supports contains so we overwrite it
Array.prototype.contains) {
Object.defineProperty(Array.prototype, 'includes', {
enumerable: false,
configurable: true,
writable: true,
value: function(target /*, fromIndex*/ ) {
if (this === undefined || this === null) {
throw new TypeError('Cannot convert this value to object');
}
var obj = Object(this),
len = parseInt(obj.length) || 0;
if (len < 1) {
return false;
}
var from = Math.floor(arguments[1] || 0);
// In ECMA 6 max length is 2^53-1, currently limited to 2^32-1
if (from >= len || from > 0xFFFFFFFF) {
return false;
}
if (from < 0) {
from = len + from;
}
if (from === -Infinity || from < 0) {
from = 0;
}
var check;
if (from >= 0) {
check = from;
} else {
check = len + Math.abs(from);
if (check < 0) {
check = 0;
}
}
while (check < len) {
var currentElement = obj[check];
if (target === currentElement ||
target !== target && currentElement !== currentElement
) {
return true;
}
check += 1;
}
return false;
}
});
}
|
import MainLayout from 'src/layouts/MainLayout.vue'
import ChatPage from 'src/pages/ChatPage.vue'
import ProfilePage from 'src/pages/ProfilePage.vue'
import AuthPage from 'src/pages/AuthPage.vue'
import UsersPage from 'src/pages/UsersPage.vue'
import Error404 from 'src/pages/Error404.vue'
const routes = [
{
path: '/',
redirect: { path: '/users' },
},
{
path: '/chat/:userId',
component: MainLayout,
children: [
{ path: '', component: ChatPage }
]
},
{
path: '/profile',
component: MainLayout,
children: [
{ path: '', component: ProfilePage }
]
},
{
path: '/auth',
component: MainLayout,
children: [
{ path: '', component: AuthPage }
]
},
{
path: '/users',
component: MainLayout,
children: [
{ path: '', component: UsersPage }
]
},
// Always leave this as last one,
// but you can also remove it
{
path: '*',
component: Error404,
}
]
export default routes
|
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import axios from './http'
import echarts from 'echarts'
// 导入格式化时间的插件
import moment from 'moment'
// 定义全局的过滤器
Vue.filter('dateFormat', function (dataStr, pattern = "YYYY-MM-DD HH:mm:ss") {
return moment(dataStr).format(pattern)
})
Vue.use(ElementUI);
Vue.prototype.$axios = axios
//echarts放在vue的原型上
Vue.prototype.$echarts = echarts
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
|
import isPlainObject from "is-plain-object";
function concat(array1, array2) {
const finalArray = [];
each(array1, value => {
finalArray.push(value);
});
each(array2, value => {
finalArray.push(value);
});
return finalArray;
}
// Copied from lodash
function isArray(value) {
return Object.prototype.toString.call(value) === "[object Array]";
}
function each(value, fn) {
if (isArray(value)) {
for (let i = 0, len = value.length; i < len; i++) {
fn(value[i], i);
}
} else if (isPlainObject(value)) {
for (const key in value) {
if (value.hasOwnProperty(key)) {
fn(value[key], key);
}
}
} else {
throw new Error("Don't know how to iterate over value");
}
}
function mergeObjects(object1, object2) {
const final = {};
each(object1, (value, key) => {
final[key] = value;
});
each(object2, (value, key) => {
final[key] = value;
});
return final;
}
/*
function sliceObject(object, keys) {
const newObject = {};
each(keys, key => {
newObject[key] = object[key];
});
return newObject;
}
*/
export { concat, each, isArray, isPlainObject, mergeObjects };
|
var empleadoModel = require("../models/empleado");
var express = require("express");
var router = express.Router();
var funciones_auxiliares = require("../auxiliar/funciones");
router.get("/dashboard",funciones_auxiliares.restrict, function(request,response){
response.render('dashboard', {user:request.session.user});
});
router.get("/alta-puesto",funciones_auxiliares.restrict,function(request,response){
console.log("hola");
response.render("empleado/altaPuesto");
});
router.post("/alta-puesto",funciones_auxiliares.restrict,function(request,response){
var puesto = {
nombrePuesto: request.body.nombrePuesto,
salario: request.body.salario
};
empleadoModel.altaPuesto(puesto,function(respuesta){
response.render("empleado/altaPuesto");
});
});
router.get("/alta-sucursal",funciones_auxiliares.restrict,function(request,response){
empleadoModel.getDelegaciones(function(delegaciones){
response.render("empleado/altaSucursal",{delegaciones: delegaciones});
});
});
router.post("/alta-sucursal",funciones_auxiliares.restrict,function(request,response){
var direccion = {
calle: request.body.calle,
colonia: request.body.colonia,
cp: request.body.cp,
delegacion: request.body.delegacion
};
var sucursal = {
nombreSucursal: request.body.nombreSucursal,
idDireccion: 0
};
empleadoModel.altaSucursal(direccion,sucursal,function(id){
response.redirect('/empleado/consulta-sucursal');
console.log("Exitoso");
});
});
router.get("/alta-empleado", funciones_auxiliares.restrict,function(request,response){
empleadoModel.getDelegaciones(function(delegaciones){
empleadoModel.getPuesto(function(puestos){
empleadoModel.getSucursal(function(sucursales){
response.render("empleado/altaEmpleado", {delegaciones: delegaciones,puestos:puestos, sucursales:sucursales});
});
});
});
});
router.post("/alta-empleado", funciones_auxiliares.restrict,function(request,response){
var direccion = {
calle: request.body.calle,
colonia: request.body.colonia,
cp: request.body.cp,
delegacion: request.body.delegacion
};
var empleado = {
rfc: request.body.rfc,
nombreEmpleado: request.body.nombreEmpleado,
turno: request.body.turno,
idSucursal: request.body.sucursal,
tel: request.body.telefono,
idDireccion: 0,
idPuesto: request.body.puesto,
horaEntrada: request.body.horaEntrada,
horaSalida: request.body.horaSalida
};
empleadoModel.altaEmpleado(direccion,empleado,function(resultado){
response.redirect("/empleado/alta-empleado/");
});
});
router.get("/consulta-empleado", funciones_auxiliares.restrict,function(request,response){
response.render("empleado/consultaEmpleado");
});
router.get("/consulta-sucursal",funciones_auxiliares.restrict,function(request,response){
empleadoModel.getSucursales(function(resultado){
console.log(resultado);
response.render("empleado/consultaSucursal",{sucursales:resultado});
});
});
module.exports = router;
|
import Gulp from 'gulp';
import GUtil from 'gulp-util';
import webpack from 'webpack';
import {BUILD_TARGET, WATCHING} from '@kpdecker/linoleum/config';
import loadWebpackConfig from '../src/webpack';
Gulp.task('webpack:electron', function(done) {
let main = loadWebpackConfig({
electron: true,
node: true,
entry: {main: './src/index'},
path: `${BUILD_TARGET}/`
}),
renderer = loadWebpackConfig({
electron: true,
entry: {renderer: './src/bootstrap'},
path: `${BUILD_TARGET}/`
}),
coverMain = loadWebpackConfig({
electron: true,
node: true,
cover: true,
entry: {main: require.resolve('@kpdecker/linoleum-webpack/src/webpack-server-test')},
path: `${BUILD_TARGET}/$cover$/`
}),
coverRenderer = loadWebpackConfig({
electron: true,
cover: true,
entry: {renderer: require.resolve('@kpdecker/linoleum-webpack/src/webpack-web-test')},
path: `${BUILD_TARGET}/$cover$/`
});
webpack([main, renderer, coverMain, coverRenderer], handleWebpack(done));
});
function handleWebpack(done) {
return function(err, stats) {
if (err) {
throw new GUtil.PluginError('webpack', err);
}
GUtil.log('[webpack]', stats.toString({
chunks: !WATCHING
}));
let hasErrors = (stats.stats || [stats]).reduce((prev, stat) => prev || stat.hasErrors(), false);
if (hasErrors) {
done(new GUtil.PluginError('webpack', 'Build completed with errors'));
} else {
done();
}
};
}
|
import connectDb from "../../../../utils/connectDb";
import Post from "../../../../models/Post";
import "../../../../models/User";
import authenticate from "../../../../middleware/auth";
import mongoose from "mongoose";
connectDb();
const handler = async (req, res) => {
switch (req.method) {
case "GET":
await handleGetRequest(req, res);
break;
default:
res.status(405).send(`Method ${req.method} not allowed`);
break;
}
};
// @route GET api/posts/postdetails/myposts
// @desc retrieve all posts that user has created
// @res posts: {... array of all posts}
// @access Public
async function handleGetRequest(req, res) {
try {
const posts = await Post.find({
user: new mongoose.Types.ObjectId(req.user.id),
});
if (!posts) {
return res.status(400).send("There is no posts");
}
res.status(200).json(posts);
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error");
}
}
export default authenticate(handler);
|
var mongodb = require('mongodb')
, MongoClient = mongodb.MongoClient
, debug = require('debug')('database')
, EventEmitter = require('events').EventEmitter
;
var database = module.exports = function (uri) {
// Connection URL
var database = {'uri': uri}
, connect = new EventEmitter()
;
var onConnect = new Promise( (resolve, reject) => {
connect.on('db', function(db) {
database.db = db;
db.on('close', function() {
database.db = null;
});
resolve(db);
});
connect.on('error', reject);
});
database.connect = function (uri) {
uri = uri || database.uri;
if (database.db && database.db.isConnected()) {
return Promise.resolve(database.db);
}
MongoClient.connect(uri, function (err, db) {
if (!err) {
debug('Connected to %s', uri);
connect.emit('db', db);
} else {
connect.emit('error', err);
}
});
return onConnect;
}
database.then = onConnect.then.bind(onConnect);
database.catch = onConnect.catch.bind(onConnect);
return database;
}
|
import crypto from 'crypto';
/**
* See {@link https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity|Subresource Integrity} at MDN
*
* @param {array} hashes - The algorithms you want to use when hashing `content`
* @param {string} content - File contents you want to hash
* @return {string} SRI hash
*/
function getSRIHash(hashes, content) {
return Array.isArray(hashes) ? hashes.map((hash) => {
const integrity = crypto.createHash(hash).update(content, 'utf-8').digest('base64');
return `${hash}-${integrity}`;
}).join(' ') : '';
}
export default getSRIHash;
|
import React, { Component } from 'react';
import { Menu} from 'semantic-ui-react'
class NavBar extends Component {
render() {
const { activeItem } = this.props.value
return (
<React.Fragment >
<Menu.Menu position='right'>
<Menu.Item
name='LOGIN'
active={activeItem === 'LOGIN'}
onClick={this.props.handleItemClick}
/>
</Menu.Menu>
</React.Fragment>
)
}
}
export default NavBar
|
const updateActiveSheet = () => {
update({ skip: false })
}
const updateActiveSheetNoChecked = () => {
update({
skip: (sheet, row) => {
const checkCol = 4
return sheet.getRange(row, checkCol).getValue()
}
})
}
const updateTimestamp = (sheet, row) => {
const timestampCol = 1
const time = new Date()
sheet.getRange(row, timestampCol).setValue(time)
}
const update = ({ skip }) => {
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet()
const sheet = spreadsheet.getActiveSheet()
const startRow = 6
const lastRow = sheet.getLastRow()
const jobIdRow = 3
const startCol = 5
for (i = 0; i <= lastRow - startRow; i++) {
const row = startRow + i
if (skip && skip(sheet, row)) {
continue
}
const jobId = sheet.getRange(row, jobIdRow).getValue()
/**
* basic: [報酬, 納品完了日, 掲載日, 応募期限]
* statistics: [応募, 契約, 募集, 気になる]
* clientInfo: [名前, ありがとう, 評価, 募集実績, プロジェクト完了率]
*/
const { basic, statistics, clientInfo } = scraping(jobId)
basic
.concat(statistics)
.concat(clientInfo)
.forEach((val, index) => {
sheet.getRange(row, startCol + index).setValue(val)
})
updateTimestamp(sheet, row)
}
}
|
import $ from 'jquery';
import Backbone from 'backbone';
import Game from 'app/models/game';
const GameList = Backbone.Collection.extend({
model: Game,
});
export default Board;
|
var pluginName = "Change name of layer to name of file";
// enable double clicking from the Macintosh Finder or the Windows Explorer
#target photoshop
// debug level: 0-2 (0:disable, 1:break on error, 2:break at beginning)
$.level = 0;
//debugger; // launch debugger on next line
// on localized builds we pull the $$$/Strings from a .dat file, see documentation for more details
$.localize = true;
var gScriptResult;
app.activeDocument.activeLayer.name = app.activeDocument.name;
|
const Engine = Matter.Engine;
const World = Matter.World;
const Bodies = Matter.Bodies;
const Body = Matter.Body;
var dustbin1, dustbin2, dustbin3;
var ball;
var ground1
function preload()
{
}
function setup() {
createCanvas(1500, 400);
engine = Engine.create();
world = engine.world;
ground1 = new ground(750,375,1500,15)
dustbin1= new Box (900,310,17,125);
dustbin1.shapeColor = "white"
dustbin2= new Box(1100,310,17,125);
dustbin2.shapeColor = "white"
dustbin3= new Box(1000,370,200,17);
dustbin3.shapeColor = "white"
ball = new Ball(250,250,20)
Engine.run(engine);
}
function draw() {
rectMode(CENTER);
background(0);
ground1.display();
dustbin1.display();
dustbin2.display();
dustbin3.display();
ball.display();
}
function keyPressed()
{
console.log(ball)
if (keyCode === UP_ARROW)
{
Matter.Body.applyForce(ball.body,ball.body.position,{x:1,y:-10});
}
}
|
const newFavorite = (db, id, title, author, thumblink) => {
db.find({id}, function (err, exist) {
if(exist.length === 0){
const schema = {id, title, author, thumblink};
db.insert(schema, function (err, newInsert) {
if(err) throw err;
console.log(newInsert);
});
}else{
return
}
})
};
const removeFavorite = (db, id, event) => {
db.remove({_id: id}, {}, function (err, numRemoved) {
if(err) throw err
if(numRemoved > 0) event.reply('favRemove', true);
});
};
const listFavorite = (db, event) => {
db.find({}, function (err, music) {
if(err) throw err;
event.reply('listFavs', music);
});
};
module.exports = {listFavorite, newFavorite, removeFavorite}
|
/**
* @name PriceGroup
* @author Oleg Kaplya
* @overview PriceGroup model.
*/
'use strict';
module.exports = function(sequelize, DataTypes) {
var PriceGroup = sequelize.define('price_group', {
title: DataTypes.STRING,
data: DataTypes.STRING,
price: DataTypes.DECIMAL
}, {
underscored: true
});
return PriceGroup;
};
|
import React from "react"
import "../styles/about.css"
import Layout from "../components/layout"
export default () => (
<Layout>
<div className="about">
<p>Such wow. Very React.</p>
</div>
</Layout>
)
|
var app = getApp()
Page({
data: {
blockIsShow: false,
details: {},
userId:"",
},
onLoad: function (options) {
this.setData({
userId: options.userId,
groupId: options.groupId
})
},
onShow: function () {
var that = this;
// 人员详情
app.wxRequest("gongguan/api/wechat/groupPersonInfo",
{ groupId: that.data.groupId, userId: that.data.userId },
"post", function (res) {
console.log(res.data.data)
if (res.data.code == 0) {
var data = res.data.data;
that.setData({
details: data
})
wx.setNavigationBarTitle({
title: data.leaderName
})
} else {
app.showLoading(res.data.msg, "none");
}
})
},
onHide: function () {
},
})
|
const { google } = require('googleapis');
const credentials = require(require('os').homedir() + '/credentials.js');
const token = require(require('os').homedir() + '/token.json');
function authorize() {
const {
client_secret,
client_id,
redirect_uris
} = credentials.value.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id,
client_secret,
redirect_uris[0]
);
oAuth2Client.setCredentials(token);
return oAuth2Client;
}
exports.authorize = authorize;
|
const mongoose = require('mongoose');
const VehiculoSchema = new mongoose.Schema({
//PK
cod_Vehiculo: {
type: String,
unique: true,
required: true
},
Descripcion:{
type: String,
required: true,
}
});
const Vehiculo = mongoose.model('Vehiculo',VehiculoSchema);
module.exports = Vehiculo;
|
import enquirer from 'enquirer';
const { Toggle } = enquirer;
const packagePrompt = new Toggle({
message: 'Preferred package manager?',
enabled: 'yarn',
disabled: 'npm',
});
export default packagePrompt;
|
function GitHubHelper() {}
/**
* Generates a url for a call to GitHub using using prototypes string interpolation
* url: string
* interplation_values: pattern {key:value}
*
* create_url("user/#{username}", {username: "my_username"})
* outputs "http://github.com/api/v2/json/user/my_username"
*/
GitHubHelper.create_url = function(url, interpolation_values) {
return "http://github.com/api/v2/json/" + url.interpolate(interpolation_values);
}
/**
* Gets the API login credentials that we've stored in the cookie
*/
GitHubHelper.get_credentials = function() {
var cred_store = new Mojo.Model.Cookie("GitopotamusLogin");
var creds = cred_store.get();
if (creds)
return {login: creds.login, token: creds.token};
else
return {login: "", token: ""};
}
|
import React, { useState } from 'react';
import { useFocusEffect } from '@react-navigation/native';
import { View, Text, Image, ScrollView, TextInput, TouchableOpacity, Button, StyleSheet } from 'react-native';
import axios from 'axios';
import { useSelector, useDispatch } from 'react-redux'
import Question from './Home'
import { Colors } from 'react-native/Libraries/NewAppScreen';
function QuizApp({ navigation }) {
const catogory = useSelector(state => state.catagory);
const dispatch = useDispatch()
// console.log(catogory);
useFocusEffect(
React.useCallback(() => {
axios.get('https://opentdb.com/api_category.php')
.then((res) => {
dispatch({ type: 'CATAGORY', catg: (res.data) })
})
.catch((err) => console.log(err.message))
}, []))
return (
<ScrollView>
<View>
<View >
{
catogory ?
catogory.trivia_categories?.map((v, i) => {
return <TouchableOpacity style={style.catgName} key={i} onPress={() => {
dispatch({ type: 'ID', id: v.id })
navigation.navigate('home')
}}>
<Text style={{color:'#1a1300', fontSize: 15,fontWeight: "bold"}} >{v.name}</Text>
</TouchableOpacity>
}) : <Text>...Loading Quiz App</Text>
}
</View>
{/* <Question/> */}
<Text>Quiz App</Text>
<TouchableOpacity onPress={() => navigation.navigate('home')} >
<Text>Home</Text>
</TouchableOpacity>
</View>
</ScrollView>
);
}
const style = StyleSheet.create({
catgName: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
borderWidth: 2,
borderColor: "#20232a",
borderRadius: 6,
backgroundColor: "#b38600",
color: "#fff",
padding: 10,
marginBottom: 10,
marginRight: 20,
marginLeft: 20,
}
})
export default QuizApp;
|
const CodesTypes = {
SET_CODES_PROJECTS: 'codeProjects:set',
SET_CODES_WORKSPACE: 'codeWorkspace:set',
ADD_CODES_OPENED_FILES: 'codeOpenedFiles:add',
CLOSE_CODES_OPENED_FILES: 'codeOpenedFiles:close',
CLEAR_CODES_OPENED_FILES: 'codeOpenedFiles:clear',
SET_CODES_SELECTED_FILES: 'codeSelectedFiles:set',
SET_CODE_CONTENT: 'codeContent:set',
}
export default CodesTypes
|
import React, { useState, useEffect } from 'react';
import { Bar } from 'react-chartjs-2';
const Dashboard = () => {
const [length, setLength] = useState(0);
const [positiveWords, setPositiveWords] = useState(0);
const [negativeWords, setNegativeWords] = useState(0);
const [recommendations, setRecommendations] = useState([]);
useEffect(() => {
setLength(localStorage.getItem('length'));
}, []);
const data = {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [
{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)',
],
borderWidth: 1,
},
],
};
const options = {
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
};
return length === 0 ? (
<div></div>
) : (
<div>
<Bar data={data} options={options} />
<h1>{length}</h1>
</div>
);
};
export default Dashboard;
|
/*
================================
EXPLANATION
================================
Upon running server.js, one will start a server on a specific port (default is port 3000).
Client side can access server, and will be re-directed to signin.html (which is in the static_files directory).
Server-client side communication involves a sqlite database for account info, and 2 json files, each containing printer and table information.
PART A: CRUD (Create, Read, Update, Delete) -- Account Info.
Client side (html) will communicate with the server's CRUD to access/edit/delete account info.
PART B: Socket Communication with Client -- Table and Printer Info.
When accessing map.html (the map interface of the table availability in the library), client and server communicate via the socket.
The client will send a message to the server in two situations:
- client changes a data in table and/or printer database
- client just connected (eg: a new client logs into map.html):
* Since client will not have info of the updated database at this point, it will send a message containing '0', which basically informs the server new client connected.
* Server will then emit a message to all client(s) of the most updated database.
When a client detects a change in the table and/or printer database, it will send a message in the socket.
The server will receive the message from the client(s), and update two sources:
- local (table and/or printer) json file; done by overwriting the json file
- other clients; done by sending a message to ALL clients of the new table/printer database.
Programmed by Alex Wong and Jin Chul Ann
*/
// ====== IMPORT node_modules ======
var express = require('express'); // minimal and flexible Node.js web application
var app = express();
var sql = require ('sql.js'); // sql 3-rd party plugin
var fs = require('fs'); // file system module
var http = require('http').Server(app); // start an http server
var io = require('socket.io')(http);
var jsonfile = require('jsonfile'); // read json file 3-rd party plugin
// ====== SETUP ======
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
//Load files in directory: static files
app.use(express.static('static_files'));
//Automatically redirect webpage to signin.html.
app.get('/', function (req, res)
{
res.sendFile(__dirname + '/static_files/signin.html');
});
// ====== PART A: CRUD (Create, Read, Update, Delete) -- Account Info ======
//TODO: Certain functionalities (such as read) may need to be disabled for security reasons.
// SETUP
// If data.sqlite exists, this is toggled on.
// If toggled off, it will create a sqlite database (data.sqlite)
// Reference the if-else statement a few lines below.
var sqliteExists = 1;
//Toggle sqliteExists off if there is no sqLite database. But this should be only done by the admin.
if(sqliteExists == 0)
{
//Create table and insert 2 accounts into it.
var db = new sql.Database();
sqlstr = "CREATE TABLE data (name char, password char, bday char, job char, email char)";
db.run(sqlstr);
db.run("INSERT INTO data VALUES ('alex', 'wong', '12', 'student', 'a@a.com')");
db.run("INSERT INTO data VALUES ('jin', 'ann', '12', 'student', 'j@j.com')");
//EXPORT (update) local SQLiteDatabase
var data = db.export();
var buffer = new Buffer(data);
fs.writeFileSync("data.sqlite", buffer);
}
else
{
//Read data
var filebuffer = fs.readFileSync('data.sqlite');
// Load the db
var db = new sql.Database(filebuffer);
}
// Listen at port 3000.
var server = http.listen(3000, function()
{
var port = server.address().port;
console.log('Server started at http://localhost:%s/', port);
});
// CREATE USER
app.post('/users', function(req, res)
{
var postBody = req.body;
var myName = postBody.name;
if(!myName)
{
res.send('ERROR');
return;
}
// In database, search for name = myName.
var stmt = db.prepare("SELECT * FROM data WHERE name=:uname", {':uname':myName});
if(!stmt.step())
{
//Insert data into the sqlite database (containing account info)
db.run("INSERT INTO data VALUES (:name, :password, :bday, :job, :email)",
{':name':postBody.name, ':password':postBody.password, ':bday':postBody.bday,
':job':postBody.job, ':email':postBody.email});
//Export new data (update local sqlite)
var data = db.export();
var buffer = new Buffer(data);
fs.writeFileSync("data.sqlite", buffer);
res.send('OK');
}
else
{
//Send Error message.
res.send('ERROR_Username');
return;
}
});
// READ LIST OF USER
app.get('/users', function(req, res)
{
var allUsers = [];
var stmt = db.prepare("SELECT * FROM data");
//Loop through all stmt, and push into allUsers list.
while (stmt.step())
allUsers.push(stmt.getAsObject().name);
res.send(allUsers);
});
// READ SPECIFIC USER
app.get('/users/*', function(req, res)
{
var stmt = db.prepare("SELECT * FROM data WHERE name=:user");
var result = stmt.getAsObject({':user':req.params[0]});
res.send(result);
return;
});
//UPDATE USER PROFILE
app.put('/users/*', function (req, res)
{
var nameToLookup = req.params[0];
var postBody = req.body;
//Update database.
for(key in postBody)
{
db.run("UPDATE data SET '" + key + "'='" + postBody[key] + "' WHERE name='" + nameToLookup + "'");
}
//Export new data
var data = db.export();
var buffer = new Buffer(data);
fs.writeFileSync("data.sqlite", buffer);
res.send('OK');
return;
});
// DELETE USER PROFILE
app.delete('/users/*', function (req, res)
{
var myName = req.params[0];
db.run("DELETE from data WHERE name=:uname", {':uname':myName});
//Export new data
var data = db.export();
var buffer = new Buffer(data);
fs.writeFileSync("data.sqlite", buffer);
res.send('OK');
});
// ===== PART B: Socket Communication with Client -- Table and Printer Info =====
/*
Clients do not talk to each other. Thus, this server receives information from
many individual clients, and emits the messages to update the rest of the clients.
At the same time, the server has a local copy of the data, and updates the local
copy as well.
*/
//Read json file synchrously
//TODO: is this fs redundant?
var fs = require('fs'); // this is used ot read json file
//Read json file (local files)
var table_data = JSON.parse(fs.readFileSync(__dirname + '/data_table.json'));
var printer_data = JSON.parse(fs.readFileSync(__dirname + '/data_printer.json'));
//Socket IO connection to client: Printer and Table message.
io.on('connection', function(socket)
{
// When any user sends a 'table' to the server, run the inner function below ...
// (note that this inner function runs only when someone sends a message to
// the server. if nobody is sending messages, this function never runs)
//Listen in socket for printer messages.
socket.on('printer', function(msg)
{
console.log("receive printer message: " + msg);
//if msg == 0, then this is the initial message when a new client is initialized.
//When this happens, emit a message to all clients to update the data (since the new client will need the update; as it's initial database might be empty).
if(msg == 0)
{
console.log("Send message out");
io.emit('printer', JSON.stringify(printer_data)); //JSON.stringify converts JSON object to a string.
}
else
{
// The format of msg is a '+' or '-', followed by the printer id.
// +<printer_id> indicates an increment in the printer queue; vice versa for -<printer_id>
if(msg.charAt(0) == '+' || msg.charAt(0) == '-')
{
//TODO: Now, printer_num is only limited to one digit.
var printer_num = msg.charAt(1);
//TOOD: need to loop through all even after found the table_id?
//Loop through printer_data, and find the printer_id. Then change the data (increment/decrement queue).
for( var i = 0; i < printer_data.features.length; i++)
{
var e = printer_data.features[i];
if (e.id.toString() == printer_num)
{
console.log("Printer to increment: " + printer_num + ": Queue: " + e.queue);
if(e.queue == 0 && msg.charAt(0) == '-')
console.log("ERROR. Queue already at 0. Cannot decrease");
else if(msg.charAt(0) == '+')
e.queue++;
else if(msg.charAt(0) == '-')
e.queue--;
else
console.log("Cannot understand input.")
console.log("Printer Queue changed: " + e.id.toString() + ": Queue: " + e.queue);
// Send 'printer' message in socket to notify ALL clients.
io.emit('printer', JSON.stringify(printer_data));
// Update the file on the server-side; local printer message.
var file = __dirname + "/data_printer.json";
jsonfile.writeFile(file, printer_data, {spaces:2}, function(err)
{
console.error(err);
});
}
}
}
else
{
//DO NOTHING.
}
}
});
// Listen in socket for 'table' messages.
socket.on('table', function(msg)
{
console.log("Receive table message: " + msg)
var tableToLookup = msg;
console.log("input: " + msg);
//if msg == 0, then this is the initial message when a new client is initialized.
//When this happens, emit a message to all clients to update the data (since the new client will need the update; as it's initial database might be empty).
if(tableToLookup == 0)
{
io.emit('table', JSON.stringify(table_data));
}
else
{
//Loop through JSON to find a match in table_id (in our local json file). Then update client and local file.
for( var i = 0; i < table_data.features.length; i++)
{
var e = table_data.features[i];
if (e.id.toString() == tableToLookup)
{
console.log("table to change: " + tableToLookup + ": Stat: " + e.occupied);
if (e.occupied == 1) {
table_data.features[i].occupied = 0;
}
else
{
table_data.features[i].occupied = 1;
}
console.log("table changed: " + e.id.toString() + ": Stat: " + e.occupied);
// Send table socket message to ALL client to update their table database.
io.emit('table', JSON.stringify(table_data));
// Update the local json file.
var file = __dirname + "/data_table.json";
jsonfile.writeFile(file, table_data, {spaces:2}, function(err)
{
console.error(err);
});
}
}
}
});
});
|
var NetworkMessageType = {
SERVERINFO: 1,
CLIENTINFO: 2,
EVENT: 3,
};
var EventType = {
ENTITY: 1, //entity data to server
LOCALENTITY: 2,
UPDATE: 3 //update clients
//ANY: 1, //default
//SCENE: 3,
//INPUT: 4,
//UNIT: 5
};
// for CLIENT only!
function enqueueEvent(event) {
G.client.clientEventHandler.enqueue(event);
};
//client event sent to server
var CreateEntityEvent = function (params) {
this.eventName = "createEntity";
this.eventType = EventType.ENTITY;
this.isLocal = params.isLocal || false;
this.entityData = params.entityData;
//var entityData = {
// entityType: "Dummy",
// spatial: {
// position: [0, 0, 0]
// },
// movement: {
// velocity: [0, 0, 0.01]
// }
//};
}
// modifies raw values
var EntityAddDataEvent = function (params) { //try to avoid this event
this.eventName = "addData";
this.eventType = EventType.ENTITY;
this.isLocal = params.isLocal || false;
this.entityData = params.entityData;
//var entityData = {
// entityId: 1,
// movement: {
// velocity: [0, 0, 0.01]
// }
//};
}
// sets raw values
var EntitySetDataEvent = function (params) {
this.eventName = "setData";
this.eventType = EventType.ENTITY;
this.isLocal = params.isLocal || false;
this.entityData = params.entityData;
//var entityData = {
// entityId: 1,
// spatial: {
// position: [0, 0, 0]
// },
// movement: {
// velocity: [0, 0, 0]
// }
//};
}
var EntitySetRTEvent = function (params) {
this.eventName = "setRT";
this.eventType = EventType.ENTITY;
this.isLocal = params.isLocal || false;
this.entityData = params.entityData;
}
var EntityAddLocalRTEvent = function (params) {
this.eventName = "addLocalRT";
this.eventType = EventType.ENTITY;
this.isLocal = params.isLocal || false;
this.entityData = params.entityData;
//enqueueEvent(new EntityLocalRTEvent({
// entityData: {
// entityId: entityId
// , spatial: {
// position: [0, 0, 2] //instantly 2 forwards (local space)
// }
// , movement: {
// velocity: [0, 0, 0.01] //velocity 0.01 forwards (local space)
// }
// , spin: {
// velocity: [roll[0], roll[1], roll[2], roll[3]] //rolling around like theres no tomorrow
// }
// }
//}));
}
// events viel intuitiver erstellen!
// roll, pitch statt orientation quaternion in localRT
// etc.
var EntityAddWorldRTEvent = function (params) {
this.eventName = "addWorldRT";
this.eventType = EventType.ENTITY;
this.isLocal = params.isLocal || false;
this.entityData = params.entityData;
}
//server event sent to all clients
var UpdateEntityEvent = function (params) {
this.eventName = "updateEntity";
this.eventType = EventType.UPDATE;
this.updateData = params.updateData;
}
//////////////////////////////////////////////
//
//var Event = Backbone.Model.extend({
// defaults: {
// eventType: EventType.ANY,
// eventName: "none",
// isNetworkEvent: false,
// networkId: null
// }
//});
//
//////////////////////////////////////////////
//
//var SpatialComponentSetTranslationEvent = Event.extend({
// defaults: {
// eventType: EventType.SCENE,
// eventName: "setTranslation",
// isNetworkEvent: true
// },
// initialize: function (params) {
// this.entityId = params.entityId;
// this.position = params.position;
// this.rotationX = params.rotationX;
// this.rotationY = params.rotationY;
// this.rotationZ = params.rotationZ;
// }
//});
//
//var SpatialComponentAddTranslationEvent = Event.extend({
// defaults: {
// eventType: EventType.SCENE,
// eventName: "addTranslation",
// isNetworkEvent: true
// },
// initialize: function (params) {
// this.scope = params.scope || "local";
// this.entityId = params.entityId;
// this.position = params.position;
// this.rotationX = params.rotationX;
// this.rotationY = params.rotationY;
// this.rotationZ = params.rotationZ;
// }
//});
//
//
//var SpatialComponentLookAtEvent = Event.extend({
// defaults: {
// eventType: EventType.SCENE,
// eventName: "lookAt",
// isNetworkEvent: true
// },
// initialize: function (params) {
// this.entityId = params.entityId;
// this.targetEntityId = params.targetEntityId;
// this.targetPoint = params.targetPoint;
// }
//});
|
/**
* Created by Neo on 2016/8/10.
*/
var React = require('react');
var InputWidget = React.createClass({
render: function () {
return(
<div className="form-group">
<label htmlFor={this.props.name} className="col-sm-3 control-label no-padding-right">{this.props.label}</label>
<div className="col-sm-9">
<input className="form-control" maxLength="50" name={this.props.name} value={this.props.value} onChange={this.props.updateState} type="text"/>
</div>
</div>
);
}
});
var CheckWidget = React.createClass({
render: function () {
return (
<div className="form-group">
<div className="checkbox col-sm-offset-1">
<label>
<input type="checkbox" name={this.props.name} className="colored-success" checked={this.props.value} onChange={this.props.updateState} />
<span className="text">{this.props.label}</span>
</label>
</div>
</div>
);
}
});
var TreeNodeWidget = React.createClass({
render: function() {
var childNodes;
var bcollapse;
var bexpand;
if (this.props.node != null && this.props.node.children != null) {
var childs = this.props.node.children.map(function(node) {
return <TreeNodeWidget key={node.id} node={node} edit={this.props.edit}/>
},this);
if(this.props.node.children.length > 0) {
childNodes = <ol className="dd-list">{childs}</ol>;
var ss = {
display:"none"
};
bcollapse = <button data-action="collapse" type="button" >Collapse</button>;
bexpand = <button data-action="expand" type="button" style={ss}>Expand</button>;
}
}
var active = this.props.node.active?"dd-handle dd2-handle bg-success":"dd-handle dd2-handle bg-danger";
return (
<li className="dd-item dd2-item" data-id={this.props.node.id}>
{bcollapse}
{bexpand}
<div className={active}>
<i className="menu-icon" className={this.props.node.icon }></i>
<i className="drag-icon fa fa-arrows-alt"></i>
</div>
<div className="dd2-content">
{this.props.node.name}
<a href="javacript:void(0)">
<i className="glyphicon glyphicon-pencil right-edit" onClick={this.props.edit.bind(null,this.props.node.id)}>编辑</i>
</a>
</div>
{childNodes}
</li>
);
}
});
var SubmitButtonWidget = React.createClass({
render: function () {
return <a href="javascript:void(0);" className="btn btn-blue" onClick={this.props.submit}>保存</a>
}
});
|
var mn = mn || {};
mn.components = mn.components || {};
mn.components.MnUserRoles =
(function (Rx) {
"use strict";
mn.core.extend(MnUserRoles, mn.core.MnEventableComponent);
MnUserRoles.annotations = [
new ng.core.Component({
templateUrl: "app-new/mn-user-roles.html"
})
];
MnUserRoles.parameters = [
mn.services.MnHelper,
mn.services.MnPools,
mn.services.MnAdmin,
mn.services.MnSecurity,
mn.services.MnUserRoles,
mn.services.MnPermissions,
window['@uirouter/angular'].UIRouter
];
MnUserRoles.prototype.filterRouterParams = filterRouterParams;
MnUserRoles.prototype.trackByFn = trackByFn;
return MnUserRoles;
function MnUserRoles(mnHelperService, mnPoolsService, mnAdminService, mnSecurityService, mnUserRolesService, mnPermissionsService, uiRouter) {
mn.core.MnEventableComponent.call(this);
var userRolesFieldsGroup = new ng.forms.FormGroup({
searchTerm: new ng.forms.FormControl(""),
pageSize: new ng.forms.FormControl()
});
this.userRolesFieldsGroup = userRolesFieldsGroup;
this.onSortByClick = new Rx.BehaviorSubject("id");
this.isEnterprise = mnPoolsService.stream.isEnterprise;
this.ldapEnabled = mnAdminService.stream.ldapEnabled;
this.isSaslauthdAuthEnabled = mnSecurityService.stream.getSaslauthdAuth.pipe(Rx.operators.pluck("enabled"));
this.securityWrite = mnPermissionsService.createPermissionStream("admin.security!write");
var routerParams =
uiRouter.globals.params$.pipe(
Rx.operators.map(this.filterRouterParams.bind(this)),
Rx.operators.distinctUntilChanged(_.isEqual)
);
var pageSizeFormValue =
this.userRolesFieldsGroup.valueChanges.pipe(
Rx.operators.pluck("pageSize"),
Rx.operators.distinctUntilChanged()
);
var searchTermFormValue =
this.userRolesFieldsGroup.valueChanges.pipe(
Rx.operators.pluck("searchTerm"),
Rx.operators.distinctUntilChanged()
);
this.users =
Rx.combineLatest(
routerParams,
Rx.timer(0, 10000)
).pipe(
Rx.operators.pluck("0"),
Rx.operators.switchMap(mnUserRolesService.getUsers.bind(mnUserRolesService)),
mn.core.rxOperatorsShareReplay(1)
);
this.filteredUsers =
Rx.combineLatest(
this.users.pipe(Rx.operators.pluck("users")),
searchTermFormValue
).pipe(
Rx.operators.map(function (resp) {
return resp[0].filter(listFiter(resp[1]));
}),
mnHelperService.sortByStream(this.onSortByClick)
);
this.firstPageParams =
pageSizeFormValue.pipe(
Rx.operators.map(function (pageSize) {
return {
pageSize: pageSize,
startFromDomain: null,
startFrom: null
};
})
);
pageSizeFormValue.pipe(
Rx.operators.takeUntil(this.mnOnDestroy)
).subscribe(function (pageSize) {
uiRouter.stateService.go('.', {pageSize: pageSize});
});
routerParams.pipe(
Rx.operators.first()
).subscribe(function (params) {
userRolesFieldsGroup.patchValue({pageSize: params.pageSize || 10});
});
}
function listFiter(searchValue) {
return function (user) {
var interestingFields = ["id", "name"];
var l1 = user.roles.length;
var l2 = interestingFields.length;
var i1;
var i2;
searchValue = searchValue.toLowerCase();
var role;
var roleName;
var rv = false;
var searchFiled;
if ((user.domain === "local" ? "Couchbase" : "External")
.toLowerCase()
.indexOf(searchValue) > -1) {
rv = true;
}
if (!rv) {
//look in roles
loop1:
for (i1 = 0; i1 < l1; i1++) {
role = user.roles[i1];
if (role.role.toLowerCase().indexOf(searchValue) > -1 ||
(role.bucket_name &&
role.bucket_name.toLowerCase().indexOf(searchValue) > -1)) {
rv = true;
break loop1;
}
}
}
if (!rv) {
//look in interestingFields
loop2:
for (i2 = 0; i2 < l2; i2++) {
searchFiled = interestingFields[i2];
if (user[searchFiled].toLowerCase().indexOf(searchValue) > -1) {
rv = true;
break loop2;
}
}
}
return rv;
}
}
function trackByFn(user) {
return user.id + user.domain;
}
function filterRouterParams(params) {
var keys = ["pageSize", "startFromDomain", "startFrom"];
return _.reduce(keys, function (params1, key) {
if (params[key]) {
params1[key] = params[key];
}
return params1;
}, {});
}
})(window.rxjs);
|
import React, { useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import styled from "styled-components";
import { ButtonCustom } from "../../components/ButtonCustom";
import { removeToken } from "../../helpers/session.js"
import { MAIN_URL } from "../../constants/routes";
import { getProfile, getSgf, getFullLog } from "../../store/Profile/actions";
import { strings } from "../../language";
const Wrapper = styled.div`
display: grid;
@media (max-width: 1000px) {
grid-template-areas:
"info"
"history";
}
@media (min-width: 1000px) {
grid-template-columns: 1fr 1fr;
grid-template-areas:
"info history";
}
height: 100vh;
position: relative;
align-items: center;
width: 100%;
padding: 20px 0;
`;
const Info = styled.div`
grid-area: info;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
min-width: 150px;
margin-bottom: 70px;
`;
const InfoPlayer = styled.div``;
const Left = styled.div`
margin-right: 8px;
display: flex;
align-items: center;
`;
const Right = styled.div`
display: flex;
align-items: center;
`;
const GameHistory = styled.div`
grid-area: history;
@media (max-width: 1000px) {
height: fit-content;
min-height: 200px;
}
@media (min-width: 1000px) {
height: 90vh;
min-height: 200px;
overflow: hidden;
overflow-y: scroll;
display: flex;
flex-direction: column;
}
margin: 0 15px 0 15px;
min-width: 150px;
`;
const Avatar = styled.img`
border-radius: 100px;
width: 200px;
margin-bottom: 20px
`;
const Name = styled.p`
text-overflow: ellipsis;
overflow:hidden;
font-weight: bold;
font-size: 24px;
line-height: 28px;
`;
const Pts = styled.p`
color: #222233;
font-size: 12px;
line-height: 14px;
`;
const Span = styled.p`
font-weight: bold;
font-size: 24px;
line-height: 28px;
color: #222233;
`;
const ScoreLeft = styled.p`
font-size: 24px;
line-height: 28px;
font-weight: bold;
color: #222233;
margin-right: 5px;
`;
const ScoreRight = styled.p`
font-size: 24px;
line-height: 28px;
font-weight: bold;
color: #222233;
margin-left: 5px;
margin-right: 16px;
`;
const AvatarHistory = styled.img`
width: 90px;
margin-right: 15px;
`;
const ButtonDownloadFile = styled.div`
width: 90px;
font-weight: 400;
text-align: center;
font-family: "Roboto",sans-serif;
display: block;
outline: none;
-webkit-flex-shrink: 0;
-ms-flex-negative: 0;
flex-shrink: 0;
background-color: #222233;
border-radius: 5px;
color: white;
padding: 5px;
cursor: pointer;
font-size: 18px;
border: none;
:first-child {
margin-bottom: 15px;
}
`;
const ButtonRow = styled.div`
display: flex;
flex-direction: column;
`;
const InfoText = styled.div `
margin-bottom: 10px;
font-size: 28px;
margin: 15px;
`
const GameHistoryItem = styled.div`
min-height: 120px;
width: 100%;
color: #222233;
border-color: #222233;
border-radius: 5px;
border-style: solid;
border-width: 1px;
margin: 10px 20px 0px 0px;
padding: 10px;
display: flex;
align-items: center;
justify-content: space-between;
overflow-y: hidden;
overflow-x: auto;
`;
const InfoHistory = styled.div``;
const Profile = ({ history }) => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(getProfile());
}, []);
const playerInfo = useSelector((state) => state.profile.userProfile.user);
const gameHistoryItems =
playerInfo?.games_history.map((item, i) => {
return item.scoreOpponent <= item.score ? (
<GameHistoryItem key={i} winner>
<Left>
<AvatarHistory alt="avatar" src={item.player.avatar} />
<InfoHistory>
<Name>{item.player.nickname}</Name>
<Pts>{item.player.pts} / {item.player.position+'th'}</Pts>
</InfoHistory>
</Left>
<Right>
<Span winner>{strings.win}</Span>
<ScoreRight winner>{"+"+item.score}</ScoreRight>
</Right>
<ButtonRow>
<ButtonDownloadFile onClick={()=>dispatch(getSgf(item.game_id))}>
{strings.file}
</ButtonDownloadFile>
<ButtonDownloadFile onClick={()=>dispatch(getFullLog(item.game_id))}>
{strings.log}
</ButtonDownloadFile>
</ButtonRow>
</GameHistoryItem>) : (
<GameHistoryItem key={i}>
<Left>
<AvatarHistory alt="avatar" src={item.player.avatar} />
<InfoHistory>
<Name>{item.player.nickname}</Name>
<Pts>{item.player.pts} / {item.player.position+'th'}</Pts>
</InfoHistory>
</Left>
<Right>
<Span>{strings.defeat}</Span>
<ScoreRight>{item.score}</ScoreRight>
</Right>
<ButtonRow>
<ButtonDownloadFile onClick={()=>dispatch(getSgf(item.game_id))}>
{strings.file}
</ButtonDownloadFile>
<ButtonDownloadFile onClick={()=>dispatch(getFullLog(item.game_id))}>
{strings.log}
</ButtonDownloadFile>
</ButtonRow>
</GameHistoryItem>
)
});
return (
<Wrapper>
<Info>
<ButtonCustom
width="400px"
mb="20"
onClick={() => {
history.push(MAIN_URL);
}}
>
{strings.back}
</ButtonCustom>
<Avatar alt="avatar" src={playerInfo?.avatar} />
<InfoPlayer>
<InfoText>
{playerInfo?.nickname}
</InfoText>
<InfoText>
{ playerInfo?.email }
</InfoText>
<InfoText>
{strings.score}: { playerInfo?.pts }
</InfoText>
<InfoText>
{strings.place}: { playerInfo?.position }
</InfoText>
</InfoPlayer>
<ButtonCustom
width="400px"
textAlign="center"
mb="20"
onClick={() => {
removeToken()
history.push(MAIN_URL);
}}
>
{strings.exit}
</ButtonCustom>
</Info>
<GameHistory>
{gameHistoryItems}
</GameHistory>
</Wrapper>
);
};
export default Profile;
|
/*
* @Author: xr
* @Date: 2021-03-20 17:42:02
* @LastEditors: xr
* @LastEditTime: 2021-04-06 14:23:35
* @version: v1.0.0
* @Descripttion: 功能说明
* @FilePath: \ui\src\components\tabs\btnMove.js
*/
import { reactive, nextTick, onUnmounted } from 'vue'
export const useBtnMove = () => {
const btnMoveState = reactive({
showBtn: false,
translateX: 0, scrollWrapDom: null, scrollDom: null
});
let startX = 0, wrapLeft = 0, beginX = 0, wrapWidth = 0, scrollWidth = 0;
/**
* @author: xr
* @descripttion: 获取尺寸
* @param {*}
* @return {*}
*/
const getTableSize = () => {
wrapWidth = parseFloat(getComputedStyle(btnMoveState.scrollWrapDom).width);
scrollWidth = parseFloat(getComputedStyle(btnMoveState.scrollDom).width);
}
/**
* @author: xr
* @descripttion: 判断是否需要显示按钮
* @param {*}
* @return {*}
*/
const triggerShowBtn = () => {
nextTick(() => {
getTableSize();
if (scrollWidth >= wrapWidth) {
btnMoveState.showBtn = true;
} else {
btnMoveState.showBtn = false;
}
})
}
/**
* @author: xr
* @descripttion: 滚动x坐标
* @param {*} num 滚动距离 正负数
* @return {*}
*/
const handleChangeX = (num) => {
getTableSize();
let x = btnMoveState.translateX + wrapWidth * 0.8 * num;
let max = wrapWidth - scrollWidth - 10;
if (x <= max) {
x = max;
} else if (x >= 0) {
x = 0;
}
btnMoveState.translateX = x;
triggerShowBtn();
};
const mouseDown = (ev) => {
getTableSize();
btnMoveState.scrollDom.classList.remove('trans');
document.addEventListener('mousemove', mouseMove);
document.addEventListener('mouseup', mouseUp);
startX = ev.clientX - wrapLeft;
beginX = btnMoveState.translateX;
ev.preventDefault();
}
const mouseMove = (ev) => {
if (scrollWidth < wrapWidth) {
btnMoveState.translateX = 0;
} else {
let x = (ev.clientX - wrapLeft - startX) + beginX;
let max = wrapWidth - scrollWidth - 10;
if (x <= max) {
x = max;
} else if (x >= 0) {
x = 0;
}
btnMoveState.translateX = x;
}
}
const mouseUp = (ev) => {
btnMoveState.scrollDom.classList.add('trans');
document.removeEventListener('mousemove', mouseMove);
document.removeEventListener('mouseup', mouseUp);
ev.preventDefault();
}
nextTick(() => {
triggerShowBtn();
wrapLeft = btnMoveState.scrollWrapDom.getBoundingClientRect().left;
btnMoveState.scrollDom.addEventListener('mousedown', mouseDown);
});
window.addEventListener('resize', triggerShowBtn);
onUnmounted(() => {
window.removeEventListener('resize', triggerShowBtn);
btnMoveState.scrollDom.removeEventListener('mousedown', mouseDown);
});
return {
btnMoveState,
handleChangeX, triggerShowBtn
}
}
|
{
"FullName":"Terry Jones",
"LastName":"Jones",
"FirstName":"Terry",
"EmailAddress":"terryj@montypyton.com",
"OfficePhone":"330.123.4567",
"MobilePhone":"330.987.6543"
}
|
const forms = require('forms')
const formFunctions = require('../../functions/forms/file');
const globalModel = require("../../models/globalModel")
var settings = require("../../models/settings")
const fs = require("fs")
const fileManager = require("../../models/fileManager")
exports.theme = async(req,res) => {
const url = req.originalUrl.replace(process.env.ADMIN_SLUG,'');
const selectedTheme = settings.getSetting(req,"selectedtheme",'night');
res.render('admin/designs/theme',{selectedTheme:selectedTheme,nav:url,title:"Manage Themes"});
}
exports.assets = async(req,res) => {
const files = {"":""}
await fileManager.findAll(req,{"column":"path","like":"image"}).then(result => {
result.forEach(res => {
let url = res.path.split(/(\\|\/)/g).pop()
files[res.path] = res.orgName
});
})
const url = req.originalUrl.replace(process.env.ADMIN_SLUG,'');
var fields = forms.fields;
var validators = forms.validators;
var widgets = forms.widgets;
const cssClasses = {
label :[""],
field : ["form-group"],
classes : ["form-control"]
};
var reg_form = forms.create({
site_theme: fields.string({
label: "Theme",
choices: {'1':"Default",'2':"Trendott"},
required:true,
widget: widgets.select({"classes":["select"]}),
cssClasses: {"field" : ["form-group"],label:['select']},
value:settings.getSetting(req,"site_theme","1").toString()
}),
favicon: fields.string({
label: "Favicon",
choices: files,
required:true,
widget: widgets.select({"classes":["select"]}),
cssClasses: {"field" : ["form-group"],label:['select']},
value:settings.getSetting(req,"favicon","").toString()
}),
darktheme_logo: fields.string({
label: "Dark Theme Logo",
choices: files,
required:true,
widget: widgets.select({"classes":["select"]}),
cssClasses: {"field" : ["form-group"],label:['select']},
value:settings.getSetting(req,"darktheme_logo","").toString()
}),
lightheme_logo: fields.string({
label: "Light Theme Logo",
choices: files,
required:true,
widget: widgets.select({"classes":["select"]}),
cssClasses: {"field" : ["form-group"],label:['select']},
value:settings.getSetting(req,"lightheme_logo","").toString()
}),
fixed_header: fields.string({
label: "Want to make Horizontal menu?",
choices: {'1':"Yes",'0':"No"},
required:true,
widget: widgets.select({"classes":["select"]}),
cssClasses: {"field" : ["form-group"],label:['select']},
value:settings.getSetting(req,"fixed_header","1").toString()
}),
hideSmallMenu: fields.string({
label: "Want to make to hide Menus default?(NOTE: below settings will work if above setting is yes.)",
choices: {'1':"Yes",'0':"No"},
required:true,
widget: widgets.select({"classes":["select"]}),
cssClasses: {"field" : ["form-group"],label:['select']},
value:settings.getSetting(req,"hideSmallMenu","0").toString()
}),
removeFixedMenu: fields.string({
label: "Do you want to make the header fixed.",
choices: {'1':"No",'0':"Yes"},
required:true,
widget: widgets.select({"classes":["select"]}),
cssClasses: {"field" : ["form-group"],label:['select']},
value:settings.getSetting(req,"removeFixedMenu","0").toString()
}),
// theme_design_mode: fields.string({
// choices: {'1':"Dark Theme",'2':"Light Theme","3" : "Dark & Light Theme (Default: light, Toggle)","4" : "Dark & Light (Default: dark, Toggle)"},
// widget: widgets.select({ "classes": ["select"] }),
// label:"Select the Theme toggle button?",
// fieldsetClasses:"form_fieldset",
// cssClasses: {"field" : ["form-group"]},
// value:settings.getSetting(req,"theme_design_mode",'3').toString()
// }),
});
reg_form.handle(req, {
success: function (form) {
settings.setSettings(req,form.data)
res.send({success:1,message:"Setting Saved Successfully."})
},
error: function(form){
const errors = formFunctions.formValidations(form);
res.send({errors:errors});
},
other: function (form) {
res.render('admin/designs/assets',{nav:url,reg_form:reg_form,title: "Manage Theme Assets"});
}
});
}
const getScript = (url) => {
return new Promise((resolve, reject) => {
const http = require('http'),
https = require('https');
let client = http;
if (url.toString().indexOf("https") === 0) {
client = https;
}
client.get(url, (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
resolve(data);
});
}).on("error", (err) => {
reject(err);
});
});
};
exports.color = async(req,res) => {
const url = req.originalUrl.replace(process.env.ADMIN_SLUG,'');
var fields = forms.fields;
var validators = forms.validators;
var widgets = forms.widgets;
var cssClasses = {
label :[""],
field : ["form-group"],
classes : ["form-control"]
};
var colors = {}
let type = "white"
if(req.params.theme){
type = req.params.theme
}
await globalModel.custom(req,"SELECT * from themes WHERE type = ?",[type]).then(result => {
result.forEach(elem => {
colors[elem.key] = elem.value
});
})
let webfontData = {
'Georgia, serif' : 'Georgia, serif',
"'Palatino Linotype', 'Book Antiqua', Palatino, serif" : '"Palatino Linotype", "Book Antiqua", Palatino, serif',
"'Times New Roman', Times, serif" : '"Times New Roman", Times, serif',
'Arial, Helvetica, sans-serif' : 'Arial, Helvetica, sans-serif',
"'Arial Black', Gadget, sans-serif" : '"Arial Black", Gadget, sans-serif',
"'Comic Sans MS', cursive, sans-serif" : '"Comic Sans MS", cursive, sans-serif',
'Impact, Charcoal, sans-serif' : 'Impact, Charcoal, sans-serif',
"'Lucida Sans Unicode', 'Lucida Grande', sans-serif" : '"Lucida Sans Unicode", "Lucida Grande", sans-serif',
'Tahoma, Geneva, sans-serif' : 'Tahoma, Geneva, sans-serif',
"'Trebuchet MS', Helvetica, sans-serif" : '"Trebuchet MS", Helvetica, sans-serif',
'Verdana, Geneva, sans-serif' : 'Verdana, Geneva, sans-serif',
"'Courier New', Courier, monospace" : '"Courier New", Courier, monospace',
"'Lucida Console', Monaco, monospace" : '"Lucida Console", Monaco, monospace',
"'Roboto', sans-serif" : '"Roboto", sans-serif'
}
let fontData = {}
//get google fonts
await getScript('https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyBZLVvcldwc6SxpeHlHzhGxdtSRPYeX7RQ').then(data => {
data = JSON.parse(data)
data.items.forEach(item => {
fontData[item.family] = item.family
})
}).catch(err => {
console.log(err)
})
var reg_form = forms.create({
mode: fields.string({
label : "Theme Mode" ,
choices: {"dark":"Dark Theme",'white':"White Theme"},
required:true,
widget: widgets.select({"classes":["select"]}),
cssClasses: {"field" : ["form-group"],label:['select']},
value:colors['fontFamily_heading'],
value:type
}),
label1: fields.string({
widget: formFunctions.makeClickable({ content: '<h3 style="text-align: center;margin: 40px;text-decoration: underline;">Settings</h3>', replace: [] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
Bgcolor_default: fields.string({
required: validators.required('%s is required'),
label : "Body Background Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['Bgcolor_default']
}),
Bgcolor_primary: fields.string({
required: validators.required('%s is required'),
label : "Theme Primary Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['Bgcolor_primary']
}),
Bgcolor_secondry: fields.string({
required: validators.required('%s is required'),
label : "Theme Secondary Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['Bgcolor_secondry']
}),
Bgcolor_tertiary: fields.string({
required: validators.required('%s is required'),
label : "Theme Tertiary Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['Bgcolor_tertiary']
}),
Border_color: fields.string({
required: validators.required('%s is required'),
label : "Border Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['Border_color']
}),
label2: fields.string({
widget: formFunctions.makeClickable({ content: '<h3 style="text-align: center;margin: 40px;text-decoration: underline;">Text Settings</h3>', replace: [] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
Textcolor_default: fields.string({
required: validators.required('%s is required'),
label : "Default Text Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['Textcolor_default']
}),
Textcolor_primary: fields.string({
required: validators.required('%s is required'),
label : "Primary Text Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['Textcolor_primary']
}),
Textcolor_secondry: fields.string({
required: validators.required('%s is required'),
label : "Secondary Text Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['Textcolor_secondry']
}),
Textcolor_tertiary: fields.string({
required: validators.required('%s is required'),
label : " Tertiary Text Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['Textcolor_tertiary']
}),
label3: fields.string({
widget: formFunctions.makeClickable({ content: '<h3 style="text-align: center;margin: 40px;text-decoration: underline;">Font Settings</h3>', replace: [] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
font_style: fields.string({
label: "Choose Fonts Style",
choices: {"web":"Web Font Style","google":"Google Fonts"},
required:true,
widget: widgets.select({"classes":["select"]}),
cssClasses: {"field" : ["form-group"],label:['select']},
value:colors['font_style']
}),
fontFamily_default_web: fields.string({
label: "Font Family Default",
choices: webfontData,
required:true,
widget: widgets.select({"classes":["select"]}),
cssClasses: {"field" : ["form-group"],label:['select']},
value:colors['fontFamily_default']
}),
fontFamily_heading_web: fields.string({
label: "Headings Font Family",
choices: webfontData,
required:true,
widget: widgets.select({"classes":["select"]}),
cssClasses: {"field" : ["form-group"],label:['select']},
value:colors['fontFamily_heading']
}),
fontFamily_default: fields.string({
label: "Font Family Default",
choices: fontData,
required:true,
widget: widgets.select({"classes":["select"]}),
cssClasses: {"field" : ["form-group"],label:['select']},
value:colors['fontFamily_default']
}),
fontFamily_heading: fields.string({
label: "Headings Font Family",
choices: fontData,
required:true,
widget: widgets.select({"classes":["select"]}),
cssClasses: {"field" : ["form-group"],label:['select']},
value:colors['fontFamily_heading']
}),
label4: fields.string({
widget: formFunctions.makeClickable({ content: '<h3 style="text-align: center;margin: 40px;text-decoration: underline;">Font Sizes</h3>', replace: [] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
fontSize_default: fields.string({
required: validators.required('%s is required'),
label : "Default Font Sizes" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:colors['fontSize_default']
}),
menu_FontSize: fields.string({
required: validators.required('%s is required'),
label : "Menu Font Sizes" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:colors['menu_FontSize']
}),
MenuDropDown_Bg: fields.string({
required: validators.required('%s is required'),
label : "Menu Dropdown Background Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['MenuDropDown_Bg']
}),
label5: fields.string({
widget: formFunctions.makeClickable({ content: '<h3 style="text-align: center;margin: 40px;text-decoration: underline;">Label Colors</h3>', replace: [] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
username_varify_color: fields.string({
required: validators.required('%s is required'),
label : "User Verified Background Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['username_varify_color']
}),
lableHot_bg: fields.string({
required: validators.required('%s is required'),
label : "Hot Label Background Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['lableHot_bg']
}),
lableFeatured_bg: fields.string({
required: validators.required('%s is required'),
label : "Featured Label Background Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['lableFeatured_bg']
}),
lableSponsored_bg: fields.string({
required: validators.required('%s is required'),
label : "Sponsored Label Background Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['lableSponsored_bg']
}),
label6: fields.string({
widget: formFunctions.makeClickable({ content: '<h3 style="text-align: center;margin: 40px;text-decoration: underline;">Videos Section</h3>', replace: [] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
videogrid_info_height: fields.string({
required: validators.required('%s is required'),
label : "Video Box Info Height" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:colors['videogrid_info_height']
}),
videogrid_text_color: fields.string({
required: validators.required('%s is required'),
label : "Video Title Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['videogrid_text_color']
}),
videoGrid_titlefontSize: fields.string({
required: validators.required('%s is required'),
label : "Video Title Font Size" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:colors['videoGrid_titlefontSize']
}),
label7: fields.string({
widget: formFunctions.makeClickable({ content: '<h3 style="text-align: center;margin: 40px;text-decoration: underline;">Channels Section</h3>', replace: [] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
chanlThmb_nameColor: fields.string({
required: validators.required('%s is required'),
label : "Channel Title Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['chanlThmb_nameColor']
}),
chanlThmb_nameFontSize: fields.string({
required: validators.required('%s is required'),
label : "Channel Title Font Size" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:colors['chanlThmb_nameFontSize']
}),
chanlThmb_bg: fields.string({
required: validators.required('%s is required'),
label : "Channel Box Background Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['chanlThmb_bg']
}),
label8: fields.string({
widget: formFunctions.makeClickable({ content: '<h3 style="text-align: center;margin: 40px;text-decoration: underline;">Artists Section</h3>', replace: [] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
artist_nameColor: fields.string({
required: validators.required('%s is required'),
label : "Artist Title Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['artist_nameColor']
}),
artist_nameFontSize: fields.string({
required: validators.required('%s is required'),
label : "Artist Title Font Size" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:colors['artist_nameFontSize']
}),
artist_imgHeight: fields.string({
required: validators.required('%s is required'),
label : "Artist Image Height" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:colors['artist_imgHeight']
}),
artist_bordercolor: fields.string({
required: validators.required('%s is required'),
label : "Artist Image Border Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['artist_bordercolor']
}),
label9: fields.string({
widget: formFunctions.makeClickable({ content: '<h3 style="text-align: center;margin: 40px;text-decoration: underline;">Members Section</h3>', replace: [] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
member_nameColor: fields.string({
required: validators.required('%s is required'),
label : "Member Title Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['member_nameColor']
}),
member_nameFontSize: fields.string({
required: validators.required('%s is required'),
label : "Member Title Font Size" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:colors['member_nameFontSize']
}),
member_imgHeigh: fields.string({
required: validators.required('%s is required'),
label : "Member Image Height" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:colors['member_imgHeigh']
}),
member_bordercolor: fields.string({
required: validators.required('%s is required'),
label : "Member Image Border Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['member_bordercolor']
}),
label10: fields.string({
widget: formFunctions.makeClickable({ content: '<h3 style="text-align: center;margin: 40px;text-decoration: underline;">Playlists Section</h3>', replace: [] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
playList_color: fields.string({
required: validators.required('%s is required'),
label : "Playlist Title Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['playList_color']
}),
playList_titleFontsize: fields.string({
required: validators.required('%s is required'),
label : "Playlist Title Font Size" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:colors['playList_titleFontsize']
}),
playList_height: fields.string({
required: validators.required('%s is required'),
required: validators.required('%s is required'),
label : "Playlist Content Box Height" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:colors['playList_height']
}),
label11: fields.string({
widget: formFunctions.makeClickable({ content: '<h3 style="text-align: center;margin: 40px;text-decoration: underline;">Category Section</h3>', replace: [] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
category_color: fields.string({
required: validators.required('%s is required'),
label : "Category Info Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['category_color']
}),
category_titleFontsize: fields.string({
required: validators.required('%s is required'),
label : "Category Title Font Size" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:colors['category_titleFontsize']
}),
category_height: fields.string({
required: validators.required('%s is required'),
label : "Category Box Height" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:colors['category_height']
}),
label12: fields.string({
widget: formFunctions.makeClickable({ content: '<h3 style="text-align: center;margin: 40px;text-decoration: underline;">Blogs Section</h3>', replace: [] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
blogBox_bg: fields.string({
required: validators.required('%s is required'),
label : "Blog Box Background Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['blogBox_bg']
}),
blogBox_titleFontSize: fields.string({
required: validators.required('%s is required'),
label : "Blog Title Font Size" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:colors['blogBox_titleFontSize']
}),
blogBox_imgHeight: fields.string({
required: validators.required('%s is required'),
label : "Blog Image Height" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:colors['blogBox_imgHeight']
}),
blogBox_Color: fields.string({
required: validators.required('%s is required'),
label : "Blog Info Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['category_color']
}),
blogBox_lightColor: fields.string({
required: validators.required('%s is required'),
label : "Blog Info Light Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['blogBox_lightColor']
}),
label13: fields.string({
widget: formFunctions.makeClickable({ content: '<h3 style="text-align: center;margin: 40px;text-decoration: underline;">Profile Tabs Section</h3>', replace: [] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
tabsBtn_bg: fields.string({
required: validators.required('%s is required'),
label : "Tabs Background Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['tabsBtn_bg']
}),
tabsBtn_bgActive: fields.string({
required: validators.required('%s is required'),
label : "Tabs Button Active Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['tabsBtn_bgActive']
}),
tabsBtn_color: fields.string({
required: validators.required('%s is required'),
label : "Tabs Text Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['tabsBtn_color']
}),
tabsBtn_Activecolor: fields.string({
required: validators.required('%s is required'),
label : "Tabs Text Active Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['tabsBtn_Activecolor']
}),
tabsBtn_fontSize: fields.string({
required: validators.required('%s is required'),
label : "Tabs Text Font Size" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:colors['tabsBtn_fontSize']
}),
label14: fields.string({
widget: formFunctions.makeClickable({ content: '<h3 style="text-align: center;margin: 40px;text-decoration: underline;">Form Section</h3>', replace: [] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
formField_lableFontColor: fields.string({
required: validators.required('%s is required'),
label : "Field Title Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['formField_lableFontColor']
}),
formField_inputBg: fields.string({
required: validators.required('%s is required'),
label : "Field Input Background Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['formField_inputBg']
}),
formField_inputColor: fields.string({
required: validators.required('%s is required'),
label : "Field Input Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['formField_inputColor']
}),
formField_inputBdrColor: fields.string({
required: validators.required('%s is required'),
label : "Field Input Border Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['formField_inputBdrColor']
}),
formField_lableFont: fields.string({
required: validators.required('%s is required'),
label : "Field Title Font Size" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:colors['formField_lableFont']
}),
formField_inputFont: fields.string({
required: validators.required('%s is required'),
label : "Field Input Font Size" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:colors['formField_inputFont']
}),
formPage_bg: fields.string({
required: validators.required('%s is required'),
label : "Form Background Color" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control script_color"]}),
value:colors['formPage_bg']
}),
label15: fields.string({
widget: formFunctions.makeClickable({ content: '<h3 style="text-align: center;margin: 40px;text-decoration: underline;">Side Menu Settings</h3>', replace: [] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
header_sidebar_bg: fields.string({
label: "Background Color",
required:validators.required('%s is required'),
widget: widgets.text({"classes":["form-control script_color"]}),
cssClasses: cssClasses,
value:colors['header_sidebar_bg']
}),
header_sidebar_color: fields.string({
label: "Link Text Color",
required:validators.required('%s is required'),
widget: widgets.text({"classes":["form-control script_color"]}),
cssClasses: cssClasses,
value:colors['header_sidebar_color']
}),
header_sidebar_hovercolor: fields.string({
label: "Link Text Hover/Active Color",
required:validators.required('%s is required'),
widget: widgets.text({"classes":["form-control script_color"]}),
cssClasses: cssClasses,
value:colors['header_sidebar_hovercolor']
}),
header_sidebar_title_color: fields.string({
label: "Heading Color",
required:validators.required('%s is required'),
widget: widgets.text({"classes":["form-control script_color"]}),
cssClasses: cssClasses,
value:colors['header_sidebar_title_color']
}),
header_sidebar_icon_color: fields.string({
label: "Icons Color",
required:validators.required('%s is required'),
widget: widgets.text({"classes":["form-control script_color"]}),
cssClasses: cssClasses,
value:colors['header_sidebar_icon_color']
}),
header_sidebar_fontsize: fields.string({
label: "Font Size",
required:validators.required('%s is required'),
widget: widgets.text({"classes":["form-control"]}),
cssClasses: cssClasses,
value:colors['header_sidebar_fontsize']
}),
header_sidebar_search_bg: fields.string({
label: "Header Search Background Color",
required:validators.required('%s is required'),
widget: widgets.text({"classes":["form-control script_color"]}),
cssClasses: cssClasses,
value:colors['header_sidebar_search_bg']
}),
header_sidebar_search_border: fields.string({
label: "Header Search Border Color",
required:validators.required('%s is required'),
widget: widgets.text({"classes":["form-control script_color"]}),
cssClasses: cssClasses,
value:colors['header_sidebar_search_border']
}),
header_sidebar_search_textcolor: fields.string({
label: "Header Search Text Color",
required:validators.required('%s is required'),
widget: widgets.text({"classes":["form-control script_color"]}),
cssClasses: cssClasses,
value:colors['header_sidebar_search_textcolor']
}),
label16: fields.string({
widget: formFunctions.makeClickable({ content: '<h3 style="text-align: center;margin: 40px;text-decoration: underline;">Popup Search Settings</h3>', replace: [] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
header_popup_bodybg: fields.string({
label: "Background Color",
required:validators.required('%s is required'),
widget: widgets.text({"classes":["form-control script_color"]}),
cssClasses: cssClasses,
value:colors['header_popup_bodybg']
}),
header_popup_headbg: fields.string({
label: "Top Head Background Color",
required:validators.required('%s is required'),
widget: widgets.text({"classes":["form-control script_color"]}),
cssClasses: cssClasses,
value:colors['header_popup_headbg']
}),
header_popup_inputtextcolor: fields.string({
label: "Input Text Color",
required:validators.required('%s is required'),
widget: widgets.text({"classes":["form-control script_color"]}),
cssClasses: cssClasses,
value:colors['header_popup_inputtextcolor']
}),
header_popup_inputbg: fields.string({
label: "Input Background Color",
required:validators.required('%s is required'),
widget: widgets.text({"classes":["form-control script_color"]}),
cssClasses: cssClasses,
value:colors['header_popup_inputbg']
}),
header_popup_inputborder: fields.string({
label: "Input Text Border Color",
required:validators.required('%s is required'),
widget: widgets.text({"classes":["form-control script_color"]}),
cssClasses: cssClasses,
value:colors['header_popup_inputborder']
}),
},{validatePastFirstError:true});
reg_form.handle(req, {
success: function (form) {
if(form.data.font_style == "web"){
form.data.fontFamily_default = form.data.fontFamily_default_web
form.data.fontFamily_heading = form.data.fontFamily_heading_web
delete form.data.fontFamily_default_web
delete form.data.fontFamily_heading_web
}
const filePath = req.serverDirectoryPath + "/../public/static/css/variables_default_"+type+".css"
fs.readFile(filePath, { encoding: 'utf8' }, function (err, data) {
if (!err) {
const filePath = req.serverDirectoryPath + "/../public/static/css/variable_"+type+".css"
for (var key in form.data) {
data = data.replace(key,form.data[key]);
}
fs.writeFile(filePath,data, 'utf8', function (err) {
if (err) {
}else{
delete form.data['mode']
delete form.data['label1']
delete form.data['label2']
delete form.data['label3']
delete form.data['label4']
delete form.data['label5']
delete form.data['label6']
delete form.data['label7']
delete form.data['label8']
delete form.data['label9']
delete form.data['label10']
delete form.data['label11']
delete form.data['label12']
delete form.data['label13']
delete form.data['label14']
delete form.data['label15']
delete form.data['label16']
for (var key in form.data) {
globalModel.custom(req,'INSERT INTO themes SET ? ON DUPLICATE KEY UPDATE value = ?',[{key:key,value:form.data[key],type:type},form.data[key]],function(err,results,fields)
{
})
}
}
});
}
})
res.send({success:1,message:"Setting Saved Successfully."})
},
error: function(form){
const errors = formFunctions.formValidations(form);
res.send({errors:errors});
},
other: function (form) {
res.render('admin/designs/site',{nav:url,reg_form:reg_form,title:"Change Site Designs (NOTE: Some settings will not work in Trendott theme.)"});
}
});
}
exports.customDesign = async(req,res) => {
const url = req.originalUrl.replace(process.env.ADMIN_SLUG,'');
var fields = forms.fields;
var validators = forms.validators;
var widgets = forms.widgets;
var cssClasses = {
label :[""],
field : ["form-group"],
classes : ["form-control"]
};
let headerJs = ""
let footerJs = ""
let headerCss = ""
//read files
const filePath = req.serverDirectoryPath + "/../public/static/custom/"
await new Promise(function(resolve, reject){
const filePathLanguage = filePath + "/header.js"
fs.readFile(filePathLanguage, { encoding: 'utf8' }, function (err, data) {
if (!err) {
headerJs = data
resolve()
}
})
})
// await new Promise(function(resolve, reject){
// const filePathLanguage = filePath + "/footer.js"
// fs.readFile(filePathLanguage, { encoding: 'utf8' }, function (err, data) {
// if (!err) {
// footerJs = data
// resolve()
// }
// })
// })
await new Promise(function(resolve, reject){
const filePathLanguage = filePath + "/header.css"
fs.readFile(filePathLanguage, { encoding: 'utf8' }, function (err, data) {
if (!err) {
headerCss = data
resolve()
}
})
})
var reg_form = forms.create({
custom_header_js: fields.string({
label : "Header Custom JavaScript (Appears on all pages in header)" ,
cssClasses:cssClasses,
widget: widgets.textarea({"classes":["form-control website_ads_textarea"]}),
value:headerJs
}),
// custom_footer_js: fields.string({
// label : "Footer Custom JavaScript (Appears on all pages in footer)" ,
// cssClasses:cssClasses,
// widget: widgets.textarea({"classes":["form-control website_ads_textarea"]}),
// value:footerJs
// }),
custom_css: fields.string({
label : "Header CSS Style (Appears on all pages in header)" ,
cssClasses:cssClasses,
widget: widgets.textarea({"classes":["form-control website_ads_textarea"]}),
value:headerCss
}),
},{validatePastFirstError:true});
reg_form.handle(req, {
success: function (form) {
new Promise(function(resolve, reject){
const filePathLanguage = filePath + "/header.js"
fs.writeFile(filePathLanguage, form.data["custom_header_js"], 'utf8', function (err) {
if (err) {
console.log(err);
}
});
});
// new Promise(function(resolve, reject){
// const filePathLanguage = filePath + "/footer.js"
// fs.writeFile(filePathLanguage, form.data["custom_footer_js"], 'utf8', function (err) {
// if (err) {
// console.log(err);
// }
// });
// });
new Promise(function(resolve, reject){
const filePathLanguage = filePath + "/header.css"
fs.writeFile(filePathLanguage, form.data["custom_css"], 'utf8', function (err) {
if (err) {
console.log(err);
}
resolve(true)
});
});
res.send({success:1,message:"Setting Saved Successfully."})
},
error: function(form){
const errors = formFunctions.formValidations(form);
res.send({errors:errors});
},
other: function (form) {
res.render('admin/designs/custom-design',{nav:url,reg_form:reg_form,title:"Custom JS / CSS"});
}
});
}
|
import React from 'react'
import { h1 } from '../styles/elements'
import styled from '@emotion/styled'
const Section = styled.div`
position: relative;
background-color: #ef7125;
padding: 50px 40px;
color: white;
`
const Heading = styled.h1`
${h1};
color: white;
margin: 0;
`
const SubHeading = styled.p`
margin-top: 0;
margin-bottom: 30px;
font-size: 24pt;
color: white;
`
const Image = styled.img`
position: absolute;
bottom: 0;
transform: translateY(50%);
width: 140px;
height: 140px;
border-radius: 100%;
background-color: white;
padding: 5px;
`
const Hello = ({ headingLevel1 = true }) => {
return (
<div>
<Section>
{headingLevel1 ? (
<Heading>Hello.</Heading>
) : (
<Heading as="h2">Hello.</Heading>
)}
<SubHeading>I'm Timothy Vernon</SubHeading>
<Image
alt="Timothy Vernon"
src="https://res.cloudinary.com/vernon-cloud/image/upload/f_auto,q_auto/v1530884463/Timothy_Headshot_25.12.2016_b4g1ak.jpg"
/>
</Section>
<div style={{ backgroundColor: 'white', padding: '70px 40px 20px' }}>
<p>
I build beautiful, modern web applications with Javascript. This is my
website where I write about what I am learning and my experiences.
</p>
</div>
</div>
)
}
export default Hello
|
function mostrar()
{
var num;
var cont = 0;
var acum = 0;
var respuesta;
do{
num = parseInt(prompt("Ingrese un número:"));
acum = acum + num;
cont ++;
respuesta = prompt("¿Desea agregar otro n°? (Si/No)");
}while(respuesta == "si" || respuesta == "SI" || respuesta == "Si" || respuesta == "sI");
document.getElementById('suma').value = acum;
document.getElementById('promedio').value = acum/cont;
}
/*
Al presionar el botón pedir números hasta que el USUARIO QUIERA e informar la suma acumulada y el promedio.
*/
|
const request=require('request')
const forcast=(latitude,longitude, callback)=>{
const url="https://api.darksky.net/forecast/c80bc76dd05c63defa04c58f5bb301c3/"+latitude+","+longitude
request({url,json:true},(error,response)=>{
if(error){
callback("unable to connect to the weather service",undefined)
}
else if(response.body.length===0){
callback('unavle to get weather for the location.try another search please',undefined)
}
else{
callback(undefined,response)
}
})
}
module.exports=forcast
|
#!/usr/bin/env node
'use strict';
process.title = 'arc-bump';
const program = require('commander');
const colors = require('colors/safe');
const semver = require('semver');
const gulp = require('gulp');
const bump = require('gulp-bump');
program
.usage('[options] <version>')
.parse(process.argv);
var currentVersion = program.args && program.args[0];
console.log();
if (!currentVersion) {
console.log(colors.red(' No components specified. Use --all to clone all components.'));
program.outputHelp();
process.exit(1);
}
if (!/^\d+\.\d+\.\d+$/.test(currentVersion)) {
console.log(colors.red(' Specified version is invalid. Please, use semver.'));
program.outputHelp();
process.exit(1);
}
function bumpCurrent(currentVersion) {
return new Promise((resolve, reject) => {
let newVer = semver.inc(currentVersion, 'patch');
console.log('Bumping version from ' + currentVersion + ' to ' + newVer + '...');
gulp.src(['./bower.json', './package.json'])
.pipe(bump({version: newVer}))
.pipe(gulp.dest('./'))
.on('data', function() {})
.on('end', function() {
resolve();
})
.on('error', function(e) {
reject(new Error('Can not bump version. ' + e.message));
});
});
}
try {
bumpCurrent(currentVersion).then(() => {
process.exit(0);
}).catch((err) => {
console.log(err);
process.exit(1);
});
} catch (e) {
console.log(colors.red(' ' + e.message));
program.outputHelp();
process.exit(1);
}
|
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import AuthModal from 'components/AuthModal';
import * as OrgSelectors from 'modules/org/selectors';
import * as AuthSelectors from 'modules/auth/selectors';
import * as UISelectors from 'modules/ui/selectors';
import * as AuthActions from 'modules/auth/actions';
const mapStateToProps = state => ({
verifyTokenPending: AuthSelectors.verifyTokenPending(state),
verifyTokenFailed: AuthSelectors.verifyTokenFailed(state),
authType: UISelectors.uiType(state),
smsLoginDisabled: OrgSelectors.getSmsLoginDisabled(state),
hasSocialLogin: OrgSelectors.getHasSocialLogin(state),
googleLoginEnabled: OrgSelectors.getGoogleLoginEnabled(state),
googleClientId: OrgSelectors.getGoogleClientId(state),
})
const mapDispatchToProps = dispatch => ({
actions: bindActionCreators({
fetchSendSMSToken: AuthActions.fetchSendSMSToken,
fetchSendSMSTokenSuccess: AuthActions.fetchSendSMSTokenSuccess,
fetchSendSMSTokenFailed: AuthActions.fetchSendSMSTokenFailed,
fetchSendSMSTokenPending: AuthActions.fetchSendSMSTokenPending,
fetchVerifySMSToken: AuthActions.fetchVerifySMSToken,
fetchVerifySMSTokenPending: AuthActions.fetchVerifySMSTokenPending,
fetchVerifySMSTokenSuccess: AuthActions.fetchVerifySMSTokenSuccess,
fetchVerifySMSTokenFailed: AuthActions.fetchVerifySMSTokenFailed,
fetchVerifyGoogle: AuthActions.fetchVerifyGoogle,
}, dispatch)
})
export default connect(mapStateToProps, mapDispatchToProps)(AuthModal);
|
let jsdom = require('jsdom-global')();
let $ = require('../jquery-3.3.1.min');
let expect = require('chai').expect;
document.body.innerHTML = `<body>
<div id="wrapper">
<input type="text" id="name">
<input type="text" id="income">
</div>
</body>`;
let sharedObject = {
name: null,
income: null,
changeName: function (name) {
if (name.length === 0) {
return;
}
this.name = name;
let newName = $('#name');
newName.val(this.name);
},
changeIncome: function (income) {
if (!Number.isInteger(income) || income <= 0) {
return;
}
this.income = income;
let newIncome = $('#income');
newIncome.val(this.income);
},
updateName: function () {
let newName = $('#name').val();
if (newName.length === 0) {
return;
}
this.name = newName;
},
updateIncome: function () {
let newIncome = $('#income').val();
if (isNaN(newIncome) || !Number.isInteger(Number(newIncome)) || Number(newIncome) <= 0) {
return;
}
this.income = Number(newIncome);
}
};
describe('Test sharedObject functionality', function () {
describe('Check if name and income values are null', function () {
it('name should be null', function () {
expect(sharedObject.name).to.be.null;
});
it('income should be null', function () {
expect(sharedObject.income).to.be.null;
});
});
describe('Check change name function', function () {
it('should be invalid with empty input', function () {
sharedObject.changeName('');
expect(sharedObject.name).to.be.null
});
it('should be valid with Pesho', function () {
sharedObject.changeName('Pesho');
expect(sharedObject.name).to.equal('Pesho');
});
it('should be invalid from to Gosho to empty string', function () {
sharedObject.changeName('Gosho');
sharedObject.changeName('');
expect(sharedObject.name).to.equal('Gosho');
});
it('should be invalid from to Gosho from Pesho', function () {
sharedObject.changeName('Pesho');
sharedObject.changeName('Gosho');
expect(sharedObject.name).to.equal('Gosho');
});
it('should be valid', function () {
sharedObject.changeName('Georgi');
sharedObject.changeName('');
let nameTextBox = $('#name');
expect(nameTextBox.val()).to.equal('Georgi')
});
it('should be valid from penka to penko', function () {
sharedObject.changeName('penka');
sharedObject.changeName('penko');
let nameTextBox = $('#name');
expect(nameTextBox.val()).to.equal('penko')
});
});
describe('Check changeIncome functionality', function () {
describe('check changeIncome() and object.income is it setting right', function () {
it('should be invalid if input is equal to empty string', function () {
sharedObject.changeIncome('');
expect(sharedObject.income).to.be.null
});
it('should be invalid if input is equal to gosho', function () {
sharedObject.changeIncome('gosho');
expect(sharedObject.income).to.be.null
});
it('should be invalid if input is equal to -1', function () {
sharedObject.changeIncome(-1);
expect(sharedObject.income).to.be.null
});
it('should be invalid if input is equal to 0', function () {
sharedObject.changeIncome(0);
expect(sharedObject.income).to.be.null
});
it('should be invalid if input is equal to 3.14', function () {
sharedObject.changeIncome(3.14);
expect(sharedObject.income).to.be.null
});
it('should be valid if input is equal to 500', function () {
sharedObject.changeIncome(500);
expect(sharedObject.income).to.equal(500);
});
it('should be valid if input is equal to 200', function () {
sharedObject.changeIncome(500);
sharedObject.changeIncome(200);
expect(sharedObject.income).to.equal(200);
});
it('should be valid if input is equal to 800', function () {
sharedObject.changeIncome(500);
sharedObject.changeIncome(800);
expect(sharedObject.income).to.equal(800);
});
});
describe('check income textBox', function () {
it('should be invalid in textBox from 500 to -1', function () {
sharedObject.changeIncome(500);
sharedObject.changeIncome(-1);
let incomeBox = $('#income');
expect(incomeBox.val()).to.equal('500');
});
it('should be invalid in textBox from 500 to 0', function () {
sharedObject.changeIncome(500);
sharedObject.changeIncome(0);
let incomeBox = $('#income');
expect(incomeBox.val()).to.equal('500');
});
it('should be invalid in textBox from 500 to 3.14', function () {
sharedObject.changeIncome(500);
sharedObject.changeIncome(3.14);
let incomeBox = $('#income');
expect(incomeBox.val()).to.equal('500');
});
it('should be invalid in textBox from 500 to kiri', function () {
sharedObject.changeIncome(500);
sharedObject.changeIncome('kiri');
let incomeBox = $('#income');
expect(incomeBox.val()).to.equal('500');
});
it('should be valid in textBox from 500 to 600', function () {
sharedObject.changeIncome(500);
sharedObject.changeIncome(600);
let incomeBox = $('#income');
expect(incomeBox.val()).to.equal('600');
});
it('should be valid in textBox from 500 to 200', function () {
sharedObject.changeIncome(500);
sharedObject.changeIncome(200);
let incomeBox = $('#income');
expect(incomeBox.val()).to.equal('200');
});
it('should be valid in textBox from 500 to empty string', function () {
sharedObject.changeIncome(500);
sharedObject.changeIncome('');
let incomeBox = $('#income');
expect(incomeBox.val()).to.equal('500');
});
});
});
describe('check updateName() how works with name text box', function () {
it('should be invalid with no input', function () {
sharedObject.name = 'roskata';
let nameBox = $('#name');
nameBox.val();
sharedObject.updateName();
expect(sharedObject.name).to.equal('roskata');
});
it('should be valid for switching names', function () {
sharedObject.name = 'krasi';
let nameBox = $('#name');
nameBox.val('johny');
sharedObject.updateName();
expect(sharedObject.name).to.equal('johny');
});
});
describe('check updateIncome() how works from textBox', function () {
it('should be equal to 300 from 800', function () {
sharedObject.income = 5000;
let incomeBox = $('#income');
incomeBox.val('hari ba');
sharedObject.updateIncome();
expect(sharedObject.income).to.equal(5000);
});
it('should be equal to 300 from 800', function () {
sharedObject.income = 5000;
let incomeBox = $('#income');
incomeBox.val();
sharedObject.updateIncome();
expect(sharedObject.income).to.equal(5000);
});
it('should be invalid with no input', function () {
sharedObject.income = 5000;
let incomeBox = $('#income');
incomeBox.val(800);
sharedObject.updateIncome();
expect(sharedObject.income).to.equal(800);
});
it('should be equal to 300 from 800', function () {
sharedObject.income = 5000;
let incomeBox = $('#income');
incomeBox.val(-1);
sharedObject.updateIncome();
expect(sharedObject.income).to.equal(5000);
});
it('should be equal to 300 from 800', function () {
sharedObject.income = 5000;
let incomeBox = $('#income');
incomeBox.val(0);
sharedObject.updateIncome();
expect(sharedObject.income).to.equal(5000);
});
it('should be equal to 300 from 800', function () {
sharedObject.income = 5000;
let incomeBox = $('#income');
incomeBox.val(3.14);
sharedObject.updateIncome();
expect(sharedObject.income).to.equal(5000);
});
it('should be equal to 300 from 800', function () {
sharedObject.income = 5000;
let incomeBox = $('#income');
incomeBox.val(6000);
sharedObject.updateIncome();
expect(sharedObject.income).to.equal(6000);
});
it('should be equal to 300 from 800', function () {
sharedObject.income = 5000;
let incomeBox = $('#income');
incomeBox.val(4000);
sharedObject.updateIncome();
expect(sharedObject.income).to.equal(4000);
});
it('should be equal to 300 from 800', function () {
sharedObject.income = 5000;
let incomeBox = $('#income');
incomeBox.val(3000);
sharedObject.updateIncome();
expect(sharedObject.income).to.equal(3000);
});
});
});
|
"use strict";
const Content = require("../models/Content");
/**
* ContentController
* @type {Xpresser.Controller.Handler}
*/
const ContentController = $.handler({
// Controller Name
name: "ContentController",
// Controller Middlewares
middlewares: {},
// Controller Default Service Error Handler.
e: $$.defaultErrorHandler,
boot: async (http, error) => {
// Get current auth user.
const user = http.authUser();
// Get Device from params
let content = http.params.content || undefined;
// if device then add to boot return values
if (content) {
content = await Content.query().where({user_id: user.id, code: content}).first();
if (!content) {
return error(`Content not found, maybe already deleted.`);
}
}
// return to every method.
return {user: http.authUser(), content};
},
/**
* Get All contents
* @returns {*}
*/
all: async (http, {user}) => {
let page = http.query('page', 1);
let search = http.query('search', undefined);
if (Number(page) < 1) page = 1;
let query = Content.query().where({user_id: user.id});
if (search && search.length > 1) {
query.where('content', 'like', `%${search}%`)
}
const contents = await query.orderBy('id', 'desc')
.paginate(page, 20);
for (const content of contents.data) {
content.$pick(Content.jsPick);
}
return http.toApi({contents, search});
},
/**
* Create content using Content.add service
*/
create: {
'content.add': true
},
/**
* Delete Content
* @param http
* @param content
* @returns {Promise<Knex.ColumnBuilder>}
*/
delete: async (http, {content}) => {
await content.$query().delete();
return http.toApi({});
},
/**
* Delete all contents
* @param http
* @param user
* @returns {Promise<Knex.ColumnBuilder>}
*/
clear: async (http, {user}) => {
const rows = await Content.query().where({user_id: user.id}).delete();
return http.sayToApi(`${rows} clips deleted successfully.`);
}
});
module.exports = ContentController;
|
export const transformObject = (obj, fnc) =>
Object.fromEntries(Object.entries(obj).map(fnc))
export function transformInitialData (initialData) {
return Object.fromEntries(
initialData.map(initialDatum => {
return [
initialDatum.key,
{
value: initialDatum.value,
initialValue: initialDatum.value,
initialValueIsOk:
'initialValueIsOk' in initialDatum
? initialDatum.initialValueIsOk
: false,
},
]
}),
)
}
export function checkIfFormIsDirty (state, fieldsToCheck) {
return Object.entries(state.data)
.filter(([key]) => checkIfKeyIsInIncludedFields(key))
.some(([key, value]) => fieldHasValueThatIsntDefault(value))
function checkIfKeyIsInIncludedFields (key) {
return fieldsToCheck.includes(key)
}
function fieldHasValueThatIsntDefault ({ value, initialValue }) {
return value !== initialValue
}
}
export function checkIfFormIsSaveable (state, fieldsToCheck) {
return Object.entries(state.data)
.filter(([key]) => checkIfKeyIsInIncludedFields(key))
.every(([key, value]) => fieldHasValueThatIsntDefault(value))
function checkIfKeyIsInIncludedFields (key) {
return fieldsToCheck.includes(key)
}
function fieldHasValueThatIsntDefault ({
value,
initialValue,
initialValueIsOk,
}) {
return value !== initialValue || initialValueIsOk
}
}
export function tryAndGetDirtyFieldsToCheckFromInitialData (initialData) {
const keyToCheckFor = 'checkForDirty'
return initialData
.map(initialDatum => {
if (keyToCheckFor in initialDatum) {
return initialDatum
}
return {
...initialDatum,
[keyToCheckFor]: true,
}
})
.filter(initialDatum => initialDatum[keyToCheckFor])
.map(initialDatum => initialDatum.key)
}
export function tryAndGetSaveableFieldsToCheckFromInitialData (initialData) {
const keyToCheckFor = 'checkForSaveable'
return initialData
.map(initialDatum => {
if (keyToCheckFor in initialDatum) {
return initialDatum
}
return {
...initialDatum,
[keyToCheckFor]: true,
}
})
.filter(initialDatum => initialDatum[keyToCheckFor])
.map(initialDatum => initialDatum.key)
}
export function extractValueFromTransformedData ([key, { value }]) {
return [key, value]
}
export function getInitialData (data, initialKeys) {
return Object.entries(data)
.filter(([key]) => initialKeys.includes(key))
.map(([key, value]) => ({
key,
value,
initialValue: value,
initialValueIsOk: true,
}))
}
export function createBaseInitialData ({
baseData = [],
data = {},
isEdit = true,
} = {}) {
if (Object.keys(data).length === 0) return baseData
return baseData.map(baseDatum => {
if (!Object.keys(data).includes(baseDatum.key)) return baseDatum
baseDatum.value = data[baseDatum.key]
baseDatum.initialValue = data[baseDatum.key]
if (isEdit) {
baseDatum.initialValueIsOk = true
}
return baseDatum
})
}
|
/**
* Select the sorting method in the galaxy view
* @param {string} state
* @param {*} action
*/
export const treeViewSorting = (state = 'latest', action) => {
switch (action.type) {
case 'SORT_BY':
return action.sortBy
default:
return state
}
}
|
var pager_8c =
[
[ "QClass", "structQClass.html", "structQClass" ],
[ "TextSyntax", "structTextSyntax.html", "structTextSyntax" ],
[ "Line", "structLine.html", "structLine" ],
[ "AnsiAttr", "structAnsiAttr.html", "structAnsiAttr" ],
[ "Resize", "structResize.html", "structResize" ],
[ "PagerRedrawData", "structPagerRedrawData.html", "structPagerRedrawData" ],
[ "ANSI_NO_FLAGS", "pager_8c.html#a67a140d412002ff1d01d0c82b887f331", null ],
[ "ANSI_OFF", "pager_8c.html#ae1a431e542b4da1c3a300ddfbb1452fe", null ],
[ "ANSI_BLINK", "pager_8c.html#a50773a74baf9b6d4245e26e966394d1e", null ],
[ "ANSI_BOLD", "pager_8c.html#a46587b83544b8e9be045bb93f644ac82", null ],
[ "ANSI_UNDERLINE", "pager_8c.html#ab9e3d5230787ccc126d1a1d8b739c740", null ],
[ "ANSI_REVERSE", "pager_8c.html#ac423db26b82c1e6f0a8162edc0900013", null ],
[ "ANSI_COLOR", "pager_8c.html#ae48c1442848dd6cd42d626ed5e14b1a0", null ],
[ "IS_HEADER", "pager_8c.html#a5e31b72a8ce0ae3a758b70d3b784ba39", null ],
[ "IsAttach", "pager_8c.html#a76b307f4371f26d624c2f21ffe558d0f", null ],
[ "IsMsgAttach", "pager_8c.html#a01bd8ec885a42de5223bc0085c6c6984", null ],
[ "IsEmail", "pager_8c.html#a81095bef2f2345bfad08e37523b0ae90", null ],
[ "NUM_SIG_LINES", "pager_8c.html#ac3bfefc6e18fff2db089c5cd4507ff99", null ],
[ "CHECK_MODE", "pager_8c.html#a16c496ac3ac92824693f5d60c4458569", null ],
[ "CHECK_READONLY", "pager_8c.html#a9bb432bd5d6e9dd5a0a2ded079bc3238", null ],
[ "CHECK_ATTACH", "pager_8c.html#a397bc5725fce5f47f8019284280cc606", null ],
[ "CHECK_ACL", "pager_8c.html#ae7fc567f7fc374bc2a448f481e396fe3", null ],
[ "AnsiFlags", "pager_8c.html#a940afd2bf2b7ec5a8c9bc2c9d12a9d41", null ],
[ "check_sig", "pager_8c.html#ababa95f38bb50d092c7105865d7f3389", null ],
[ "comp_syntax_t", "pager_8c.html#a757dbf002697f11969b757fcf5ef398d", null ],
[ "resolve_color", "pager_8c.html#a0332f4c924e94ceeea60609b80a3839f", null ],
[ "append_line", "pager_8c.html#a76e6b70fd73d484bcb93d06a0603464c", null ],
[ "class_color_new", "pager_8c.html#adc70921d341abe693a6b4f075c89a19e", null ],
[ "shift_class_colors", "pager_8c.html#a56b217df2e73402623ff6d13669df1da", null ],
[ "cleanup_quote", "pager_8c.html#a95cd2cb5ef2f627dc7f823e870689075", null ],
[ "classify_quote", "pager_8c.html#a532fb6a97919126e8be9659db3ecb23f", null ],
[ "check_marker", "pager_8c.html#ae58da0d6c7d5f49e2eee702f04edd284", null ],
[ "check_attachment_marker", "pager_8c.html#a920c283cb82368914ae6de672b14194e", null ],
[ "check_protected_header_marker", "pager_8c.html#a18e1fdb87db0cf8e9e0585a0b4b55c31", null ],
[ "mutt_is_quote_line", "pager_8c.html#a1f9daa6945087758fdee1bdf76e62354", null ],
[ "resolve_types", "pager_8c.html#a423ab61788ace956cf2945f6d70d3014", null ],
[ "is_ansi", "pager_8c.html#adf290d8b56802820bc1934d76afba50f", null ],
[ "grok_ansi", "pager_8c.html#a18178dab26ab08b802f7194d1394fe64", null ],
[ "mutt_buffer_strip_formatting", "pager_8c.html#a29a3939691dd7a49875fc11c290bdfe1", null ],
[ "fill_buffer", "pager_8c.html#a23a8aa1356e8b8fdcc34eab387136f93", null ],
[ "format_line", "pager_8c.html#ab3d610ae528f103462e8cb98ff2c9859", null ],
[ "display_line", "pager_8c.html#abb544ac601507e39432ffb33671f632b", null ],
[ "up_n_lines", "pager_8c.html#a3a00a793bf2a50cf8d7006624c37dfb6", null ],
[ "mutt_clear_pager_position", "pager_8c.html#a52cb29b8a518d62062551b6ff7a3cb4f", null ],
[ "pager_custom_redraw", "pager_8c.html#a3cada4018e0a7997a5c2d539e5d10b9f", null ],
[ "mutt_pager", "pager_8c.html#a4cc11143557f95ded6a80f3cffff4483", null ],
[ "C_AllowAnsi", "pager_8c.html#a6b700cbac399d0f8221c7e61fcec27e1", null ],
[ "C_HeaderColorPartial", "pager_8c.html#a8b3696d504ae42d6bd92761c36932ad7", null ],
[ "C_PagerContext", "pager_8c.html#ad9e4cd6ca02577884aa93eed2061bbc6", null ],
[ "C_PagerIndexLines", "pager_8c.html#a8a2ea9f39ac5b790c9ba6c2d7bfae1ea", null ],
[ "C_PagerStop", "pager_8c.html#a68ce551360f9ef21bddce323cd5c908f", null ],
[ "C_SearchContext", "pager_8c.html#a7bcc9b4c39c4d3521107e8541594f58f", null ],
[ "C_SkipQuotedOffset", "pager_8c.html#a991a66797f24f565ba5d2968675f172c", null ],
[ "C_SmartWrap", "pager_8c.html#a25c1dd2ddd3e5c9425ee317835553131", null ],
[ "C_Smileys", "pager_8c.html#aa68ee60b325ec00be0ab092a52ecad10", null ],
[ "C_Tilde", "pager_8c.html#af45c1784dee197faf429be89ac0a97e1", null ],
[ "TopLine", "pager_8c.html#af7c753f5d70592c25bcb40f78dc67709", null ],
[ "OldEmail", "pager_8c.html#a7b51b25e5cf603a3d6e977e2ed2f8b0e", null ],
[ "InHelp", "pager_8c.html#a01485d486b1a37232c37a6725c9c96e0", null ],
[ "braille_line", "pager_8c.html#a993a56af49dd35bb20f81af870a6a65c", null ],
[ "braille_col", "pager_8c.html#a73d27448f470ca570bf892c2f5420b10", null ],
[ "Resize", "pager_8c.html#a92126aa6c3775a9a81f666771def1b01", null ],
[ "Not_available_in_this_menu", "pager_8c.html#a58b4ae9e30b595f5eded392bcf9f2e00", null ],
[ "Mailbox_is_read_only", "pager_8c.html#a12ff66bc53a0f656ef581441f836aafe", null ],
[ "Function_not_permitted_in_attach_message_mode", "pager_8c.html#a902bce6ff62a5b8e0c4c05e0c10e8c2e", null ],
[ "PagerHelp", "pager_8c.html#acf47b3ffd858fe087c093fd8bb2eac18", null ],
[ "PagerHelpHelp", "pager_8c.html#aa28a1c2205b6faa48305586807d75a23", null ],
[ "PagerNormalHelp", "pager_8c.html#abe1f6fa814dc62f21af8f5e9370f9d88", null ],
[ "PagerNewsHelp", "pager_8c.html#aa6187d937a0f4e3c2243780eb3fbe15d", null ]
];
|
import styles from 'styled-components'
export const Div = styles.div`
display: grid;
grid-template-columns: repeat(${props => props.cols}, 1fr);
grid-template-rows: repeat(${props => props.rows}, 1fr);
grid-gap: ${props => (props.gap ? props.gap + 'px' : '30px')};
`
|
import mongoose from 'mongoose'
import autoIncrement from 'mongoose-auto-increment'
const { Schema } = mongoose
const commentSchema = new Schema({
groupId: { type: Number, ref: 'Group' },
groupName: String,
postId: { type: Number, ref: 'Post' },
postOwner: { type: String, ref: 'User' },
text: String,
owner: { type: String, ref: 'User' },
createdAt: { type: Date, default: Date.now() },
modifiedAt: Date,
score: Number,
votes: [Schema.Types.Mixed],
})
autoIncrement.initialize(mongoose.connection)
commentSchema.plugin(autoIncrement.plugin, {
model: 'Comment',
field: '_id',
startAt: 0,
incrementBy: Math.floor(Math.random() * 40) + 1,
})
const Comment = mongoose.model('Comment', commentSchema)
export default Comment
|
'use strict';
const fs = require('fs');
let counter = 1;
fs.watch('./6-watch.js', (event, file) => {
console.log(counter, {
event,
file,
});
counter++;
});
|
const fs = require('fs');
const path = require('path');
const bundle = fs.createWriteStream(path.resolve(__dirname, 'project-dist', 'bundle.css'));
fs.readdir(path.resolve(__dirname, 'styles'), (err, files) => {
if (!err) {
files.forEach(file => {
if (path.extname(file) == '.css') {
const stream = fs.createReadStream(
path.resolve(__dirname, 'styles', file));
let data = '';
stream.on('data', partData => bundle.write(data += partData));
}
});
}
});
|
/**
* Created by nick on 16-6-4.
*/
require.config({
baseUrl: basePath,
paths: {
all: 'public/js/all',
md5: 'core/js/md5' //引用md5
}
})
define( ['md5','all'], function( md5 ){
$( '#registerForm' ).on( 'submit', function(){
var data = {
username: $('#username').val(),
password: md5.hex_md5( $('#password').val() ), //对password加密
email: $('#email').val()
}
$.ajax({
url: '/register',
type: 'post',
dataType: 'json',
data: data,
success: function( ret ){
console.log( ret );
}
});
return false;
})
});
|
const { check, validationResult } = require('express-validator')
class Validate{
showErrors(req,res,next){
let errors = validationResult(req);
if (errors.isEmpty()) {
next();
}else{
let alert = errors.array();
let data = req.body;
res.render('add-user', { alert, data });
}
}
//check add-user inputs
checkValidate(){
return [
check('name', '*Name is required').notEmpty(),
check('email', '*Email is required').notEmpty().isEmail().withMessage('*Enter a valid email'),
check('password', '*Password is required').notEmpty().isLength({min:4, max:10}).withMessage('length must be 4 to 10 characters'),
check('salary', '*Salary is required').notEmpty().isLength({min:4, max:10}).withMessage('length must be 4 to 10 characters'),
check('phone', '*Phone is required').notEmpty().isLength({min:8, max:10}).withMessage('length must be 8 to 10 characters'),
check('date', '*Date is required').notEmpty(),
check('address1', '*Address1 is required').notEmpty(),
check('address2', '*Address2 is required').notEmpty(),
check('city', '*City is required').notEmpty(),
check('state', '*State is required').notEmpty(),
check('zip', '*Zip is required').notEmpty()
]
}
}
module.exports = Validate;
|
const express = require('express');
const multer = require('multer');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const app = express();
const expressValidator = require('express-validator');
const morgan = require('morgan');
const dotenv = require('dotenv');
const mongoose = require('mongoose');
dotenv.config();
// connection to database
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true})
.then(() => console.log('DB connected'));
mongoose.connection.on('error', err => {
console.log(`Db connection error: ${err.message}`);
})
// Bringing routes
const routesPost = require('./routes/post');
const routesAuth = require('./routes/auth');
const routesUser = require('./routes/user');
/* const myOwnMiddleware = (req, res, next) => {
console.log("middleware applied!!!");
next();
} */
const myFileStorage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, './imagFolder')
},
fileName: function(req, res, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
const myfileFilter = (req, file, cb) => {
if(file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
console.log('This file passed the security test');
cb(null, true);
} else {
console.log('This file did not pass the security test');
cb(null, false);
}
}
// middleware
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(multer({storage: myFileStorage, fileFilter: myfileFilter}).single('image'));
app.use('/', routesPost);
app.use('/', routesAuth);
app.use('/', routesUser);
app.use((err, req, res, next) => {
if (err.name === 'UnauthorizedError') {
res.status(401).json({
error: "You are not authorized"
})
}
})
const port = 8080;
app.listen(port, () => console.log(`A nodejs API is listening on port: ${port}`));
|
import React, { Component } from 'react';
import './Reply.scss';
import { IconContext } from 'react-icons';
import { GoTrashcan } from 'react-icons/go/';
import { GoTools } from 'react-icons/go/';
import { read_cookie } from 'sfcookies';
const modifyReply = reply_id => {};
const nicknameFromSession = () => {
if (localStorage.getItem('webber_user') !== null)
return JSON.parse(localStorage.getItem('webber_user')).nickname;
};
class Reply extends Component {
state = {
Active: false,
nickname: {}
};
constructor(props) {
super(props);
this.deleteReply = this.deleteReply.bind(this);
}
deleteReply = e => {
fetch('http://localhost:9090/api/reply/' + this.props.data.reply_id, {
credentials: 'same-origin',
method: 'DELETE',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: read_cookie('access_token')
}).then(res => {
console.log('삭제');
res.json().then(data => {
console.log(data);
window.location.reload();
});
});
};
render() {
const {
reply_id,
//board_id,
content,
nickname,
date,
thumbnail
} = this.props.data;
console.log(nicknameFromSession());
console.log(nickname);
return (
<div className="Reply">
<div className="Reply_thumbnail">
<img src={thumbnail} alt={nickname} />
</div>
<div className="Reply_body">
<div className="Reply_head">
<div className="Reply_nickname">{nickname}</div>
<div className="Reply_regdate">{date}</div>
</div>
<div className="Reply_contents">{content}</div>
{nicknameFromSession() === nickname && (
<div className="Reply_buttons">
<div className="Reply_trash" onClick={this.deleteReply}>
<IconContext.Provider
className="Reply_trash_button"
value={{ size: '18' }}
>
<GoTrashcan />
</IconContext.Provider>
</div>
</div>
)}
</div>
</div>
);
}
}
export default Reply;
|
var county_store = undefined;
function CountyStore()
{
this.county_data = undefined;
this.state_names = undefined;
this.state_names_list = undefined;
this.state_counties = undefined;
this.data_scale = {
"population" : d3.scale.linear().domain([0, 10000000]).range([0, 200]),
"labor" : d3.scale.linear().domain([0, 5000000]).range([0, 200]),
"labor-scaled" : d3.scale.linear().domain([0, 2800]).range([0, 200]),
"unemployment" : d3.scale.linear().domain([0.0, 20.0]).range([0, 200]),
"unemployment-percent" : d3.scale.linear().domain([0.0, 0.2]).range([0, 200]),
"education-index" : d3.scale.linear().domain([0.0, 10.0]).range([0, 200]),
"income-index" : d3.scale.linear().domain([0.0, 10.0]).range([0, 200]),
"health-index" : d3.scale.linear().domain([0.0, 10.0]).range([0, 200])
};
this.SetCountyStore = function(a_countyData)
{
this.county_data = a_countyData;
}
this.SetStateNames = function(a_stateNames)
{
this.state_names = a_stateNames;
}
this.SetStateCounties = function(a_stateCounties)
{
this.state_counties = a_stateCounties;
}
this.GetCountyNames = function(a_stateName)
{
if ( this.state_counties.hasOwnProperty(a_stateName) ) {
return this.state_counties[a_stateName];
}
return undefined;
}
this.GetStateNamesList = function()
{
if ( this.state_names != undefined && this.state_names_list == undefined ) {
this.state_names_list = [];
for (var state_name in this.state_names ) {
if ( this.state_names.hasOwnProperty(state_name) ) {
this.state_names_list.push(state_name.toUpperCase());
}
}
this.state_names_list.sort();
}
return this.state_names_list;
}
this.GetCountyStore = function(a_countyName)
{
if ( this.county_data != undefined && this.county_data.hasOwnProperty(a_countyName) ) {
return this.county_data[a_countyName];
}
return undefined;
}
this.GetStateAbbreviation = function(a_stateName)
{
var state_name = a_stateName.toLowerCase();
if ( this.state_names.hasOwnProperty(state_name) ) {
return this.state_names[state_name];
}
return undefined;
}
this.Capitalize = function(a_countyName)
{
var state_name = a_countyName.substr(0, a_countyName.indexOf(",")).toUpperCase();
var county_name = a_countyName.substr(a_countyName.indexOf(",") + 1).trim();
// a_countyName = a_countyName.replace(state_part, '');
var name_parts = county_name.split(' ');
for (var ii = 0; ii < name_parts.length; ++ii) {
name_parts[ii] = name_parts[ii].charAt(0).toUpperCase() + name_parts[ii].substr(1);
}
county_name = name_parts.join(' ');
// a_countyName = a_countyName.charAt(0).toUpperCase() + a_countyName.substr(1);
return county_name + ', ' + state_name;
}
this.MakeNumberLabel = function(a_number)
{
var number_str = a_number.toString(10);
if ( a_number < 1000 ) {
return number_str;
}
var number_part_array = [];
while ( number_str.length > 0 ) {
console.log("number_str: " + number_str);
var mod_3 = (number_str.length % 3);
number_part_array.push(number_str.substr(0, (mod_3 != 0 ? mod_3 : 3)));
number_str = number_str.substr(mod_3 != 0 ? mod_3 : 3);
}
return number_part_array.join(',');
}
this.DrawBarChart = function(a_d3Svg, a_countyData, a_metaData)
{
var data_name = a_metaData.data_name;
var data_set = a_countyData;
var d3_scale = county_store.data_scale[data_name];
var data_title = a_metaData.graph_title;
// var c_labels = [data_set[0].toString(10), data_set[1].toString(10)];
var c_labels = [county_store.MakeNumberLabel(data_set[0]), county_store.MakeNumberLabel(data_set[1])];
var rect_height = "30px";
var fill_color = ["#365697", "#ED416F"];
// var fill_color = ["#FEE944", "#208267"];
var x_base = 20, y_base = 55;
a_d3Svg.append("line").attr("x1", x_base).attr("y1", y_base - 10).attr("x2", x_base).attr("y2", y_base + 125)
.attr("stroke", "black").attr("stroke-width", "1").attr("stroke-opacity", 0.9);
var rects = a_d3Svg.selectAll("rect").data(data_set).enter().append("rect");
rects.attr("x", function(d, ii) { return x_base; })
.attr("y", function(d, ii) { return (y_base + 10 + 36 * ii); })
.attr("width", function(d, ii) { return Math.round(d3_scale(d)); })
.attr("height", rect_height)
.attr("fill", function(d, ii) { return fill_color[ii]; });
var texts = a_d3Svg.selectAll("text").data(data_set).enter().append("text");
texts.attr("x", function(d, ii) {
var x_pos = x_base + Math.round(d3_scale(d)) - c_labels[ii].length * 5;
return (x_pos > x_base + 3 ? x_pos : x_base + 3);
})
.attr("y", function(d, ii) { return y_base + 91 * ii; })
.attr("fill", function(d, ii) { return fill_color[ii]; })
.text(function(d, ii) { console.log("Text " + c_labels[ii] + ", scaled d:" + d3_scale(d) + ", @ x: " + (x_base + Math.round(d3_scale(d)) * 1.8 - c_labels[ii].length * 8) + ", y: " + (y_base + 91 * ii)); return c_labels[ii]; });
/*
a_d3Svg.append("text").attr("x", x_base + 5).attr("y", y_base + 7).text(c_labels[0]);
a_d3Svg.append("text").attr("x", x_base + 5).attr("y", y_base + 90).text(c_labels[1]);
*/
a_d3Svg.append("g").attr("class", "axis").attr("transform", "translate(" + x_base + "," + (y_base + 115) + ")").call(a_metaData.x_axis);
a_d3Svg.append("text").attr("x", x_base).attr("y", y_base - 25).text(data_title);
}
this.ShowPopulation = function(a_d3Svg, a_countyDataPair, a_metaData)
{
var c_data0 = a_countyDataPair[0]['population'], c_data1 = a_countyDataPair[1]['population'];
a_d3Svg.attr("height", "30%").attr("width", "34%");
if ( !c_data0 || !c_data1 ) { return; }
console.log("Population data found in data object for both counties.");
// county_store.DrawBarChart(a_d3Svg, [c_data0, c_data1], county_store.data_scale['population'], "Population");
county_store.DrawBarChart(a_d3Svg, [c_data0, c_data1], a_metaData);
}
this.ShowLaborForceSize = function(a_d3Svg, a_countyDataPair, a_metaData)
{
var c_data0 = a_countyDataPair[0]['labor'], c_data1 = a_countyDataPair[1]['labor'];
a_d3Svg.attr("height", "30%").attr("width", "33%");
if ( !c_data0 || !c_data1 ) { return; }
console.log("Labor-size data found in data object for both counties.");
// county_store.DrawBarChart(a_d3Svg, [c_data0[0], c_data1[0]], county_store.data_scale['labor'], "Labor Force Size");
county_store.DrawBarChart(a_d3Svg, [c_data0[0], c_data1[0]], a_metaData);
/*
var data_set = [c_data0[0], c_data1[0]];
var d3_scale = county_store.data_scale['labor-scaled'];
var fill_color = ["#365697", "#ED416F"];
var bubbles = a_d3Svg.selectAll("circle").data(data_set).enter().append("circle");
bubbles.attr("cx", function(d, ii) { return 360 + 180 * ii; })
.attr("cy", function(d, ii) { return 120; })
.attr("r", function(d, ii) { return d3_scale(Math.round(Math.sqrt(d))) / 2; })
.attr("fill", function(d, ii) { return fill_color[ii]; });
a_d3Svg.append("text").attr("x", 335).attr("y", d3_scale(Math.round(Math.sqrt(data_set[0]))) / 2 + 130).text(county_store.MakeNumberLabel(data_set[0]));
a_d3Svg.append("text").attr("x", 515).attr("y", d3_scale(Math.round(Math.sqrt(data_set[1]))) / 2 + 130).text(county_store.MakeNumberLabel(data_set[1]));
a_d3Svg.append("text").attr("x", 280).attr("y", 30).text("Labor Force Size");
*/
}
this.ShowUnemploymentRate = function(a_d3Svg, a_countyDataPair, a_metaData)
{
var c_data0 = a_countyDataPair[0]['labor'], c_data1 = a_countyDataPair[1]['labor'];
a_d3Svg.attr("height", "30%").attr("width", "33%");
if ( !c_data0 || !c_data1 ) { return; }
console.log("Labor data found in data object for both counties.");
// county_store.DrawBarChart(a_d3Svg, [c_data0[3], c_data1[3]], county_store.data_scale['unemployment'], "Unemployment Rate");
county_store.DrawBarChart(a_d3Svg, [c_data0[3], c_data1[3]], a_metaData);
}
this.ShowEducation = function(a_d3Svg, a_countyDataPair, a_metaData)
{
var c_data0 = a_countyDataPair[0]['education-index'], c_data1 = a_countyDataPair[1]['education-index'];
a_d3Svg.attr("height", "30%").attr("width", "34%");
if ( !c_data0 || !c_data1 ) { return; }
console.log("Education-index data found in data object for both counties.");
// county_store.DrawBarChart(a_d3Svg, [c_data0, c_data1], county_store.data_scale['education-index'], "Education Index");
county_store.DrawBarChart(a_d3Svg, [c_data0, c_data1], a_metaData);
}
this.ShowIncomeIndex = function(a_d3Svg, a_countyDataPair, a_metaData)
{
var c_data0 = a_countyDataPair[0]['income-index'], c_data1 = a_countyDataPair[1]['income-index'];
a_d3Svg.attr("height", "30%").attr("width", "33%");
if ( !c_data0 || !c_data1 ) { return; }
console.log("Income-index data found in data object for both counties.");
// county_store.DrawBarChart(a_d3Svg, [c_data0, c_data1], county_store.data_scale['income-index'], "Median Income Index");
county_store.DrawBarChart(a_d3Svg, [c_data0, c_data1], a_metaData);
}
this.ShowHealthIndex = function(a_d3Svg, a_countyDataPair, a_metaData)
{
var c_data0 = a_countyDataPair[0]['health-index'], c_data1 = a_countyDataPair[1]['health-index'];
a_d3Svg.attr("height", "30%").attr("width", "33%");
if ( !c_data0 || !c_data1 ) { return; }
console.log("Health-Index data found in data object for both counties.");
// county_store.DrawBarChart(a_d3Svg, [c_data0, c_data1], county_store.data_scale['health-index'], "Health Index");
county_store.DrawBarChart(a_d3Svg, [c_data0, c_data1], a_metaData);
}
this.DrawParallelCoordinatesChart = function(a_countyDataPair, a_d3Svg)
{
var x_base = 50, y_base = 25;
var fill_color = ["#365697", "#ED416F"];
a_d3Svg.attr("viewBox", "0 0 900 280");
var chart_scale = {
"population" : d3.scale.linear().domain([0, 10000000]).range([200, 0]),
"labor" : d3.scale.linear().domain([0, 5000000]).range([200, 0]),
"labor-scaled" : d3.scale.linear().domain([0, 2800]).range([200, 0]),
"unemployment" : d3.scale.linear().domain([0.0, 0.2]).range([200, 0]),
"education-index" : d3.scale.linear().domain([0.0, 10.0]).range([200, 0]),
"income-index" : d3.scale.linear().domain([0.0, 10.0]).range([200, 0]),
"health-index" : d3.scale.linear().domain([0.0, 10.0]).range([200, 0])
};
var y_axis = d3.svg.axis().scale(chart_scale['population']).orient('left').ticks(5).tickFormat(d3.format("s"));
a_d3Svg.append("g").attr("class", "axis").attr("transform", "translate(" + 75 + ", 20)").call(y_axis);
a_d3Svg.append("text").attr("x", 50).attr("y", 250).text("Population");
var y_axis = d3.svg.axis().scale(chart_scale['labor']).orient('left').ticks(5).tickFormat(d3.format("s"));
a_d3Svg.append("g").attr("class", "axis").attr("transform", "translate(" + 225 + ", 20)").call(y_axis);
a_d3Svg.append("text").attr("x", 190).attr("y", 250).text("Labor Force Size");
var y_axis = d3.svg.axis().scale(chart_scale['unemployment']).orient('left').ticks(5).tickFormat(d3.format('%'));
a_d3Svg.append("g").attr("class", "axis").attr("transform", "translate(" + 375 + ", 20)").call(y_axis);
a_d3Svg.append("text").attr("x", 340).attr("y", 250).text("Unemployment Rate");
var y_axis = d3.svg.axis().scale(chart_scale['education-index']).orient('right').ticks(5);
a_d3Svg.append("g").attr("class", "axis").attr("transform", "translate(" + 525 + ", 20)").call(y_axis);
a_d3Svg.append("text").attr("x", 500).attr("y", 250).text("Education Index");
var y_axis = d3.svg.axis().scale(chart_scale['income-index']).orient('right').ticks(5);
a_d3Svg.append("g").attr("class", "axis").attr("transform", "translate(" + 675 + ", 20)").call(y_axis);
a_d3Svg.append("text").attr("x", 630).attr("y", 250).text("Median Income Index");
var y_axis = d3.svg.axis().scale(chart_scale['health-index']).orient('right').ticks(5);
a_d3Svg.append("g").attr("class", "axis").attr("transform", "translate(" + 825 + ", 20)").call(y_axis);
a_d3Svg.append("text").attr("x", 800).attr("y", 250).text("Health-Care Index");
c_data0 = a_countyDataPair[0];
/*
c_path0 = "M 50, 100 L 80, 120 L 200, 120 L 500, 150 L 700, 150 L 850, 30";
*/
c_path0 = "M 75," + (20 + Math.round(chart_scale['population'](c_data0['population']), 2))
+ " L 225," + (20 + Math.round(chart_scale['labor'](c_data0['labor'][0]), 2))
+ " L 375," + (20 + chart_scale['unemployment'](c_data0['labor'][3] / 100.0))
+ " L 525," + (20 + chart_scale['education-index'](c_data0['education-index']))
+ " L 675," + (20 + chart_scale['income-index'](c_data0['income-index']))
+ " L 825," + (20 + chart_scale['health-index'](c_data0['health-index']));
a_d3Svg.append("path").attr("d", c_path0).attr("fill", "none").attr("stroke", fill_color[0]).attr("stroke-width", "1");
c_data1 = a_countyDataPair[1];
c_path1 = "M 75," + (20 + Math.round(chart_scale['population'](c_data1['population']), 2))
+ " L 225," + (20 + Math.round(chart_scale['labor'](c_data1['labor'][0]), 2))
+ " L 375," + (20 + chart_scale['unemployment'](c_data1['labor'][3]/100.0))
+ " L 525," + (20 + chart_scale['education-index'](c_data1['education-index']))
+ " L 675," + (20 + chart_scale['income-index'](c_data1['income-index']))
+ " L 825," + (20 + chart_scale['health-index'](c_data1['health-index']));
a_d3Svg.append("path").attr("d", c_path1).attr("fill", "none").attr("stroke", fill_color[1]).attr("stroke-width", "1");
}
this.data_fields = [
{
"data_name" : "population",
"renderer" : this.ShowPopulation,
"graph_title" : "Population",
"x_axis" : d3.svg.axis().scale(this.data_scale['population']).orient('bottom').ticks(5).tickFormat(d3.format("s"))
},
{
"data_name" : "labor",
"renderer" : this.ShowLaborForceSize,
"graph_title" : "Labor Force Size",
"x_axis" : d3.svg.axis().scale(this.data_scale['labor']).orient('bottom').ticks(5).tickFormat(d3.format("s"))
},
{
"data_name" : "unemployment",
"renderer" : this.ShowUnemploymentRate,
"graph_title" : "Unemployment Rate",
"x_axis" : d3.svg.axis().scale(this.data_scale['unemployment-percent']).orient('bottom').ticks(5).tickFormat(d3.format("%"))
},
{
"data_name" : "education-index",
"renderer" : this.ShowEducation,
"graph_title" : "Education Index",
"x_axis" : d3.svg.axis().scale(this.data_scale['education-index']).orient('bottom').ticks(5)
},
{
"data_name" : "income-index",
"renderer" : this.ShowIncomeIndex,
"graph_title" : "Income Index",
"x_axis" : d3.svg.axis().scale(this.data_scale['income-index']).orient('bottom').ticks(5)
},
{
"data_name" : "health-index",
"renderer" : this.ShowHealthIndex,
"graph_title" : "Health-Index",
"x_axis" : d3.svg.axis().scale(this.data_scale['health-index']).orient('bottom').ticks(5)
}
];
this.ShowCountyCounty = function()
{
$("#county-county .svg-panel").each(function() { // Clear contents of SVG
// console.log("this: " + this);
// console.log("this.children(): " + $(this).children());
// console.log("List returned - length: " + $(this).children().length);
$(this).empty();
});
var state1_name = $("select[name='state1']" ).val().trim();
var state2_name = $("select[name='state2']" ).val().trim();
var county1_name = $("select[name='county1']").val();
if ( !county1_name ) {
return;
}
county1_name = county1_name.trim();
var county2_name = $("select[name='county2']").val()
if ( !county2_name ) {
return;
}
county2_name = county2_name.trim();
var state_county1 = this.GetStateAbbreviation(state1_name) + ", " + county1_name.toLowerCase();
var state_county2 = this.GetStateAbbreviation(state2_name) + ", " + county2_name.toLowerCase();
console.log("State-county 1: " + state_county1 + " & " + "State-county 2: " + state_county2);
c_name1 = this.Capitalize(state_county1);
c_name2 = this.Capitalize(state_county2);
console.log("County 1 = " + state_county1 + ", c_name1: " + c_name1);
console.log("County 2 = " + state_county2 + ", c_name2: " + c_name2);
var county_data1 = this.GetCountyStore(state_county1);
var county_data2 = this.GetCountyStore(state_county2);
console.log("County 1 data: " + county_data1);
console.log("County 2 data: " + county_data2);
var county_pair = [ county_data1, county_data2 ];
var font_style = "Lucida Console", font_size = "18px";
var rect_height = "30px";
var fill_color = ["#365697", "#ED416F"];
var d3_scale = this.data_scale['labor-force'];
// var svg_titles = [ "Population", "Labor Force Details", "Education Index",
// "Income Index", "Health-Care Index" ];
$("#svg-panel").empty(); // Clear all SVG elements and redraw graphs!
var d3_svg_panel = d3.select("#svg-panel");
var d3_svg;
for (var ii = 0; ii < county_store.data_fields.length; ++ii) {
var meta_data = county_store.data_fields[ii];
d3_svg = d3_svg_panel.append("svg");
d3_svg.attr("viewBox", "0 0 250 216");
d3_svg.attr("preserveAspectRatio", "none");
console.log("DATA-INDEX: " + ii + ", obj: " + meta_data['graph-title']);
// var data_name = this.data_fields[ii];
meta_data.renderer(d3_svg, county_pair, meta_data);
}
d3_svg = d3_svg_panel.append("svg");
d3_svg.attr("height", "40%").attr("width", "100%");
this.DrawParallelCoordinatesChart(county_pair, d3_svg);
}
this.UpdateSelect = function(a_stateSelect, a_countySelect)
{
var state_name = $(a_stateSelect).val().trim();
var name_parts = state_name.toLowerCase().split(' ');
for (var ii = 0; ii < name_parts.length; ++ii) {
name_parts[ii] = name_parts[ii].charAt(0).toUpperCase() + name_parts[ii].substr(1);
}
state_name = name_parts.join(' ');
var county_list = this.GetCountyNames(state_name);
console.log("UpdateSelect(): state_name: " + state_name + ", county_list: " + county_list);
if ( county_list ) {
$(a_countySelect).empty();
for (var ii = 0; ii < county_list.length; ++ii) {
a_countySelect.add(new Option(county_list[ii]));
}
}
}
this.DoPageSetup = function()
{
$("#county-county .state-select").each(function () {
state_list = county_store.GetStateNamesList();
for (var ii = 0; ii < state_list.length; ++ii) {
this.add(new Option(state_list[ii]));
}
console.log("select options changed.");
});
$("select[name='state1']").bind('change', function() {
console.log("State 1 select input changed, event.target: " + event.target.tagName);
// county_store.UpdateSelect(event.target, $("select[name='county1']")[0]);
county_store.UpdateSelect($("select[name='state1']")[0], $("select[name='county1']")[0]);
county_store.ShowCountyCounty();
});
$("select[name='state2']").bind('change', function() {
console.log("State 2 select input changed, event.target: " + event.target.tagName);
// county_store.UpdateSelect(event.target, $("select[name='county2']")[0]);
county_store.UpdateSelect($("select[name='state2']")[0], $("select[name='county2']")[0]);
county_store.ShowCountyCounty();
});
$("select[name='county1']").bind('change', function() {
console.log("County 1 select input changed.");
county_store.ShowCountyCounty();
});
$("select[name='county2']").bind('change', function() {
console.log("County 2 select input changed.");
county_store.ShowCountyCounty();
});
$("button.show-hide").each(function () {
var current_button = $(this);
current_button.bind('click', function() {
current_button.parent().children('button').each(function() {
if ( current_button.text() == $(this).text() ) {
current_button.hide();
} else {
$(this).show();
}
});
current_button.parent().children('.data-pane').each(function() {
if ( current_button.text() == '-' ) {
$(this).hide();
} else {
$(this).show();
}
});
});
if ( current_button.text() == '+' ) {
current_button.hide();
}
});
$("select[name='state1']").triggerHandler('change', event = { target : $("select[name='state1']")[0] });
$("select[name='state2']").triggerHandler('change', event = { target : $("select[name='state2']")[0] });
}
}
$(document).ready(function() {
console.log("Document ready - get JSON object.");
county_store = new CountyStore();
var downloaded_datasets = 0;
$.ajax({
url: "data/county_data.json",
dataType: 'json',
success: function(a_countyData) {
console.log("JSON object received: " + a_countyData['ca, santa clara']['population']);
county_store.SetCountyStore(a_countyData); // Save data list!
},
error: function(request, textStatus, errorThrown) {
// console.log(textStatus + " " + errorThrown);
console.log("GET County data error! " + textStatus);
console.log("GET County data error! " + errorThrown);
},
complete: function(request, textStatus) { // for additional info
// console.log(request.responseText);
// console.log(textStatus);
console.log("GET county-data JSON - done!");
if ( ++downloaded_datasets == 3 ) {
county_store.DoPageSetup();
}
}
});
$.ajax({
url: "data/state_names.json",
dataType: 'json',
success: function(a_stateNames) {
console.log("JSON object received: " + a_stateNames['california']);
county_store.SetStateNames(a_stateNames); // Save data list!
},
error: function(request, textStatus, errorThrown) {
// console.log(textStatus + " " + errorThrown);
console.log("GET State Names JSON - error!");
},
complete: function(request, textStatus) { // for additional info
// console.log(request.responseText);
// console.log(textStatus);
console.log("GET State Names JSON - done!");
if ( ++downloaded_datasets == 3 ) {
county_store.DoPageSetup();
}
}
});
$.ajax({
url: "data/state_county.json",
dataType: 'json',
success: function(a_stateCounties) {
console.log("JSON object received: " + a_stateCounties['California']);
county_store.SetStateCounties(a_stateCounties); // Save data list!
},
error: function(request, textStatus, errorThrown) {
console.log(textStatus + " " + errorThrown);
console.log("GET State Counties JSON - error!");
},
complete: function(request, textStatus) { // for additional info
// console.log(request.responseText);
// console.log(textStatus);
console.log("GET State Counties JSON - done!");
if ( ++downloaded_datasets == 3 ) {
county_store.DoPageSetup();
}
}
});
});
|
import SingleLineTextBoxData from './SingleLineTextBoxData';
export default class SearchBoxData extends SingleLineTextBoxData {
constructor(displayObject, role, domIdPrefix) {
super(displayObject, role, domIdPrefix);
this._reactProps.type = 'search';
}
}
|
"use strict";
var page = require('webpage').create();
var server = require('webserver').create();
var system = require('system');
var url;
var listening = server.listen(8910, function (request, response) {
console.log(request.post['url']);
url = request.post['url'];
response.statusCode = 200;
response.headers = {
"Cache": "no-cache",
"Content-Type": "text/html"
};
page.settings.userAgent = 'Mozilla/5.0 (iPhone; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.25 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1';
page.open(url, function (status) {
function checkReadyState() {
setTimeout(function () {
var readyState = page.evaluate(function () {
return document.readyState;
});
if ("complete" === readyState) {
response.write(page.content);
response.close;
} else {
checkReadyState();
}
});
}
checkReadyState();
});
});
|
import React, {Component} from 'react';
import '../styles/App.css';
import {product} from '../product.js';
import {NavLink} from 'react-router-dom';
export default class Shop extends Component {
constructor(props) {
super(props);
let match = this.props.match;
console.log(match);
}
render() {
let categories = []
product.forEach((shopItem) => {
if (categories.indexOf(shopItem.category) === -1) {
categories.push(shopItem.category);
console.log("testing", categories[0].description)
}
});
let category_links = categories.map((shopItem) => {
return (
<div key={shopItem} className="link">
<NavLink to={`/shop/${shopItem}`}>{shopItem}</NavLink>
</div>
)
});
console.log(category_links);
return (
<div className="shop">
<header className="shopHeader">Shop</header>
{category_links}
</div>
);
}
}
|
'use strict';
var express = require('express');
var router = express.Router();
//for upload
var uploadcek = require('../config/upload')
var upload = uploadcek.destination('public')
const user = require('../controllers/userControllers');
const verify = require('../middleware/verify');
/* GET users listing. */
// router.get('/', user.users);
router.post('/register', upload.none(), user.createUsers);
router.get('/verifyuser/', upload.none(), user.verifyUser);
router.post('/login', upload.none(), user.loginUser);
router.post('/getuser',verify.verifyToken, upload.none(), user.getUser);
router.post('/sendrequestforget', upload.none(), user.sendRequestForget);
router.post('/changepassword', upload.none(), user.changePassword);
module.exports = router;
|
/**
* Configuração de rotas
*/
angular.module("appAgendinha").config(function($routeProvider){
$routeProvider.when("/usuarios", {
templateUrl: "view/usuarios.html",
controller: "listaUsuarioCtrl",
resolve:{
usuarios: function(usuarioApi){
return usuarioApi.getUsuarios();
}
}
});
$routeProvider.when("/novoUsuario",{
templateUrl: "view/novoUsuario.html",
controller: "UsuarioController",
resolve:{
perfis: function(perfilApi){
return perfilApi.getPerfis();
},
usuario: function(){
var usuario = {};
return usuario;
}
}
});
$routeProvider.when("/detalharUsuario/:id",{
templateUrl: "view/detalharUsuario.html",
controller: "UsuarioController",
resolve:{
perfis: function(perfilApi){
return perfilApi.getPerfis();
},
usuario: function (usuarioApi, $route) {
return usuarioApi.getUsuario($route.current.params.id);
}
}
});
$routeProvider.when("/error",{
templateUrl: "view/error.html"
});
$routeProvider.otherwise({redirectTo:"/usuarios"});
});
|
'use strict';
const express = require('express');
const app = express();
const config = {
port: 3000,
path: __dirname
};
app.use((req, res, next) => {
console.log(req.url);
req.next();
});
app.get('/', (_, res) => {
res.sendFile(config.path + '/resources/index.html');
});
app.get('/index.js', (_, res) => {
res.sendFile(config.path + '/resources/index.js');
});
app.use('/wasm', express.static(__dirname + '/wasm_src/pkg'));
app.listen(config.port, () => console.log(`Listening on ${config.port} at ${Date()}`));
|
// JavaScript source code for node
var portNum = 52273;
// 모듈
var os = require('os');
var express = require('express');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var WebSocket = require("ws").Server;
var chatSocket = new WebSocket({ port: portNum + 1 });
var gameSocket = new WebSocket({ port: portNum + 2 });
// 정의 모듈
var loginJson = require('./server/loginJson.js');
// mysql 연결
var db = mysql.createConnection({
user: 'root',
password: '14109383',
database: 'member'
});
// networkInterfaces 생성
var networkInterfaces = os.networkInterfaces();
// web server 생성
var app = express();
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
// 강제로 db와 연결유지
setInterval(function () {
db.query('SELECT 1');
}, 5000);
/* 로그인&회원가입 */
// login request 응답
app.post('/login.json', function (request, response) {
var userId = request.body.userId;
var userPw = request.body.userPw;
var idsPw = '';
var failType = '';
console.log('login request: ' + userId + ' / ' + userPw);
db.query('select password from member ' +
"where id = binary('" + userId + "')", function (error, rows) {
if (error) {
console.log(error);
}
else {
if (rows.length == 0)
failType = 'id';
else
idsPw = rows[0].password;
if (failType == 'id') {
response.send(loginJson(false, failType));
console.log('login fail: ' + failType);
}
else if (userPw == idsPw) {
response.send(loginJson(true, userId));
console.log('login: ' + userId);
db.query("update member set score = score + 3 where id = binary('"
+ userId + "')", function (error, rows) {
if (error) {
console.log(error);
}
});
}
else {
failType = 'password';
response.send(loginJson(false, failType));
console.log('login fail: ' + failType);
}
}
});
});
// sing_up request 응답
app.post('/sign_up.json', function (request, response) {
var userId = request.body.userId;
var userPw = request.body.userPw;
var failType = '';
console.log('sign up request: ' + userId + ' / ' + userPw);
db.query('select password from member ' +
"where id = binary('" + userId + "')", function (error, rows) {
if (error) {
console.log(error);
}
else {
if (rows.length != 0) {
failType = 'id';
}
else {
db.query('insert into member (id, password, authority) values (?,?,?)',
[userId, userPw, 'user'],
function (error) {
if (error)
console.log(error);
});
}
if (failType == 'id') {
response.send(loginJson(false, failType));
console.log('sign up fail: ' + failType);
}
else{
response.send(loginJson(true, userId));
console.log('sign_up: ' + userId);
db.query("update member set score = score + 3 where id = binary('"
+ userId + "')", function (error, rows) {
if (error) {
console.log(error);
}
});
}
}
});
});
/*---------------------------------------------*/
/* 프로필 카드 */
app.get('/profile/:id', function (request, response) {
var id = request.params.id;
db.query('select authority, score from member '
+ " where id = binary('" + id + "')"
, function(error, rows, fields){
if (error) {
console.log(error);
response.send({
result: 'failed',
failType: error
});
}
else {
if (rows.length == 0) {
response.send({
'rank': 'kakao',
'score': '---'
})
}
else {
response.send({
'rank': rows[0].authority,
'score': rows[0].score
})
}
console.log('send profile_card info');
}
})
});
/*---------------------------------------------*/
/* 게시판 */
// 게시판 응답
app.get('/board/:offset', function (request, response) {
var offset = Number(request.params.offset);
db.query('select * from board\n'+ 'order by post_date desc\n' + 'limit ?, 5'
, [offset], function (error, rows, fields) {
if (error) {
console.log(error);
response.send({
result: 'failed',
failType: error
});
}
else {
var items = rows.length;
var titles = [];
var post_dates = [];
var writers = [];
var contents = [];
for (var i = 0; i < items; i++) {
titles.push(rows[i].title);
post_dates.push(rows[i].post_date);
writers.push(rows[i].writer);
contents.push(rows[i].content);
}
console.log('board data sent ');
response.send({
'items': items,
'titles': titles,
'post_dates': post_dates,
'writers': writers,
'contents': contents
});
}
});
});
// board post 응답
app.post('/post.json', function (request, response) {
console.log('board post request');
var post_title = request.body.title;
var post_writer = request.body.writer;
var post_content = request.body.content;
db.query('INSERT INTO board (writer, title, content) values (?, ?, ?)'
, [post_writer, post_title, post_content], function (error, results, fields) {
if (error) {
response.send({
result: 'failed',
failType: error
});
}
else {
console.log('board post successed');
response.send({
result: 'successed',
failType: ''
});
}
});
});
/*---------------------------------------------*/
/* 채팅 */
// 채팅 데이터 생성 함수
function encodeChattingData(type, who, message) {
return encodeURIComponent(JSON.stringify({
'type': type, //< type: join, message, peoples
'who': who, //< who: user, system
'message': message //< message: contents
}));
}
// 채팅 데이터 파싱 함수
function decodeChattingData(raw) {
return JSON.parse(decodeURIComponent(raw));
}
// 채팅방 연결
chatSocket.on("connection", function (ws) {
ws.on('pong', heartbeat);
console.log("chatting socket conneted:" + Date());
//ws.send(chatDataForm('join', ws));
ws.on("message", function (raw) {
var data = decodeChattingData(raw);
var type = data['type'];
var who = data['who'];
var message = data['message'];
chatSocket.clients.forEach(function each(client) {
try {
encodeChattingData('peoples', 'system', peoples); //< 인원 수 정보
client.send(encodeChattingData(type, who, message));
} catch (e) {
}
});
});
});
// 연결 상태 체크
var peoples = 0;
function noop() { /* empty */ }
function heartbeat() {
this.isAlive = true;
}
function ping() {
peoples = 0;
chatSocket.clients.forEach(function each(ws) {
peoples++;
ws.isAlive = false;
ws.ping(noop);
});
chatSocket.clients.forEach(function each(client) {
try {
client.send(encodeChattingData('peoples', 'system', peoples));
} catch (e) {
}
});
}
setInterval(ping, 1000);
ping();
/*---------------------------------------------*/
/* JavaScript Code for Game ------------------------------------------------------------------------------------------ */
/* enum */
const red = 1; // 위 팀
const blue = 2; // 아래 팀
const player = 1;
const missile = 2;
const width = 720;
const height = 640;
const redLine = height / 3;
const blueLine = height * 2 / 3;
const speedOfMissile = 2;
const speedOfPlayer = 10;
const radiusOfMissile = 20;
const radiusOfPlayer = 10;
const stop = 0;
const east = 1;
const west = 2;
const south = 3;
const north = 4;
const launch = 5;
const die = 0;
const live = 1;
/*----------------------------------------------*/
var createRedPlayer = function () {
return {
'team': red,
'x': (width / 2),
'y': (height / 5),
'action': stop,
'status': live
};
}
var createBluePlayer = function () {
return {
'team': blue,
'x': (width / 2),
'y': (height * 4 / 5),
'action': stop,
'status': live
};
}
var moveRedPlayer = function (redPlayer) {
if (redPlayer['status'] == die)
return;
switch (redPlayer['action']) {
case stop:
break;
case east:
if (redPlayer['x'] + radiusOfPlayer + speedOfPlayer < width)
redPlayer['x'] += speedOfPlayer;
break;
case west:
if (redPlayer['x'] - radiusOfPlayer - speedOfPlayer > 0)
redPlayer['x'] -= speedOfPlayer;
break;
case south:
if (redPlayer['y'] + radiusOfPlayer + speedOfPlayer < redLine)
redPlayer['y'] += speedOfPlayer;
break;
case north:
if (redPlayer['y'] - radiusOfPlayer - speedOfPlayer > 0)
redPlayer['y'] -= speedOfPlayer;
break;
}
redPlayer['action'] = stop;
}
var moveBluePlayer = function (bluePlayer) {
if (bluePlayer['status'] == die)
return;
switch (bluePlayer['action']) {
case stop:
break;
case east:
if (bluePlayer['x'] + radiusOfPlayer + speedOfPlayer < width)
bluePlayer['x'] += speedOfPlayer;
break;
case west:
if (bluePlayer['x'] - radiusOfPlayer - speedOfPlayer > 0)
bluePlayer['x'] -= speedOfPlayer;
break;
case south:
if (bluePlayer['y'] + radiusOfPlayer + speedOfPlayer < height)
bluePlayer['y'] += speedOfPlayer;
break;
case north:
if (bluePlayer['y'] - radiusOfPlayer - speedOfPlayer > blueLine)
bluePlayer['y'] -= speedOfPlayer;
break;
}
bluePlayer['action'] = stop;
}
var createRedMissile = function (redPlayer) {
return {
'team': red,
'x': redPlayer['x'],
'y': redPlayer['y'],
'status': live
}
}
var createBlueMissile = function (bluePlayer) {
return {
'team': blue,
'x': bluePlayer['x'],
'y': bluePlayer['y'],
'status': live
}
}
var moveRedMissile = function (redMissile) {
if (redMissile['status'] != live)
return;
if (redMissile['y'] - radiusOfMissile + speedOfMissile < height)
redMissile['y'] += speedOfMissile;
else
redMissile['status'] = die;
}
var moveBlueMissile = function (blueMissile) {
if (blueMissile['status'] != live)
return;
if (blueMissile['y'] + radiusOfMissile - speedOfMissile > 0)
blueMissile['y'] -= speedOfMissile;
else
blueMissile['status'] = die;
}
var collision = function (player, missile) {
var distance = Math.sqrt((player['x'] - missile['x']) * (player['x'] - missile['x'])
+ (player['y'] - missile['y']) * (player['y'] - missile['y']));
if (distance < radiusOfMissile + radiusOfPlayer) {
player['status'] = die;
}
}
var redPlayersCollision = function (redPlayers, blueMissiles) {
for (var player in redPlayers) {
if (redPlayers[player]['status'] != live)
continue;
for (var missile in blueMissiles) {
if (blueMissiles[missile]['status'] != live)
continue;
if (blueMissiles[missile]['y'] > redLine + radiusOfMissile)
continue;
collision(redPlayers[player], blueMissiles[missile]);
}
}
}
var bluePlayersCollision = function (bluePlayers, redMissiles) {
for (var player in bluePlayers) {
if (bluePlayers[player]['status'] != live)
continue;
for (var missile in redMissiles) {
if (redMissiles[missile]['status'] != live)
continue;
if (redMissiles[missile]['y'] < blueLine - radiusOfMissile)
continue;
collision(bluePlayers[player], redMissiles[missile]);
}
}
}
/*-------------------------------------------------------------------------------------------------------------------------*/
/* Game Thread ---------------------------------------------------------------------------------------------------------*/
var gameSeed = 1;
var players = {};
var missiles = [];
var decideTeam = function () {
if (gameSeed % 2 == 0)
return blue;
else
return red;
}
gameSocket.on("connection", function (ws) {
console.log("game socket conneted:" + Date());
// assign team
var team = decideTeam();
if (team == blue)
players[String(gameSeed)] = createBluePlayer();
else
players[String(gameSeed)] = createRedPlayer();
try {
ws.send(JSON.stringify(
{
'type': 'seed',
'value': (gameSeed++)
}
));
}
catch (e) {
}
ws.on("message", function (raw) {
var data = JSON.parse(raw);
var seed = data['seed'];
var type = data['type'];
var value = data['value'];
switch (type) {
case 'control':
if (value == north)
players[seed]['action'] = north;
else if (value == south)
players[seed]['action'] = south;
else if (value == east)
players[seed]['action'] = east;
else if (value == west)
players[seed]['action'] = west;
else if (value == launch)
players[seed]['action'] = launch;
break;
}
});
});
setInterval(function () {
if (!players)
return;
// Initialize
var redPlayers = [];
var bluePlayers = [];
var redMissiles = [];
var blueMissiles = [];
for (var player in players) {
if (players[player]['status'] == die)
;
else if (players[player]['team'] == red)
redPlayers.push(players[player]);
else if (players[player]['team'] == blue)
bluePlayers.push(players[player]);
}
for (var missile in missiles) {
if (missiles[missile]['status'] == die)
;
else if (missiles[missile]['team'] == red)
redMissiles.push(missiles[missile]);
else if (missiles[missile]['team'] == blue)
blueMissiles.push(missiles[missile]);
}
// Action
redPlayersCollision(redPlayers, blueMissiles);
bluePlayersCollision(bluePlayers, redMissiles);
for (var redPlayer in redPlayers) {
if (redPlayers[redPlayer]['action'] == launch)
missiles.push(createRedMissile(redPlayers[redPlayer]));
moveRedPlayer(redPlayers[redPlayer]);
}
for (var bluePlayer in bluePlayers) {
if (bluePlayers[bluePlayer]['action'] == launch)
missiles.push(createBlueMissile(bluePlayers[bluePlayer]));
moveBluePlayer(bluePlayers[bluePlayer]);
}
for (var redMissile in redMissiles) {
moveRedMissile(redMissiles[redMissile]);
}
for (var blueMissile in blueMissiles) {
moveBlueMissile(blueMissiles[blueMissile]);
}
gameSocket.clients.forEach(function each(client) {
stringOfPlayers = JSON.stringify(players);
stringOfMissiles = JSON.stringify(missiles);
try {
client.send(JSON.stringify({
'type': 'players',
'value': stringOfPlayers
}));
client.send(JSON.stringify({
'type': 'missiles',
'value': stringOfMissiles
}));
} catch (e){
}
});
}, 10);
/*------------------------------------------------------------------------------------------------------------------------*/
// web server 실행
app.listen(portNum, function () {
console.log('Server Running:');
console.log(networkInterfaces);
console.log('at port number ' + portNum);
});
|
import React, { useState, useEffect } from 'react';
import { Checkbox } from 'antd';
const CheckboxList = ({ defaultValue, title, plainOptions, onChange }) => {
const [showAll, setShowAll] = useState(false);
const [options, setOptions] = useState([]);
useEffect(() => {
showAll ? setOptions(plainOptions) : setOptions(plainOptions.slice(0, 2))
}, [showAll]);
return (
<div className='sidebar__container'>
<p>{title}</p>
<Checkbox.Group style={{ width: '100%' }} options={options} value={defaultValue} onChange={onChange} />
<p className='sidebar__expand' onClick={() => setShowAll(!showAll)}>{showAll ? 'Collapse' : 'Expand All'}</p>
</div>
)
}
export default CheckboxList;
|
import React from 'react';
import { render, screen } from '@testing-library/react';
import { useDispatch } from 'react-redux';
import { loadPM25HeatMapData, loadMapEventsData } from 'redux/MapData/operations';
import MapContainer from './MapContainer';
jest.mock('react-redux', () => ({
...jest.requireActual('react-redux'),
useDispatch: jest.fn(),
}));
jest.mock('your-hooks', () => ({
usePM25HeatMapData: jest.fn(() => ({ features: [] })),
useEventsMapData: jest.fn(() => ({ features: [] })),
}));
describe('MapContainer', () => {
it('dispatches actions on initial render if data is empty', () => {
const mockDispatch = jest.fn();
useDispatch.mockReturnValue(mockDispatch);
render(<MapContainer />);
expect(mockDispatch).toHaveBeenCalledWith(loadPM25HeatMapData());
expect(mockDispatch).toHaveBeenCalledWith(
loadMapEventsData({
recent: 'yes',
external: 'no',
metadata: 'site_id',
frequency: 'hourly',
active: 'yes',
})
);
});
it('renders OverlayMap when heatMapData is available', () => {
const mockDispatch = jest.fn();
useDispatch.mockReturnValue(mockDispatch);
jest.mock('your-hooks', () => ({
usePM25HeatMapData: jest.fn(() => ({
features: [{ "geometry": { "coordinates": [33.269948767666726, 0.3976606461111487], "type": "Point" }, "properties": { "interval": 26.61421875414251, "latitude": 0.3976606461111487, "longitude": 33.269948767666726, "pm2_5": 54.08361977962887, "variance": 184.38063304179272 }, "type": "Feature" }, { "geometry": { "coordinates": [33.22026394233339, 0.40645178522225933], "type": "Point" }, "properties": { "interval": 26.659677319838934, "latitude": 0.40645178522225933, "longitude": 33.22026394233339, "pm2_5": 55.434074134188336, "variance": 185.01103571374807 }, "type": "Feature" }],
})),
useEventsMapData: jest.fn(() => ({ features: [] })),
}));
render(<MapContainer />);
expect(screen.getByTestId('overlay-map')).toBeInTheDocument();
});
it('renders CircularLoader when heatMapData is empty', () => {
const mockDispatch = jest.fn();
useDispatch.mockReturnValue(mockDispatch);
jest.mock('your-hooks', () => ({
usePM25HeatMapData: jest.fn(() => ({ features: [] })),
useEventsMapData: jest.fn(() => ({ features: [] })),
}));
render(<MapContainer />);
expect(screen.getByTestId('circular-loader')).toBeInTheDocument();
});
});
|
let bullshit = false;
class Console
{
constrctor()
{
}
}
function EnableBullShit() //uninportant function that can be run through console in Inspect Element on the site
{
alert("Oh boi, You've Done it now!");
bullshit = true;
EnableOverlay();
}
|
import React from 'react';
export default ({ mnemonic }) => (
<div>
<code>{mnemonic}</code>
</div>
);
|
/**
* @swagger
* components:
* responses:
* pasLesDroits:
* description: vous ne correspondes pas aux critere pour acceder a cette fonction
*/
module.exports.mustbeAdmin = (req, res, next) => {
if( req.session && req.session.authLevel === "admin"){
next();
}
else{
res.sendStatus(403);
}
}
module.exports.mustbeAtLeastUSer = (req, res, next) =>{
if(req.session && (req.session.authLevel ==="user" || req.session.authLevel === "admin" )){
next();
}
else{
res.sendStatus(403);
}
}
|
import Validator from 'validator';
import { isEmpty } from 'lodash';
const findBookGenre = (genres, item) => {
const bookFound = genres.filter((genre) => {
return genre.name === item
})
return { bookFound }
}
/**
* @class defaultClass
* @description Validate inputs for book categories
* @param {object} inputs
* @return {object} isValid and errors
*/
export default (inputs, type) => {
let errors = {};
const {
id,
name,
genres,
genreName
} = inputs;
let validText = /^\w*(\s*\w*)*$/i
if (type === 'create') {
if (Validator.isEmpty(name) || !name) {
errors.name = 'This field is required'
}
if (!Validator.isEmpty(name) && !validText.test(name)) {
errors.name = 'Please enter a valid book category'
}
}
if (type === 'select') {
if (Validator.isEmpty(genreName)) {
errors.genreName = 'Please select a book category'
}
if (!Validator.isEmpty(genreName)) {
const { bookFound } = findBookGenre(genres, genreName);
if (!validText.test(genreName)) {
errors.genreName = 'Please select from the list of valid options'
} else if (isEmpty(bookFound)) {
errors.genreName = 'Book category does not exist'
}
}
}
return {
errors,
isValid: isEmpty(errors)
}
};
|
function solution(A, K) {
K = K % A.length;
if (K === 0) return A;
return A.slice(-K).concat(A.slice(0, A.length - K));
}
module.exports = solution
|
var assert = require('assert')
var Channel = require('..')
describe('Channel', function () {
it('should sum to 10', function (done) {
var chan = new Channel()
var sum = 0
chan.each(function (num) {
sum += num
})
chan.put(1)
chan.put(2)
chan.put(3)
chan.put(4)
chan.close(null, 'DONE')
chan.done(function (err, val) {
assert(val === 'DONE')
assert(sum === 10)
done()
})
})
})
|
var FlowerPot = cc.Layer.extend({
sparkEmitter: null,
pointEmitter: null,
glow: null,
flowerPot: null,
totalDuration: 0,
ctor:function () {
this._super();
var size = cc.winSize;
var self = this;
var particleCount = 1000;
var totalDuration = 10;
var pot = new cc.Sprite(res.flowerPot);
pot.scale = 0.8;
pot.setPositionY(-20);
this.addChild(pot, 2);
this.flowerPot = pot;
// Spark Line Emitter
var texture = cc.textureCache.addImage(res.flowerParticle);
var se = new cc.ParticleFireworks();
se.texture = texture;
se.angle = 90;
se.angleVar = 5;
se.totalParticles = particleCount;
se.startSize = 12;
se.startSizeVar = 6;
se.startColor = cc.color(255, 180, 50, 150);
se.startColorVar = cc.color(50, 50, 50, 50);
se.endColor = cc.color(255, 180, 50, 10);
se.endColorVar = cc.color(50, 50, 50, 10);
se.duration = totalDuration;
se.blendAdditive = true;
se.emissionRate = 10;
se.speed = 20;
se.life = 0.1;
se.gravity = cc.p(0, se.gravity.y * 2.5);
se.setPosition(cc.p(0, 0));
this.sparkEmitter = se;
this.addChild(this.sparkEmitter);
// Point Emitter
var texture = cc.textureCache.addImage(res.dotParticle);
var pe = new cc.ParticleFireworks();
pe.texture = texture;
pe.angle = 90;
pe.angleVar = 5;
pe.totalParticles = particleCount;
pe.startSize = 5;
pe.startSizeVar = 3;
pe.startColor = cc.color(255, 180, 50, 150);
pe.startColorVar = cc.color(50, 50, 50, 50);
pe.endColor = cc.color(255, 180, 50, 10);
pe.endColorVar = cc.color(50, 50, 50, 10);
pe.duration = totalDuration;
pe.blendAdditive = true;
pe.emissionRate = 10;
pe.speed = 20;
pe.life = 0.1;
pe.gravity = cc.p(0, pe.gravity.y * 2.5);
pe.setPosition(cc.p(0, 0));
this.pointEmitter = pe;
this.addChild(this.pointEmitter);
// Glow
texture = cc.textureCache.addImage(res.whiteParticle);
var gl = new cc.ParticleSun();
gl.texture = texture;
gl.totalParticles = 200;
gl.life *= 1.5
gl.scaleX = 2;
gl.scaleY = 4;
gl.startSize = 32;
gl.startSizeVar = 8;
gl.startColor = cc.color(255, 210, 150, 2);
gl.startColorVar = cc.color(0, 0, 0, 4);
gl.endColor = cc.color(255, 210, 150, 1);
gl.endColorVar = cc.color(0, 0, 0, 1);
gl.duration = totalDuration;
gl.setPosition(cc.p(0, 0));
this.glow = gl;
this.addChild(this.glow);
cc.eventManager.addListener({
event: cc.EventListener.TOUCH_ONE_BY_ONE,
swallowTouches: true,
onTouchBegan: this.onTouchBegan,
onTouchMoved: this.onTouchMoved,
onTouchEnded: this.onTouchEnded
}, this);
this.runAction(cc.sequence(
cc.delayTime(totalDuration - 2),
cc.callFunc(this.stopSystem, this)
));
this.schedule(this.sparkEmissionUpdate);
this.schedule(this.sparkSpeedUpdate);
this.schedule(this.sparkLifeUpdate);
return true;
},
sparkEmissionUpdate: function(dt) {
this.sparkEmitter.emissionRate += dt * 100;
this.pointEmitter.emissionRate += dt * 100;
if ( this.sparkEmitter.emissionRate > 200) {
this.unschedule(this.sparkEmissionUpdate);
}
},
sparkSpeedUpdate: function(dt) {
this.sparkEmitter.speed += dt * 200;
this.pointEmitter.speed += dt * 200;
if ( this.sparkEmitter.speed > 400) {
this.unschedule(this.sparkSpeedUpdate);
}
},
sparkLifeUpdate: function(dt) {
this.sparkEmitter.life += dt * 2.5;
this.pointEmitter.life += dt * 2.5;
if ( this.sparkEmitter.life > 5) {
this.unschedule(this.sparkLifeUpdate);
}
},
stopSystem: function () {
this.runAction(cc.sequence(
cc.delayTime(6.0),
cc.callFunc(this.removeSystem, this)
));
},
removeSystem: function() {
this.removeFromParent(true);
},
onTouchBegan:function(touch, event) {
return true;
},
onTouchMoved:function(touch, event) {
},
onTouchEnded:function(touch, event) {
var pos = touch.getLocation();
var pot = new FlowerPot();
pot.setPosition(pos);
cc.director.getRunningScene().addChild(pot);
}
});
|
import React, { useEffect, useState } from 'react';
import portfoliosData from '../../portfoliosData/portfoliosData.json';
import Portfolio from '../Portfolio/Portfolio';
const Portfolios = () => {
const [portfolio, setPortfolios] = useState([]);
useEffect(() => {
setPortfolios(portfoliosData);
}, []);
return (
<div className="container">
<div className="row g-3">
{portfolio.map(portfolio => (
<Portfolio key={portfolio.id} portfolio={portfolio} />
))}
</div>
</div>
);
};
export default Portfolios;
|
import React from "react";
import { ApiService } from '../../../../services/apiService';
import GetAssetBalance from '../GetAssetBalance'
import { store } from 'react-notifications-component'
import { connect } from "react-redux";
import { withRouter } from "react-router-dom";
import { setProduct } from "../../../../redux/actions";
import { setTheme } from "../../../../redux/actions";
const symbolMainAssets = {
'BTCTRY' : 'BTC',
'BTCUSDT' : 'BTC',
'ETHTRY' : 'ETH',
'ETHBTC' : 'ETH',
'XRPTRY' : 'XRP',
'XRPBTC' : 'XRP',
'LTCTRY' : 'LTC',
'LTCBTC' : 'LTC',
'USDTTRY' : 'USDT',
'XRPUSDT' : 'XRP',
'LTCUSDT' : 'LTC',
'ETHUSDT' : 'ETH'
}
const symbolSecondAssets = {
'BTCTRY' : 'TRY',
'BTCUSDT' : 'USDT',
'ETHTRY' : 'TRY',
'ETHBTC' : 'BTC',
'XRPTRY' : 'TRY',
'XRPBTC' : 'BTC',
'LTCTRY' : 'TRY',
'LTCBTC' : 'BTC',
'USDTTRY' : 'TRY',
'XRPUSDT' : 'USDT',
'LTCUSDT' : 'USDT',
'ETHUSDT' : 'USDT'
}
const minAssets = {
'BTCTRY' : 0.00000100,
'BTCUSDT' : 0.00000100,
'ETHTRY' : 0.00001000,
'ETHBTC' : 0.00100000,
'XRPTRY' : 0.10000000,
'XRPBTC' : 1.00000000,
'LTCTRY' : 0.00001000,
'LTCBTC' : 0.01000000,
'USDTTRY' : '',
'XRPUSDT' : 0.10000000,
'LTCUSDT' : 0.00001000,
'ETHUSDT' : 0.00001000
}
const maxAssets = {
'BTCTRY' : 9000.00000000,
'BTCUSDT' : 9000.00000000,
'ETHTRY' : 9000.00000000,
'ETHBTC' : 100000.00000000,
'XRPTRY' : 9000000.00000000,
'XRPBTC' : 90000000.00000000,
'LTCTRY' : 900000.00000000,
'LTCBTC' : 100000.00000000,
'USDTTRY' : '',
'XRPUSDT' : 9000000.00000000,
'LTCUSDT' : 900000.00000000,
'ETHUSDT' : 9000.00000000
}
const stepAssets = {
'BTCTRY' : 0.00000100,
'BTCUSDT' : 0.00000100,
'ETHTRY' : 0.00001000,
'ETHBTC' : 0.00100000,
'XRPTRY' : 0.10000000,
'XRPBTC' : 1.00000000,
'LTCTRY' : 0.00001000,
'LTCBTC' : 0.01000000,
'USDTTRY' : '',
'XRPUSDT' : 0.10000000,
'LTCUSDT' : 0.00001000,
'ETHUSDT' : 0.00001000
}
const BuyStepAssets = {
'BTCTRY' : 0.01,
'BTCUSDT' : 0.01,
'ETHTRY' : 0.01,
'ETHBTC' : "",
'XRPTRY' : 0.01,
'XRPBTC' : "",
'LTCTRY' : 0.01,
'LTCBTC' : "",
'USDTTRY' : "",
'XRPUSDT' : 0.01,
'LTCUSDT' : 0.01,
'ETHUSDT' : 0.01
}
const BuyMinAssets = {
'BTCTRY' : 100,
'BTCUSDT' : 10,
'ETHTRY' : 100,
'ETHBTC' : "",
'XRPTRY' : 100,
'XRPBTC' : "",
'LTCTRY' : 100,
'LTCBTC' : "",
'USDTTRY' : "",
'XRPUSDT' : 10,
'LTCUSDT' : 10,
'ETHUSDT' : 10
}
const BuyMaxAssets = {
'BTCTRY' : 5000000,
'BTCUSDT' : 1000000,
'ETHTRY' : 5000000,
'ETHBTC' : "",
'XRPTRY' : 5000000,
'XRPBTC' : "",
'LTCTRY' : 5000000,
'LTCBTC' : "",
'USDTTRY' : "",
'XRPUSDT' : 1000000,
'LTCUSDT' : 1000000,
'ETHUSDT' : 1000000
}
// const TRY = {
// min: 0.01,
// max: 100000,
// step: 0.01,
// multipler:1000
// };
// const USDT = {
// min: 0.01,
// max: 100000,
// step: 0.01,
// multipler:1000
// };
// const BTC = {
// min: 0.01,
// max: 100000,
// step: 0.01,
// multipler:1000
// };
class MarketBuyAndSell extends React.Component {
constructor(props) {
super(props);
this.state = {
value:0,
orderType: 0,
assetMain: symbolMainAssets[this.props.product],
assetSecondary: symbolSecondAssets[this.props.product],
price: 0,
notification: '',
isLoggedin: ''
};
this.apiService = new ApiService();
this.handleChange = this.handleChange.bind(this);
this.sendMarketOrder = this.sendMarketOrder.bind(this);
this.handleBuySellType = this.handleBuySellType.bind(this);
}
async sendMarketOrder () {
let data;
let response = '';
if(!this.state.isLoggedin) {
store.addNotification({...this.state.notification,message:'Lütfen giriş yapın.',type:'warning',title:'Hata!'});
return;
}
if(this.state.value === 0)
{
store.addNotification({...this.state.notification,message:'Değer giriniz',type:'warning',title:'Hata!'});
}
else
{
if(this.state.value > 0) {
if(this.state.orderType === 0) {
if(this.props.product == 'ETHBTC' || this.props.product == 'XRPBTC' || this.props.product == 'LTCBTC' || this.props.product == 'USDTTRY'){
data = {
"Symbol": this.props.product,
"Side" : this.state.orderType, // 0 Buy, 1 Sell
"QuoteQuantity": this.state.value
}
response = await this.apiService.callApiPost( 'order/NewMarketOrder', data)
.catch((err)=>{
let message = '';
switch (err.response.data[0]) {
case "invalid_symbol":
message = "Hatalı sembol değeri."
break;
case "another_order_in_progress":
message = "Başka bir talep işlem görüyor lütfen bekleyiniz."
break;
case "has_pending_trades":
message = "Bekleyen işlemler var."
break;
case "duplicate_amount":
message = "Mükerrer tutar."
break;
case "invalid_amount":
message = "Hatalı tutar."
break;
case "insufficient_funds":
message = "Yetersiz bakiye."
break;
case "wrong_amount_type":
message = "Hatalı tutar tipi."
break;
default:
message = "İşlem başarısız."
break;
}
store.addNotification({...this.state.notification,message:message,type:'danger',title:'Hata!'});
return;
});
if(response) {
if(response.status === 200) {
if(response.data.isFilled) {
store.addNotification({...this.state.notification,message:'İşleminiz tamamlandı.'});
} else {
store.addNotification({...this.state.notification,message:'İşlem başarısız.',type:'danger',title:'Hata!'});
}
} else {
store.addNotification({...this.state.notification,message:'İşlem başarısız.',type:'danger',title:'Hata!'});
}
}
}
else{
if(this.state.value*1000 >= BuyMinAssets[this.props.product]*1000 && this.state.value*1000 <= BuyMaxAssets[this.props.product]*1000 && (this.state.value*1000 - BuyMinAssets[this.props.product]*1000) % (BuyStepAssets[this.props.product]*1000) == 0){
data = {
"Symbol": this.props.product,
"Side" : this.state.orderType, // 0 Buy, 1 Sell
"QuoteQuantity": this.state.value
}
response = await this.apiService.callApiPost( 'order/NewMarketOrder', data)
.catch((err)=>{
let message = '';
switch (err.response.data[0]) {
case "invalid_symbol":
message = "Hatalı sembol değeri."
break;
case "another_order_in_progress":
message = "Başka bir talep işlem görüyor lütfen bekleyiniz."
break;
case "has_pending_trades":
message = "Bekleyen işlemler var."
break;
case "duplicate_amount":
message = "Mükerrer tutar."
break;
case "invalid_amount":
message = "Hatalı tutar."
break;
case "insufficient_funds":
message = "Yetersiz bakiye."
break;
case "wrong_amount_type":
message = "Hatalı tutar tipi."
break;
default:
message = "İşlem başarısız."
break;
}
store.addNotification({...this.state.notification,message:message,type:'danger',title:'Hata!'});
return;
});
if(response) {
if(response.status === 200) {
if(response.data.isFilled) {
store.addNotification({...this.state.notification,message:'İşleminiz tamamlandı.'});
} else {
store.addNotification({...this.state.notification,message:'İşlem başarısız.',type:'danger',title:'Hata!'});
}
} else {
store.addNotification({...this.state.notification,message:'İşlem başarısız.',type:'danger',title:'Hata!'});
}
}
}
else{
store.addNotification({...this.state.notification,message:'Değerler istenen aralıkta olmalıdır.' ,type:'danger',title:'Hata!'});
}
}
} else if (this.state.orderType === 1) {
if(this.state.value*100000000 >= minAssets[this.props.product]*100000000 && this.state.value*100000000 <= maxAssets[this.props.product]*100000000 && (this.state.value*100000000 - minAssets[this.props.product]*100000000) % (stepAssets[this.props.product]*100000000) == 0)
{
data = {
"Symbol": this.props.product,
"Side" : this.state.orderType, // 0 Buy, 1 Sell
"Quantity": this.state.value
}
//buralarda işlemler yapılacak ! ! ! ^
response = await this.apiService.callApiPost( 'order/NewMarketOrder', data)
.catch((err)=>{
let message = '';
switch (err.response.data[0]) {
case "invalid_symbol":
message = "Hatalı sembol değeri."
break;
case "another_order_in_progress":
message = "Başka bir talep işlem görüyor lütfen bekleyiniz."
break;
case "has_pending_trades":
message = "Bekleyen işlemler var."
break;
case "duplicate_amount":
message = "Mükerrer tutar."
break;
case "invalid_amount":
message = "Hatalı tutar."
break;
case "insufficient_funds":
message = "Yetersiz bakiye."
break;
case "wrong_amount_type":
message = "Hatalı tutar tipi."
break;
default:
message = "İşlem başarısız."
break;
}
store.addNotification({...this.state.notification,message:message,type:'danger',title:'Hata!'});
return;
});
if(response) {
if(response.status === 200) {
if(response.data.isFilled) {
store.addNotification({...this.state.notification,message:'İşleminiz tamamlandı.'});
} else {
store.addNotification({...this.state.notification,message:'İşlem başarısız.',type:'danger',title:'Hata!'});
}
} else {
store.addNotification({...this.state.notification,message:'İşlem başarısız.',type:'danger',title:'Hata!'});
}
}
}
else{
store.addNotification({...this.state.notification,message:'Değerler istenen aralıkta olmalıdır.' ,type:'danger',title:'Hata!'});
}
}
} else {
store.addNotification({...this.state.notification,message:'Değeri sıfırdan büyük sayı veya rakam olmalıdır.',type:'danger',title:'Hata!'});
}
}
// setTimeout(function(){
// window.location.reload(); //bu kısım bakılacak!
// },1000);
}
async componentWillMount() {
// this.setState({assetMain : symbolMainAssets[this.props.product]});
// this.setState({assetSecondary : symbolSecondAssets[this.props.product]});
this.setState({notification : {
title: "İşlem başarılı!",
message: "",
type: "success",
insert: "top",
dismiss: {
duration: 1500,
onScreen: true
},
container: "top-right",
animationIn: ["animated", "fadeIn"],
animationOut: ["animated", "fadeOut"]
}});
this.setState({isLoggedin: await this.apiService.isLoggedin()});
}
componentWillUpdate() {
this.state.notification = {
title: "İşlem başarılı!",
message: "",
type: "success",
insert: "top",
dismiss: {
duration: 1500,
onScreen: true
},
container: "top-right",
animationIn: ["animated", "fadeIn"],
animationOut: ["animated", "fadeOut"]
}
}
handleChange(event) {
this.setState({value: parseFloat(event.target.value) });
this.setState({price: parseFloat(event.target.value)*0.998});
}
handleBuySellType(event) {
this.setState({orderType: parseInt(event.target.value)});
this.setState({price:0, value:0});
}
async handlePercentButtons(data) {
const orderType = data.split('_')[1];
const orderPercent = data.split('_')[0];
let assetBalance;
let valuepercent;
if(orderType === 'b'){
console.log( await GetAssetBalance(symbolSecondAssets[this.props.product]))
assetBalance = parseFloat(await GetAssetBalance(symbolSecondAssets[this.props.product]));
console.log(assetBalance)
valuepercent = (assetBalance*(orderPercent/100)-(((assetBalance*(orderPercent/100))- BuyMinAssets[this.props.product]) % BuyStepAssets[this.props.product]));
if(this.props.product == 'ETHBTC' || this.props.product == 'XRPBTC' || this.props.product == 'LTCBTC' || this.props.product == 'USDTTRY'){
this.setState({value: valuepercent})
}
else{
if(valuepercent*1000 >= BuyMinAssets[this.props.product]*1000 && valuepercent*1000 <= BuyMaxAssets[this.props.product]*1000 && (valuepercent*1000 - BuyMinAssets[this.props.product]*1000) % (BuyStepAssets[this.props.product]*1000) == 0){
this.setState({value: valuepercent})
}
else{
store.addNotification({...this.state.notification,message:'Değerler istenen aralıkta olmalıdır.' ,type:'danger',title:'Hata!'});
}
}
}
else if(orderType === 's') {
assetBalance = parseFloat(await GetAssetBalance(symbolMainAssets[this.props.product]));
valuepercent = assetBalance*(orderPercent/100);
if(this.props.product == 'ETHBTC' || this.props.product == 'XRPBTC' || this.props.product == 'LTCBTC' || this.props.product == 'USDTTRY'){
this.setState({value: valuepercent})
}
else{
if(valuepercent*100000000 >= minAssets[this.props.product]*100000000 && valuepercent*100000000 <= maxAssets[this.props.product]*100000000 && (valuepercent*100000000 - minAssets[this.props.product]*100000000) % (stepAssets[this.props.product]*100000000) == 0){
this.setState({value: valuepercent})
}
else{
store.addNotification({...this.state.notification,message:'Değerler istenen aralıkta olmalıdır.' ,type:'danger',title:'Hata!'});
}
}
}
}
render() {
this.state.assetMain = symbolMainAssets[this.props.product]
this.state.assetSecondary = symbolSecondAssets[this.props.product]
return (
<div>
<div className="crypt-boxed-area">
<div className={"row" +this.props.themes?"no-gutters":"no-gutters-light"}>
<div className="tab-content" style={{minHeight:"430px"}}>
<ul
className="nav market-buttons"
style={{ backgroundColor: "transparent" }}
>
<li role="presentation">
<button
href="#Buy"
className="button-buy market-btn active show"
data-toggle="tab" value='0' onClick={this.handleBuySellType}
>
AL
</button>
</li>
<li role="presentation">
<button
href="#Sell"
className="button-sell market-btn"
data-toggle="tab" value='1' onClick={this.handleBuySellType}
>
SAT
</button>
</li>
</ul>
<div role="tabpanel" className="tab-pane active" id="Buy">
<div className="col-md-12">
<div className="crypt-buy-sell-form">
<div className="crypt-buy">
<div className="input-group mb-3">
<div className="input-group-prepend">
{" "}
<span className="input-group-text">Miktar</span>{" "}
</div>
<input type="number" className="form-control" value={this.state.value} onChange={this.handleChange} />
<div className="input-group-append">
{" "}
<span className="input-group-text">{this.state.assetSecondary}</span>{" "}
</div>
</div>
<div className="row">
<div className="col"><button className="percent-btn" onClick={async ()=>this.handlePercentButtons('25_b')}>%25</button></div>
<div className="col"><button className="percent-btn" onClick={async ()=>this.handlePercentButtons('50_b')}>%50</button></div>
<div className="col"><button className="percent-btn" onClick={async ()=>this.handlePercentButtons('75_b')}>%75</button></div>
<div className="col"><button className="percent-btn" onClick={async ()=>this.handlePercentButtons('100_b')}>%100</button></div>
</div>
<div>
<p>
Ücret: <span className="fright">100x0.2%=0.02</span>
</p>
</div>
<div className="menu-green">
<button className="crypt-button-green-full" onClick={this.sendMarketOrder}>AL</button>
</div>
</div>
</div>
</div>
</div>
<div role="tabpanel" className="tab-pane" id="Sell">
<div className="col-md-12">
<div className="crypt-buy-sell-form">
<div className="crypt-sell">
<div className="input-group mb-3">
<div className="input-group-prepend">
{" "}
<span className="input-group-text">Miktar</span>{" "}
</div>
<input type="number" className="form-control" value={this.state.value} onChange={this.handleChange} />
<div className="input-group-append">
{" "}
<span className="input-group-text">{this.state.assetMain}</span>{" "}
</div>
</div>
<div className="row">
<div className="col"><button className="percent-btn" onClick={async ()=>this.handlePercentButtons('25_s')}>%25</button></div>
<div className="col"><button className="percent-btn" onClick={async ()=>this.handlePercentButtons('50_s')}>%50</button></div>
<div className="col"><button className="percent-btn" onClick={async ()=>this.handlePercentButtons('75_s')}>%75</button></div>
<div className="col"><button className="percent-btn" onClick={async ()=>this.handlePercentButtons('100_s')}>%100</button></div>
</div>
<div>
<p>
Ücret: <span className="fright">100x0.2%=0.02</span>
</p>
</div>
<div>
<button className="crypt-button-red-full" onClick={this.sendMarketOrder}>SAT</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
)
};
};
const mapStateToProps = (state) => {
return {
product: state.testRedux.product,
themes: state.themeReducer.themes,
};
};
const mapDispatchToProps = (dispatch) => ({
setProduct: (payload) => dispatch(setProduct(payload)),
setTheme: (payload) => dispatch(setTheme(payload)),
});
export default withRouter(
connect(mapStateToProps, mapDispatchToProps)(MarketBuyAndSell)
);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.